hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
7c79283aafc8b3c28b9d4233973db8cc197abc50
1,413
import java.text.NumberFormat; import java.util.Locale; import java.util.concurrent.atomic.AtomicInteger; public class Customer { private static final AtomicInteger maxId = new AtomicInteger(0); private static final NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.US); private final int id; private String name; private double cash; public Customer() { id = maxId.incrementAndGet(); } public int getId() { return id; } public Customer setName(String name) { this.name = name; return this; } public String getName() { return name; } public Customer addCash(double amount) { cash += amount; System.out.println(String.format("%s found %s lying around.", name, formatter.format(amount))); return this; } public double getCash() { return cash; } public Customer buySnacks(Snack snack, int quantity) { double totalCost = snack.getTotalCost(quantity); if (totalCost <= cash && snack.buy(quantity)) cash -= totalCost; System.out.println(String.format("%s bought %d %s for %s.", name, quantity, snack.getName(), formatter.format(totalCost))); return this; } @Override public String toString() { return String.format("Customer %d (%s) has %s cash on hand.", id, name, formatter.format(cash)); } }
27.705882
131
0.640481
3bc0fcecfe6d0e4032d92e03855f78971fa84e99
688
package net.notejam.spring.security; import org.springframework.stereotype.Controller; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import net.notejam.spring.URITemplates; /** * Login controller. * * @author [email protected] * @see <a href="bitcoin:1335STSwu9hST4vcMRppEPgENMHD2r1REK">Donations</a> */ @Controller public class LoginController extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { registry.addViewController(URITemplates.SIGNIN).setViewName("user/login"); } }
28.666667
82
0.799419
1e43a9391dbf75238c16207b3ac8e1fe10b196eb
50,614
/* *AVISO LEGAL © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.nomina.util; import org.apache.log4j.Logger; import java.sql.Time; import java.sql.Timestamp; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.util.CellRangeAddress; import javax.swing.border.Border; import java.io.InputStream; import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.Date; //import java.util.ArrayList; import com.bydan.framework.erp.business.entity.GeneralEntity; import com.bydan.framework.erp.business.entity.GeneralEntityReturnGeneral; import com.bydan.framework.erp.business.entity.GeneralEntityParameterGeneral; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.entity.OrderBy; import com.bydan.framework.erp.business.entity.Classe; import com.bydan.framework.erp.business.entity.Reporte; import com.bydan.framework.erp.util.ConstantesJsp; import com.bydan.framework.erp.business.dataaccess.ConstantesSql; import com.bydan.erp.nomina.util.TipoCuotaConstantesFunciones; import com.bydan.erp.nomina.util.TipoCuotaParameterReturnGeneral; //import com.bydan.erp.nomina.util.TipoCuotaParameterGeneral; import com.bydan.framework.erp.business.logic.DatosCliente; import com.bydan.framework.erp.util.*; import com.bydan.erp.nomina.business.entity.*; import com.bydan.erp.seguridad.business.entity.*; import com.bydan.erp.contabilidad.business.entity.*; import com.bydan.erp.seguridad.util.*; import com.bydan.erp.contabilidad.util.*; //import com.bydan.framework.erp.util.*; //import com.bydan.framework.erp.business.logic.*; //import com.bydan.erp.nomina.business.dataaccess.*; //import com.bydan.erp.nomina.business.logic.*; //import java.sql.SQLException; //CONTROL_INCLUDE import com.bydan.erp.seguridad.business.entity.*; @SuppressWarnings("unused") final public class TipoCuotaConstantesFunciones extends TipoCuotaConstantesFuncionesAdditional { public static String S_TIPOREPORTE_EXTRA=""; //USADO MAS EN RELACIONADO PARA MANTENIMIENTO MAESTRO-DETALLE public static Integer TAMANIO_ALTO_MAXIMO_TABLADATOS=Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS; public static Integer TAMANIO_ALTO_MINIMO_TABLADATOS=Constantes.ISWING_TAMANIOMINIMO_TABLADATOS; //PARA TABLA RELACIONES(DESCRIPCION HEIGHTPE_REL_TAB) public static Integer ALTO_TABPANE_RELACIONES=Constantes.ISWING_ALTO_TABPANE + Funciones2.getValorProporcion(Constantes.ISWING_ALTO_TABPANE,0); //PARA TABLA RELACIONADO(DESCRIPTION HEIGHTPE_REL) public static Integer TAMANIO_ALTO_MAXIMO_TABLADATOSREL=Constantes.ISWING_TAMANIOMAXIMO_TABLADATOSREL + Funciones2.getValorProporcion(Constantes.ISWING_TAMANIOMAXIMO_TABLADATOSREL,0); public static Integer TAMANIO_ALTO_MINIMO_TABLADATOSREL=Constantes.ISWING_TAMANIOMINIMO_TABLADATOSREL + Funciones2.getValorProporcion(Constantes.ISWING_TAMANIOMINIMO_TABLADATOSREL,0); //PARA CAMBIAR TODO--> SE CAMBIA EN TABLA RELACIONES Y TABLAS RELACIONADOS /* PARA MANEJAR EL TAB RELACIONES CON TABLA DE DATOS SE DEBE MODIFICAR Y VERIFICAR LOS VALORES CONTANTES: final public static Integer ISWING_TAMANIOMAXIMO_TABLADATOSREL=240;//230;350; final public static Integer ISWING_TAMANIOMINIMO_TABLADATOSREL=240;//230;260 final public static Integer ISWING_ALTO_TABPANE=375;//375;400;260; CASO CONTRARIO, ESTOS VALORES SERIAN PARA CADA CASO (NO CONSTANTES) NOTA: * LA ALINEACION HORIZONTAL,FALTA */ public static final String SFINALQUERY=Constantes.SFINALQUERY; public static final String SNOMBREOPCION="TipoCuota"; public static final String SPATHOPCION="Nomina"; public static final String SPATHMODULO="nomina/"; public static final String SPERSISTENCECONTEXTNAME=""; public static final String SPERSISTENCENAME="TipoCuota"+TipoCuotaConstantesFunciones.SPERSISTENCECONTEXTNAME+Constantes.SPERSISTENCECONTEXTNAME; public static final String SEJBNAME="TipoCuotaHomeRemote"; public static final String SEJBNAME_ADDITIONAL="TipoCuotaHomeRemoteAdditional"; //RMI public static final String SLOCALEJBNAME_RMI=TipoCuotaConstantesFunciones.SCHEMA+"_"+TipoCuotaConstantesFunciones.SEJBNAME+"_"+Constantes.SEJBLOCAL;//"erp/TipoCuotaHomeRemote/local" public static final String SREMOTEEJBNAME_RMI=TipoCuotaConstantesFunciones.SCHEMA+"_"+TipoCuotaConstantesFunciones.SEJBNAME+"_"+Constantes.SEJBREMOTE;//remote public static final String SLOCALEJBNAMEADDITIONAL_RMI=TipoCuotaConstantesFunciones.SCHEMA+"_"+TipoCuotaConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+"_"+Constantes.SEJBLOCAL;//"erp/TipoCuotaHomeRemote/local" public static final String SREMOTEEJBNAMEADDITIONAL_RMI=TipoCuotaConstantesFunciones.SCHEMA+"_"+TipoCuotaConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+"_"+Constantes.SEJBREMOTE;//remote //RMI //JBOSS5.1 public static final String SLOCALEJBNAME=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+TipoCuotaConstantesFunciones.SEJBNAME+Constantes.SEJBSEPARATOR+Constantes.SEJBLOCAL;//"erp/TipoCuotaHomeRemote/local" public static final String SREMOTEEJBNAME=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+TipoCuotaConstantesFunciones.SEJBNAME+Constantes.SEJBSEPARATOR+Constantes.SEJBREMOTE;//remote public static final String SLOCALEJBNAMEADDITIONAL=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+TipoCuotaConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+Constantes.SEJBSEPARATOR+Constantes.SEJBLOCAL;//"erp/TipoCuotaHomeRemote/local" public static final String SREMOTEEJBNAMEADDITIONAL=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+TipoCuotaConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+Constantes.SEJBSEPARATOR+Constantes.SEJBREMOTE;//remote //JBOSS5.1 public static final String SSESSIONNAME=TipoCuotaConstantesFunciones.OBJECTNAME + Constantes.SSESSIONBEAN; public static final String SSESSIONNAME_FACE=Constantes.SFACE_INI+TipoCuotaConstantesFunciones.SSESSIONNAME + Constantes.SFACE_FIN; public static final String SREQUESTNAME=TipoCuotaConstantesFunciones.OBJECTNAME + Constantes.SREQUESTBEAN; public static final String SREQUESTNAME_FACE=Constantes.SFACE_INI+TipoCuotaConstantesFunciones.SREQUESTNAME + Constantes.SFACE_FIN; public static final String SCLASSNAMETITULOREPORTES="Tipo Cuotas"; public static final String SRELATIVEPATH="../../../"; public static final String SCLASSPLURAL="s"; public static final String SCLASSWEBTITULO="Tipo Cuota"; public static final String SCLASSWEBTITULO_LOWER="Tipo Cuota"; public static Integer INUMEROPAGINACION=10; public static Integer ITAMANIOFILATABLA=Constantes.ISWING_ALTO_FILA; public static Boolean ES_DEBUG=false; public static Boolean CON_DESCRIPCION_DETALLADO=false; public static final String CLASSNAME="TipoCuota"; public static final String OBJECTNAME="tipocuota"; //PARA FORMAR QUERYS public static final String SCHEMA=Constantes.SCHEMA_NOMINA; public static final String TABLENAME="tipo_cuota"; public static final String SQL_SECUENCIAL=SCHEMA+"."+TABLENAME+"_id_seq"; public static String QUERYSELECT="select tipocuota from "+TipoCuotaConstantesFunciones.SPERSISTENCENAME+" tipocuota"; public static String QUERYSELECTNATIVE="select "+TipoCuotaConstantesFunciones.SCHEMA+"."+TipoCuotaConstantesFunciones.TABLENAME+".id,"+TipoCuotaConstantesFunciones.SCHEMA+"."+TipoCuotaConstantesFunciones.TABLENAME+".version_row,"+TipoCuotaConstantesFunciones.SCHEMA+"."+TipoCuotaConstantesFunciones.TABLENAME+".id_empresa,"+TipoCuotaConstantesFunciones.SCHEMA+"."+TipoCuotaConstantesFunciones.TABLENAME+".codigo,"+TipoCuotaConstantesFunciones.SCHEMA+"."+TipoCuotaConstantesFunciones.TABLENAME+".nombre,"+TipoCuotaConstantesFunciones.SCHEMA+"."+TipoCuotaConstantesFunciones.TABLENAME+".es_prove from "+TipoCuotaConstantesFunciones.SCHEMA+"."+TipoCuotaConstantesFunciones.TABLENAME;//+" as "+TipoCuotaConstantesFunciones.TABLENAME; //AUDITORIA public static Boolean ISCONAUDITORIA=false; public static Boolean ISCONAUDITORIADETALLE=true; //GUARDAR SOLO MAESTRO DETALLE FUNCIONALIDAD public static Boolean ISGUARDARREL=false; protected TipoCuotaConstantesFuncionesAdditional tipocuotaConstantesFuncionesAdditional=null; public TipoCuotaConstantesFuncionesAdditional getTipoCuotaConstantesFuncionesAdditional() { return this.tipocuotaConstantesFuncionesAdditional; } public void setTipoCuotaConstantesFuncionesAdditional(TipoCuotaConstantesFuncionesAdditional tipocuotaConstantesFuncionesAdditional) { try { this.tipocuotaConstantesFuncionesAdditional=tipocuotaConstantesFuncionesAdditional; } catch(Exception e) { ; } } public static final String ID=ConstantesSql.ID; public static final String VERSIONROW=ConstantesSql.VERSIONROW; public static final String IDEMPRESA= "id_empresa"; public static final String CODIGO= "codigo"; public static final String NOMBRE= "nombre"; public static final String ESPROVE= "es_prove"; //TITULO CAMPO public static final String LABEL_ID= "Id"; public static final String LABEL_ID_LOWER= "id"; public static final String LABEL_VERSIONROW= "Versionrow"; public static final String LABEL_VERSIONROW_LOWER= "version Row"; public static final String LABEL_IDEMPRESA= "Empresa"; public static final String LABEL_IDEMPRESA_LOWER= "Empresa"; public static final String LABEL_CODIGO= "Codigo"; public static final String LABEL_CODIGO_LOWER= "Codigo"; public static final String LABEL_NOMBRE= "Nombre"; public static final String LABEL_NOMBRE_LOWER= "Nombre"; public static final String LABEL_ESPROVE= "Es Prove"; public static final String LABEL_ESPROVE_LOWER= "Es Prove"; public static final String SREGEXCODIGO=ConstantesValidacion.SREGEXCADENA; public static final String SMENSAJEREGEXCODIGO=ConstantesValidacion.SVALIDACIONCADENA; public static final String SREGEXNOMBRE=ConstantesValidacion.SREGEXCADENA; public static final String SMENSAJEREGEXNOMBRE=ConstantesValidacion.SVALIDACIONCADENA; public static String getTipoCuotaLabelDesdeNombre(String sNombreColumna) { String sLabelColumna=""; if(sNombreColumna.equals(TipoCuotaConstantesFunciones.IDEMPRESA)) {sLabelColumna=TipoCuotaConstantesFunciones.LABEL_IDEMPRESA;} if(sNombreColumna.equals(TipoCuotaConstantesFunciones.CODIGO)) {sLabelColumna=TipoCuotaConstantesFunciones.LABEL_CODIGO;} if(sNombreColumna.equals(TipoCuotaConstantesFunciones.NOMBRE)) {sLabelColumna=TipoCuotaConstantesFunciones.LABEL_NOMBRE;} if(sNombreColumna.equals(TipoCuotaConstantesFunciones.ESPROVE)) {sLabelColumna=TipoCuotaConstantesFunciones.LABEL_ESPROVE;} if(sLabelColumna.equals("")) { sLabelColumna=sNombreColumna; } return sLabelColumna; } public static String getNombreEjb_JBoss81(String sAplicacion,String sModule,String sClaseEjb,String sInterfaceEjb) throws Exception { String sDescripcion=""; sDescripcion="ejb:"+sAplicacion+"/"+sModule+"/"+sClaseEjb+"!" + sInterfaceEjb; return sDescripcion; } public static String getes_proveDescripcion(TipoCuota tipocuota) throws Exception { String sDescripcion=Constantes.SCAMPOVERDADERO; if(!tipocuota.getes_prove()) { sDescripcion=Constantes.SCAMPOFALSO; } return sDescripcion; } public static String getes_proveHtmlDescripcion(TipoCuota tipocuota) throws Exception { String sDescripcion=FuncionesJsp.getStringHtmlCheckBox(tipocuota.getId(),tipocuota.getes_prove()); return sDescripcion; } public static String getTipoCuotaDescripcion(TipoCuota tipocuota) { String sDescripcion=Constantes.SCAMPONONE; if(tipocuota !=null/* && tipocuota.getId()!=0*/) { sDescripcion=tipocuota.getcodigo();//tipocuotatipocuota.getcodigo().trim(); } return sDescripcion; } public static String getTipoCuotaDescripcionDetallado(TipoCuota tipocuota) { String sDescripcion=""; sDescripcion+=TipoCuotaConstantesFunciones.ID+"="; sDescripcion+=tipocuota.getId().toString()+","; sDescripcion+=TipoCuotaConstantesFunciones.VERSIONROW+"="; sDescripcion+=tipocuota.getVersionRow().toString()+","; sDescripcion+=TipoCuotaConstantesFunciones.IDEMPRESA+"="; sDescripcion+=tipocuota.getid_empresa().toString()+","; sDescripcion+=TipoCuotaConstantesFunciones.CODIGO+"="; sDescripcion+=tipocuota.getcodigo()+","; sDescripcion+=TipoCuotaConstantesFunciones.NOMBRE+"="; sDescripcion+=tipocuota.getnombre()+","; sDescripcion+=TipoCuotaConstantesFunciones.ESPROVE+"="; sDescripcion+=tipocuota.getes_prove().toString()+","; return sDescripcion; } public static void setTipoCuotaDescripcion(TipoCuota tipocuota,String sValor) throws Exception { if(tipocuota !=null) { tipocuota.setcodigo(sValor);;//tipocuotatipocuota.getcodigo().trim(); } } public static String getEmpresaDescripcion(Empresa empresa) { String sDescripcion=Constantes.SCAMPONONE; if(empresa!=null/*&&empresa.getId()>0*/) { sDescripcion=EmpresaConstantesFunciones.getEmpresaDescripcion(empresa); } return sDescripcion; } public static String getNombreIndice(String sNombreIndice) { if(sNombreIndice.equals("Todos")) { sNombreIndice="Tipo=Todos"; } else if(sNombreIndice.equals("PorId")) { sNombreIndice="Tipo=Por Id"; } else if(sNombreIndice.equals("FK_IdEmpresa")) { sNombreIndice="Tipo= Por Empresa"; } return sNombreIndice; } public static String getDetalleIndicePorId(Long id) { return "Parametros->Porid="+id.toString(); } public static String getDetalleIndiceFK_IdEmpresa(Long id_empresa) { String sDetalleIndice=" Parametros->"; if(id_empresa!=null) {sDetalleIndice+=" Codigo Unico De Empresa="+id_empresa.toString();} return sDetalleIndice; } public static void quitarEspaciosTipoCuota(TipoCuota tipocuota,ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { tipocuota.setcodigo(tipocuota.getcodigo().trim()); tipocuota.setnombre(tipocuota.getnombre().trim()); } public static void quitarEspaciosTipoCuotas(List<TipoCuota> tipocuotas,ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { for(TipoCuota tipocuota: tipocuotas) { tipocuota.setcodigo(tipocuota.getcodigo().trim()); tipocuota.setnombre(tipocuota.getnombre().trim()); } } public static void InicializarGeneralEntityAuxiliaresTipoCuota(TipoCuota tipocuota,Boolean conAsignarBase,Boolean conInicializarAuxiliar) throws Exception { if(conAsignarBase && tipocuota.getConCambioAuxiliar()) { tipocuota.setIsDeleted(tipocuota.getIsDeletedAuxiliar()); tipocuota.setIsNew(tipocuota.getIsNewAuxiliar()); tipocuota.setIsChanged(tipocuota.getIsChangedAuxiliar()); //YA RESTAURO, NO DEBERIA HACERLO NUEVAMENTE AL MENOS NO HASTA GUARDAR OTRA VEZ tipocuota.setConCambioAuxiliar(false); } if(conInicializarAuxiliar) { tipocuota.setIsDeletedAuxiliar(false); tipocuota.setIsNewAuxiliar(false); tipocuota.setIsChangedAuxiliar(false); tipocuota.setConCambioAuxiliar(false); } } public static void InicializarGeneralEntityAuxiliaresTipoCuotas(List<TipoCuota> tipocuotas,Boolean conAsignarBase,Boolean conInicializarAuxiliar) throws Exception { for(TipoCuota tipocuota : tipocuotas) { if(conAsignarBase && tipocuota.getConCambioAuxiliar()) { tipocuota.setIsDeleted(tipocuota.getIsDeletedAuxiliar()); tipocuota.setIsNew(tipocuota.getIsNewAuxiliar()); tipocuota.setIsChanged(tipocuota.getIsChangedAuxiliar()); //YA RESTAURO, NO DEBERIA HACERLO NUEVAMENTE AL MENOS NO HASTA GUARDAR OTRA VEZ tipocuota.setConCambioAuxiliar(false); } if(conInicializarAuxiliar) { tipocuota.setIsDeletedAuxiliar(false); tipocuota.setIsNewAuxiliar(false); tipocuota.setIsChangedAuxiliar(false); tipocuota.setConCambioAuxiliar(false); } } } public static void InicializarValoresTipoCuota(TipoCuota tipocuota,Boolean conEnteros) throws Exception { if(conEnteros) { Short ish_value=0; } } public static void InicializarValoresTipoCuotas(List<TipoCuota> tipocuotas,Boolean conEnteros) throws Exception { for(TipoCuota tipocuota: tipocuotas) { if(conEnteros) { Short ish_value=0; } } } public static void TotalizarValoresFilaTipoCuota(List<TipoCuota> tipocuotas,TipoCuota tipocuotaAux) throws Exception { TipoCuotaConstantesFunciones.InicializarValoresTipoCuota(tipocuotaAux,true); for(TipoCuota tipocuota: tipocuotas) { if(tipocuota.getsType().equals(Constantes2.S_TOTALES)) { continue; } } } public static ArrayList<String> getArrayColumnasGlobalesTipoCuota(ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); arrColumnasGlobales=TipoCuotaConstantesFunciones.getArrayColumnasGlobalesTipoCuota(arrDatoGeneral,new ArrayList<String>()); return arrColumnasGlobales; } public static ArrayList<String> getArrayColumnasGlobalesTipoCuota(ArrayList<DatoGeneral> arrDatoGeneral,ArrayList<String> arrColumnasGlobalesNo) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); Boolean noExiste=false; noExiste=false; for(String sColumnaGlobalNo:arrColumnasGlobalesNo) { if(sColumnaGlobalNo.equals(TipoCuotaConstantesFunciones.IDEMPRESA)) { noExiste=true; } } if(!noExiste) { arrColumnasGlobales.add(TipoCuotaConstantesFunciones.IDEMPRESA); } return arrColumnasGlobales; } public static ArrayList<String> getArrayColumnasGlobalesNoTipoCuota(ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); return arrColumnasGlobales; } public static Boolean ExisteEnLista(List<TipoCuota> tipocuotas,TipoCuota tipocuota,Boolean conIdNulo) throws Exception { Boolean existe=false; for(TipoCuota tipocuotaAux: tipocuotas) { if(tipocuotaAux!=null && tipocuota!=null) { if((tipocuotaAux.getId()==null && tipocuota.getId()==null) && conIdNulo) { existe=true; break; } else if(tipocuotaAux.getId()!=null && tipocuota.getId()!=null){ if(tipocuotaAux.getId().equals(tipocuota.getId())) { existe=true; break; } } } } return existe; } public static ArrayList<DatoGeneral> getTotalesListaTipoCuota(List<TipoCuota> tipocuotas) throws Exception { ArrayList<DatoGeneral> arrTotalesDatoGeneral=new ArrayList<DatoGeneral>(); DatoGeneral datoGeneral=new DatoGeneral(); for(TipoCuota tipocuota: tipocuotas) { if(tipocuota.getsType().equals(Constantes2.S_TOTALES)) { continue; } } return arrTotalesDatoGeneral; } public static ArrayList<OrderBy> getOrderByListaTipoCuota() throws Exception { ArrayList<OrderBy> arrOrderBy=new ArrayList<OrderBy>(); OrderBy orderBy=new OrderBy(); orderBy=new OrderBy(false,TipoCuotaConstantesFunciones.LABEL_ID, TipoCuotaConstantesFunciones.ID,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,TipoCuotaConstantesFunciones.LABEL_VERSIONROW, TipoCuotaConstantesFunciones.VERSIONROW,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,TipoCuotaConstantesFunciones.LABEL_IDEMPRESA, TipoCuotaConstantesFunciones.IDEMPRESA,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,TipoCuotaConstantesFunciones.LABEL_CODIGO, TipoCuotaConstantesFunciones.CODIGO,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,TipoCuotaConstantesFunciones.LABEL_NOMBRE, TipoCuotaConstantesFunciones.NOMBRE,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,TipoCuotaConstantesFunciones.LABEL_ESPROVE, TipoCuotaConstantesFunciones.ESPROVE,false,""); arrOrderBy.add(orderBy); return arrOrderBy; } public static List<String> getTodosTiposColumnasTipoCuota() throws Exception { List<String> arrTiposColumnas=new ArrayList<String>(); String sTipoColumna=new String(); sTipoColumna=new String(); sTipoColumna=TipoCuotaConstantesFunciones.ID; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=TipoCuotaConstantesFunciones.VERSIONROW; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=TipoCuotaConstantesFunciones.IDEMPRESA; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=TipoCuotaConstantesFunciones.CODIGO; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=TipoCuotaConstantesFunciones.NOMBRE; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=TipoCuotaConstantesFunciones.ESPROVE; arrTiposColumnas.add(sTipoColumna); return arrTiposColumnas; } public static ArrayList<Reporte> getTiposSeleccionarTipoCuota() throws Exception { return TipoCuotaConstantesFunciones.getTiposSeleccionarTipoCuota(false,true,true,true,true); } public static ArrayList<Reporte> getTiposSeleccionarTipoCuota(Boolean conFk) throws Exception { return TipoCuotaConstantesFunciones.getTiposSeleccionarTipoCuota(conFk,true,true,true,true); } public static ArrayList<Reporte> getTiposSeleccionarTipoCuota(Boolean conFk,Boolean conStringColumn,Boolean conValorColumn,Boolean conFechaColumn,Boolean conBitColumn) throws Exception { ArrayList<Reporte> arrTiposSeleccionarTodos=new ArrayList<Reporte>(); Reporte reporte=new Reporte(); if(conFk) { reporte=new Reporte(); reporte.setsCodigo(TipoCuotaConstantesFunciones.LABEL_IDEMPRESA); reporte.setsDescripcion(TipoCuotaConstantesFunciones.LABEL_IDEMPRESA); arrTiposSeleccionarTodos.add(reporte); } if(conStringColumn) { reporte=new Reporte(); reporte.setsCodigo(TipoCuotaConstantesFunciones.LABEL_CODIGO); reporte.setsDescripcion(TipoCuotaConstantesFunciones.LABEL_CODIGO); arrTiposSeleccionarTodos.add(reporte); } if(conStringColumn) { reporte=new Reporte(); reporte.setsCodigo(TipoCuotaConstantesFunciones.LABEL_NOMBRE); reporte.setsDescripcion(TipoCuotaConstantesFunciones.LABEL_NOMBRE); arrTiposSeleccionarTodos.add(reporte); } if(conBitColumn) { reporte=new Reporte(); reporte.setsCodigo(TipoCuotaConstantesFunciones.LABEL_ESPROVE); reporte.setsDescripcion(TipoCuotaConstantesFunciones.LABEL_ESPROVE); arrTiposSeleccionarTodos.add(reporte); } return arrTiposSeleccionarTodos; } public static ArrayList<Reporte> getTiposRelacionesTipoCuota(Boolean conEspecial) throws Exception { ArrayList<Reporte> arrTiposRelacionesTodos=new ArrayList<Reporte>(); Reporte reporte=new Reporte(); //ESTO ESTA EN CONTROLLER return arrTiposRelacionesTodos; } public static void refrescarForeignKeysDescripcionesTipoCuota(TipoCuota tipocuotaAux) throws Exception { tipocuotaAux.setempresa_descripcion(EmpresaConstantesFunciones.getEmpresaDescripcion(tipocuotaAux.getEmpresa())); } public static void refrescarForeignKeysDescripcionesTipoCuota(List<TipoCuota> tipocuotasTemp) throws Exception { for(TipoCuota tipocuotaAux:tipocuotasTemp) { tipocuotaAux.setempresa_descripcion(EmpresaConstantesFunciones.getEmpresaDescripcion(tipocuotaAux.getEmpresa())); } } public static ArrayList<Classe> getClassesForeignKeysOfTipoCuota(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { classes.add(new Classe(Empresa.class)); } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(Classe clas:classesP) { if(clas.clas.equals(Empresa.class)) { classes.add(new Classe(Empresa.class)); } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesForeignKeysFromStringsOfTipoCuota(ArrayList<String> arrClasses,DeepLoadType deepLoadType)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { for(String sClasse:arrClasses) { if(Empresa.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(Empresa.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(String sClasse:arrClasses) { if(Empresa.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(Empresa.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsOfTipoCuota(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception { try { return TipoCuotaConstantesFunciones.getClassesRelationshipsOfTipoCuota(classesP,deepLoadType,true); } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsOfTipoCuota(ArrayList<Classe> classesP,DeepLoadType deepLoadType,Boolean conMuchosAMuchos)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { classes.add(new Classe(Prestamo.class)); } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(Classe clas:classesP) { if(clas.clas.equals(Prestamo.class)) { classes.add(new Classe(Prestamo.class)); break; } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsFromStringsOfTipoCuota(ArrayList<String> arrClasses,DeepLoadType deepLoadType)throws Exception { try { return TipoCuotaConstantesFunciones.getClassesRelationshipsFromStringsOfTipoCuota(arrClasses,deepLoadType,true); } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsFromStringsOfTipoCuota(ArrayList<String> arrClasses,DeepLoadType deepLoadType,Boolean conMuchosAMuchos)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { for(String sClasse:arrClasses) { if(Prestamo.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(Prestamo.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(String sClasse:arrClasses) { if(Prestamo.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(Prestamo.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } //FUNCIONES CONTROLLER public static void actualizarLista(TipoCuota tipocuota,List<TipoCuota> tipocuotas,Boolean permiteQuitar) throws Exception { try { Boolean existe=false; TipoCuota tipocuotaEncontrado=null; for(TipoCuota tipocuotaLocal:tipocuotas) { if(tipocuotaLocal.getId().equals(tipocuota.getId())) { tipocuotaEncontrado=tipocuotaLocal; tipocuotaLocal.setIsChanged(tipocuota.getIsChanged()); tipocuotaLocal.setIsNew(tipocuota.getIsNew()); tipocuotaLocal.setIsDeleted(tipocuota.getIsDeleted()); tipocuotaLocal.setGeneralEntityOriginal(tipocuota.getGeneralEntityOriginal()); tipocuotaLocal.setId(tipocuota.getId()); tipocuotaLocal.setVersionRow(tipocuota.getVersionRow()); tipocuotaLocal.setid_empresa(tipocuota.getid_empresa()); tipocuotaLocal.setcodigo(tipocuota.getcodigo()); tipocuotaLocal.setnombre(tipocuota.getnombre()); tipocuotaLocal.setes_prove(tipocuota.getes_prove()); tipocuotaLocal.setPrestamos(tipocuota.getPrestamos()); existe=true; break; } } if(!tipocuota.getIsDeleted()) { if(!existe) { tipocuotas.add(tipocuota); } } else { if(tipocuotaEncontrado!=null && permiteQuitar) { tipocuotas.remove(tipocuotaEncontrado); } } } catch(Exception e) { throw e; } } public static void actualizarSelectedLista(TipoCuota tipocuota,List<TipoCuota> tipocuotas) throws Exception { try { for(TipoCuota tipocuotaLocal:tipocuotas) { if(tipocuotaLocal.getId().equals(tipocuota.getId())) { tipocuotaLocal.setIsSelected(tipocuota.getIsSelected()); break; } } } catch(Exception e) { throw e; } } public static void setEstadosInicialesTipoCuota(List<TipoCuota> tipocuotasAux) throws Exception { //this.tipocuotasAux=tipocuotasAux; for(TipoCuota tipocuotaAux:tipocuotasAux) { if(tipocuotaAux.getIsChanged()) { tipocuotaAux.setIsChanged(false); } if(tipocuotaAux.getIsNew()) { tipocuotaAux.setIsNew(false); } if(tipocuotaAux.getIsDeleted()) { tipocuotaAux.setIsDeleted(false); } } } public static void setEstadosInicialesTipoCuota(TipoCuota tipocuotaAux) throws Exception { //this.tipocuotaAux=tipocuotaAux; if(tipocuotaAux.getIsChanged()) { tipocuotaAux.setIsChanged(false); } if(tipocuotaAux.getIsNew()) { tipocuotaAux.setIsNew(false); } if(tipocuotaAux.getIsDeleted()) { tipocuotaAux.setIsDeleted(false); } } public static void seleccionarAsignar(TipoCuota tipocuotaAsignar,TipoCuota tipocuota) throws Exception { tipocuotaAsignar.setId(tipocuota.getId()); tipocuotaAsignar.setVersionRow(tipocuota.getVersionRow()); tipocuotaAsignar.setid_empresa(tipocuota.getid_empresa()); tipocuotaAsignar.setempresa_descripcion(tipocuota.getempresa_descripcion()); tipocuotaAsignar.setcodigo(tipocuota.getcodigo()); tipocuotaAsignar.setnombre(tipocuota.getnombre()); tipocuotaAsignar.setes_prove(tipocuota.getes_prove()); } public static void inicializarTipoCuota(TipoCuota tipocuota) throws Exception { try { tipocuota.setId(0L); tipocuota.setid_empresa(-1L); tipocuota.setcodigo(""); tipocuota.setnombre(""); tipocuota.setes_prove(false); } catch(Exception e) { throw e; } } public static void generarExcelReporteHeaderTipoCuota(String sTipo,Row row,Workbook workbook) { Cell cell=null; int iCell=0; CellStyle cellStyle = Funciones2.getStyleTitulo(workbook,"PRINCIPAL"); if(sTipo.equals("RELACIONADO")) { iCell++; } cell = row.createCell(iCell++); cell.setCellValue(TipoCuotaConstantesFunciones.LABEL_IDEMPRESA); cell.setCellStyle(cellStyle); cell = row.createCell(iCell++); cell.setCellValue(TipoCuotaConstantesFunciones.LABEL_CODIGO); cell.setCellStyle(cellStyle); cell = row.createCell(iCell++); cell.setCellValue(TipoCuotaConstantesFunciones.LABEL_NOMBRE); cell.setCellStyle(cellStyle); cell = row.createCell(iCell++); cell.setCellValue(TipoCuotaConstantesFunciones.LABEL_ESPROVE); cell.setCellStyle(cellStyle); } public static void generarExcelReporteDataTipoCuota(String sTipo,Row row,Workbook workbook,TipoCuota tipocuota,CellStyle cellStyle) throws Exception { Cell cell=null; int iCell=0; if(sTipo.equals("RELACIONADO")) { iCell++; } cell = row.createCell(iCell++); cell.setCellValue(tipocuota.getempresa_descripcion()); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } cell = row.createCell(iCell++); cell.setCellValue(tipocuota.getcodigo()); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } cell = row.createCell(iCell++); cell.setCellValue(tipocuota.getnombre()); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } cell = row.createCell(iCell++); cell.setCellValue(Funciones2.getDescripcionBoolean(tipocuota.getes_prove())); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } } //FUNCIONES CONTROLLER public String sFinalQueryTipoCuota=Constantes.SFINALQUERY; public String getsFinalQueryTipoCuota() { return this.sFinalQueryTipoCuota; } public void setsFinalQueryTipoCuota(String sFinalQueryTipoCuota) { this.sFinalQueryTipoCuota= sFinalQueryTipoCuota; } public Border resaltarSeleccionarTipoCuota=null; public Border setResaltarSeleccionarTipoCuota(ParametroGeneralUsuario parametroGeneralUsuario/*TipoCuotaBeanSwingJInternalFrame tipocuotaBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //tipocuotaBeanSwingJInternalFrame.jTtoolBarTipoCuota.setBorder(borderResaltar); this.resaltarSeleccionarTipoCuota= borderResaltar; return borderResaltar; } public Border getResaltarSeleccionarTipoCuota() { return this.resaltarSeleccionarTipoCuota; } public void setResaltarSeleccionarTipoCuota(Border borderResaltarSeleccionarTipoCuota) { this.resaltarSeleccionarTipoCuota= borderResaltarSeleccionarTipoCuota; } //RESALTAR,VISIBILIDAD,HABILITAR COLUMNA public Border resaltaridTipoCuota=null; public Boolean mostraridTipoCuota=true; public Boolean activaridTipoCuota=true; public Border resaltarid_empresaTipoCuota=null; public Boolean mostrarid_empresaTipoCuota=true; public Boolean activarid_empresaTipoCuota=true; public Boolean cargarid_empresaTipoCuota=true;//ConNoLoadForeignKeyColumnOTable=false public Boolean event_dependid_empresaTipoCuota=false;//ConEventDepend=true public Border resaltarcodigoTipoCuota=null; public Boolean mostrarcodigoTipoCuota=true; public Boolean activarcodigoTipoCuota=true; public Border resaltarnombreTipoCuota=null; public Boolean mostrarnombreTipoCuota=true; public Boolean activarnombreTipoCuota=true; public Border resaltares_proveTipoCuota=null; public Boolean mostrares_proveTipoCuota=true; public Boolean activares_proveTipoCuota=true; public Border setResaltaridTipoCuota(ParametroGeneralUsuario parametroGeneralUsuario/*TipoCuotaBeanSwingJInternalFrame tipocuotaBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //tipocuotaBeanSwingJInternalFrame.jTtoolBarTipoCuota.setBorder(borderResaltar); this.resaltaridTipoCuota= borderResaltar; return borderResaltar; } public Border getresaltaridTipoCuota() { return this.resaltaridTipoCuota; } public void setResaltaridTipoCuota(Border borderResaltar) { this.resaltaridTipoCuota= borderResaltar; } public Boolean getMostraridTipoCuota() { return this.mostraridTipoCuota; } public void setMostraridTipoCuota(Boolean mostraridTipoCuota) { this.mostraridTipoCuota= mostraridTipoCuota; } public Boolean getActivaridTipoCuota() { return this.activaridTipoCuota; } public void setActivaridTipoCuota(Boolean activaridTipoCuota) { this.activaridTipoCuota= activaridTipoCuota; } public Border setResaltarid_empresaTipoCuota(ParametroGeneralUsuario parametroGeneralUsuario/*TipoCuotaBeanSwingJInternalFrame tipocuotaBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //tipocuotaBeanSwingJInternalFrame.jTtoolBarTipoCuota.setBorder(borderResaltar); this.resaltarid_empresaTipoCuota= borderResaltar; return borderResaltar; } public Border getresaltarid_empresaTipoCuota() { return this.resaltarid_empresaTipoCuota; } public void setResaltarid_empresaTipoCuota(Border borderResaltar) { this.resaltarid_empresaTipoCuota= borderResaltar; } public Boolean getMostrarid_empresaTipoCuota() { return this.mostrarid_empresaTipoCuota; } public void setMostrarid_empresaTipoCuota(Boolean mostrarid_empresaTipoCuota) { this.mostrarid_empresaTipoCuota= mostrarid_empresaTipoCuota; } public Boolean getActivarid_empresaTipoCuota() { return this.activarid_empresaTipoCuota; } public void setActivarid_empresaTipoCuota(Boolean activarid_empresaTipoCuota) { this.activarid_empresaTipoCuota= activarid_empresaTipoCuota; } public Boolean getCargarid_empresaTipoCuota() { return this.cargarid_empresaTipoCuota; } public void setCargarid_empresaTipoCuota(Boolean cargarid_empresaTipoCuota) { this.cargarid_empresaTipoCuota= cargarid_empresaTipoCuota; } public Border setResaltarcodigoTipoCuota(ParametroGeneralUsuario parametroGeneralUsuario/*TipoCuotaBeanSwingJInternalFrame tipocuotaBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //tipocuotaBeanSwingJInternalFrame.jTtoolBarTipoCuota.setBorder(borderResaltar); this.resaltarcodigoTipoCuota= borderResaltar; return borderResaltar; } public Border getresaltarcodigoTipoCuota() { return this.resaltarcodigoTipoCuota; } public void setResaltarcodigoTipoCuota(Border borderResaltar) { this.resaltarcodigoTipoCuota= borderResaltar; } public Boolean getMostrarcodigoTipoCuota() { return this.mostrarcodigoTipoCuota; } public void setMostrarcodigoTipoCuota(Boolean mostrarcodigoTipoCuota) { this.mostrarcodigoTipoCuota= mostrarcodigoTipoCuota; } public Boolean getActivarcodigoTipoCuota() { return this.activarcodigoTipoCuota; } public void setActivarcodigoTipoCuota(Boolean activarcodigoTipoCuota) { this.activarcodigoTipoCuota= activarcodigoTipoCuota; } public Border setResaltarnombreTipoCuota(ParametroGeneralUsuario parametroGeneralUsuario/*TipoCuotaBeanSwingJInternalFrame tipocuotaBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //tipocuotaBeanSwingJInternalFrame.jTtoolBarTipoCuota.setBorder(borderResaltar); this.resaltarnombreTipoCuota= borderResaltar; return borderResaltar; } public Border getresaltarnombreTipoCuota() { return this.resaltarnombreTipoCuota; } public void setResaltarnombreTipoCuota(Border borderResaltar) { this.resaltarnombreTipoCuota= borderResaltar; } public Boolean getMostrarnombreTipoCuota() { return this.mostrarnombreTipoCuota; } public void setMostrarnombreTipoCuota(Boolean mostrarnombreTipoCuota) { this.mostrarnombreTipoCuota= mostrarnombreTipoCuota; } public Boolean getActivarnombreTipoCuota() { return this.activarnombreTipoCuota; } public void setActivarnombreTipoCuota(Boolean activarnombreTipoCuota) { this.activarnombreTipoCuota= activarnombreTipoCuota; } public Border setResaltares_proveTipoCuota(ParametroGeneralUsuario parametroGeneralUsuario/*TipoCuotaBeanSwingJInternalFrame tipocuotaBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //tipocuotaBeanSwingJInternalFrame.jTtoolBarTipoCuota.setBorder(borderResaltar); this.resaltares_proveTipoCuota= borderResaltar; return borderResaltar; } public Border getresaltares_proveTipoCuota() { return this.resaltares_proveTipoCuota; } public void setResaltares_proveTipoCuota(Border borderResaltar) { this.resaltares_proveTipoCuota= borderResaltar; } public Boolean getMostrares_proveTipoCuota() { return this.mostrares_proveTipoCuota; } public void setMostrares_proveTipoCuota(Boolean mostrares_proveTipoCuota) { this.mostrares_proveTipoCuota= mostrares_proveTipoCuota; } public Boolean getActivares_proveTipoCuota() { return this.activares_proveTipoCuota; } public void setActivares_proveTipoCuota(Boolean activares_proveTipoCuota) { this.activares_proveTipoCuota= activares_proveTipoCuota; } public void setMostrarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setMostraridTipoCuota(esInicial); this.setMostrarid_empresaTipoCuota(esInicial); this.setMostrarcodigoTipoCuota(esInicial); this.setMostrarnombreTipoCuota(esInicial); this.setMostrares_proveTipoCuota(esInicial); for(Classe campo:campos) { if(campo.clase.equals(TipoCuotaConstantesFunciones.ID)) { this.setMostraridTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.IDEMPRESA)) { this.setMostrarid_empresaTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.CODIGO)) { this.setMostrarcodigoTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.NOMBRE)) { this.setMostrarnombreTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.ESPROVE)) { this.setMostrares_proveTipoCuota(esAsigna); continue; } } } public void setActivarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setActivaridTipoCuota(esInicial); this.setActivarid_empresaTipoCuota(esInicial); this.setActivarcodigoTipoCuota(esInicial); this.setActivarnombreTipoCuota(esInicial); this.setActivares_proveTipoCuota(esInicial); for(Classe campo:campos) { if(campo.clase.equals(TipoCuotaConstantesFunciones.ID)) { this.setActivaridTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.IDEMPRESA)) { this.setActivarid_empresaTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.CODIGO)) { this.setActivarcodigoTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.NOMBRE)) { this.setActivarnombreTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.ESPROVE)) { this.setActivares_proveTipoCuota(esAsigna); continue; } } } public void setResaltarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos,ParametroGeneralUsuario parametroGeneralUsuario/*,TipoCuotaBeanSwingJInternalFrame tipocuotaBeanSwingJInternalFrame*/)throws Exception { Border esInicial=null; Border esAsigna=null; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=null; esAsigna=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); esAsigna=null; } this.setResaltaridTipoCuota(esInicial); this.setResaltarid_empresaTipoCuota(esInicial); this.setResaltarcodigoTipoCuota(esInicial); this.setResaltarnombreTipoCuota(esInicial); this.setResaltares_proveTipoCuota(esInicial); for(Classe campo:campos) { if(campo.clase.equals(TipoCuotaConstantesFunciones.ID)) { this.setResaltaridTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.IDEMPRESA)) { this.setResaltarid_empresaTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.CODIGO)) { this.setResaltarcodigoTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.NOMBRE)) { this.setResaltarnombreTipoCuota(esAsigna); continue; } if(campo.clase.equals(TipoCuotaConstantesFunciones.ESPROVE)) { this.setResaltares_proveTipoCuota(esAsigna); continue; } } } public Border resaltarPrestamoTipoCuota=null; public Border getResaltarPrestamoTipoCuota() { return this.resaltarPrestamoTipoCuota; } public void setResaltarPrestamoTipoCuota(Border borderResaltarPrestamo) { if(borderResaltarPrestamo!=null) { this.resaltarPrestamoTipoCuota= borderResaltarPrestamo; } } public Border setResaltarPrestamoTipoCuota(ParametroGeneralUsuario parametroGeneralUsuario/*TipoCuotaBeanSwingJInternalFrame tipocuotaBeanSwingJInternalFrame*/) { Border borderResaltarPrestamo=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //tipocuotaBeanSwingJInternalFrame.jTtoolBarTipoCuota.setBorder(borderResaltarPrestamo); this.resaltarPrestamoTipoCuota= borderResaltarPrestamo; return borderResaltarPrestamo; } public Boolean mostrarPrestamoTipoCuota=true; public Boolean getMostrarPrestamoTipoCuota() { return this.mostrarPrestamoTipoCuota; } public void setMostrarPrestamoTipoCuota(Boolean visibilidadResaltarPrestamo) { this.mostrarPrestamoTipoCuota= visibilidadResaltarPrestamo; } public Boolean activarPrestamoTipoCuota=true; public Boolean gethabilitarResaltarPrestamoTipoCuota() { return this.activarPrestamoTipoCuota; } public void setActivarPrestamoTipoCuota(Boolean habilitarResaltarPrestamo) { this.activarPrestamoTipoCuota= habilitarResaltarPrestamo; } public void setMostrarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setMostrarPrestamoTipoCuota(esInicial); for(Classe clase:clases) { if(clase.clas.equals(Prestamo.class)) { this.setMostrarPrestamoTipoCuota(esAsigna); continue; } } } public void setActivarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setActivarPrestamoTipoCuota(esInicial); for(Classe clase:clases) { if(clase.clas.equals(Prestamo.class)) { this.setActivarPrestamoTipoCuota(esAsigna); continue; } } } public void setResaltarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases,ParametroGeneralUsuario parametroGeneralUsuario/*,TipoCuotaBeanSwingJInternalFrame tipocuotaBeanSwingJInternalFrame*/)throws Exception { Border esInicial=null; Border esAsigna=null; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=null; esAsigna=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); esAsigna=null; } this.setResaltarPrestamoTipoCuota(esInicial); for(Classe clase:clases) { if(clase.clas.equals(Prestamo.class)) { this.setResaltarPrestamoTipoCuota(esAsigna); continue; } } } public Boolean mostrarFK_IdEmpresaTipoCuota=true; public Boolean getMostrarFK_IdEmpresaTipoCuota() { return this.mostrarFK_IdEmpresaTipoCuota; } public void setMostrarFK_IdEmpresaTipoCuota(Boolean visibilidadResaltar) { this.mostrarFK_IdEmpresaTipoCuota= visibilidadResaltar; } public Boolean activarFK_IdEmpresaTipoCuota=true; public Boolean getActivarFK_IdEmpresaTipoCuota() { return this.activarFK_IdEmpresaTipoCuota; } public void setActivarFK_IdEmpresaTipoCuota(Boolean habilitarResaltar) { this.activarFK_IdEmpresaTipoCuota= habilitarResaltar; } public Border resaltarFK_IdEmpresaTipoCuota=null; public Border getResaltarFK_IdEmpresaTipoCuota() { return this.resaltarFK_IdEmpresaTipoCuota; } public void setResaltarFK_IdEmpresaTipoCuota(Border borderResaltar) { this.resaltarFK_IdEmpresaTipoCuota= borderResaltar; } public void setResaltarFK_IdEmpresaTipoCuota(ParametroGeneralUsuario parametroGeneralUsuario/*TipoCuotaBeanSwingJInternalFrame tipocuotaBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"TAB"); this.resaltarFK_IdEmpresaTipoCuota= borderResaltar; } //CONTROL_FUNCION2 }
33.630565
731
0.763109
abb0ee688d14bbfe9aaa9bdd768ca5b589855aa2
1,501
package com.zhengzhou.hadoop.webkpi; import java.io.IOException; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; public class KPIJob { //定义全局变量 hdfs地址url public static final String HDFS = "hdfs://127.0.0.1:9000"; public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException, URISyntaxException { //定义一个map集合,存放程序中所需要的路径 Map<String, String> path = new HashMap<String, String>(); // path.put("local_path", "webLogKPI/weblog/access.log"); //本地目录 path.put("input_log", HDFS + "/mr/webLogKPI/log_files"); //hdfs上存放log的目录 path.put("output_oneip", HDFS + "/mr/webLogKPI/KPI_OneIP_Sum"); //hdfs上KPI_OneIP_Sum对应的输出文件 path.put("output_pv", HDFS + "/mr/webLogKPI/KPI_OnePV_Sum"); //hdfs上KPI_OnePV_Sum对应的输出文件 path.put("output_request", HDFS + "/mr/webLogKPI/KPI_OneRequest_Sum"); //hdfs 上KPI_OneRequest_Sum对应的输出文件 path.put("output_time", HDFS + "/mr/webLogKPI/KPI_OneTime_Sum"); //hdfs上KPI_OneTime_Sum对应的输出文件 path.put("output_source", HDFS + "/mr/webLogKPI/KPI_OneResource_Sum"); //hdfs上KPI_OneResource_Sum对应的输出文件 KPI_OneIP_Sum.main(path); //计算独立IP访问量 KPI_OnePV_Sum.main(path); //计算PV访问量 KPI_OneRequest_Sum.main(path); //获得请求方式 KPI_OneTime_Sum.main(path); //每小时的PV KPI_OneSource_Sum.main(path); //日访问设备统计 System.exit(0); } }
44.147059
129
0.672219
c871d5bd33498a70dc83d3b785f20218de68def4
457
package com.relaxed.common.risk.engine.rules.statistics.executor; import com.relaxed.common.risk.engine.rules.statistics.AggregateExecutor; import com.relaxed.common.risk.engine.rules.statistics.domain.IAggregateParam; /** * @author Yakir * @Topic AbstractAggregateExecutor * @Description * @date 2021/8/30 16:38 * @Version 1.0 */ public abstract class AbstractAggregateExecutor<T extends IAggregateParam, R> implements AggregateExecutor<T, R> { }
28.5625
114
0.789934
0dbac351a57f70746b5a79e54962c872004ef63f
2,389
package net.mattlabs.crewchat.listeners; import net.mattlabs.crewchat.Channel; import net.mattlabs.crewchat.CrewChat; import net.mattlabs.crewchat.util.ChannelManager; import net.mattlabs.crewchat.util.PlayerManager; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import java.util.ArrayList; public class JoinListener implements Listener{ private final PlayerManager playerManager = CrewChat.getInstance().getPlayerManager(); private final ChannelManager channelManager = CrewChat.getInstance().getChannelManager(); private boolean configError; @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { playerManager.updateMutedPlayers(); Player player = event.getPlayer(); // Find active channel String activeChannel = null; for (Channel channel : channelManager.getChannels()) { if (player.hasPermission("crewchat.default.active." + channel.getName())) { activeChannel = channel.getName(); } } // Check if player already played if (!playerManager.playerExists(player)) { // Find subscriptions ArrayList<String> subscribedChannels = new ArrayList<>(); for (Channel channel : channelManager.getChannels()) { if (channel.isAutoSubscribe()) subscribedChannels.add(channel.getName()); } addPlayer(player, activeChannel, subscribedChannels); if (!configError) playerManager.setOnline(player); } else { playerManager.updateChannels(player); playerManager.setOnline(player); playerManager.setActiveChannel(player, activeChannel); } } // Adds a new player, will fail if there's a configuration issue (usually default active channel) private void addPlayer(Player player, String activeChannel, ArrayList<String> subscribedChannels) { try { playerManager.addPlayer(player, activeChannel, subscribedChannels); configError = false; } catch (NullPointerException e) { CrewChat.getInstance().getLogger().warning("Player " + player.getName() + " could not be added, check permissions!"); configError = true; } } }
38.532258
129
0.675178
293cace1c40a03661738e48bee08a577f3068ee1
422
import edu.princeton.cs.algs4.StdOut; public class TestMutability { private int me; public TestMutability(int me) { this.me = me; } private void mutateMe(TestMutability taget) { taget.me = 4; } // do unit testing of this class public static void main(String[] args) { TestMutability testme = new TestMutability(2); StdOut.println(testme.me); testme.mutateMe(testme); StdOut.println(testme.me); } }
19.181818
48
0.71327
416bf1d6e723d78d795c5bd368c211102d71981d
503
package com.example.elk; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; /** * @Author: vector * @Date: 2020/8/15 22:43 */ @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class SpringElkApplication { public static void main(String[] args){ SpringApplication.run(SpringElkApplication.class, args); } }
26.473684
79
0.787276
b325293d3ee8a2c9486f3bb3deef79ea25ad56a2
7,484
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package net.leadware.persistence.tools.test.dao.entities.base; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.SequenceGenerator; import javax.persistence.Version; import net.leadware.persistence.tools.api.generator.annotaions.FieldGenerator; import net.leadware.persistence.tools.api.validator.jsr303ext.annotations.Length; import net.leadware.persistence.tools.test.dao.entities.field.generator.IdentityFieldGenerator; /** * Classe de base des parametrages * @author <a href="mailto:[email protected]">Jean-Jacques ETUNE NGI (Leadware Enterprise Architect)</a> * @since 31 janv. 2018 - 16:52:34 */ @MappedSuperclass public class AbstractParameterBase implements Serializable, Comparable<AbstractParameterBase> { /** * ID Genere par Eclipse */ private static final long serialVersionUID = 1L; /** * Constante definissant la taille Max des codes de parametrage */ public static final int CODE_MAX_LENGTH = 25; /** * Constante definissant la taille Min des codes de parametrage */ public static final int CODE_MIN_LENGTH = 1; /** * Constante definissant la taille Max du libelle du parametre */ public static final int DESIGNATION_MAX_LENGTH = 300; /** * Identifiant artificiel */ @Id @SequenceGenerator(name="Seq_AbstractParameterBase", sequenceName="SEQ_ABSTRACT_PARAMETER_BASE", allocationSize = 1, initialValue = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Seq_AbstractParameterBase") @Column(name = "ID") private Long id; /** * Code du parametre */ @Column(name = "CODE", nullable = false, length = CODE_MAX_LENGTH) @Length(min = CODE_MIN_LENGTH, max = CODE_MAX_LENGTH, message = "AbstractParameterBase.code.length") protected String code; /** * Libelle du parametre */ @Column(name = "DESIGNATION", nullable = true, length = DESIGNATION_MAX_LENGTH) @Length(min = 1, max = DESIGNATION_MAX_LENGTH, message = "AbstractParameterBase.designation.length") @FieldGenerator(generator = IdentityFieldGenerator.class) protected String designation; /** * Version de l'enregistrement */ @Version @Column(name = "PARAMETER_VERSION") private Integer version = 1; /** * Constructeur par defaut */ public AbstractParameterBase() {} /** * Constructeur avec initialisation des parametres * @param code Code du type de piece * @param designation Libelle du type de piece */ public AbstractParameterBase(String code, String designation) { this.code = code; this.designation = designation; if(this.code != null) this.code = this.code.trim().toUpperCase(); if(this.designation != null) this.designation = this.designation.trim().toUpperCase(); } /** * Methode d'obtention de la Version de l'enregistrement * @return Version de l'enregistrement */ public Integer getVersion() { return version; } /** * Methode de mise a jour de la Version de l'enregistrement * @param version Version de l'enregistrement */ public void setVersion(Integer version) { this.version = version; } /** * Methode d'obtention de l'Identifiant artificiel de l'agence * @return Identifiant artificiel de l'agence */ public Long getId() { return id; } /** * Methode de mise a jour de l'Identifiant artificiel de l'agence * @param id Identifiant artificiel de l'agence */ public void setId(Long id) { this.id = id; } /** * Methode d'obtention du Code du parametre * @return Code du parametre */ public String getCode() { return code; } /** * Methode de mise a jour du Code du parametre * @param code Code du parametre */ public void setCode(String code) { this.code = code; if(this.code != null) this.code = this.code.trim().toUpperCase(); } /** * Methode d'obtention du Libelle du parametre * @return Libelle du parametre */ public String getDesignation() { return designation; } /** * Methode de mise a jour du Libelle du parametre * @param designation Libelle du parametre */ public void setDesignation(String designation) { this.designation = designation; if(this.designation != null) this.designation = this.designation.trim().toUpperCase(); } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object parameter) { // Si le parametre est null if(parameter == null) return false; // Si le parametre n'est pas de l'instance if(!(parameter instanceof AbstractParameterBase)) return false; // On caste AbstractParameterBase abstractParameter = (AbstractParameterBase) parameter; // Si le Parametre a un ID if(abstractParameter.id != null) { // Si l'Objet courant n'a pas d'ID if(id == null) return false; // On retourne la comparaison des IDs return abstractParameter.id.equals(id); } else { // Si l'Objet en cours a un Id if(id != null) return false; } // Si le code du parametre est vide if(abstractParameter.code == null || abstractParameter.code.trim().length() == 0) return false; // Si le code du parametre en cours est vide if(code == null || code.trim().length() == 0) return false; // On retourne la comparaison des codes return code.equals(abstractParameter.code); } /* * (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(AbstractParameterBase abstractParameter) { // Si le parametre est null if(abstractParameter == null) return -1; // Si le code du parametre est vide if(abstractParameter.code == null || abstractParameter.code.trim().length() == 0) return -1; // Si le code du parametre en cours est vide if(code == null || code.trim().length() == 0) return 1; // On retourne la comparaison des codes return code.compareTo(abstractParameter.code); } @Override public String toString() { // Le Buffer StringBuffer buffer = new StringBuffer(); // ID buffer.append("ID: ").append(id); // Separateur buffer.append(", "); // Code buffer.append("Code: ").append(code); // Separateur buffer.append(", "); // Designation buffer.append("Designation: ").append(designation); // On retourne le Buffer return buffer.toString(); } }
28.348485
136
0.686665
6b1c2ab5b6e1804da5a7bcc12a58bb98bfeeb195
7,371
package be.kwakeroni.scratch.test; import be.kwakeroni.parameters.basic.client.model.Ranged; import be.kwakeroni.parameters.basic.client.model.Simple; import be.kwakeroni.parameters.basic.client.query.EntryQuery; import be.kwakeroni.parameters.basic.client.query.RangedQuery; import be.kwakeroni.parameters.basic.client.query.ValueQuery; import be.kwakeroni.parameters.basic.type.Range; import be.kwakeroni.parameters.client.api.model.Entry; import be.kwakeroni.parameters.client.api.model.Parameter; import be.kwakeroni.parameters.client.api.model.ParameterGroup; import be.kwakeroni.parameters.client.api.query.Query; import be.kwakeroni.parameters.types.api.ParameterType; import be.kwakeroni.scratch.EntryAssert; import be.kwakeroni.scratch.env.Environment; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public abstract class RangedGroupTestSupport<V extends Comparable<? super V>, ET extends Ranged<V, Simple>> extends GroupTestSupport<ET> { private final Logger LOG = LoggerFactory.getLogger(this.getClass()); private final RangeTestParameter<V> values; private final ParameterType<V> rangeValueType; protected RangedGroupTestSupport(Environment environment, ParameterGroup<ET> group, RangeTestParameter<V> rangeParameter, TestParameter<?>... otherParameters) { super(environment, group, ExtArrays.prepend(rangeParameter, otherParameters)); this.values = rangeParameter; this.rangeValueType = rangeParameter.rangeValueType; } protected Query<ET, ?> valueQuery(V value, int paramIndex) { return new RangedQuery<>(value, rangeValueType, new ValueQuery<>(parameter(paramIndex))); } protected Query<ET, Entry> entryQuery(V value) { return new RangedQuery<>(value, rangeValueType, new EntryQuery()); } protected static <T extends Comparable<? super T>> RangeTestParameter<T> rangeParam(Parameter<Range<T>> parameter, ParameterType<T> rangeValueType, T lowerValue, T originalLowValue, T originalMidValue1, T originalMidValue2, T originalHighValue, T otherLowValue, T otherMidValue, T otherHighValue, T higherValue) { return new RangeTestParameter<T>(parameter, rangeValueType, lowerValue, originalLowValue, originalMidValue1, originalMidValue2, originalHighValue, otherLowValue, otherMidValue, otherHighValue, higherValue); } @DisplayName("Changing a parameter value") @Test public void testWriteRangedValue() { Query<ET, ?> query = valueQuery(this.values.originalMidValue1, 1); assertThat(get(query)).isEqualTo(originalValue(1)); set(query, otherValue(1)); assertThat(get(query)).isEqualTo(otherValue(1)); } @Test @DisplayName("Changing an entry") public void testWriteRangedEntry() { Query<ET, Entry> query = entryQuery(this.values.originalMidValue1); EntryAssert.assertThat(get(query)).hasParameters(this.parameters).withValues(this.originalValues); set(query, entry(this.otherValues)); assertThat(optGet(query)).isEmpty(); EntryAssert.assertThat(get(entryQuery(this.values.otherMidValue))) .hasParameters(this.parameters).withValues(this.otherValues); } @Test @DisplayName("Adding an entry") public void testAddRangedEntry() { assertThat(optGet(entryQuery(this.values.otherMidValue))).isEmpty(); addEntry(entry(this.otherValues)); EntryAssert.assertThat(get(entryQuery(this.values.otherMidValue))) .hasParameters(this.parameters) .withValues(this.otherValues); } @Test @DisplayName("Does not allow adding an overlapping range") public void testAddOverlappingRange() { assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1)); assertThat(optGet(valueQuery(this.values.otherMidValue, 1))).isEmpty(); assertThatThrownBy(() -> addEntry(entry(ExtArrays.replace(this.originalValues, 0, Range.of(this.values.lowerValue, this.values.originalMidValue2)))) ).isInstanceOf(IllegalStateException.class) .satisfies(throwable -> LOG.error(throwable.toString())) .hasMessageContaining(parameter(0).getName()); assertThatThrownBy(() -> addEntry(entry(ExtArrays.replace(this.originalValues, 0, Range.of(this.values.originalMidValue2, this.values.otherMidValue)))) ).isInstanceOf(IllegalStateException.class) .satisfies(throwable -> LOG.error(throwable.toString())) .hasMessageContaining(parameter(0).getName()); assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1)); assertThat(optGet(valueQuery(this.values.otherMidValue, 1))).isEmpty(); } @Test @DisplayName("Does not allow adding a fully-contained range") public void testAddFullyContainedOverlappingRange() { assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1)); assertThat(get(valueQuery(this.values.originalMidValue2, 1))).isEqualTo(originalValue(1)); assertThatThrownBy(() -> addEntry(entry(ExtArrays.replace(this.originalValues, 0, Range.of(this.values.originalMidValue1, this.values.originalMidValue2)))) ).isInstanceOf(IllegalStateException.class) .satisfies(throwable -> LOG.error(throwable.toString())) .hasMessageContaining(parameter(0).getName()); assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1)); assertThat(get(valueQuery(this.values.originalMidValue2, 1))).isEqualTo(originalValue(1)); } @Test @DisplayName("Adding an entry preceding another entry") public void testAddAdjoiningRangeBefore() { assertThat(optGet(valueQuery(this.values.lowerValue, 1))).isEmpty(); assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1)); addEntry(entry(ExtArrays.replace(this.otherValues, 0, Range.of(this.values.lowerValue, this.values.originalLowValue)))); assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1)); assertThat(get(valueQuery(this.values.lowerValue, 1))).isEqualTo(otherValue(1)); } @Test @DisplayName("Adding an entry following another entry") public void testAddAdjoiningRangeAfter() { assertThat(optGet(valueQuery(this.values.otherMidValue, 1))).isEmpty(); assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1)); addEntry(entry(ExtArrays.replace(this.otherValues, 0, Range.of(this.values.originalHighValue, this.values.higherValue)))); assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1)); assertThat(get(valueQuery(this.values.otherMidValue, 1))).isEqualTo(otherValue(1)); } }
46.651899
146
0.708045
b238b3bf8f97320e29e8ceefa58e111076aae81d
1,095
package ru.dns.qa; import java.util.ArrayList; import java.util.List; public class VirtualBasket { private static List<VirtualProduct> virtualBasket = new ArrayList<>(); public static void addToBasket(VirtualProduct virtualProduct){ virtualBasket.add(virtualProduct); } public static void deleteFromBasket(VirtualProduct virtualProduct){ virtualBasket.remove(virtualProduct); } public static void changeProductInVirtualBasket(VirtualProduct virtualProduct){ } public static void getAllProductInfoFromVirtualBasket(){ System.out.println("Товаров в виртуальной корзине = "+virtualBasket.size()); for ( VirtualProduct vp: virtualBasket ) { System.out.println(vp.toString()); } } //TODO получение продукта, изменение цены, гарантии. получение общей цены public static int getTotalPriceFromVirtualBasket() { int totalPrice = 0; for ( VirtualProduct vp: virtualBasket ) { totalPrice+=vp.getPrice(); } return totalPrice; } }
26.071429
84
0.674886
c1dbec9daed36c0608dbd9568c0bcb6f8141bf29
4,958
package com.jaspersoft.jasperserver.api.metadata.security; import com.jaspersoft.jasperserver.api.metadata.user.service.impl.InternalURIDefinition; import org.springframework.security.acls.domain.AccessControlEntryImpl; import org.springframework.security.acls.model.*; import org.springframework.util.Assert; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author Oleg.Gavavka */ public class JasperServerAclImpl implements Acl { private ObjectIdentity objectIdentity; private transient Acl parentAcl; private ObjectIdentity parentOid=null; private Boolean entriesInheriting=false; private final List<AccessControlEntry> aces = new ArrayList<AccessControlEntry>(); private transient PermissionGrantingStrategy permissionGrantingStrategy; public JasperServerAclImpl(ObjectIdentity objectIdentity,List<AccessControlEntry> aces) { this(objectIdentity, (new JasperServerPermissionGrantingStrategy()), aces); } public JasperServerAclImpl(ObjectIdentity objectIdentity,List<AccessControlEntry> aces,Acl parentAcl) { this(objectIdentity, (new JasperServerPermissionGrantingStrategy()), aces); if (parentAcl!=null) { this.parentAcl=parentAcl; this.parentOid=parentAcl.getObjectIdentity(); this.entriesInheriting=true; } } public JasperServerAclImpl(ObjectIdentity objectIdentity,PermissionGrantingStrategy permissionGrantingStrategy,List<AccessControlEntry> aces) { Assert.notNull(objectIdentity, "Object Identity required"); //Assert.notNull(id, "Id required"); if (permissionGrantingStrategy==null) { this.permissionGrantingStrategy = new JasperServerPermissionGrantingStrategy(); } else { this.permissionGrantingStrategy=permissionGrantingStrategy; } this.objectIdentity=objectIdentity instanceof InternalURIDefinition ? objectIdentity : new InternalURIDefinition(objectIdentity.getIdentifier().toString()); //this.id=id; if (aces!=null) { // Recreating ACE and binding them to this ACL for(AccessControlEntry ace: aces) { AccessControlEntry entry = new AccessControlEntryImpl(ace.getId(),this,ace.getSid(),ace.getPermission(),ace.isGranting(),false,false); this.aces.add(entry); } } } @Override public List<AccessControlEntry> getEntries() { return aces; } @Override public ObjectIdentity getObjectIdentity() { return objectIdentity; } @Override public Sid getOwner() { return null; } @Override public Acl getParentAcl() { return parentAcl; } @Override public boolean isEntriesInheriting() { return entriesInheriting; } @Override public boolean isGranted(List<Permission> permission, List<Sid> sids, boolean administrativeMode) throws NotFoundException, UnloadedSidException { Assert.notEmpty(permission, "Permissions required"); Assert.notEmpty(sids, "SIDs required"); /* if (!this.isSidLoaded(sids)) { throw new UnloadedSidException("ACL was not loaded for one or more SID"); } */ return permissionGrantingStrategy.isGranted(this, permission, sids, administrativeMode); } @Override public boolean isSidLoaded(List<Sid> sids) { List<Sid> loadedSids = new ArrayList<Sid>(); for(AccessControlEntry ace: getEntries()) { if (!loadedSids.contains(ace.getSid())) { loadedSids.add(ace.getSid()); } } return loadedSids.containsAll(sids); } public ObjectIdentity getParentOid() { return parentOid; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("JasperServerAclImpl["); // sb.append("id: ").append(this.id).append("; "); sb.append("objectIdentity: ").append(this.objectIdentity).append("; "); // sb.append("owner: ").append(this.owner).append("; "); int count = 0; for (AccessControlEntry ace : aces) { count++; if (count == 1) { sb.append("\n"); } sb.append(ace).append("\n"); } if (count == 0) { sb.append("no ACEs; "); } sb.append("inheriting: ").append(this.entriesInheriting).append("; "); sb.append("parent: ").append((this.parentAcl == null) ? "Null" : this.parentAcl.getObjectIdentity().toString()); sb.append("; "); sb.append("permissionGrantingStrategy: ").append(this.permissionGrantingStrategy); sb.append("]"); return sb.toString(); } }
33.275168
165
0.636345
b47bf61da6dd5fd2565a89890b9eebac19fd34f4
446
package com.ty.user.service.impl; import com.ty.user.entity.RoleEntity; import com.ty.user.dao.RoleDao; import com.ty.user.service.RoleService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author taleyoung * @since 2021-03-24 */ @Service public class RoleServiceImpl extends ServiceImpl<RoleDao, RoleEntity> implements RoleService { }
21.238095
94
0.762332
18e85cebc7336352a39bad19689514d238887c7a
373
package com.synopsys.integration.detector.result; import java.util.Set; import org.apache.commons.lang3.StringUtils; public class YieldedDetectorResult extends FailedDetectorResult { public YieldedDetectorResult(Set<String> yieldedTo) { super(String.format("Yielded to detectors: %s", StringUtils.join(yieldedTo, ",")), YieldedDetectorResult.class); } }
31.083333
120
0.772118
56a1324541ca05d052f46e7bbb8c2c7bcd098135
3,203
package es.redmic.vesselslib.dto.vesseltype; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import es.redmic.brokerlib.avro.common.CommonDTO; @JsonIgnoreProperties(ignoreUnknown = true) public class VesselTypeDTO extends CommonDTO { // @formatter:off @JsonIgnore public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse( "{\"type\":\"record\",\"name\":\"VesselTypeDTO\",\"namespace\":\"es.redmic.vesselslib.dto.vesseltype\",\"fields\":[" + "{\"name\":\"code\",\"type\":\"string\"}," + "{\"name\":\"name\",\"type\":[\"string\", \"null\"]}," + "{\"name\":\"name_en\",\"type\":[\"string\", \"null\"]}," + "{\"name\":\"id\",\"type\":\"string\"}]}"); // @formatter:on public VesselTypeDTO() { } @NotNull @Size(min = 1, max = 10) private String code; @NotNull @Size(min = 1, max = 500) private String name; @NotNull @Size(min = 1, max = 500) private String name_en; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getName_en() { return name_en; } public void setName_en(String name_en) { this.name_en = name_en; } @JsonIgnore @Override public org.apache.avro.Schema getSchema() { return SCHEMA$; } @JsonIgnore @Override public java.lang.Object get(int field$) { switch (field$) { case 0: return code; case 1: return name; case 2: return name_en; case 3: return getId(); default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } } @JsonIgnore @Override public void put(int field$, java.lang.Object value$) { switch (field$) { case 0: code = value$ != null ? value$.toString() : null; break; case 1: name = value$ != null ? value$.toString() : null; break; case 2: name_en = value$ != null ? value$.toString() : null; break; case 3: setId(value$.toString()); break; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((code == null) ? 0 : code.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((name_en == null) ? 0 : name_en.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; VesselTypeDTO other = (VesselTypeDTO) obj; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (name_en == null) { if (other.name_en != null) return false; } else if (!name_en.equals(other.name_en)) return false; return true; } }
21.938356
118
0.640337
cce778e498cf8a5cf2d0e7b1fe9743ddb8e2ab5a
8,638
package graphql.java.generator.type; import java.lang.reflect.Type; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import graphql.java.generator.BuildContext; import graphql.java.generator.BuildContextAware; import graphql.introspection.Introspection.TypeKind; import graphql.java.generator.UnsharableBuildContextStorer; import graphql.java.generator.type.strategies.TypeStrategies; import graphql.schema.GraphQLEnumType; import graphql.schema.GraphQLEnumValueDefinition; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLInputObjectField; import graphql.schema.GraphQLInputType; import graphql.schema.GraphQLInterfaceType; import graphql.schema.GraphQLOutputType; import graphql.schema.GraphQLType; import graphql.schema.GraphQLTypeReference; import graphql.schema.TypeResolver; /** * Given any object, decide how you wish the GraphQL type to be generated. * This class defines the implementation contract, and further TypeGenerators * must be built off of this, using {@link #getType(Object, Type, TypeKind)} * Use {@link WrappingTypeGenerator} to create types from {@code List<?>}s, otherwise * this generator will be happy to create an object based on the interface List.class, which * is not what you want. * @author dwinsor * */ public abstract class TypeGenerator extends UnsharableBuildContextStorer implements ITypeGenerator, BuildContextAware { private static Logger logger = LoggerFactory.getLogger(TypeGenerator.class); private final TypeStrategies strategies; private final TypeRepository typeRepository; public TypeGenerator(TypeStrategies strategies) { this.strategies = strategies; this.typeRepository = strategies.getTypeRepository(); } /** * * @param object A representative "object" from which to construct * a {@link GraphQLOutputType}, the exact type of which is contextual * @return */ @Override public final GraphQLOutputType getOutputType(Object object) { return (GraphQLOutputType) getParameterizedType(object, null, TypeKind.OBJECT); } /** * @param object A representative "object" from which to construct * a {@link GraphQLInterfaceType}, the exact type of which is contextual, * but MUST represent a java interface, NOT an object or class with an interface. * Will be stored internally as a {@link GraphQLOutputType}, so its name * must not clash with any GraphQLOutputType. * * @return */ @Override public final GraphQLInterfaceType getInterfaceType(Object object) { return (GraphQLInterfaceType) getParameterizedType(object, null, TypeKind.INTERFACE); } /** * @param object A representative "object" from which to construct * a {@link GraphQLInputType}, the exact type of which is contextual * @return */ @Override public final GraphQLInputType getInputType(Object object) { return (GraphQLInputType) getParameterizedType(object, null, TypeKind.INPUT_OBJECT); } @Override public GraphQLType getParameterizedType(Object object, Type genericType, TypeKind typeKind) { return getType(object, genericType, typeKind); } /** * An internal, unchanging impl. * @param object * @param genericType * @param typeKind * @return */ protected final GraphQLType getType(Object object, Type genericType, TypeKind typeKind) { logger.debug("{} object is [{}]", typeKind, object); //short circuit if it's a primitive type or some other user defined default GraphQLType defaultType = getDefaultType(object, typeKind); if (defaultType != null) { return defaultType; } String typeName = getGraphQLTypeName(object); if (typeName == null) { logger.debug("TypeName was null for object [{}]. " + "Type will attempt to be built but not placed in the TypeRepository", object); return generateType(object, typeKind); } //this check must come before generated*Types.get //necessary for synchronicity to avoid duplicate object creations Set<String> typesBeingBuilt = getContext().getTypesBeingBuilt(); if (typesBeingBuilt.contains(typeName)) { logger.debug("Using a reference to: [{}]", typeName); if (TypeKind.OBJECT.equals(typeKind)) { return new GraphQLTypeReference(typeName); } logger.error("While constructing type, using a reference to: [{}]", typeName); throw new RuntimeException("Cannot put type-cycles into input or interface types, " + "there is no GraphQLTypeReference"); } GraphQLType prevType = getTypeRepository().getGeneratedType(typeName, typeKind); if (prevType != null) { return prevType; } typesBeingBuilt.add(typeName); try { GraphQLType type = generateType(object, typeKind); if (getTypeRepository() != null && type != null) { getTypeRepository().registerType(typeName, type, typeKind); } return type; } catch (RuntimeException e) { logger.warn("Failed to generate type named {} with kind {}", typeName, typeKind); logger.debug("Failed to generate type, exception is ", e); throw e; } finally { typesBeingBuilt.remove(typeName); } } protected GraphQLType generateType(Object object, TypeKind typeKind) { switch (typeKind) { case OBJECT: return generateOutputType(object); case INTERFACE: return generateInterfaceType(object); case INPUT_OBJECT: return generateInputType(object); case ENUM: return generateEnumType(object); default: return null; } } protected abstract GraphQLOutputType generateOutputType(Object object); protected abstract GraphQLInterfaceType generateInterfaceType(Object object); protected abstract GraphQLInputType generateInputType(Object object); protected abstract GraphQLEnumType generateEnumType(Object object); protected List<GraphQLFieldDefinition> getOutputFieldDefinitions(Object object) { List<GraphQLFieldDefinition> definitions = getContext().getFieldsGeneratorStrategy() .getOutputFields(object); return definitions; } protected List<GraphQLInputObjectField> getInputFieldDefinitions(Object object) { List<GraphQLInputObjectField> definitions = getContext().getFieldsGeneratorStrategy() .getInputFields(object); return definitions; } protected GraphQLType getDefaultType(Object object, TypeKind typeKind) { return getStrategies().getDefaultTypeStrategy().getDefaultType(object, typeKind); } protected String getGraphQLTypeNameOrIdentityCode(Object object) { String typeName = getGraphQLTypeName(object); if (typeName == null) { typeName = "Object_" + String.valueOf(System.identityHashCode(object)); } return typeName; } protected String getGraphQLTypeName(Object object) { return getStrategies().getTypeNameStrategy().getTypeName(object); } protected String getTypeDescription(Object object) { return getStrategies().getTypeDescriptionStrategy().getTypeDescription(object); } protected List<GraphQLEnumValueDefinition> getEnumValues(Object object) { return getStrategies().getEnumValuesStrategy().getEnumValueDefinitions(object); } protected GraphQLInterfaceType[] getInterfaces(Object object) { return getStrategies().getInterfacesStrategy().getInterfaces(object); } protected TypeResolver getTypeResolver(Object object) { return getStrategies().getTypeResolverStrategy().getTypeResolver(object); } @Override public void setContext(BuildContext context) { super.setContext(context); getStrategies().setContext(context); } @Override public TypeStrategies getStrategies() { return strategies; } protected TypeRepository getTypeRepository() { return typeRepository; } }
36.142259
100
0.671799
8971afe225ad4580a76c0860cb9e00c706649cee
728
/** Generated Assertion Class - DO NOT CHANGE */ package au.org.greekwelfaresa.idempiere.test.assertj.ad_ldapaccess; import javax.annotation.Generated; import org.compiere.model.X_AD_LdapAccess; /** Generated assertion class for AD_LdapAccess * @author idempiere-test model assertion generator * @version Release 6.2 - $Id: 8971afe225ad4580a76c0860cb9e00c706649cee $ */ @Generated("class au.org.greekwelfaresa.idempiere.test.generator.ModelAssertionGenerator") public class AD_LdapAccessAssert extends AbstractAD_LdapAccessAssert<AD_LdapAccessAssert, X_AD_LdapAccess> { /** Standard Constructor */ public AD_LdapAccessAssert (X_AD_LdapAccess actual) { super (actual, AD_LdapAccessAssert.class); } }
36.4
106
0.789835
53835f7bfcd1f03a30aa27d938eb071c5090fee2
11,922
/** * Copyright (c) 2009-2011 University of Cardiff and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * Contributors: * University of Cardiff - initial API and implementation * - */ package org.openhealthtools.openatna.audit.server; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openhealthtools.openatna.net.ConnectionFactory; import org.openhealthtools.openatna.net.IConnectionDescription; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Loads XML actor and connection files. * This throws RuntimeExceptions if something goes pear shaped - no point in carrying * on if errors occur here. * * @author Andrew Harrison * @version $Revision:$ * @created Oct 21, 2009: 10:24:00 AM * @date $Date:$ modified by $Author:$ */ public class ServerConfiguration { private static Log log = LogFactory.getLog("org.openhealthtools.openatna.audit.server.ServerConfiguration"); private Set<AtnaServer> servers = new HashSet<AtnaServer>(); private String actorDir; private String actorFile; public String getActorDir() { return actorDir; } public void setActorDir(String actorDir) { this.actorDir = actorDir; } public String getActorFile() { return actorFile; } public void setActorFile(String actorFile) { this.actorFile = actorFile; } public List<AtnaServer> getServers() { return new ArrayList(servers); } private File getActorsFile() { if (actorDir == null || actorFile == null) { throw new RuntimeException("ERROR. Please set both actorDir and actorFile."); } String actorsFile = new File(actorDir).getAbsolutePath(); actorsFile = actorsFile.replace(File.separator + "." + File.separator, File.separator); File actors = new File(actorsFile); if (!actors.exists()) { log.warn("Could not find actors dir:" + actors.getAbsolutePath()); return null; } File configFile = new File(actors, actorFile); if (!configFile.exists()) { log.warn("Could not find actors file:" + configFile.getAbsolutePath()); return null; } return configFile; } public boolean load() { return loadActors(getActorsFile()); } public boolean loadActors(File configFile) { boolean okay = true; Document configuration = null; try { configuration = createDocument(configFile); } catch (Exception e) { throw new RuntimeException("Error loading config file:" + configFile.getAbsolutePath(), e); } // Get the list of XML elements in the configuration file NodeList configurationElements = configuration.getDocumentElement().getChildNodes(); // Load all the connection definitions first for (int elementIndex = 0; elementIndex < configurationElements.getLength(); elementIndex++) { Node element = configurationElements.item(elementIndex); if (element instanceof Element) { // See what type of element it is String name = element.getNodeName(); if (name.equalsIgnoreCase("CONNECTIONFILE")) { // An included connection file, load it if (!processConnectionFile((Element) element, configFile)) { okay = false; } } else if (name.equalsIgnoreCase("SECURECONNECTION") || name.equalsIgnoreCase("STANDARDCONNECTION")) { // An included connection, load it if (!ConnectionFactory.loadConnectionDescriptionsFromXmlNode(element, configFile)) { throw new RuntimeException("Error loading configuration file \"" + configFile.getAbsolutePath() + "\" in configFile:" + configFile.getAbsolutePath()); } } } } // If all the connection files loaded okay, define the various actors if (okay) { for (int elementIndex = 0; elementIndex < configurationElements.getLength(); elementIndex++) { Node element = configurationElements.item(elementIndex); if (element instanceof Element) { // See what type of element it is String name = element.getNodeName(); if (name.equalsIgnoreCase("ACTORFILE")) { if (!processActorFile((Element) element, configFile)) { okay = false; } } else if (name.equalsIgnoreCase("ACTOR")) { // An IHE actor definition if (!processActorDefinition((Element) element)) { okay = false; } } } } } return okay; } private boolean processActorDefinition(Element parent) { boolean okay; String type = parent.getAttribute("type"); String name = parent.getAttribute("name"); if (name == null || type == null) { throw new RuntimeException("No name or type for actor defined!"); } if ("SECURENODE".equalsIgnoreCase(type) && "ARR".equalsIgnoreCase(name)) { okay = processArr(parent); } else { log.warn("Unknown actor type or name. Expecting name=arr and type=SecureNode but got name=" + name + " type=" + type); okay = false; } return okay; } private boolean processArr(Element parent) { IConnectionDescription tcp = null; IConnectionDescription udp = null; NodeList children = parent.getChildNodes(); int threads = 5; boolean nio = false; for (int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if (n instanceof Element) { Element el = (Element) n; if (el.getTagName().equalsIgnoreCase("TCP")) { String conn = el.getAttribute("connection"); if (conn == null) { throw new RuntimeException("No connection defined for Audit Record Repository"); } tcp = ConnectionFactory.getConnectionDescription(conn); if (tcp == null) { throw new RuntimeException("No connection defined for Audit Record Repository"); } } else if (el.getTagName().equalsIgnoreCase("UDP")) { String conn = el.getAttribute("connection"); if (conn == null) { throw new RuntimeException("No connection defined for Audit Record Repository"); } udp = ConnectionFactory.getConnectionDescription(conn); if (udp == null) { throw new RuntimeException("No connection defined for Audit Record Repository"); } } else if (el.getTagName().equalsIgnoreCase("EXECUTIONTHREADS")) { String t = el.getTextContent().trim(); if (t.length() > 0) { try { threads = Integer.parseInt(t); } catch (NumberFormatException e) { log.warn("Could not parse number of execution threads. Using default"); } if (threads < 1) { threads = 5; } } } else if (el.getTagName().equalsIgnoreCase("NIO")) { String t = el.getTextContent().trim(); if (t.length() > 0) { if (t.equalsIgnoreCase("true") || t.equalsIgnoreCase("1") || t.equalsIgnoreCase("yes")) { nio = true; } } } } } if (tcp != null && udp != null) { AtnaServer server = new AtnaServer(tcp, udp, threads, nio); servers.add(server); return true; } else { log.warn("No connections defined for server. This ARR will be not able to receive Syslog Messages.\n" + "The service will shut down unless it is being run from inside a separate execution thread."); return false; } } private boolean processConnectionFile(Element element, File configFile) { boolean okay = false; // Get out the file name String filename = element.getAttribute("file"); if (filename == null) { filename = element.getAttribute("name"); } if (filename == null) { filename = element.getTextContent().trim(); } if (filename != null) { // Got the connection file name, load it File includeFile = new File(configFile.getParentFile(), filename); if (ConnectionFactory.loadConnectionDescriptionsFromFile(includeFile)) { okay = true; } else { throw new RuntimeException("Error loading connection file \"" + filename + "\" from config file:" + configFile.getAbsolutePath()); } } else { // No connection file name given throw new RuntimeException("No connection file specified in config file:" + configFile.getAbsolutePath()); } // Done return okay; } private boolean processActorFile(Element element, File configFile) { boolean okay = false; // Get out the file name String filename = element.getAttribute("file"); if (filename == null) { filename = element.getAttribute("name"); } if (filename == null) { filename = element.getTextContent().trim(); } if (filename != null) { // Got the actor file name, load it File includeFile = new File(configFile.getParentFile(), filename); if (loadActors(includeFile)) { okay = true; } else { throw new RuntimeException("Error loading actor file \"" + filename + "\" in config file:" + configFile.getAbsolutePath()); } } else { // No connection file name given throw new RuntimeException("No connection file specified in config file:" + configFile.getAbsolutePath()); } // Done return okay; } private Document createDocument(File configFile) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); return factory.newDocumentBuilder().parse(configFile); } }
39.87291
118
0.56207
764beba50a40cd45ee5b97713453e30bdf04cc68
648
package com.brianway.learning.spring.aop.aspectj; public class SmartSeller implements Seller { public int sell(String goods, String clientName) { System.out.println("SmartSeller: sell " + goods + " to " + clientName + "..."); return 100; } protected int showGoods(String goods) { System.out.println("SmartSeller: show goods: " + goods); return 100; } public void checkBill(int billId) { if (billId == 1) { throw new IllegalArgumentException("iae Exception"); } else { throw new RuntimeException("re Exception"); } } }
28.173913
88
0.584877
61ca9ee5ac9c909056d73c78f62ebb43080cbf01
992
package org.panda_lang.pandomium.util; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; class JarUtilsTest{ @Test void testFindVersion() throws IOException { Assertions.assertEquals("1.0.0", extractVersion("<version>1.0.0</version>")); } private String extractVersion(String input) throws IOException { try(BufferedReader bw = new BufferedReader(new StringReader(input))){ String line; int startIndex; int stopIndex; while ((line = bw.readLine()) != null) { startIndex = line.indexOf("<version>"); stopIndex = line.indexOf("</version>"); if (startIndex != -1 && stopIndex != -1){ return line.substring(startIndex+9, stopIndex); } } } return null; } }
31
85
0.603831
ed166e5b93255dd3a69c3c09e2aec8e37a977e9e
5,496
/* Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.engedu.anagrams; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; public class AnagramDictionary { private static final String APP_TAG = "AnaDict"; private static final int MIN_NUM_ANAGRAMS = 5; private static final int DEFAULT_WORD_LENGTH = 4; private static final int MAX_WORD_LENGTH = 7; private static boolean OML = true; private static int wordLength = DEFAULT_WORD_LENGTH; private Random random = new Random(); private ArrayList<String> wordList = new ArrayList<>(); private Set<String> wordSet = new HashSet<>(); private Map<String, ArrayList<String >> lettersToWord = new HashMap<>(); private Map<Integer,ArrayList<String>> sizeToWords = new HashMap<>(); public AnagramDictionary(Reader reader) throws IOException { BufferedReader in = new BufferedReader(reader); String line; while((line = in.readLine()) != null) { String word = line.trim(); wordList.add(word); wordSet.add(word); String keyString = sortLetters(word); int length = word.length(); if(sizeToWords.containsKey(length)){ sizeToWords.get(length).add(word); } else { ArrayList<String> wordsOfThisLength = new ArrayList<>(); wordsOfThisLength.add(word); sizeToWords.put(length,wordsOfThisLength); } if (lettersToWord.containsKey(keyString)) { lettersToWord.get(keyString).add(word); } else { ArrayList<String> aList = new ArrayList<>(); aList.add(word); lettersToWord.put(keyString, aList); } } } public boolean isGoodWord(String word, String base) { return (wordSet.contains(word) && !word.contains(base)); } public List<String> getAnagrams(String targetWord) { java.lang.String key = sortLetters(targetWord); int keyLen = key.length(); ArrayList<java.lang.String> result = new ArrayList<java.lang.String>(); for (java.lang.String word : wordList) { if (word.length() == keyLen) { if (key.equals(sortLetters(word))) { result.add(word); } } } return result; } public String sortLetters(String word) { // takes a string, turns it into a Character array, sorts, and return the array as a string. char temp[] = word.toCharArray(); Arrays.sort(temp); return new String(temp); } public List<String> getAnagramsWithOneMoreLetter(String word) { ArrayList<String> result = new ArrayList<String>(); for(char alphabet = 'a'; alphabet <= 'z'; alphabet++) { String key = word + alphabet; if (lettersToWord.containsKey(sortLetters(key))) { ArrayList<String> listAnagrams = lettersToWord.get(sortLetters(key)); for (String anagram : listAnagrams) { if (isGoodWord(word, anagram)) { result.add(anagram); } } } } return result; } public List<String> getAnagramsWithTwoMoreLetters(String word) { ArrayList<String> result = new ArrayList<String>(); for(char alphabet = 'a'; alphabet <= 'z'; alphabet++) { for (char alphabet2 = 'a'; alphabet2 <= 'z'; alphabet2++) { String key = word + alphabet + alphabet2; if (lettersToWord.containsKey(sortLetters(key))) { ArrayList<String> listAnagrams = lettersToWord.get(sortLetters(key)); for (String anagram : listAnagrams) { if (isGoodWord(word, anagram)) { result.add(anagram); } } } } } return result; } public String pickGoodStarterWord() { int length = sizeToWords.get(wordLength).size(); String word = sizeToWords.get(wordLength).get(random.nextInt(length)); int numAnagrams = lettersToWord.get(sortLetters(word)).size(); while (numAnagrams < MIN_NUM_ANAGRAMS) { word = sizeToWords.get(wordLength).get(random.nextInt(length)); numAnagrams = lettersToWord.get(sortLetters(word)).size(); } //Revert to a short starter word after some time. if ( wordLength!=MAX_WORD_LENGTH ){ wordLength++; } else { wordLength = DEFAULT_WORD_LENGTH; } return word; } public boolean isOML() { return OML; } public void changeMode() { OML = !OML; } }
36.157895
100
0.612263
58b8da54ab2f548e4d59ef653affb6caf38a3149
87
package rx; /** * Created by kbahr on 10/20/14. */ public class ObservableTests { }
10.875
32
0.655172
080290b3c996eaa6e6ba30ff53614d17f66ce8e6
10,080
/* * Copyright (c) 2017 Gowtham Parimelazhagan. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gm.repository.di.module; import android.app.Application; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import com.gm.repository.cache.Cache; import com.gm.repository.cache.CacheType; import com.gm.repository.cache.LruCache; import com.gm.repository.http.BaseUrl; import com.gm.repository.http.GlobalHttpHandler; import com.gm.repository.rxerrorhandler.handler.listener.ResponseErrorListener; import com.gm.repository.utils.DataHelper; import com.gm.repository.http.RequestInterceptor; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.HttpUrl; import okhttp3.Interceptor; /** * Author : Gowtham * Email : [email protected] * Github : https://github.com/goutham106 * Created on : 9/18/17. * <p> * RepositoryConfigModule */ @Module public class RepositoryConfigModule { private Application mApplication; private HttpUrl mApiUrl; private BaseUrl mBaseUrl; private File mCacheFile; private GlobalHttpHandler mHandler; private List<Interceptor> mInterceptors; private ResponseErrorListener mErrorListener; private ClientModule.RetrofitConfiguration mRetrofitConfiguration; private ClientModule.OkhttpConfiguration mOkhttpConfiguration; private ClientModule.GsonConfiguration mGsonConfiguration; private ClientModule.RxCacheConfiguration mRxCacheConfiguration; private RequestInterceptor.Level mPrintHttpLogLevel; private DatabaseModule.RoomConfiguration mRoomConfiguration; private Cache.Factory mCacheFactory; private RepositoryConfigModule(Builder builder) { this.mApplication = builder.application; this.mApiUrl = builder.apiUrl; this.mBaseUrl = builder.baseUrl; this.mHandler = builder.handler; this.mCacheFile = builder.cacheFile; this.mInterceptors = builder.interceptors; this.mErrorListener = builder.responseErrorListener; this.mRetrofitConfiguration = builder.retrofitConfiguration; this.mOkhttpConfiguration = builder.okhttpConfiguration; this.mGsonConfiguration = builder.gsonConfiguration; this.mRxCacheConfiguration = builder.rxCacheConfiguration; this.mPrintHttpLogLevel = builder.printHttpLogLevel; this.mRoomConfiguration = builder.roomConfiguration; this.mCacheFactory = builder.cacheFactory; } public static Builder builder() { return new Builder(); } @Singleton @Provides @Nullable List<Interceptor> provideInterceptors() { return mInterceptors; } @Singleton @Provides HttpUrl provideBaseUrl() { if (mBaseUrl != null) { HttpUrl httpUrl = mBaseUrl.url(); if (httpUrl != null) { return httpUrl; } } return mApiUrl == null ? HttpUrl.parse("https://api.github.com/") : mApiUrl; } @Singleton @Provides File provideCacheFile() { //Provide cache file return mCacheFile == null ? DataHelper.getCacheFile(mApplication) : mCacheFile; } @Singleton @Provides @Nullable GlobalHttpHandler provideGlobalHttpHandler() { return mHandler;//Handle Http request and response results } @Singleton @Provides ResponseErrorListener provideResponseErrorListener() { return mErrorListener == null ? ResponseErrorListener.EMPTY : mErrorListener; } @Singleton @Provides @Nullable ClientModule.RetrofitConfiguration provideRetrofitConfiguration() { return mRetrofitConfiguration; } @Singleton @Provides @Nullable ClientModule.OkhttpConfiguration provideOkhttpConfiguration() { return mOkhttpConfiguration; } @Singleton @Provides @Nullable ClientModule.GsonConfiguration provideGsonConfiguration() { return mGsonConfiguration; } @Singleton @Provides @Nullable ClientModule.RxCacheConfiguration provideRxCacheConfiguration() { return mRxCacheConfiguration; } @Singleton @Provides @Nullable RequestInterceptor.Level providePrintHttpLogLevel() { return mPrintHttpLogLevel; } @Singleton @Provides DatabaseModule.RoomConfiguration provideRoomConfiguration() { return mRoomConfiguration == null ? DatabaseModule.RoomConfiguration.EMPTY : mRoomConfiguration; } @Singleton @Provides Cache.Factory provideCacheFactory() { return mCacheFactory == null ? new Cache.Factory() { @NonNull @Override public Cache build(CacheType type) { //If you want to customize the size of LruCache, or do not want to use LruCache, want to use your own custom strategy //Please use the RepositoryConfigModule.Builder #cacheFactory() extension switch (type) { case EXTRAS_CACHE_TYPE: //External extras can only cache up to 500 content by default return new LruCache(500); default: //The container in the RepositoryManager caches 100 content by default return new LruCache(Cache.Factory.DEFAULT_CACHE_SIZE); } } } : mCacheFactory; } public static final class Builder { private Application application; private HttpUrl apiUrl; private BaseUrl baseUrl; private File cacheFile; private GlobalHttpHandler handler; private List<Interceptor> interceptors; private ResponseErrorListener responseErrorListener; private ClientModule.RetrofitConfiguration retrofitConfiguration; private ClientModule.OkhttpConfiguration okhttpConfiguration; private ClientModule.GsonConfiguration gsonConfiguration; private ClientModule.RxCacheConfiguration rxCacheConfiguration; private RequestInterceptor.Level printHttpLogLevel; private DatabaseModule.RoomConfiguration roomConfiguration; private Cache.Factory cacheFactory; private Builder() { } @NonNull public Builder application(Application application) { this.application = application; return this; } public Builder baseUrl(String baseUrl) {//Base url if (TextUtils.isEmpty(baseUrl)) { throw new IllegalArgumentException("BaseUrl can not be empty"); } this.apiUrl = HttpUrl.parse(baseUrl); return this; } public Builder baseUrl(BaseUrl baseUrl) { if (baseUrl == null) { throw new IllegalArgumentException("BaseUrl can not be null"); } this.baseUrl = baseUrl; return this; } public Builder cacheFile(File cacheFile) { this.cacheFile = cacheFile; return this; } public Builder globalHttpHandler(GlobalHttpHandler handler) {//Used to handle http response results this.handler = handler; return this; } public Builder addInterceptor(Interceptor interceptor) {//Dynamically add any of the interceptors if (interceptors == null) interceptors = new ArrayList<>(); this.interceptors.add(interceptor); return this; } public Builder responseErrorListener(ResponseErrorListener listener) {//Handle all the Error logic of Rxjava this.responseErrorListener = listener; return this; } public Builder retrofitConfiguration(ClientModule.RetrofitConfiguration retrofitConfiguration) { this.retrofitConfiguration = retrofitConfiguration; return this; } public Builder okhttpConfiguration(ClientModule.OkhttpConfiguration okhttpConfiguration) { this.okhttpConfiguration = okhttpConfiguration; return this; } public Builder gsonConfiguration(ClientModule.GsonConfiguration gsonConfiguration) { this.gsonConfiguration = gsonConfiguration; return this; } public Builder rxCacheConfiguration(ClientModule.RxCacheConfiguration rxCacheConfiguration) { this.rxCacheConfiguration = rxCacheConfiguration; return this; } public Builder printHttpLogLevel(RequestInterceptor.Level printHttpLogLevel) { //Whether the framework to print Http request and response information if (printHttpLogLevel == null) throw new IllegalArgumentException("printHttpLogLevel == null. Use RequestInterceptor.Level.NONE instead."); this.printHttpLogLevel = printHttpLogLevel; return this; } public Builder roomConfiguration(DatabaseModule.RoomConfiguration roomConfiguration) { this.roomConfiguration = roomConfiguration; return this; } public Builder cacheFactory(Cache.Factory cacheFactory) { this.cacheFactory = cacheFactory; return this; } public RepositoryConfigModule build() { return new RepositoryConfigModule(this); } } }
33.377483
157
0.676091
8591589594b58f7e9a6a282ded5b963e0af3594b
1,762
/******************************************************************************* * Copyright (c) 2011 Google, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Google, Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.wb.core.controls.flyout; /** * Implementation of {@link IFlyoutPreferences} for keeping settings in memory. * * @author scheglov_ke * @coverage core.control */ public final class MemoryFlyoutPreferences implements IFlyoutPreferences { private int m_dockLocation; private int m_state; private int m_width; //////////////////////////////////////////////////////////////////////////// // // Constructor // //////////////////////////////////////////////////////////////////////////// public MemoryFlyoutPreferences(int dockLocation, int state, int width) { m_dockLocation = dockLocation; m_state = state; m_width = width; } //////////////////////////////////////////////////////////////////////////// // // IFlyoutPreferences // //////////////////////////////////////////////////////////////////////////// public int getDockLocation() { return m_dockLocation; } public int getState() { return m_state; } public int getWidth() { return m_width; } public void setDockLocation(int location) { m_dockLocation = location; } public void setState(int state) { m_state = state; } public void setWidth(int width) { m_width = width; } }
27.968254
81
0.511918
60b1455ec1e61f9d9e8c315446aee5cbb42a1a29
2,025
/* * Copyright 2013-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.rules; import javax.annotation.Nullable; /** * This is a union type that represents either a success or a failure. This exists so that * {@code com.facebook.buck.rules.CachingBuildEngine#buildOnceDepsAreBuilt()} * can return a strongly typed value. */ public class BuildResult { private final BuildRule rule; private final BuildRuleStatus status; private final CacheResult cacheResult; @Nullable private final BuildRuleSuccessType success; @Nullable private final Throwable failure; public BuildResult(BuildRule rule, BuildRuleSuccessType success, CacheResult cacheResult) { this.rule = rule; this.status = BuildRuleStatus.SUCCESS; this.cacheResult = cacheResult; this.success = success; this.failure = null; } /** * Note: This should only be used inside {@link CachingBuildEngine} and unit tests. */ public BuildResult(BuildRule rule, Throwable failure) { this.rule = rule; this.status = BuildRuleStatus.FAIL; this.cacheResult = CacheResult.miss(); this.success = null; this.failure = failure; } public BuildRule getRule() { return rule; } BuildRuleStatus getStatus() { return status; } CacheResult getCacheResult() { return cacheResult; } @Nullable public BuildRuleSuccessType getSuccess() { return success; } @Nullable Throwable getFailure() { return failure; } }
26.644737
93
0.722963
83cf4296a0665e096aea2fc5912e7662d0643fde
431
package pu.study.framework.bean; import java.util.Map; /** * Created by project on 2016/4/20. */ public class Data { /** * 模型数据 */ private Map<String,Object> model; public Data(Map<String, Object> model) { this.model = model; } public Map<String, Object> getModel() { return model; } public void setModel(Map<String, Object> model) { this.model = model; } }
16.576923
53
0.582367
2f7ab4b42519fe6736c4b4362d3af2096f4ade56
30,528
class JQ5e { public WzKCg L6znFqU; public static void lPIBSO (String[] eyylZ) throws Xd3Ze2 { boolean q = !-true[ !--true[ !new int[ --!3252[ 41991207.l9To]].l()]] = --null._RBo5; void FxNJ79H = VtIuOc[ -true.Nbmc1Z73xY]; boolean nY6jpXs9; boolean[] QSluroaw = -this.tXlHljuw = -!!null[ 18077442.w_z]; yHR64M().KMx9F5_JtvLLx(); nN7dSzuA3mN().ZHH(); boolean[] W9r; while ( !-new Vp_Wrj_h8z3s().AfvJo7u0()) while ( QG3PIx6puZoL.qbvCA06DE) return; if ( ( -!false.E).Y26qXSftDobESR) return; void[][][][][][][][][][][][][][] CjW = !!-new CfXFsKOkF().zO5xgnz9u7Y = this[ -true.Ay8SYXrw]; ; LcjnC102UhQYhX[][] Ky1WWMLO3; boolean[][] jtk13We0hD = !this.eUyx95JTamFD = -!!p.uAJGVvHr2Ll0; return -!!true.pJ4; int ozyT = new m0btxGZZXaHSUt[ !n0b9.Wv_0aZVh()][ -!jQYq21aQt.dRTAlejN1I]; boolean fwwyvUKJ7z = new ac4[ 208288463.C3jMbsWV8()][ false[ !false[ -( -30.c9j2ObE9()).k9]]]; boolean w = false.vwnc = false.O7oWRIWKS; } public yN0uB6FiDaH[][][][] YvXlw0A; public static void bu9Y (String[] F) { while ( this.THNHsD1g3L()) { null.xmRWuH(); } return; if ( -null.x6MSlIU3()) true[ tzwZFagri.w1];else return; boolean Axe6LuNryVU; int[] pWeR_jDlPu; boolean[] OrrES3cA; boolean[] l = !-new Ni3fagQfUkv().jgCp7E1; int Xl1BtUJTt5A3 = -!juomrk4qSsfxo_.xMJ(); void[][] u52fj0SAdc = new void[ !!DvE4pVudY1v38()[ 066084908[ !Z7pKkDsD3AJ().g]]][ Zj6q.M()] = -!Rh7qxZ().iRZ3EZE9v9jKQ(); NrUDsF7P V; H0xl t_ = !-!( -!xAGXZ[ sdl.tFB6JD8K6tm_]).x2CpbFUxHRj = true[ false.jC823()]; ; return !new t3AH5I1pTgl[ q8kT9ewG.Zjj].JC(); return; boolean _6sOaxfVmd0YwB; boolean SPpQP8Z0MKuu = !--false.uy2g99IqW_4; !!this[ !-this[ ---new rI6CmJErYpw4Ht()[ -!this.K0eYeAubUU()]]]; if ( 01907361[ o7fUcn.n6NTn0TGs0d]) ;else new Zru8()[ !new kSBbsTiWc2QLhz()[ Pd8m4eMAA()[ new Ags0()[ false.QMP8_58U]]]]; ; d[][] bMGTa_Qb; } public IC7 S8B () { int xVZ = p2s().HS1m7XE2r0(); return; void[] zHa0UMXmJ; --new I6k()[ !MY().B2Kd_wUMP9krw()]; boolean[][] XkPhPWzyFYuQf = !true[ this[ !-!!YXOCjix7bEuoC()[ AX8.uQ()]]]; ; C4vr[] N8R54XKgI; ; void jltoq6ShNU2L = tczZ().EPBHZon_O5Ai8() = new tC8hD1aYW9().Z; ; boolean[] EU794mlxlnyzT7; return -!211.WStH6(); ; int vn__ = !--new boolean[ !true.OMDQT1FEFGqW8].A2X = !--ukJ1jqCBdEHVA[ 505307436[ !true[ --new dteO6dN348H().Z()]]]; boolean G6OJXrR0; boolean GU8WVhMW = !L.AthSmoXGMeZ6I(); new boolean[ !-!-----pHxzt().gnqZJqK()][ -2883.hX3Zn1()]; boolean[] lCQ1dqc6TfT = -!new boolean[ ---this[ -!-!waUjcp()[ !( -false[ -165[ !!!new p().Ewcz1]]).EPu()]]].XKxTDRIQ = this[ false.ky()]; } public void _LtO9WcMq; public void[] Aug (void[] J, boolean G_, qn_[] n) { while ( -!new qJmdM_KJvST().rrvL5ng()) { while ( ( -!!qqHPSi().gt).NYhm) while ( !!!-null.S) return; } void[][] eST_64g = new void[ onRG[ --!( this[ -new hnXn().gApVc2n9Aa]).zQ2yN]].FCRftKx = -new int[ -!!!230.Cr25P].PcRV13; ; int ycJKEngU1jYBn; int ua0Rwqxao1nkR = -new N2fQdE6C2U5B().LS() = false.T3H(); { int[][][] sJUSa7zZk2JJzs; void JIr8Lcddw_Z; int[][] mFz3xhDWY7Mum; ; boolean[][][] D; void[] jpo2OjL; int tkmrljTCAN2; ; int MSaRXvVVZv; while ( !-true.rfHl) new GvNL[ false.Hwqauhe].Qui3RCjy6a(); while ( true.hBkippJe) return; void[] Fl0JFc; void Hfir1Dm0S3; int[] MMRqdmsV; int CD; } int Z8amSVFB2 = OvYd3lRSDZ20.YehKsu1wWdL = -new PDB6()[ this[ true.ctr()]]; if ( this.SLdS) while ( null.tuU) if ( ( -!this.SPs8McJ3hfR())[ false.D5aKKvB9Az6R]) -Gaxr48AL8N[ 1902.cvBAWDs3c4Onv];else { EQ9[][][] FPWXQEFItLO; } int JQ; return; int[] l9K = !!( ( EUsS1()[ --new void[ --Le().udHyhcQP4()].S()]).rEoIpsOisHU()).Fdb0y; boolean CKzkWud2n = ( rH().fG87Q5N).rvf0 = -new void[ !true.W0Mi5DYTKLD2GZ].Qv; void[][][] Bw; Z4Q3tN9if3XgT[] llbf = !new q8().KkVe() = 0.rndxKQc(); while ( It()[ -new OhdAST().Wl_FLwKmzgW()]) while ( _qgj.mF) return; ZCRsvdMdv ZqYB = !new niufiN53c()[ --bbxHv.ToHgcwBFR9GBLr]; { void iHrJtELQ1F; int bzHVc; ; return; hrjWDpLOWON[] C; while ( !new void[ !new void[ CCvjNPqPx.um].q8PhapyGeGOk][ -null._hdKQDy()]) return; ; j3PMklLSvX4R8f dsF; void rBmXB29a; new xN().uQ1D0g; return; hvUcKAKkFf.pQCX9qDxPaW3; return; rDN MCbLizpuae_3mE; void[][][][] mQQv; int[][] eOhRoHAxWp7; if ( ----Ui165AMk.HwQ8HcoP()) ; return; ; } int[][] fcPMZ4 = !true[ --!new Ccsok2utcD8B[ true.AziiKdwe][ new F1GLkR5Y_b[ !null.ryFQOcAMkSDO()].q693S2VwZU1DhP]] = -( ---new int[ -new B7QYd().dibGsL()].kl4Nu1uD()).v0L6ELDSZ3sfHI(); void[] MsOs0jz5r; } public r7ZoUtQoz6w BPFr2K1IvsG0I2; public static void Zj3dU (String[] DeBZANYszk1V) throws xqpTBDsiq7H6qb { if ( -!!false[ !this[ --( false.WHpSGuOy4())[ null._8ebHf69R]]]) if ( EDeoc4RW.aRqqjMT5KcYcs()) ; boolean pRZfl5FLMts9 = -4.FXypfVeHUL = true.Ma; boolean d = !null[ 629242608[ !sqhVwBDWI()[ LpsvmR6iAgF.Jvgx()]]]; nHk140dioo1KKl[] HSh9UTYoH = 80171115.iBjT6mHx = new mORZessbOdTL().t2aree57l00(); void[][][][][] LclchxhosKY; } } class tADXRW { public void[][] e3p2PW; public static void msZOvitrrVXM (String[] BlfJHK0O8cRr) { return -!new void[ ( l2.d())[ -( new void[ --427923348[ VRjX68[ !KI0rs4m2Y.Kjxh31V]]].UhWQ7Le01())[ sHJj1UBxlWh().GzWLfKzGjZ8BN]]][ this.rdr_gd()]; { while ( false.fg3LsCyJr6()) ; nUE_[][] tgH7; boolean g; void ULL; void[] EiqAtuoR; { !---null.qBCe1ukjKiG_b(); } ; q1r_Sqyb[][][] LmPnBpq81_d; void z; UG3gwb8S[][] tt; ; if ( new void[ ( dfUbSn.ouf()).Z43oHw()].CW2aBOAmzeTyO) return; ; return; } nuGqkfojTELoN8 _XCPH0OI6 = !-!!( !new vup5uWeU8().Ni())[ !this[ null[ true.pRbGWISS]]] = -!false.Cp0(); -!!!444706832.iG; while ( wC_JgfC.T()) -!!!new int[ -new int[ -new int[ !--new int[ !null[ -!!false.j7bC9yi]][ !4[ Iym5().jNm1Ca()]]].K_hdL4Drm2fX()].kmVz4Q()].D7VqOYveD0; } public boolean I3rco91ctWq (int[][][] nJvtRA3vX) { if ( !KUyiKt()[ -By8aKGK()[ ( !new void[ -!-!WOgM8UaSg_[ !null.ufO9kWh]].MM8OsaDxIxBd_).oPtpFrBmZSUg]]) { lYR3jY4lQzysW als8BhSMJZ; }else { ; } while ( new YfWesurlB().sOfM) while ( false.Ge()) !20347.vfKYr7gSkVEfC; boolean[][][][] OaFx = !!kjuhTCc[ -this.p9hI]; { int Zu; while ( 4749602.CZlfAPr8l7QpXc) { return; } { EESlNs uey; } return; !obl().JSL8; this.JWRHxQl_5; if ( 8903[ -!new boolean[ new void[ this[ true.lKn4UjiJp()]].QgVu2Dt4QVmL7i].C2SlLGBCQDSa()]) { -true.aXbLpSCjFyo(); } while ( null.yRXeHaz17) while ( true[ false[ !this.LEB7kpp6w_()]]) while ( false[ -399038008.D3bdWin4a9wdzv()]) return; if ( true.FJPGW6Vd116()) ; } ; while ( --( -( !!new wOoGdOFjME[ false.TUVP_()].PLhHl5auB())[ ( -b5PPzW02r8.dRVwT3UQYH).KI3EqjOvfw0d3()]).AuSdpLm15) return; int[] RxKAxzOTa1OWc = true.gn; void dv3L0Sv = 74[ new Wg()[ 5595784.Zc]]; void RfrrKUfg; boolean G7ieROy9hgXMXI = ---new uKVgwACV[ new void[ !XtA4sMIu3b[ ( !34905734.Vr_5tw7S).uXy3bqopq]][ --!( 95514693[ new void[ X6S0().HxT].C()]).L02DeAvzexfSD()]][ this[ --false.I()]] = Yj9oVLqp.xUS8SQnu; int[][][][] cJM_1FI7FW; H syuhm; return LE[ -this.O8uWQB1v0TAN1u()]; void lw1; Vg Kg8zxKWBLaoBP = true[ !-( new int[ ---Slck9U()[ ---true.uGBOfpxy()]][ true[ true[ this.w0wwShbWhLbr]]]).gWpygz1rB]; } public DuhMEn36XuCaRw[][][] ocf () { int[][][] uc4ExOHa4s2NQ; { if ( this[ new int[ this.B2EiG].q34mWX()]) { V VUJA; } { void NpCKR9k0Y9yD; } int TR1qa7eQC; VvehSqLFgEvnN J; return; void[][][][][] J97; int[][] oPju; new a9c0_kJoVr_KwF().v_Xovkgqlfxwhq(); while ( -new void[ !this[ TTYOmhp().DL7UHg]].jV03LU7IdOz1q()) { { boolean[] ontzW0; } } return; l7Jo13g20hnvHC[][] vWQts_CiEaJ; int A2pyK8T; boolean tZGd; { ; } return; return; } ; !!--false.CyPcTqIOL; { return; boolean mx4qkzCLuynKa; if ( !VBNsz5p4.tzS3sWhs) if ( --true.zZ3Z) while ( -false.Z()) if ( !false[ null.p]) if ( -null.W0giaf) { { { return; } } } AR3z1KS[][][] Ou; while ( new boolean[ CEKIlPdhi_3n._0wRn][ this[ 307931713[ null.GGcn_()]]]) ; boolean[] UO3mRKhJ; while ( --!false.cl()) -!new Zfh()[ true.RKOn6AcrMszw]; while ( -this.vhVj) { !this.o304; } int[] bU0SKJp; void k; while ( this[ -!null.B0DZ()]) { int i; } } { if ( !!zbTNq().rM56siv) { int[] RCZnIPv2Q; } boolean p83QzJDtA; ZJPjstVt iNCJ4fb4nikCRF; L66XEn4Csx1q6v[][] RYtSDU629_7; ; boolean[][][][] x7Sdg3iCVTbeVA; DD32lkXgez Jr3HIVqPxT; if ( null.D4o5()) while ( -!( --true.tGeU)[ _COD()[ !new int[ this[ -null.zSg()]].u_Vgo()]]) return; if ( -false[ new ISaLwwxw0_IsKh().jX]) ; ; if ( 4.EDTW4Pov4q()) ; if ( !!l[ G5M3j[ !!false[ !--z2xjPmgAvCfB0()[ new boolean[ this.rBeDc4vB][ true.hpau22]]]]]) return; while ( new void[ -this[ -this.hPDnvny4a1()]].SZ2()) while ( this[ -!( wlUI1_5t4()[ 028.B()]).z0QER]) return; boolean rzBgGmAVOU; int[][][][] wSZKP2GT0C; JROso P; int[] u17; ; boolean w3CM4; return; } boolean jUbof1cQJjgq = !new b2fhLDRmfBbUh1().m; return false.Nap0dtZyd(); void[] BQY7; _lO[ -!KUSTRppJX4W.SQFnde4ADvHvGL()]; } public static void zd2Ilb4O (String[] ZlOpGCU0X55) { ; return _BSv.C9gnU; while ( null.pwlqk) { { kavEK1SkK3Zyh oD; } } boolean[][] KcIN3FFZIS5Oz; ; lh3sNEvv[ !null[ KYtIEsrQpjS().RoqZhr]]; ITBvmRje9ep[] nAEj_1 = ( !true.ZRNCVbbM030e()).oy; OM oJaf4MZBn; { void[] kDL8_JfK5js; boolean hyp59; if ( --( -this.wp0Y).Lao6RqOtIvCAD) if ( !new iQH9QZ().V8JOJHmA()) ; int[][][][][] YudLPm3pU; 21364414[ null.MqBlmmR2fkLJk()]; { I3CUbfCTOB6Vq[] Q_yGQJCL0xZr; } { if ( !-null[ 539[ null.FuR()]]) return; } ; while ( -!JcQLdFVA().bIJuOkoUNR7) return; SIiDHbxaJ BdK_TNOV3evfGt; boolean xvB2RES; void XEu; cpg5N8V[][][][] nHr9PQd3LvKB; boolean[] Lt; int J51XPF; new boolean[ --( -QurT().c())[ this.XaEVE_OwCdZ()]].v4V(); } int Qqb; if ( --null.hsznZToR) while ( !!-!null.oeihwscUphFFPl) return; while ( new boolean[ !true[ -!false.dSZHS]].hj46eL2Zghuh) new Lw().cw6s12Tim2Y(); } public boolean cWeFTuq; public static void A9 (String[] YlfMehrGsyJ) { boolean[][][] RIBkrX9SuVGLR = !-APIp.MghbhX21ln5(); } public static void RAJufskT (String[] K) { return uq_KVS.eMfRUly0aDPs(); } public int Vgy6r62SMb (SXClNz5 OL, t_zzt8QYZVn pVji, void[] JHNGvBS, void eP0Pu0avZ) { int ZC = !-!-new AwpaNuj().jFN() = -( new int[ 944957542.p()].xI2saGqkDKy6).VyMn; return; RkAzfM[][][][][][] gGLlZiwVPqionh; { if ( !!false.fEv) { { z0LAvFy WhV; } } ; void fKBNS7Jo9Ykk; int dRkB7Hj5nBTP1P; if ( this[ !!KdIjpmr415m.vNDQBiE2OxU9]) ; YpLWeQwf u9tYZ4FURzJHa; if ( -!false[ !---this.Y()]) return; ; int W; boolean ttN2b9DgvKZe3V; int NsvKJ6IFuE_X; return; AL[] TaKJkNAmvQ; boolean[] vK8KKSw; dT3 VNKWOx; } int[][] yUxnH = gs0AgPcq6t2tDw().FS9s5NTrMDKq; { void mtS0xpmP0; { boolean[] R9; } AsxdJRBvlt[][] mH; void Om_opUy; TnOsGaHgDhvkFx[] V; int[][][] mTxQNtP1rckf9w; while ( new g7__cNqUDNOXV8().IpI5GZ()) { ; } int Ds3Myh3L; int htoF5_n9n; while ( null.gwEAxn9Eup4) if ( true[ -ulnU[ --rSyr54s().BXzz696]]) { while ( ( true.dNL())[ ( ( -new void[ !false.riSA3()].yTf)[ -true.Pf9U()]).bJX7HWaI()]) while ( new g5YHiJ7BTFHR[ -true.bWyFIqcMWhCQ2()].M5KQLdNhN) ; } ; while ( -new int[ this.C7O7dJn9MwFFGw].Nsd4Jz()) if ( true.A()) -580938.pYw0XwqzxmGx; int[][] r7s5Q8y9W1H; !EWjfjL4nk.XW(); int[][][][][] UWWtc4HXJoFu; return; int[][] M_; } gYJZYuRDyHv3 oleSO = --DOI_c3s.aSd = -( --!null.k7bgrkw).LwB7wHIhbe; int[] Sn7w = !-null[ !( -!Z[ s05.V6]).cPSdlRi1EVhw] = -this.BKQeG7IaE5; if ( -null.FdcZ2t6tA()) return; z4cMno4zHg5hXL[] SOZ3xxEujb; HwlLUP wxSAz99EownBLJ; while ( -new V_mewM()[ true[ -new int[ --!-true.A_()].I()]]) while ( null[ 129[ -( new q4WpCUh()[ null.LeE2wJeyA()]).S4iyi2p()]]) if ( tqp.yK9XtsYsZKX) return; { I5nPwbeSyGYA[] iXYlIK; { return; } ; n6nqCdd6SOj rkWv8f; aYXlB[][] cLPKUYO22gMLWY; { cTSpEAZxi[][][][] FbQC; } int oNHglDuuBaz7; void[] _Aup; { hf[][] USJ1Nqu25FUc; } void[][] tuTN9EUE; boolean[][][][][][][][] N_FoAy; !new Fc4OEKxJ()[ ( -new h3g1vI().YJGhEcYZJQ())[ new oBXC0kR4aI5()[ ---88833.HRWst()]]]; Ev QZbVPe; int lWiQ5; CW_B4NW[][][] wMKOt; { if ( j().T1RXs3PPS2L) return; } int[][] Jd; N2CMK5pZPvZoL[][] Is; int v; int[] _; } return; wdKUF2yS[][][] T8SOurRa; boolean[] s26IMyMdsVwcK6 = 4210.v = new hqLJjwpKFsr().VlrYJtNxKI(); int q = new bob3Sm[ 25392793[ new ksPKc91RnjM().z_PdQKsz2k0]].ar3iHDho7kn; ET[][] sk0Nmph; xkC8XvQs ywBHZiahp; } public void[][][] HdHaW8jgZ (void SjAXYB, wmIOkFrI7moOHO smIrZ33PIpN, _QT7[] RWStprlWFqmgJo) throws vchdmI { C_HyGCJ_SfMrlg t_4fxnZZ0PjGoS = -new Bkc_KV2YM().zK39P7PEENZ_(); null.Mko(); return this.S1n(); false.xmqu1F(); int[] zOfjA3s3KJr7 = !!!-null.DrMjhV0bNN; void[][] xo4o42aQA7 = null[ -ZCz.Z()]; } public static void F (String[] dd) throws Kod17ROdA { int[][][][] wp1iPvLSq = -bLOf0MlB().jN63gtgLaU; !null[ -new PI().KQiFBPl]; boolean[] L26tEDOU; kCej Xl; int[][][] puUIInDI7; return ZlHD2n702bNr().O9tnFpHM1(); while ( true.nTQjK5ZmdNS()) false.yZ4KbcLvu59; void iSIrHNdnm = --true[ !-!-!-new int[ this[ -PI32JU8o5TJ.voehjjYCU9o84B]].BqN8G4s()] = eeQSxRT().puWWv5RMNK(); wkzmvV7hjqQD[] tZcLOBBgC = !new Nc8fEOwvW1B().k = !this[ --!( !new boolean[ -new ec().cmZrP8][ -false.zIVwkdcTHwJA()]).sFQYVQgk5qcjJk()]; int X78bC = 6[ false.oG4cEwOC7sZn] = -new qK609sEwitz[ -bgeUz9zJvfgU().APY_bj5rFM].FyDJmD; void[][] gYXGrZwRVm; { n43_AhZim[] lTJAhF; int[] MemNb; ; boolean YI3ExBOfY; ; ; while ( -new eLSYgLK().BwgvhJxHQi_r()) { boolean[] NhoYgFqWnD; } Y_dbMlvWsKM4 ue; while ( ---!!!this.NN) return; int qRr7lSceoDe79o; { int cB; } int[][][][] Tk8ZBjoL; boolean n; } } public int jJm; public WU15Af[] LuGCD; public int b2udrLpjI30QKP; public static void JySm (String[] RCu2) { { boolean vyDbk; while ( 67760847[ -this[ null[ -ZJrqSRa4_.AV]]]) --Uc2zI[ true.MLMY2v]; --nQIPCSOC7_Zu().T(); int[] fmQTMwMPETQVxp; while ( true[ true.jIQVouf9qD()]) { int[][][][] u; } while ( -new pWn4JMprUqi1zx()._kXZrSu) if ( -this[ false[ !null.kSkQxIKngqyp()]]) return; GQteVz.yWSrz9ixFx9; void HA; void zdANKyyk2tdj; while ( this.MK61rXSQm3) { x1Xc O32SPH; } return; while ( !-!true[ ( true.qd_VgU6O1vvG()).yUiI0fmDGAlDVK()]) if ( -!-this.q4CZN()) if ( 68.aLhWpjG4rOM()) ; } boolean ooQJzxyWI8psTr = this.JdrGHco1() = true.g7JCECR(); boolean[] jll5ABEV = -84.d7f75YEIO() = 323917400[ ( -!-!DqIN0dRQvy[ -80954140.Kn1ceOAske()]).vKdBAbZt()]; boolean[][][] qiAXm3uD5ytk3 = null[ 43563.hz8CBGWEZs] = !null.JMtC; void[] Bhbkf5fRGKH_Bl; while ( this.n3Z()) if ( -new pIsTOTshxoQ().On) ; { SHSZvlDOp AEQwtyORwSy; while ( xAJEax[ --IwrtIspb59[ 83575.EjTHj6_X]]) ; ; while ( V_1fzuEC64zh.B()) while ( -null[ ( new int[ !ud.hQHhH8nfOm1qwi][ !!!!--!false.xtmajbq])[ !( ( true.UBh).gMVdKLCN()).itNuxgQIeEY]]) return; void YHrGt1yGm7c; lw[][][][][] e7ZPL; return; } { int[] K79Apz8jBtkMbd; int AitICn7; while ( !-!!!---!this.kU()) !null.EDY9TLkc; boolean Ld; void[][][][] wMpjg; ; int Qg; void DFoB2Mh2i; void VVI8_ayR82Yf; F4rOIsbuav t3UjhmSQbMH; if ( new TPz[ new boolean[ ( -X().Rcs).eNpS()][ false.bTDV4V9oT()]].C9) true.kwx29mg9BCebKB; int[] SbLxwMxXq; } return; void[][][][] u1CoPkxk3O8; return; return 228.C6pv(); if ( !true[ null.MX09QR71Qz]) --!-null[ false.e];else return; int[] U5HeTar_LM3; return; while ( true.ZtbDILZYpG()) while ( !!false[ new NCt9k7qmb().AhXFzFW()]) new lEeV5B().nZLTEd(); boolean lB9bMnE; } } class WeieA { public void[] euD4d; public int OnoaW () throws cTy23F0m { int[] Nje6Iv8; while ( !-!true[ -!322875705.u1rkqYpJLKQuHW]) if ( new boolean[ new CaH5FalqxMhUHr[ !!--new MVBnTer_b().e].CJm41k_hXx].AXoG()) if ( -!G0pe.w_0KNzC3()) ; ; } public boolean ZDq0Z0RQu71M () throws RLqDhQ0 { new GJmp1iCj().ekPqRI_b1yPSak; if ( --!iD2mbz48.n5vWFimbIDJi) null.Y6ubW4yj_wkds(); if ( false[ NHCT[ !-!null[ this[ bs4ve4B5OY5Ub()[ U98cr.lhzktfePt0pfl()]]]]]) if ( 619873[ true.J_TL_N]) if ( fQN.dfQXrRRrcd) { ; }else while ( CakOn33HLT1().PAVzJS8kTPVD()) return; return cWz[ ( !59488719.Ch).LOtpCj_jZQ]; int OXzIjCDOwwHmok = ZkWV[ null.DbzV8m] = !-SLpkizMJ().zgenE2; int a = new boolean[ ---this.InQxT()][ false[ !!znMF.nfOWF0ftxLHPP()]] = -LXaKUpi5ny()[ this[ -!!-this.b56r36Xshu1c()]]; ; } } class AD8ItGx { } class xiA8pqcSTQgz { public boolean I; public int[] C2y7aPg6oMTg (void[] NrX, rKaKh[] D4Swu5HrVXXAHP, void U6MVI5ztf) throws ofSFvtYD { 5552335[ --U_tIRVqh.OxsHnVosk]; boolean[][][][] J = new HjDisN0ctm5()[ -!false.gXVP] = false.PVnWLQNAi1FZG; ; int[][][][][][][][][][] K9z5wCJgxm = -new BsO03pqGC()[ !null[ !this[ bidv3v0BVjRI7().Qwh3X_FWJd5p5A]]]; { return; aazfsmr8[][][][] HLi; int D; { return; } wl[][] eqre7XdRZ4tO; ; int[][][][] KA2YOoSXgVZH; void I3rz6gSEL8lqPH; while ( false.CwMN9oYVo()) return; return; if ( new void[ new z2q_WjUp7Wx()[ --230[ -!-true.FSDHFmLe]]].RmS9puHnYbCsuK()) this.GAl6; !-( !!1565[ -this[ !false[ !-!!---this.CK3mgbTjPtmLR9()]]])[ -!-new boolean[ !false.qtBMoL2LCLw3ZY].qog()]; return; return; } int Vvn3gSry; boolean Xf2HOphrvck; } public boolean SsPhOKT8mkAejQ; public Ds1HGXKm9Al[] vsqsDPdq_cbF; public static void NIxS8 (String[] asgwd) throws jOSfW { int D; } public NWp8KMlOdwUF VKZtsisgGG; public int[] ogjSWd7grg9; public boolean rIGw (boolean l6u8G8ScKsI, int CAYpCCBTXrW, int VeX, boolean vRCyp, jPPwTDsKC0[] Fb8u4YgkzGzXp, m_Pa[] iquiU, void qvuRaF) throws DiTR8IlxbR { void[] UravjOu = ---!YZR0S75().nuOua = !38317.okkR; return; while ( this.J5lSau49KHy) ; dC3dHyvDBIN.HhlpTn; return -!BiUJuPBbYt().x7hnCgMUZ4NWi; int VlwX = !false.FSyEPcVOh5ST6R() = -new int[ false.MN9a()].v0qCmb7IA2(); boolean[][][][][] SXyIKJb1PIAVRV; tJkv J8umzbKHzfo; { void[][] NQOAXyccLU1; boolean[][][] CfQoaoXCIpM; { { while ( ( -52586.z9g())[ y25vYUNCnji.dGj69pij_5qezg]) if ( this.Br1DZK7lgoBjj) -true.UHlgYj3LVuO; } } void[] AD8LK; jCPAheLGmqNi ChdqgO; if ( Qjn[ this[ o9tDiw9cK54_y[ this.pF6JEVD]]]) while ( -!( ----!true.uMiaSBuCUMm()).fz3JOt8X9c) ; boolean MXLsL6U7SI; qQjlgF[] kFVXM9lj8hA; if ( WnOMJ().zbWcuX) { if ( -null[ -6595[ ZfNV2jP2KzAxhi()[ new f8pGSn().UfKNS2()]]]) if ( -true[ this.dWKzTAPwpFY]) if ( !!!!false[ -!!new Iu2LOZzKf()[ null.Y]]) !cvyeAp_uAbrxe.yN6BAd(); } k5ZzSSYeDi_[] vB; if ( new boolean[ !-!-!!new int[ -!null.EybIK7AeM()].TYr].wsVCa0GPkN_()) if ( !-!( d1Ti().Zl).Up()) while ( ( false.PnZ983Fc)[ LlPRK().d04JY()]) -!!!!!-this[ !!-26[ !true.cETNA()]]; U5ZrG44hUJv0[][][] dxBHN; } while ( -705449.skbUDMBFY()) if ( null[ !true.geqzg8Cdevye7()]) ; ; while ( !!--!--!!( null[ new ASQ().Q6IjxoAmA]).IcHbIm6S) fX9[ this.V6cK7N7QW3f]; } public int[][][] HBdZY3OfmpRb; public static void s (String[] Eg3GuntHAOYL) { if ( !!---!-null.dh) ;else -new fs6wZPBwKcso().xQa; _[][][] mYzmqD = null.WfGCx = null[ new lwTe6w72Bmk().lXMitauq3zoD]; void mnrQ8FpbFg11Ub; void[][] k8qT; return; boolean[][] Po5ZQmq2PWk = new cPEgVMIjJ().dinkSREH = new int[ true.ecTLGo].esobMK(); while ( !--null.cSW5I7()) while ( false[ --!----null[ PJp1C_vPLg7Uz()[ new EyGyBlX()[ !-new int[ LhZikyFXoRu.eT4ZZO3QUJWx0].lq7lZ5BvH()]]]]) if ( false.Qp6G()) return; int yZWKB; while ( !-gUGHLod1P().fzrQ7QJS9()) ; { void F; return; u[] X_nwOnawa; while ( Ucc7fZO().p_fLy5C()) ; void P3VMaBjWHoS; boolean MamIy9; } if ( ( true.xzIHrb0YVzQ()).CR2uz0IGjCZ()) if ( !new GRrh5Z[ 7592102.ZrdjnQSG].af__osuHp) while ( !-!-x()[ !!false.slf()]) ;else return; void[] i = !new boolean[ true[ 19.w9KzYCbc]][ ( !-!!-this[ new int[ false[ !-WLnADox8().XEqA6npi()]].Gol8t9]).AfsW3_OOkUW()] = tQf1lTjO8qFbQ[ -883507.sgJ99bgvmhb]; void P; CcxUAa0GG opFUzP8Icn = !!-( true.e).qFIlXaBKd(); -!-1.G3TrYUU9nRLr(); } public int UPE () { int[][][][][][][] Y8ePbLtoraF; int[][][] frY = GYCr8HA85().eZrldNKp(); int[][] qYOYNIfVVY = OtwmkdCz28bP().p65o() = null[ true[ -new cKf().v5()]]; { int[] CM5xMXGSL3fUz9; new void[ null.wGE()][ -this.UDeb6pjSoD2Z_S]; if ( !--this.zIBM0l()) ( !-!lk0S2tVXRb.X_Y).ncauXzzHs3Vp(); if ( -!-( null[ new void[ --NUoe().Cl1k].AOpMNnofL1YOMn]).VE()) return; } if ( !false.eh09mQzvC()) ;else { q9bEG().URlOhvbJEzg2; } return --new nJ()[ YyQIEozMf.WTs4hr]; boolean FhlJv = --c5OvOItR.ti1wUf() = -new cNE9dzO().JsJA2b1ijJr; _().kzzGfaIB(); void O7fRpYAL = -false.j4TDfPhs; jDqbv[] rDjo84ZPm = null.oWTqi() = this.DvR; } public static void fyvmieUAYTP (String[] WjnSiHbh04dHF0) throws xfjgIKK0Nf9 { while ( false.CagIcEsug) !new boolean[ ---true[ -!this.VM()]].WC52xiPk3x2Qvh(); if ( -!new J69q6q8Fjs().S9SA()) ;else while ( !!new zDW4()[ null.u]) return; int[][][][][] Pcmoie2KvEX = ( false[ -new boolean[ SxqWtwh4YviEO.QKJ].VRcX30k()])[ !GyIP[ !!-true[ OzAf[ !!o().WklGI3ht20D()]]]] = DItQsjADwAo().DNP9wwuoCh; ; void haHwgK7h = jY7.FnBdtkGx; boolean g7pgV_O_kL; return null.d3_Ul0uRVZ; boolean S339t84lOS; fXoVMlAic3jA[] idoCEAW = false.f1wLFNC() = !( !57.abPiOMChFq9NC).PFARZk8_XT5; boolean[] wG0; boolean[] Lq1dzSr3wQS5m = -W4().g26BdY5SS() = !--false.CVUH7ZzL1CE76i(); boolean lZEG = ( !this.QjNLm0Knxf8).iT_5kcsk6NzE() = _buLLx4rE.eljHdCF3prFz_(); E[][][] DkTq_mP7zzh = !!-!04575230.fX; void j9nAegIUA7; void[] gi3 = !!-Hp()[ !this[ new MKrTQ()[ !new void[ ( !new Be95o().k1_p7d7Yq)[ !-_2OOhJYvlVlQK().B()]].Ub3J2]]]; boolean[][] LreqH3OrV; while ( --GO[ -( this[ 5016.RH()]).l9]) while ( i_gO().fMJIvlEvItnmw()) ; while ( 7.KDnXXrgk()) { while ( !AABhm[ new eh6SiRD[ true[ LzR.qgZ()]].Hbmwq6AL9AXFo]) if ( -this[ !( new int[ null[ new PadP().miqjYr6Q9o17T0]].FaGlo00f00loBc).kmXV3()]) if ( -aFrl()[ !Ozo2G9ebOve().vK()]) if ( !9183.hBcDGCerG9qF0) while ( false[ null.B7()]) if ( --new int[ !( -!92.zBvnvBaOzg2dd)[ !new g4OFD()[ this.s9St9FK2H8v9PI()]]].xCwMyI8YKBtW()) ; } { while ( !--true.Q) { boolean r1MEwVpBR; } void Y7xGQoS; --true[ l().SLcOItI79_9HqC]; boolean[] cjiEan; if ( 7671648._1TQXwNBkAzmqz()) !false.Tg(); } } public tKc XtvhBw_CPUDx2 () throws aAzZ6w { if ( !null[ --true.F5EJFULfEHd()]) while ( !!!-new int[ true[ new hqYZl3cOQS[ --!!!925646032.XyIQ82eIwgW()].VjVPV]].Nh4Ksxx3) if ( new boolean[ zB[ -!new int[ !!-KP3C().jYR7Ks3xfqOB][ null[ new NXI5njPmHAWHZy().tQphRGa8W8Ien_()]]]].WrO3S5vj) return; boolean[] DVCp; while ( !----( ZEAR34dRmb.C).ZbM81nhAeSqs_p) return; ; IVK Qhnq0Cnu = null._a4FXXaYXDrB(); boolean xTqH; false.LLc(); boolean[] sNF = false.MY = qYY7ltGNeNHHR().L4cSnXS46qloxa; { void[] p1Rc5VLq9dLk5G; mqTvN[][] JfX; int doGHzxOfWuu; { { void[][] cCtoVdBL2WhZ2; } } } void q; boolean[] R6krO6d; ; this.ybRZW0JSeTK(); boolean Hg2d3H0kTAgn; if ( ( -767015774._xG9NFQXy())[ new c().LRZ()]) while ( new HBVm().LwojNYc()) while ( !!!!!!new ix97fKT().pOmaUN40NmGq()) !null.cMzEP824; while ( new boolean[ --( mqgXH0RCfZST[ new kqTDIOmqiMYC9().LX7RZD2o]).G2T4ujd6G0B()].oxqxwoqb2()) return; boolean Vep6; { Zcxe20hAh[] WM8hcQ6qFP9Gp; { false.LYbRytUg9(); } ; if ( this[ xPRPF9X()[ true.K]]) while ( false[ !!8560801.qLb_m3qk]) ( null.LKhgnlo2DoI_3H)[ !true.WZt()]; while ( Ls8P().bTr7r()) while ( s3Hvt().acyRvi9ZEXqk()) return; int[] Q1jeS0nE_YmmI; if ( new void[ 35.qPDYx][ !-new int[ -!!---!---this.uK_fGV6QLuh4()].SCXXK8Tfw]) return; boolean[][] ID; if ( -true[ -!null[ true.Gs_pC60HGIW]]) ; void UIImML; while ( false.CdVX5) return; if ( false.lGcsfXrc0tEjp9) return; boolean Vg; int[] AOjKn3XboRTQv; !true.bkfFl; if ( false.BAI2Hi2S()) { boolean[][][][] gP7kXqXbL; } } ; } } class RYNF { } class sZH { public static void Glut (String[] plCCLy1LYV0py) throws RdSRXjiaHo5TU7 { if ( new z_xSrSmgLSt_P7().msJWcyAUtjkqH()) ; oE svdHf88nXd2 = --eyp().TbHDF2H() = !this.PTU; void MujkNB6QpB6nu; int[] u; while ( !---!!( -this.YMO9RzVg).lyESfGgBDCD) ; boolean[] UPQIfs; return; void[][][] O72kaUkDBx = !!false[ !X[ 3.fI6LZLQzT]] = new boolean[ !pnWKaIrlb()[ uY3NU63ANU().WMX()]][ ( -YFa3i7Q().iVo6qztTeVxzmi).D7KaJ6z]; false.G_BQIGMIVRL(); } }
39.905882
344
0.497674
b6ca3d735d303d0cbb20377098be353e08f3dc78
3,409
/* */ package jp.cssj.sakae.pdf.g.b; /* */ /* */ import java.io.FilterOutputStream; /* */ import java.io.IOException; /* */ import java.io.OutputStream; /* */ /* */ /* */ /* */ /* */ /* */ public class b /* */ implements e /* */ { /* 14 */ private final int[] a = new int[256]; /* */ /* */ class a /* */ extends FilterOutputStream { /* */ private final int[] b; /* 19 */ private final int[] c = new int[] { 0, 0 }; /* */ /* */ public a(b this$0, OutputStream out) { /* 22 */ super(out); /* 23 */ this.b = (int[])b.a(this$0).clone(); /* */ } /* */ /* */ public void write(int x) throws IOException { /* 27 */ this.out.write(b.a(this.a, this.b, this.c, (byte)x)); /* */ } /* */ /* */ public void write(byte[] bytes) throws IOException { /* 31 */ for (int i = 0; i < bytes.length; i++) { /* 32 */ write(bytes[i]); /* */ } /* */ } /* */ /* */ public void write(byte[] bytes, int off, int len) throws IOException { /* 37 */ for (int i = 0; i < len; i++) { /* 38 */ write(bytes[i + off]); /* */ } /* */ } /* */ } /* */ /* */ public b(byte[] key, int len) { /* 44 */ if (len < 0 || len > 32) { /* 45 */ throw new IllegalArgumentException("The key length is limited to 1 to 32."); /* */ } /* 47 */ for (int i = 0; i < this.a.length; i++) { /* 48 */ this.a[i] = i; /* */ } /* */ /* 51 */ int keyIndex = 0; /* 52 */ int saltIndex = 0; /* 53 */ for (int j = 0; j < this.a.length; j++) { /* 54 */ byte x = key[keyIndex]; /* 55 */ saltIndex = (((x < 0) ? (256 + x) : x) + this.a[j] + saltIndex) % 256; /* 56 */ a(this.a, j, saltIndex); /* 57 */ keyIndex = (keyIndex + 1) % len; /* */ } /* */ } /* */ /* */ public final void b(byte[] data, int off, int len) { /* 62 */ int[] salt = (int[])this.a.clone(); /* 63 */ int[] bc = { 0, 0 }; /* 64 */ for (int i = 0; i < len; i++) { /* 65 */ data[i + off] = a(salt, bc, data[i + off]); /* */ } /* */ } /* */ /* */ private final void a(int[] salt, int firstIndex, int secondIndex) { /* 70 */ int tmp = salt[firstIndex]; /* 71 */ salt[firstIndex] = salt[secondIndex]; /* 72 */ salt[secondIndex] = tmp; /* */ } /* */ /* */ private byte a(int[] salt, int[] bc, byte x) { /* 76 */ bc[0] = (bc[0] + 1) % 256; /* 77 */ bc[1] = (salt[bc[0]] + bc[1]) % 256; /* 78 */ a(salt, bc[0], bc[1]); /* 79 */ int saltIndex = (salt[bc[0]] + salt[bc[1]]) % 256; /* 80 */ return (byte)(x ^ (byte)salt[saltIndex]); /* */ } /* */ /* */ public OutputStream a(OutputStream out) { /* 84 */ return new a(this, out); /* */ } /* */ /* */ public byte[] a(byte[] data) { /* 88 */ b(data, 0, data.length); /* 89 */ return data; /* */ } /* */ /* */ public boolean a() { /* 93 */ return false; /* */ } /* */ /* */ public byte[] a(byte[] data, int off, int len) { /* 97 */ throw new UnsupportedOperationException(); /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/jp/cssj/sakae/pdf/g/b/b.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
32.466667
91
0.422998
f4bb51514c4a2087fe62fd3c7e3d3c792476ddd8
509
package io.amoe.cloud.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * @author Amoe * @date 2020/4/17 17:27 */ @EnableDiscoveryClient @SpringBootApplication(scanBasePackages = {"io.amoe.cloud"}) public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
28.277778
72
0.779961
dfb13366c05d701ca086332c18e58455910a30ba
10,286
/**************************************************************************** Copyright 2004, Colorado School of Mines and others. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ package edu.mines.jtk.sgl; import java.awt.*; import java.awt.event.*; import javax.swing.*; import edu.mines.jtk.awt.Mode; import edu.mines.jtk.awt.ModeManager; /** * A mode for manipulating an orbit view. * @author Dave Hale, Colorado School of Mines * @version 2005.06.02 */ public class OrbitViewMode extends Mode { private static final long serialVersionUID = 1L; /** * Constructs an orbit view mode with specified manager. * @param modeManager the mode manager for this mode. */ public OrbitViewMode(ModeManager modeManager) { super(modeManager); setName("View"); Class<OrbitViewMode> cls = OrbitViewMode.class; setIcon(loadIcon(cls,"ViewHandIcon16.png")); setCursor(loadCursor(cls,"ViewHandCursor16.png",3,2)); setMnemonicKey(KeyEvent.VK_SPACE); setAcceleratorKey(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,0)); setShortDescription("Manipulate view"); } /////////////////////////////////////////////////////////////////////////// // protected protected void setActive(Component component, boolean active) { if ((component instanceof ViewCanvas)) { if (active) { component.addMouseListener(_ml); component.addKeyListener(_kl); } else { component.removeMouseListener(_ml); component.removeKeyListener(_kl); _rotating = false; _scaling = false; _translating = false; } } } /////////////////////////////////////////////////////////////////////////// // private private ViewCanvas _canvas; // the canvas private OrbitView _view; // the view private int _xmouse; // mouse x coordinate private int _ymouse; // mouse y coordinate private double _zmouse; // mouse z coordinate private double _scale; // view scale factor at beginning of scale private double _azimuth; // view azimuth at beginning of rotate private double _elevation; // view elevation at beginning of rotate private Vector3 _translate; // view translate at beginning of translate private Point3 _translateP; // used in translate (see below) private Matrix44 _translateM; // used in translate (see below) private boolean _rotating; private boolean _scaling; private boolean _translating; private KeyListener _kl = new KeyAdapter() { public void keyPressed(KeyEvent e) { ViewCanvas canvas = (ViewCanvas)e.getSource(); OrbitView view = (OrbitView)canvas.getView(); int kc = e.getKeyCode(); // Home. if (kc==KeyEvent.VK_HOME) { view.reset(); // End. } else if (kc==KeyEvent.VK_END) { float azimuth = (float)view.getAzimuth(); float elevation = (float)view.getElevation(); float scale = (float)view.getScale(); Vector3 t = view.getTranslate(); System.out.println("OrbitView: azimuth="+azimuth); System.out.println(" elevation="+elevation); System.out.println(" scale="+scale); System.out.println(" translate=("+t.x+","+t.y+","+t.z+")"); // Z shrink. } else if (kc==KeyEvent.VK_PAGE_DOWN) { Tuple3 s = view.getAxesScale(); view.setAxesScale(s.x,s.y,s.z/1.1); // Z stretch. } else if (kc==KeyEvent.VK_PAGE_UP) { Tuple3 s = view.getAxesScale(); view.setAxesScale(s.x,s.y,s.z*1.1); // Projection. } else if (kc==KeyEvent.VK_INSERT) { OrbitView.Projection projection = view.getProjection(); if (projection==OrbitView.Projection.ORTHOGRAPHIC) { projection = OrbitView.Projection.PERSPECTIVE; } else if (projection==OrbitView.Projection.PERSPECTIVE) { projection = OrbitView.Projection.ORTHOGRAPHIC; } view.setProjection(projection); } // Scale. else if (e.isControlDown() || e.isAltDown()) { // Alt/Option for Mac double scale = view.getScale(); if (kc==KeyEvent.VK_UP) { scale *= 0.9; } else if (kc==KeyEvent.VK_DOWN) { scale *= 1.1; } view.setScale(scale); } // Translate. else if (e.isShiftDown()) { Matrix44 viewToCube = _canvas.getViewToCube(); Matrix44 unitSphereToView = _view.getUnitSphereToView(); Matrix44 unitSphereToCube = viewToCube.times(unitSphereToView); Matrix44 cubeToUnitSphere = unitSphereToCube.inverse(); Vector3 translate = view.getTranslate(); Matrix44 m = Matrix44.translate(translate).times(cubeToUnitSphere); double xc = 0.0; double yc = 0.0; double zc = 0.0; Point3 c1 = new Point3(xc,yc,zc); if (kc==KeyEvent.VK_LEFT) { xc -= 0.05; } else if (kc==KeyEvent.VK_RIGHT) { xc += 0.05; } else if (kc==KeyEvent.VK_UP) { yc += 0.05; } else if (kc==KeyEvent.VK_DOWN) { yc -= 0.05; } Point3 c2 = new Point3(xc,yc,zc); translate.plusEquals(m.times(c2).minus(m.times(c1))); view.setTranslate(translate); } // Rotate. else { double azimuth = view.getAzimuth(); double elevation = view.getElevation(); if (kc==KeyEvent.VK_LEFT) { azimuth += 5.0; } else if (kc==KeyEvent.VK_RIGHT) { azimuth -= 5.0; } else if (kc==KeyEvent.VK_UP) { elevation -= 5.0; } else if (kc==KeyEvent.VK_DOWN) { elevation += 5.0; } view.setAzimuthAndElevation(azimuth,elevation); } } }; private MouseListener _ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isControlDown() || e.isAltDown()) { // Alt/Option for Mac beginScale(e); _scaling = true; } else if (e.isShiftDown()) { beginTranslate(e); _translating = true; } else { beginRotate(e); _rotating = true; } } public void mouseReleased(MouseEvent e) { if (_scaling) { endScale(); _scaling = false; } else if (_translating) { endTranslate(); _translating = false; } else if (_rotating) { endRotate(); _rotating = false; } } }; private MouseMotionListener _mml = new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if (_scaling) { duringScale(e); } else if (_translating) { duringTranslate(e); } else if (_rotating) { duringRotate(e); } } }; private void beginScale(MouseEvent e) { _ymouse = e.getY(); _canvas = (ViewCanvas)e.getSource(); _canvas.addMouseMotionListener(_mml); _view = (OrbitView)_canvas.getView(); _scale = _view.getScale(); } private void duringScale(MouseEvent e) { int h = _canvas.getHeight(); int y = e.getY(); int dy = y-_ymouse; double ds = 2.0*(double)dy/(double)h; _view.setScale(_scale*Math.pow(10.0,ds)); } private void endScale() { _canvas.removeMouseMotionListener(_mml); } private void beginTranslate(MouseEvent e) { _xmouse = e.getX(); _ymouse = e.getY(); _canvas = (ViewCanvas)e.getSource(); _canvas.addMouseMotionListener(_mml); _view = (OrbitView)_canvas.getView(); // The mouse z coordinate, read from the depth buffer. The value 1.0 // corresponds to the far clipping plane, which indicates that the // mouse was not pressed on any object rendered into the z-buffer. // In this case, we use the middle value pixel z value 0.5. _zmouse = _canvas.getPixelZ(_xmouse,_ymouse); if (_zmouse==1.0) _zmouse = 0.5; // Pixel-to-unit-sphere transform. Matrix44 cubeToPixel = _canvas.getCubeToPixel(); Matrix44 viewToCube = _canvas.getViewToCube(); Matrix44 viewToPixel = cubeToPixel.times(viewToCube); Matrix44 unitSphereToView = _view.getUnitSphereToView(); Matrix44 unitSphereToPixel = viewToPixel.times(unitSphereToView); Matrix44 pixelToUnitSphere = unitSphereToPixel.inverse(); // The current translate vector. _translate = _view.getTranslate(); // The matrix inverse of the unit-sphere-to-pixel transform, but // with the current translate part removed, because that is the // part that we will change during translate. _translateM = Matrix44.translate(_translate).times(pixelToUnitSphere); // The transformed 3-D pixel (mouse) coordinates. _translateP = _translateM.times(new Point3(_xmouse,_ymouse,_zmouse)); } private void duringTranslate(MouseEvent e) { int x = e.getX(); int y = e.getY(); Point3 p = new Point3(x,y,_zmouse); Vector3 t = _translate.plus(_translateM.times(p).minus(_translateP)); _view.setTranslate(t); } private void endTranslate() { _canvas.removeMouseMotionListener(_mml); } private void beginRotate(MouseEvent e) { _xmouse = e.getX(); _ymouse = e.getY(); _canvas = (ViewCanvas)e.getSource(); _canvas.addMouseMotionListener(_mml); _view = (OrbitView)_canvas.getView(); _azimuth = _view.getAzimuth(); _elevation = _view.getElevation(); } private void duringRotate(MouseEvent e) { int w = _canvas.getWidth(); int h = _canvas.getHeight(); int x = e.getX(); int y = e.getY(); int dx = x-_xmouse; int dy = y-_ymouse; double da = -360.0*(double)dx/(double)w; double de = 360.0*(double)dy/(double)h; _view.setAzimuthAndElevation(_azimuth+da,_elevation+de); } private void endRotate() { _canvas.removeMouseMotionListener(_mml); } }
32.653968
77
0.619094
dc062ac9f6f5ca9de71afb74b21160ea8cf48614
6,739
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser; import android.util.Log; import android.view.MotionEvent; import org.chromium.base.CalledByNative; // This class converts android MotionEvent into an array of touch points so // that they can be forwarded to the renderer process. class TouchPoint { public static final int CONVERSION_ERROR = -1; // Type of motion event to send to the native side. The values originate from their // webkit WebInputEvent counterparts, and are set via initializeConstants(). static int TOUCH_EVENT_TYPE_START; static int TOUCH_EVENT_TYPE_MOVE; static int TOUCH_EVENT_TYPE_END; static int TOUCH_EVENT_TYPE_CANCEL; // Type of motion event to send to the native side. The values originate from their // webkit WebTouchPoint counterparts, and are set via initializeConstants(). private static int TOUCH_POINT_STATE_UNDEFINED; private static int TOUCH_POINT_STATE_RELEASED; private static int TOUCH_POINT_STATE_PRESSED; private static int TOUCH_POINT_STATE_MOVED; private static int TOUCH_POINT_STATE_STATIONARY; private static int TOUCH_POINT_STATE_CANCELLED; private final int mState; private final int mId; private final float mX; private final float mY; private final float mPressure; private final float mTouchMajor; private final float mTouchMinor; private final float mOrientation; TouchPoint(int state, int id, float x, float y, float pressure, float touchMajor, float touchMinor, float orientation) { mState = state; mId = id; mX = x; mY = y; mPressure = pressure; mTouchMajor = touchMajor; mTouchMinor = touchMinor; mOrientation = orientation; } // The following methods are called by native to parse the java TouchPoint // object it has received. @SuppressWarnings("unused") @CalledByNative public int getState() { return mState; } @SuppressWarnings("unused") @CalledByNative public int getId() { return mId; } @SuppressWarnings("unused") @CalledByNative public int getX() { return (int) mX; } @SuppressWarnings("unused") @CalledByNative public int getY() { return (int) mY; } @SuppressWarnings("unused") @CalledByNative public float getPressure() { return mPressure; } @SuppressWarnings("unused") @CalledByNative public float getTouchMajor() { return mTouchMajor; } @SuppressWarnings("unused") @CalledByNative public float getTouchMinor() { return mTouchMinor; } @SuppressWarnings("unused") @CalledByNative public float getOrientation() { return mOrientation; } // Converts a MotionEvent into an array of touch points. // Returns the WebTouchEvent::Type for the MotionEvent and -1 for failure. public static int createTouchPoints(MotionEvent event, TouchPoint[] pts) { int type; int defaultState; switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: type = TOUCH_EVENT_TYPE_START; defaultState = TOUCH_POINT_STATE_PRESSED; break; case MotionEvent.ACTION_MOVE: type = TOUCH_EVENT_TYPE_MOVE; defaultState = TOUCH_POINT_STATE_MOVED; break; case MotionEvent.ACTION_UP: type = TOUCH_EVENT_TYPE_END; defaultState = TOUCH_POINT_STATE_RELEASED; break; case MotionEvent.ACTION_CANCEL: type = TOUCH_EVENT_TYPE_CANCEL; defaultState = TOUCH_POINT_STATE_CANCELLED; break; case MotionEvent.ACTION_POINTER_DOWN: type = TOUCH_EVENT_TYPE_START; defaultState = TOUCH_POINT_STATE_STATIONARY; break; case MotionEvent.ACTION_POINTER_UP: type = TOUCH_EVENT_TYPE_END; defaultState = TOUCH_POINT_STATE_STATIONARY; break; default: Log.e("Chromium", "Unknown motion event action: " + event.getActionMasked()); return CONVERSION_ERROR; } for (int i = 0; i < pts.length; ++i) { int state = defaultState; if (defaultState == TOUCH_POINT_STATE_STATIONARY && event.getActionIndex() == i) { // An additional pointer has started or ended. Map this pointer state as // required, and all other pointers as "stationary". state = event.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN ? TOUCH_POINT_STATE_PRESSED : TOUCH_POINT_STATE_RELEASED; } pts[i] = new TouchPoint(state, event.getPointerId(i), event.getX(i), event.getY(i), event.getPressure(i), event.getTouchMajor(i), event.getTouchMinor(i), event.getOrientation(i)); } return type; } // This method is called by native to initialize all the constants from // their counterparts in WebInputEvent and WebTouchPoint. @SuppressWarnings("unused") @CalledByNative private static void initializeConstants( int touchTypeStart, int touchTypeMove, int touchTypeEnd, int touchTypeCancel, int touchPointUndefined, int touchPointReleased, int touchPointPressed, int touchPointMoved, int touchPointStationary, int touchPointCancelled) { TOUCH_EVENT_TYPE_START = touchTypeStart; TOUCH_EVENT_TYPE_MOVE = touchTypeMove; TOUCH_EVENT_TYPE_END = touchTypeEnd; TOUCH_EVENT_TYPE_CANCEL = touchTypeCancel; TOUCH_POINT_STATE_UNDEFINED = touchPointUndefined; TOUCH_POINT_STATE_RELEASED = touchPointReleased; TOUCH_POINT_STATE_PRESSED = touchPointPressed; TOUCH_POINT_STATE_MOVED = touchPointMoved; TOUCH_POINT_STATE_STATIONARY = touchPointStationary; TOUCH_POINT_STATE_CANCELLED = touchPointCancelled; } /** * Initialize the constants to distinct values if they have not been initialized. * During pure-Java testing, initializeConstants() may not be called by native code. * Unit tests should call this method before using the values. */ static void initializeConstantsForTesting() { if (TOUCH_EVENT_TYPE_START == TOUCH_EVENT_TYPE_MOVE) { initializeConstants(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); } } }
38.729885
94
0.657368
b6d2a0af988170b6fc7dde47942d64d7610ec125
1,139
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * BQTestingSpecificationRetrieveInputModelTestingSpecificationInstanceAnalysis */ public class BQTestingSpecificationRetrieveInputModelTestingSpecificationInstanceAnalysis { private String testingSpecificationInstanceAnalysisReference = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the control record instance analysis view * @return testingSpecificationInstanceAnalysisReference **/ public String getTestingSpecificationInstanceAnalysisReference() { return testingSpecificationInstanceAnalysisReference; } public void setTestingSpecificationInstanceAnalysisReference(String testingSpecificationInstanceAnalysisReference) { this.testingSpecificationInstanceAnalysisReference = testingSpecificationInstanceAnalysisReference; } }
34.515152
194
0.841089
f54488bc42991100a16fc92bca0bbc39cc1ad608
3,527
package org.folio.marccat.dao; import net.sf.hibernate.HibernateException; import net.sf.hibernate.Query; import net.sf.hibernate.Session; import org.folio.marccat.business.common.View; import org.folio.marccat.dao.persistence.Descriptor; import org.folio.marccat.dao.persistence.PUBL_HDG; import java.util.List; /** * This class implements the browse specific methods * special to publishers when Publisher place is being browsed. * * @author paulm * @author carment */ public class PublisherPlaceDescriptorDAO extends PublisherDescriptorDAO { private static final String ORDER_BY_HDG_PLACE_SORT_FORM = " order by hdg.placeSortForm "; private static final String HDG_NAME_SORT_FORM = ", hdg.nameSortForm "; /** * Gets the persistent class. * * @return the persistent class */ @Override public Class getPersistentClass() { return PUBL_HDG.class; } /** * Gets the headings by sortform. * * @param operator the operator * @param direction the direction * @param term the term * @param filter the filter * @param cataloguingView the cataloguing view * @param count the count * @param session the session * @return the headings by sortform * @throws HibernateException the hibernate exception */ @Override public List<Descriptor> getHeadingsBySortform(final String operator, final String direction, final String term, String filter, final int cataloguingView, final int count, final Session session) throws HibernateException { return getSortformBySearchTerm(operator, direction, term, filter, cataloguingView, count, session); } /** * Gets the sortform by search term. * * @param operator the operator * @param direction the direction * @param term the term * @param filter the filter * @param cataloguingView the cataloguing view * @param count the count * @param session the session * @return the sortform by one search term * @throws HibernateException the hibernate exception */ private List<Descriptor> getSortformBySearchTerm(final String operator, final String direction, final String term, final String filter, final int cataloguingView, final int count, final Session session) throws HibernateException { Query q = session.createQuery( "from " + getPersistentClass().getName() + " as hdg where hdg.placeSortForm " + operator + " :term and " + " hdg.key.userViewString = '" + View.makeSingleViewString(cataloguingView) + "' " + filter + ORDER_BY_HDG_PLACE_SORT_FORM + direction + HDG_NAME_SORT_FORM + direction); q.setString("term", term); q.setMaxResults(count); List<Descriptor> publisherList = q.list(); publisherList = (List<Descriptor>) isolateViewForList(publisherList, cataloguingView, session); return publisherList; } /** * Gets the browsing sort form. * * @param descriptor the descriptor * @return the browsing sort form */ @Override public String getBrowsingSortForm(final Descriptor descriptor) { if (!(descriptor instanceof PUBL_HDG)) { throw new IllegalArgumentException(); } final PUBL_HDG publisher = (PUBL_HDG) descriptor; return new StringBuilder() .append(publisher.getPlaceSortForm()) .append(" : ").append(publisher.getNameSortForm()).toString(); } }
32.063636
204
0.683017
2e0c46468b0407d642f75ba728165f3aa5b21e69
245
package com.violetbeach.daengbu.controller.v1.command; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(chain = true) public class ChangePasswordCommand { private String newPassword; private String oldPassword; }
18.846154
54
0.808163
9819cf090aab86cf41b37ab451bf4af5c45dddbe
439
package com.cesi.ressourcesrelationnelles.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @NoArgsConstructor @AllArgsConstructor @Data @Document(collection = "Statistic") public class Statistic { @Id private String id; private Long resourceId; private int nbVues; }
21.95
62
0.8041
48f206e7b99eb748988a50fa2c1bf37977077162
271
package com.jcodes.mongodb; public class Home { private String address; public Home(String address) { super(); this.address = address; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
15.055556
41
0.701107
f70910dd9a7c1c0f560350c45f6053ea5b6b517a
835
package io.smallrye.reactive.messaging.amqp.fault; import static io.smallrye.reactive.messaging.amqp.i18n.AMQPLogging.log; import java.util.concurrent.CompletionStage; import io.smallrye.reactive.messaging.amqp.AmqpMessage; import io.smallrye.reactive.messaging.amqp.ConnectionHolder; import io.vertx.mutiny.core.Context; public class AmqpFailStop implements AmqpFailureHandler { private final String channel; public AmqpFailStop(String channel) { this.channel = channel; } @Override public <V> CompletionStage<Void> handle(AmqpMessage<V> msg, Context context, Throwable reason) { // We mark the message as rejected and fail. log.nackedFailMessage(channel); return ConnectionHolder.runOnContextAndReportFailure(context, reason, () -> msg.getAmqpMessage().rejected()); } }
32.115385
117
0.755689
e7ded1c16c989718282b8cbd665ece6f112442c9
14,411
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode.bookkeeper; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.LedgerEntry; import org.apache.bookkeeper.client.LedgerHandle; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import static org.apache.hadoop.hdfs.server.namenode.bookkeeper.BookKeeperJournalManager.bkException; import static org.apache.hadoop.hdfs.server.namenode.bookkeeper.zk.ZkUtil.interruptedException; /** * A {@link InputStream} over a BookKeeper ledger which maps to a specific * edit log segment. */ public class BookKeeperJournalInputStream extends InputStream { private static final Log LOG = LogFactory.getLog(BookKeeperJournalInputStream.class); // BookKeeper ledger is mutable as the ledger may need to be re-opened // by the caller in order to find the true end for tailing private LedgerHandle ledger; // This is not txId, this is the id of the first ledger entry private final long firstLedgerEntryId; // Maximum ledger entry id seen so far. In an in-progress edit log // stream this changes over time private long maxLedgerEntryIdSeen; private InputStream entryStream; // Keep track of the current state (see the InputStreamState inner // class for more detailed information) and the "last known good" state // (updated by calling savePosition()). private InputStreamState currentStreamState; private InputStreamState savedStreamState; static class InputStreamState { private long offsetInLedger; // How many bytes have we read from this ledger private long readerPosition; // How many bytes has the reader read private long nextLedgerEntryId; // Next ledger entry id to read private int offsetInEntry; // Bytes read from the current ledger entry InputStreamState() { offsetInLedger = 0; offsetInEntry = 0; } /** * Create a copy of another state object. Used to save the current state. */ static InputStreamState copyOf(InputStreamState state) { InputStreamState copyState = new InputStreamState(); copyState.setNextLedgerEntryId(state.getNextLedgerEntryId()); copyState.setOffsetInEntry(state.getOffsetInEntry()); copyState.setOffsetInLedger(state.getOffsetInLedger()); copyState.setReaderPosition(state.getReaderPosition()); return copyState; } long getOffsetInLedger() { return offsetInLedger; } void setOffsetInLedger(long offsetInLedger) { this.offsetInLedger = offsetInLedger; } void advanceOffsetInLedger(long numBytes) { offsetInLedger += numBytes; } long getReaderPosition() { return readerPosition; } void setReaderPosition(long readerPosition) { this.readerPosition = readerPosition; } long getNextLedgerEntryId() { return nextLedgerEntryId; } void incrementNextLedgerEntryId() { this.nextLedgerEntryId++; } void setNextLedgerEntryId(long nextLedgerEntryId) { this.nextLedgerEntryId = nextLedgerEntryId; } int getOffsetInEntry() { return offsetInEntry; } void setOffsetInEntry(int offsetInEntry) { this.offsetInEntry = offsetInEntry; } void advanceOffsetInEntry(long numBytes) { offsetInEntry += numBytes; } } /** * Create an input stream object for a specified BookKeper ledger * @param ledger The initial ledger instance * @param firstLedgerEntryId First ledger entry id (this is different from * HDFS transaction id!) to read from the ledger. */ public BookKeeperJournalInputStream(LedgerHandle ledger, long firstLedgerEntryId) { this.ledger = ledger; this.firstLedgerEntryId = firstLedgerEntryId; maxLedgerEntryIdSeen = ledger.getLastAddConfirmed(); currentStreamState = new InputStreamState(); currentStreamState.setNextLedgerEntryId(firstLedgerEntryId); } @Override public int read() throws IOException { byte[] data = new byte[1]; if (read(data, 0, 1) != 1) { return -1; } return data[0]; } // Once we've reached the end of an entry stream, we want to open // a new stream for a new ledger entry private InputStream nextEntryStream() throws IOException { long nextLedgerEntryId = currentStreamState.getNextLedgerEntryId(); if (nextLedgerEntryId > maxLedgerEntryIdSeen) { updateMaxLedgerEntryIdSeen(); if (nextLedgerEntryId > maxLedgerEntryIdSeen) { // Return null if we've reached the end of the ledger: we can not // read beyond the end of the ledger and it is up to the caller to // either find the new "tail" of the ledger (if the ledger is in- // progress) or open the next ledger (if the ledger is finalized) if (LOG.isDebugEnabled()) { LOG.debug("Requesting to ledger entryId " + nextLedgerEntryId + ", but "+ " maxLedgerEntryIdSeen is " + maxLedgerEntryIdSeen + ", ledger length is " + ledger.getLength()); } return null; } } try { Enumeration<LedgerEntry> entries = ledger.readEntries(nextLedgerEntryId, nextLedgerEntryId); currentStreamState.incrementNextLedgerEntryId(); if (entries.hasMoreElements()) { LedgerEntry entry = entries.nextElement(); if (entries.hasMoreElements()) { throw new IllegalStateException("More than one entry retrieved!"); } currentStreamState.setOffsetInEntry(0); return entry.getEntryInputStream(); } } catch (BKException e) { throw new IOException("Unrecoverable BookKeeper error reading entry " + nextLedgerEntryId, e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted reading BookKeeper entry " + nextLedgerEntryId, e); } return null; } /** * Change the underlying ledger object in order to be able to correctly * determine the "tail" of the ledger. * @param ledger The new ledger object */ public void resetLedger(LedgerHandle ledger) throws IOException { this.ledger = ledger; updateMaxLedgerEntryIdSeen(); } /** * Set <code>maxLedgerEntryIdSeen</code> to the maximum of last confirmed * entry-id from a quorum of bookies and last confirmed entry-id from * metadata stored in ZooKeeper. The reason is to handle the case of * when a ledger becomes finalized mid-flight: in this case last confirmed * entry-id that is read from a quorum is no longer reliable, but a reliable * last-confirmed entry-id is now available in ZooKeeper metadata which is * updated when a ledger is finalized. * @throws IOException If there's an error talking to BookKeeper * or ZooKeeper */ private void updateMaxLedgerEntryIdSeen() throws IOException { long lcFromMetadata = ledger.getLastAddConfirmed(); long lcFromQuorum; try { lcFromQuorum = ledger.readLastConfirmed(); } catch (BKException e) { bkException("Unable to read last confirmed ledger entry id " + "from ledger " + ledger.getId(), e); return; } catch (InterruptedException e) { interruptedException("Interrupted reading last confirmed ledger " + "entry id from ledger " + ledger.getId(), e); return; } long newMaxLedgerEntryIdSeen = Math.max(lcFromMetadata, lcFromQuorum); if (newMaxLedgerEntryIdSeen > maxLedgerEntryIdSeen) { if (LOG.isDebugEnabled()) { LOG.debug("Resetting maxLedgerEntryIdSeen from " + maxLedgerEntryIdSeen + " to " + newMaxLedgerEntryIdSeen); } maxLedgerEntryIdSeen = newMaxLedgerEntryIdSeen; } } /** * Preserve the state associated with the specified reader position * (meant for use with {@link #position(long)} * @param position The external reader position associated with the * current ledger state. */ public void savePosition(long position) { currentStreamState.setReaderPosition(position); savedStreamState = InputStreamState.copyOf(currentStreamState); } /** * "Go back" to the specified reader position by resetting the reader * a saved state associated with that position. * @param position The reader position we want to go back to * @throws IllegalArgumentException If an illegal position is specified * @throws IOException If there is an error communicating with BookKeeper */ public void position(long position) throws IOException { if (position == 0) { currentStreamState.setNextLedgerEntryId(firstLedgerEntryId); currentStreamState.setOffsetInEntry(0); entryStream = null; } else if (savedStreamState == null || position != savedStreamState.getReaderPosition()) { // Seek to an arbitrary position through "brute force" if (position > Integer.MAX_VALUE) { throw new IllegalArgumentException("Asked to position to " + position + ", but can only \"brute-force\" skip up" + Integer.MAX_VALUE); } position(0); skip(position, (int) position); } else { // savedStream != null && position == savedStream.getReaderPosition() int bytesToSkip = 0; if (savedStreamState.getOffsetInLedger() > position) { // Since reading from the input stream is buffered, we usually will // read further into the ledger than the reader has actually // read into. In this case we will need to find out exactly *what* // position within the ledger entry matches with the reader's last // known good position. long entryStartPosition = savedStreamState.getOffsetInLedger() - savedStreamState.getOffsetInEntry(); bytesToSkip = (int) (position - entryStartPosition); } else if (savedStreamState.getOffsetInLedger() < position) { throw new IllegalArgumentException("Saved offset in ledger (" + savedStreamState.getOffsetInLedger() + ") < position(" + position + ")"); } long nextLedgerEntryId = savedStreamState.getNextLedgerEntryId() == firstLedgerEntryId ? firstLedgerEntryId : (savedStreamState.getNextLedgerEntryId() - 1); currentStreamState.setNextLedgerEntryId(nextLedgerEntryId); if (bytesToSkip > 0) { entryStream = null; skip(position, bytesToSkip); } else { if (currentStreamState.getNextLedgerEntryId() > 0) { currentStreamState.setNextLedgerEntryId(currentStreamState.getNextLedgerEntryId() - 1); } entryStream = nextEntryStream(); } } currentStreamState.setOffsetInLedger(position); } private void skip(long position, int bytesToSkip) throws IOException { // Read further into the ledger such that our position matches the // position last consumed by the reader. Discard the data read. LOG.info("Attempting to skip " + bytesToSkip + " bytes to get to position " + position); byte[] data = new byte[bytesToSkip]; int skipped; if ((skipped = read(data, 0, bytesToSkip)) != bytesToSkip) { throw new IllegalStateException("Could not skip to position " + position + ", tried to read " + bytesToSkip + " but only read " + skipped + " bytes!"); } } @Override public int read(byte[] buf, int off, int len) throws IOException { int bytesRead = readInternal(buf, off, len); currentStreamState.advanceOffsetInLedger(bytesRead); return bytesRead; } private int readInternal(byte[] buf, int off, int len) throws IOException { if (maxLedgerEntryIdSeen == -1) { // If this is an in-progress ledger, find out the true "tail" of the // ledger maxLedgerEntryIdSeen = ledger.getLastAddConfirmed(); if (maxLedgerEntryIdSeen == -1) { // Nothing has been added to the ledger return 0; } } if (entryStream == null) { // If we are the end of the current entry, fetch the next one entryStream = nextEntryStream(); if (entryStream == null) { // We are the end of the ledger return 0; } } // The calling classes may want to read a sequence of bytes that is // spread across multiple ledger entries. In this case, we will need to // in a loop: maintain the number of bytes read so far (the offset into // the buffer), when we reach the end of the current ledger entry, use // nextEntryStream() to begin reading the next ledger entry int bytesReadTotal = 0; while (bytesReadTotal < len) { int bytesReadLast = entryStream.read(buf, off + bytesReadTotal, len - bytesReadTotal); if (bytesReadLast == -1) { entryStream = nextEntryStream(); if (entryStream == null) { return bytesReadTotal; } } else { currentStreamState.advanceOffsetInEntry(bytesReadLast); bytesReadTotal += bytesReadLast; } } return bytesReadTotal; } public long getLedgerLength() { return ledger.getLength(); } public String getLedgerName() { return ledger.toString(); } public void close() throws IOException { try { ledger.close(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted during close()", e); } catch (BKException e) { throw new IOException("BookKeeper error during close()", e); } } }
37.237726
101
0.68753
71780930032aec2a6c5ab7242f83d15acb02f250
1,715
package com.thanos.contract.mockserver.infrastructure.dto; import com.thanos.contract.mockserver.domain.mockserver.model.Contract; import com.thanos.contract.mockserver.domain.mockserver.model.ContractField; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import java.util.*; @Getter @Setter @NoArgsConstructor @ToString public class ContractFileDTO { String name; String version; String consumer; Map<String, String> schema; LinkedHashMap<String, String> req; LinkedHashMap<String, String> res; public static List<Contract> buildFrom(Iterable<Object> ymlResult) { final List<Contract> result = new ArrayList<>(); for (Object record : ymlResult) { if (record instanceof ContractFileDTO) { result.add(((ContractFileDTO) record).toContract()); } } return result; } public Contract toContract() { LinkedList<ContractField> request = buildContractFieldList(req); LinkedList<ContractField> response = buildContractFieldList(res); String schemaIndex = schema.get("provider") + "-" + schema.get("name") + "-" + schema.get("version"); return new Contract(name, version, schemaIndex, consumer, schema.get("provider"), request, response); } LinkedList<ContractField> buildContractFieldList(LinkedHashMap<String, String> originDtoMap) { LinkedList<ContractField> result = new LinkedList<>(); for (String key : originDtoMap.keySet()) { String content = originDtoMap.get(key); result.add(new ContractField(key, content)); } return result; } }
32.358491
109
0.6793
4215aa398acbc154bc98926d5499866c20ca96a9
542
/* * This snippet shows how to get an environment variable * (e.g. the PATH environment variable here). * * For more information, read "Le guide de survie Java" (chap. 2) * (by Timothy Fisher, ed. CampusPress). * * Usage: * - compile: javac EnvironmentVariables.java * - execute: java EnvironmentVariables */ public class EnvironmentVariables { public static void main(String [] args) { // Get the PATH environment variable String envPath = System.getenv("PATH"); System.out.println(envPath); } }
24.636364
65
0.673432
25f5ce418538c1ac4ec72a1b79eb84d5d3efb63e
1,504
package player.project.com.musicplayer.Controllers; import android.content.Context; import android.content.SharedPreferences; import player.project.com.musicplayer.Ultilities.Constant; /** * Created by Cuong on 2/4/2018. */ public class SettingManager { int sMode; int rMode; Context context; private static class SettingMangagerHolder { static SettingManager instance = new SettingManager(); } public static SettingManager getInstance(Context context) { SettingMangagerHolder.instance.context = context; return SettingMangagerHolder.instance; } public int getsMode() { SharedPreferences settings = context.getSharedPreferences("PlayerMode", 0); return settings.getInt("shuffle", Constant.SETTING_SHUFFLE_MODE_OFF); } public int getrMode() { SharedPreferences settings = context.getSharedPreferences("PlayerMode", 0); return settings.getInt("repeat", Constant.SETTING_REPEAT_MODE_OFF); } public void setsMode(int mode) { SharedPreferences settings = context.getSharedPreferences("PlayerMode", 0); SharedPreferences.Editor editor = settings.edit(); editor.putInt("shuffle", mode); editor.commit(); } public void setrMode(int mode) { SharedPreferences settings = context.getSharedPreferences("PlayerMode", 0); SharedPreferences.Editor editor = settings.edit(); editor.putInt("repeat", mode); editor.commit(); } }
29.490196
83
0.700133
ba369fe5e088cb1d77b2d96d1d6da62604cab5b3
480
/* * 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 edu.eci.arsw.parcial.services; import java.io.IOException; /** * * @author 2110111 */ public interface HttpConnection { /** * * @param city * @return * @throws IOException */ public StringBuffer getCityData(String city) throws IOException; }
20
79
0.670833
0dcb3a86f3747e9da68fd82e86b42e92b6caf594
1,004
package io.bokun.inventory.plugin.harness.validation; import javax.annotation.*; import com.google.inject.*; import io.bokun.inventory.common.api.grpc.*; /** * Ensures fields of given {@link Reservation} are set. * * @author Mindaugas Žakšauskas */ public final class ReservationValidator implements Validator<Reservation> { private final PassengerValidator passengerValidator; @Inject public ReservationValidator(PassengerValidator passengerValidator) { this.passengerValidator = passengerValidator; } /** * {@inheritDoc} */ @Nonnull @Override public ValidationResult validate(@Nonnull Reservation reservation) { return new ValidationResult.Builder() .assertNotEmpty(reservation.getRateId(), "rateId") .assertNotEmpty(reservation.getPassengersList(), "passengers") .assertElementsValid(reservation.getPassengersList(), passengerValidator, "passengers") .build(); } }
28.685714
103
0.696215
fc696a219696fab6b88abe8c0098a83799113daa
1,207
/* * File: KeyValuePair.java * Authors: Justin Basilico * Company: Sandia National Laboratories * Project: Cognitive Foundry * * Copyright November 28, 2010, Sandia Corporation. * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive * license for use of this work by or on behalf of the U.S. Government. Export * of this program may require a license from the United States Government. * See CopyrightHistory.txt for complete details. * */ package gov.sandia.cognition.util; /** * Represents a key-value pair. The key is the first element in the pair and * the value is the second. * * @param <KeyType> * The type of the key. * @param <ValueType> * The type of the value. * @author Justin Basilico * @since 3.1 */ public interface KeyValuePair<KeyType, ValueType> extends Pair<KeyType, ValueType> { /** * Gets the key part of the key-value pair. * * @return * The key. */ public KeyType getKey(); /** * Gets the value part of the key-value pair. * * @return * The value. */ public ValueType getValue(); }
24.14
78
0.618061
72ce0cac28872877f42a6d1784b81b31239d7529
14,254
package com.fence.airdrop.service; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.support.annotation.Nullable; import android.text.TextUtils; import com.fence.airdrop.observer.ApkPublisher; import com.koushikdutta.async.AsyncServer; import com.koushikdutta.async.http.body.MultipartFormDataBody; import com.koushikdutta.async.http.body.UrlEncodedFormBody; import com.koushikdutta.async.http.server.AsyncHttpServer; import com.koushikdutta.async.http.server.AsyncHttpServerRequest; import com.koushikdutta.async.http.server.AsyncHttpServerResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.DecimalFormat; public class WebService extends Service { private static final String ACTION_START_WEB_SERVICE = "com.fence.airdrop.action.START_WEB_SERVICE"; private static final String ACTION_STOP_WEB_SERVICE = "com.fence.airdrop.action.STOP_WEB_SERVICE"; private static final String CSS_CONTENT_TYPE = "text/css;charset=utf-8"; private static final String JS_CONTENT_TYPE = "application/javascript"; private static final String PNG_CONTENT_TYPE = "application/x-png"; private static final String JPG_CONTENT_TYPE = "application/jpeg"; private static final String SWF_CONTENT_TYPE = "application/x-shockwave-flash"; private static final String WOFF_CONTENT_TYPE = "application/x-font-woff"; private static final String TTF_CONTENT_TYPE = "application/x-font-truetype"; private static final String SVG_CONTENT_TYPE = "image/svg+xml"; private static final String EOT_CONTENT_TYPE = "image/vnd.ms-fontobject"; private static final String MP3_CONTENT_TYPE = "audio/mp3"; private static final String MP4_CONTENT_TYPE = "video/mpeg4"; public static final int PORT = 8888; public static final String APK_DIR = Environment.getExternalStorageDirectory() + File.separator + "airdrop"; private AsyncHttpServer mServer = new AsyncHttpServer(); private AsyncServer mAsyncServer = new AsyncServer(); private FileUploadHolder mUploadHolder = new FileUploadHolder(); private FileHandler mHandler = new FileHandler(mUploadHolder); public static void start(Context context) { Intent intent = new Intent(context, WebService.class); intent.setAction(ACTION_START_WEB_SERVICE); context.startService(intent); } public static void stop(Context context) { Intent intent = new Intent(context, WebService.class); intent.setAction(ACTION_STOP_WEB_SERVICE); context.startService(intent); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { String action = intent.getAction(); if (ACTION_START_WEB_SERVICE.equals(action)) { startServer(); loadResources(); setQueryListener(); setUploadListener(); setDownloadListener(); setDeleteListener(); } else if (ACTION_STOP_WEB_SERVICE.equals(action)) { stopSelf(); } } return super.onStartCommand(intent, flags, startId); } private void startServer() { mServer.listen(mAsyncServer, PORT); } private void loadResources() { mServer.get("/images/.*", this::sendResources); mServer.get("/scripts/.*", this::sendResources); mServer.get("/css/.*", this::sendResources); mServer.get("/", (request, response) -> { try { response.send(getIndex()); } catch (IOException e) { e.printStackTrace(); response.code(500).end(); } }); } private String getIndex() throws IOException { BufferedInputStream bis = null; try { bis = new BufferedInputStream(getAssets().open("airdrop/index.html")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; byte[] tmp = new byte[10240]; while ((len = bis.read(tmp)) > 0) { baos.write(tmp, 0, len); } return new String(baos.toByteArray(), "utf-8"); } catch (IOException exception) { exception.printStackTrace(); throw exception; } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void sendResources(final AsyncHttpServerRequest request, final AsyncHttpServerResponse response) { try { String fullPath = request.getPath(); fullPath = fullPath.replace("%20", " "); String resourceName = fullPath; if (resourceName.startsWith("/")) { resourceName = resourceName.substring(1); } if (resourceName.indexOf("?") > 0) { resourceName = resourceName.substring(0, resourceName.indexOf("?")); } if (!TextUtils.isEmpty(getContentTypeByResourceName(resourceName))) { response.setContentType(getContentTypeByResourceName(resourceName)); } BufferedInputStream bInputStream = new BufferedInputStream(getAssets().open("airdrop/" + resourceName)); response.sendStream(bInputStream, bInputStream.available()); } catch (IOException e) { e.printStackTrace(); response.code(404).end(); return; } } private String getContentTypeByResourceName(String resourceName) { if (resourceName.endsWith(".css")) { return CSS_CONTENT_TYPE; } else if (resourceName.endsWith(".js")) { return JS_CONTENT_TYPE; } else if (resourceName.endsWith(".swf")) { return SWF_CONTENT_TYPE; } else if (resourceName.endsWith(".png")) { return PNG_CONTENT_TYPE; } else if (resourceName.endsWith(".jpg") || resourceName.endsWith(".jpeg")) { return JPG_CONTENT_TYPE; } else if (resourceName.endsWith(".woff")) { return WOFF_CONTENT_TYPE; } else if (resourceName.endsWith(".ttf")) { return TTF_CONTENT_TYPE; } else if (resourceName.endsWith(".svg")) { return SVG_CONTENT_TYPE; } else if (resourceName.endsWith(".eot")) { return EOT_CONTENT_TYPE; } else if (resourceName.endsWith(".mp3")) { return MP3_CONTENT_TYPE; } else if (resourceName.endsWith(".mp4")) { return MP4_CONTENT_TYPE; } return ""; } private void setUploadListener() { mServer.post("/files", (request, response) -> { MultipartFormDataBody body = (MultipartFormDataBody) request.getBody(); body.setMultipartCallback(part -> { if (part.isFile()) { body.setDataCallback((emitter, list) -> { mUploadHolder.write(list.getAllByteArray()); list.recycle(); }); } else { if (body.getDataCallback() == null) { body.setDataCallback((emitter, list) -> { try { String fileName = URLDecoder.decode(new String(list.getAllByteArray()), "UTF-8"); mUploadHolder.setFileName(fileName); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } list.recycle(); }); } } }); request.setEndCallback((Exception e) -> { mHandler.sendEmptyMessage(0); mUploadHolder.reset(); response.end(); }); } ); } private void setQueryListener() { mServer.get("/files", (request, response) -> { JSONArray array = new JSONArray(); File dir = new File(APK_DIR); if (!dir.exists() || !dir.isDirectory()) { return; } String[] fileNames = dir.list(); if (fileNames == null) { return; } for (String fileName : fileNames) { File file = new File(dir, fileName); if (!file.exists() || !file.isFile()) { continue; } try { DecimalFormat df = new DecimalFormat("0.00"); JSONObject jsonObject = new JSONObject(); jsonObject.put("name", fileName); long fileLen = file.length(); if (fileLen > 1024 * 1024) { jsonObject.put("size", df.format(fileLen * 1f / 1024 / 1024) + "MB"); } else if (fileLen > 1024) { jsonObject.put("size", df.format(fileLen * 1f / 1024) + "KB"); } else { jsonObject.put("size", fileLen + "B"); } array.put(jsonObject); } catch (JSONException e) { e.printStackTrace(); } } response.send(array.toString()); }); } private void setDownloadListener() { mServer.get("/files/.*", (request, response) -> { String path = request.getPath().replace("/files/", ""); try { path = URLDecoder.decode(path, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File file = new File(APK_DIR, path); if (file.exists() && file.isFile()) { try { response.getHeaders().add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } response.sendFile(file); return; } response.code(404).send("Not found!"); }); } private void setDeleteListener() { mServer.post("/files/.*", (request, response) -> { final UrlEncodedFormBody body = (UrlEncodedFormBody) request.getBody(); if ("delete".equalsIgnoreCase(body.get().getString("_method"))) { String path = request.getPath().replace("/files/", ""); try { path = URLDecoder.decode(path, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File file = new File(APK_DIR, path); if (file.exists() && file.isFile()) { file.delete(); Message message = mHandler.obtainMessage(-1); message.obj = file; mHandler.sendMessage(message); } } response.end(); }); } @Override public void onDestroy() { super.onDestroy(); if (mServer != null) { mServer.stop(); } if (mAsyncServer != null) { mAsyncServer.stop(); } } public class FileUploadHolder { private String mFileName; private File mFile; private BufferedOutputStream mOutputStream; private long mTotalSize; public void setFileName(String fileName) { mFileName = fileName; mTotalSize = 0; File dir = new File(APK_DIR); if (!dir.exists()) { dir.mkdirs(); } mFile = new File(APK_DIR, mFileName); try { mOutputStream = new BufferedOutputStream(new FileOutputStream(mFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void reset() { if (mOutputStream != null) { try { mOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } mOutputStream = null; } public void write(byte[] data) { if (mOutputStream != null) { try { mOutputStream.write(data); } catch (IOException e) { e.printStackTrace(); } } mTotalSize += data.length; } } private static class FileHandler extends Handler { private FileUploadHolder mHolder; public FileHandler(FileUploadHolder holder) { mHolder = holder; } @Override public void handleMessage(Message msg) { if (msg.what == 0) { // upload ApkPublisher.getInstance().setDeleteApk(false); ApkPublisher.getInstance().notify(mHolder.mFile); } else if (msg.what == -1) { // delete File file = (File) msg.obj; ApkPublisher.getInstance().setDeleteApk(true); ApkPublisher.getInstance().notify(file); } } } }
34.936275
138
0.545601
26532219811d952d02125402c216d089bb477a22
3,431
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util.extendable; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class UnmodifiableExtendableItem implements ExtendableItem { private final Map attributes = new HashMap(); private final Map unmodifiableAttributesView = Collections.unmodifiableMap(attributes); private final Map extraAttributes = new HashMap(); private final Map unmodifiableExtraAttributesView = Collections.unmodifiableMap(extraAttributes); /* * this is the only place where extra attributes are stored in qualified form. In all other maps * they are stored unqualified. */ private final Map qualifiedExtraAttributes = new HashMap(); private final Map unmodifiableQualifiedExtraAttributesView = Collections.unmodifiableMap(qualifiedExtraAttributes); public UnmodifiableExtendableItem(Map stdAttributes, Map extraAttributes) { if (stdAttributes != null) { this.attributes.putAll(stdAttributes); } if (extraAttributes != null) { for (Iterator iter = extraAttributes.entrySet().iterator(); iter.hasNext();) { Entry extraAtt = (Entry) iter.next(); setExtraAttribute((String) extraAtt.getKey(), (String) extraAtt.getValue()); } } } public String getAttribute(String attName) { return (String) attributes.get(attName); } public String getExtraAttribute(String attName) { String v = (String) qualifiedExtraAttributes.get(attName); if (v == null) { v = (String) extraAttributes.get(attName); } return v; } protected void setExtraAttribute(String attName, String attValue) { qualifiedExtraAttributes.put(attName, attValue); // unqualify att name if required int index = attName.indexOf(':'); if (index != -1) { attName = attName.substring(index + 1); } extraAttributes.put(attName, attValue); attributes.put(attName, attValue); } protected void setStandardAttribute(String attName, String attValue) { attributes.put(attName, attValue); } public Map getAttributes() { return unmodifiableAttributesView; } public Map getExtraAttributes() { return unmodifiableExtraAttributesView; } public Map getQualifiedExtraAttributes() { return unmodifiableQualifiedExtraAttributesView; } }
34.31
100
0.675896
d5805a443f2484956156028b202aa3063b8cfcbe
1,055
package Chapter9_ConstructorAndGC; import java.util.ArrayList; public class TestLifeSupportSim { public static void main(String[] args) { ArrayList list = new ArrayList(); V2Radiator v2 = new V2Radiator(list); // 5 個對象 System.out.println("------------------------------------"); V3Radiator v3 = new V3Radiator(list); // (上圖V2 的5個對象) + ( V3 繼承V2 而來的5個對象) + ( V3 自己的10個對象) } } class V2Radiator { public V2Radiator(ArrayList list) { for (int x = 0; x < 5; x++) { list.add(new SimUnit("V2Radiator")); } System.out.println(list); } } class V3Radiator extends V2Radiator { public V3Radiator(ArrayList list) { super(list); for (int x = 0; x < 10; x++) { list.add(new SimUnit("V3Radiator")); } System.out.println(list); } } class RetentionBot { public RetentionBot(ArrayList list) { list.add(new SimUnit("Retention")); } } class SimUnit { String botType; SimUnit(String type) { this.botType = type; } int powerUse() { if ("Retention".equals(this.botType)) { return 2; } else { return 4; } } }
18.508772
94
0.633175
2fc3cf639ca2d14a6ca691c18460f1a0151c2cd7
5,449
/*- * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.so.bpmn.infrastructure.validations; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import java.util.Optional; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; public class CloudRegionOrchestrationValidatorTest { private BuildingBlockExecution mockExecution; private CloudRegion cloudRegion; @Before public void setUp() { cloudRegion = new CloudRegion(); cloudRegion.setCloudOwner("CloudOwner"); cloudRegion.setLcpCloudRegionId("my-region-id"); GeneralBuildingBlock gbb = new GeneralBuildingBlock(); gbb.setCloudRegion(cloudRegion); mockExecution = mock(BuildingBlockExecution.class); doReturn(gbb).when(mockExecution).getGeneralBuildingBlock(); } @Test public void validateDisabledTest() { cloudRegion.setOrchestrationDisabled(true); CloudRegionOrchestrationValidator validation = new CloudRegionOrchestrationValidator(); Optional<String> result = validation.validate(mockExecution); assertEquals( "Error: The request has failed due to orchestration currently disabled for the target cloud region my-region-id for cloud owner CloudOwner", result.get()); } @Test public void validateNotDisabledTest() { cloudRegion.setOrchestrationDisabled(false); CloudRegionOrchestrationValidator validation = new CloudRegionOrchestrationValidator(); Optional<String> result = validation.validate(mockExecution); assertFalse(result.isPresent()); } @Test public void validateDisabledIsNullTest() { CloudRegionOrchestrationValidator validation = new CloudRegionOrchestrationValidator(); Optional<String> result = validation.validate(mockExecution); assertFalse(result.isPresent()); } @Test public void shouldRunForTest() { CloudRegionOrchestrationValidator validator = new CloudRegionOrchestrationValidator(); assertTrue(validator.shouldRunFor("ActivateNetworkBB")); assertTrue(validator.shouldRunFor("AssignNetworkBB")); assertTrue(validator.shouldRunFor("CreateNetworkBB")); assertTrue(validator.shouldRunFor("DeactivateNetworkBB")); assertTrue(validator.shouldRunFor("DeleteNetworkBB")); assertTrue(validator.shouldRunFor("UnassignNetworkBB")); assertTrue(validator.shouldRunFor("UpdateNetworkBB")); assertTrue(validator.shouldRunFor("ActivateVnfBB")); assertTrue(validator.shouldRunFor("AssignVnfBB")); assertTrue(validator.shouldRunFor("UnassignVnfBB")); assertTrue(validator.shouldRunFor("DeactivateVnfBB")); assertTrue(validator.shouldRunFor("ActivateVfModuleBB")); assertTrue(validator.shouldRunFor("AssignVfModuleBB")); assertTrue(validator.shouldRunFor("CreateVfModuleBB")); assertTrue(validator.shouldRunFor("DeactivateVfModuleBB")); assertTrue(validator.shouldRunFor("DeleteVfModuleBB")); assertTrue(validator.shouldRunFor("UnassignVfModuleBB")); assertTrue(validator.shouldRunFor("ActivateVolumeGroupBB")); assertTrue(validator.shouldRunFor("AssignVolumeGroupBB")); assertTrue(validator.shouldRunFor("CreateVolumeGroupBB")); assertTrue(validator.shouldRunFor("DeactivateVolumeGroupBB")); assertTrue(validator.shouldRunFor("DeleteVolumeGroupBB")); assertTrue(validator.shouldRunFor("UnassignVolumeGroupBB")); assertTrue(validator.shouldRunFor("ActivateFabricConfigurationBB")); assertTrue(validator.shouldRunFor("AssignFabricConfigurationBB")); assertTrue(validator.shouldRunFor("UnassignFabricConfigurationBB")); assertTrue(validator.shouldRunFor("DeactivateFabricConfigurationBB")); assertFalse(validator.shouldRunFor("AssignServiceInstanceBB")); assertFalse(validator.shouldRunFor("AAICheckVnfInMaintBB")); assertFalse(validator.shouldRunFor("ChangeModelVfModuleBB")); assertFalse(validator.shouldRunFor("CreateNetworkCollectionBB")); } }
46.177966
156
0.701964
72b342031c3202b02b86be2ec85a42dfef8d006b
1,652
package com.macro.mall.controller; import com.macro.mall.common.api.CommonResult; import com.macro.mall.model.PmsSkuStock; import com.macro.mall.service.PmsSkuStockService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * sku inventory controller * Created by macro on 2018/4/27. */ @Controller @Api(tags = "PmsSkuStockController", description = "sku commodity inventory management") @RequestMapping("/sku") public class PmsSkuStockController { @Autowired private PmsSkuStockService skuStockService; @ApiOperation("Fuzzy search for sku inventory based on product number and number") @RequestMapping(value = "/{pid}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsSkuStock>> getList(@PathVariable Long pid, @RequestParam(value = "keyword", required = false) String keyword) { List<PmsSkuStock> skuStockList = skuStockService.getList(pid, keyword); return CommonResult.success(skuStockList); } @ApiOperation("Bulk Update Inventory Information") @RequestMapping(value = "/update/{pid}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long pid, @RequestBody List<PmsSkuStock> skuStockList) { int count = skuStockService.update(pid, skuStockList); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } }
36.711111
143
0.736683
d3be12d555dd3392539faae7bb9317f8770bcdd5
5,775
package com.ruoyi.project.compdata.productPrincipal.service.impl; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.ShiroUtils; import com.ruoyi.project.compdata.productPrincipal.mapper.ProductPrincipalMapper; import com.ruoyi.project.compdata.productPrincipal.domain.ProductPrincipal; import com.ruoyi.project.compdata.productPrincipal.service.IProductPrincipalService; import com.ruoyi.common.utils.text.Convert; /** * 产品负责人映射Service业务层处理 * * @author Beignet * @date 2021-02-23 */ @Service public class ProductPrincipalServiceImpl implements IProductPrincipalService { private static final Logger log = LoggerFactory.getLogger(ProductPrincipal.class); @Autowired private ProductPrincipalMapper productPrincipalMapper; /** * 查询产品负责人映射 * * @param id 产品负责人映射ID * @return 产品负责人映射 */ @Override public ProductPrincipal selectProductPrincipalById(Long id) { return productPrincipalMapper.selectProductPrincipalById(id); } /** * 查询产品负责人映射列表 * * @param productPrincipal 产品负责人映射 * @return 产品负责人映射 */ @Override public List<ProductPrincipal> selectProductPrincipalList(ProductPrincipal productPrincipal) { return productPrincipalMapper.selectProductPrincipalList(productPrincipal); } /** * 新增产品负责人映射 * * @param productPrincipal 产品负责人映射 * @return 结果 */ @Override public int insertProductPrincipal(ProductPrincipal productPrincipal) { return productPrincipalMapper.insertProductPrincipal(productPrincipal); } /** * 修改产品负责人映射 * * @param productPrincipal 产品负责人映射 * @return 结果 */ @Override public int updateProductPrincipal(ProductPrincipal productPrincipal) { return productPrincipalMapper.updateProductPrincipal(productPrincipal); } /** * 删除产品负责人映射对象 * * @param ids 需要删除的数据ID * @return 结果 */ @Override public int deleteProductPrincipalByIds(String ids) { return productPrincipalMapper.deleteProductPrincipalByIds(Convert.toStrArray(ids)); } /** * 删除产品负责人映射信息 * * @param id 产品负责人映射ID * @return 结果 */ @Override public int deleteProductPrincipalById(Long id) { return productPrincipalMapper.deleteProductPrincipalById(id); } /** * 导入产品负责人映射 * * @param productPrincipalList 产品负责人映射List数据 * @return 导入结果 */ @Override public String importProductPrincipal(List<ProductPrincipal> productPrincipalList, boolean isUpdateSupport) { //TODO 此方法为模板生成,需要完善,完善后请将此注释删除或修改 if (StringUtils.isNull(productPrincipalList) || productPrincipalList.size() == 0) { throw new BusinessException("导入数据不能为空!"); } int successNum = 0; int failureNum = 0; StringBuilder successMsg = new StringBuilder(); StringBuilder failureMsg = new StringBuilder(); String operName = ShiroUtils.getLoginName(); for (ProductPrincipal productPrincipal : productPrincipalList) { try { // 验证数据是否已经 ProductPrincipal domain = productPrincipalMapper.selectProductPrincipalByOnlyCondition(productPrincipal); if (domain==null) { productPrincipal.setCreateBy(operName); productPrincipal.setCreateTime(new Date()); this.insertProductPrincipal(productPrincipal); successNum++; successMsg.append("<br/>" + successNum + "、"+ productPrincipal.getSku()+" 的数据导入成功"); } else if (isUpdateSupport) { productPrincipal.setUpdateBy(operName); productPrincipal.setUpdateTime(new Date()); productPrincipalMapper.updateProductPrincipalByOnlyCondition(productPrincipal); successNum++; successMsg.append("<br/>" + successNum + "、" + productPrincipal.getSku()+" 的数据更新成功"); } else { failureNum++; failureMsg.append("<br/>" + failureNum + "、" + productPrincipal.getSku()+" 的数据已存在"); } } catch (Exception e) { failureNum++; String msg = "<br/>" + failureNum + "、" + productPrincipal.getSku()+" 的数据导入失败:"; failureMsg.append(msg + e.getMessage()); log.error(msg, e); } } if (failureNum > 0) { failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:"); throw new BusinessException(failureMsg.toString()); } else { successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); } return successMsg.toString(); } @Override public Map<String, ProductPrincipal> getProductPrincipalMap() { List<ProductPrincipal> productPrincipalList = this.selectProductPrincipalList(null); Map<String, ProductPrincipal> maps = productPrincipalList.stream().collect(Collectors.toMap(ProductPrincipal::getPlatformSku, Function.identity())); return maps; } }
31.906077
156
0.634459
2fb53df7c2740293430362f8d6f506edbca3b162
1,419
package com.example.controlbank.activity.detail; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.annotation.Nullable; import com.example.controlbank.R; import com.example.controlbank.activity.base.BaseActivity; import com.example.controlbank.view.CommonDialog; public class DialogActivity extends BaseActivity implements View.OnClickListener { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dialog_layout); mContext = getApplicationContext(); Button btn = (Button)findViewById(R.id.button); btn.setOnClickListener(this); } @Override public void onClick(View view) { switch(view.getId()){ case R.id.button: CommonDialog dialog = new CommonDialog( DialogActivity.this ,"这是一个封装好的Dialog", "这是内容", "左部button", "右部button", new CommonDialog.DialogClickListener() { @Override public void onDialogClick() { //时间监听处理 Toast.makeText(getApplicationContext(),"你点击了左边",Toast.LENGTH_LONG).show(); } }); dialog.show(); break; } } }
30.847826
167
0.650458
7c39c4fb183db7b3c94f3dff68c34a5c700b0db8
3,843
package at.ac.tuwien.inso.ticketline.server.unittest.service; import at.ac.tuwien.inso.ticketline.dao.EmployeeDao; import at.ac.tuwien.inso.ticketline.model.Employee; import at.ac.tuwien.inso.ticketline.model.Permission; import at.ac.tuwien.inso.ticketline.server.exception.ServiceException; import at.ac.tuwien.inso.ticketline.server.service.implementation.SimpleAdminService; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * @author Alexander Poschenreithner (1328924) */ public class AdminServiceTest { @Rule public ExpectedException exception = ExpectedException.none(); private SimpleAdminService service = null; private List<Employee> employees = null; @Before public void setUp() throws Exception { service = new SimpleAdminService(); employees = new ArrayList<>(); Employee e1 = new Employee("firstname1", "lastname1", "username1", "password1"); e1.setInsuranceNumber("1"); e1.setPermission(Permission.ROLE_USER); e1.setId(1); employees.add(e1); Employee e2 = new Employee("firstname2", "lastname2", "username2", "password2"); e2.setInsuranceNumber("2"); e2.setPermission(Permission.ROLE_USER); e2.setId(2); employees.add(e2); Employee e3 = new Employee("firstname3", "lastname3", "username3", "password3"); e3.setInsuranceNumber("3"); e3.setPermission(Permission.ROLE_USER); e3.setId(3); employees.add(e3); Employee e4 = new Employee("firstname4", "lastname4", "username4", "password4"); e4.setInsuranceNumber("4"); e4.setPermission(Permission.ROLE_USER); e4.setId(4); employees.add(e4); Employee e5 = new Employee("firstname5", "lastname5", "username5", "password5"); e5.setInsuranceNumber("5"); e5.setPermission(Permission.ROLE_USER); e5.setId(5); employees.add(e5); } @Test public void getAllEmployees() { EmployeeDao dao = Mockito.mock(EmployeeDao.class); Mockito.when(dao.findAll()).thenReturn(employees); service.setEmployeeDao(dao); try { assertEquals(5, service.getAllEmployees().size()); } catch (ServiceException e) { fail("ServiceException thrown"); } } @Test public void getAllEmployees_NoDb() throws Exception { EmployeeDao dao = Mockito.mock(EmployeeDao.class); Mockito.when(dao.findAll()).thenThrow(new RuntimeException("No DB")); service.setEmployeeDao(dao); exception.expect(ServiceException.class); service.getAllEmployees(); } @Test public void getPageCount() throws Exception { EmployeeDao dao = Mockito.mock(EmployeeDao.class); Mockito.when(dao.count()).thenReturn(100L); service.setEmployeeDao(dao); assertEquals("According to 20 Entries per page, we expect 5", 5, service.getPageCount()); } @Test public void getPageCount_new_page_for_101() throws Exception { EmployeeDao dao = Mockito.mock(EmployeeDao.class); Mockito.when(dao.count()).thenReturn(101L); service.setEmployeeDao(dao); assertEquals("According to 20 Entries per page, we expect 6", 6, service.getPageCount()); } @Test public void getPageCount_for_0_entries() throws Exception { EmployeeDao dao = Mockito.mock(EmployeeDao.class); Mockito.when(dao.count()).thenReturn(0L); service.setEmployeeDao(dao); assertEquals("For 0 records we expect 0 pages", 0, service.getPageCount()); } }
32.846154
97
0.671611
7ee5b38c1d14d647a6b84a1becb3f6fa4116ae53
1,025
package com.artemis.io; import com.artemis.Component; import com.artemis.utils.Bag; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; public class TransmuterEntrySerializer implements Json.Serializer<ArchetypeMapper.TransmuterEntry> { SaveFileFormat.ComponentIdentifiers identifiers; @Override public void write(Json json, ArchetypeMapper.TransmuterEntry object, Class knownType) { json.writeArrayStart(); for (int i = 0; i < object.componentTypes.size(); i++) { Class<? extends Component> type = object.componentTypes.get(i); String name = identifiers.typeToName.get(type); json.writeValue(name); } json.writeArrayEnd(); } @Override public ArchetypeMapper.TransmuterEntry read(Json json, JsonValue jsonData, Class type) { Bag components = new Bag(); for (JsonValue child = jsonData.child; child != null; child = child.next) components.add(identifiers.getType(json.readValue(String.class, child))); return new ArchetypeMapper.TransmuterEntry(components); } }
32.03125
100
0.765854
746a58566f3e14c294fa8fcb2a097edcdcfd2ac3
1,642
package com.sunit.global.singleLogin.po; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * * * 类名称:ClusterSingleLogin * 类描述: 用于记录当前登录用户的sessionId,保证每个用户只能有一个sessionId 处于可用状态 * 创建人:Administrator * 创建时间:Nov 14, 2013 9:14:57 AM * 修改人:joye * 修改时间:Nov 14, 2013 9:14:57 AM * 修改备注: * @version * */ @Entity @Table(name = "TB_CLUSTERSINGLELOGIN") public class ClusterSingleLogin { private String id; private String account; private String sessionId; private String lastDate; private Integer tryCount; @GenericGenerator(name = "generator", strategy = "uuid") @Id @GeneratedValue(generator = "generator") @Column(name = "ID", unique = true, nullable = false, length = 32) public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "ACCOUNT", length = 500) public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } @Column(name = "SESSIONID", length = 500) public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "LASTDATE", length = 30) public String getLastDate() { return lastDate; } public void setLastDate(String lastDate) { this.lastDate = lastDate; } public Integer getTryCount() { return tryCount; } @Column(name = "TRYCOUNT") public void setTryCount(Integer tryCount) { this.tryCount = tryCount; } }
21.893333
67
0.714373
f44af97bacba9669885b080765a890634aa1fbac
9,073
/** * Copyright 2017 Syncleus, Inc. * with portions copyright 2004-2017 Bo Zimmerman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.syncleus.aethermud.game.Commands; import com.syncleus.aethermud.game.Areas.interfaces.Area; import com.syncleus.aethermud.game.Areas.interfaces.Area.Stats; import com.syncleus.aethermud.game.MOBS.interfaces.MOB; import com.syncleus.aethermud.game.core.*; import com.syncleus.aethermud.game.core.collections.IteratorEnumeration; import com.syncleus.aethermud.game.core.interfaces.SpaceObject; import java.util.*; public class Areas extends StdCommand { private final String[] access = I(new String[]{"AREAS"}); public Areas() { } @Override public String[] getAccessWords() { return access; } @Override public boolean execute(MOB mob, List<String> commands, int metaFlags) throws java.io.IOException { String expression = null; Enumeration<Area> a = CMLib.map().areas(); int addStat = -1; String append = ""; int numCols = 3; for (int i = 1; i < commands.size(); i++) { final String s = commands.get(i); if (s.toUpperCase().startsWith("SORT=NA")) { append = " (sorted by name)"; commands.remove(i); i--; } else if (s.toUpperCase().startsWith("SORT=REV")) { final List<Area> levelSorted = new ArrayList<Area>(); for (; a.hasMoreElements(); ) levelSorted.add(a.nextElement()); Collections.sort(levelSorted, new Comparator<Area>() { @Override public int compare(Area arg0, Area arg1) { return arg1.Name().compareTo(arg0.Name()); } }); a = new IteratorEnumeration<Area>(levelSorted.iterator()); append = " (sorted by name, reverse)"; commands.remove(i); i--; } else if (s.toUpperCase().startsWith("SORT=LEV")) { final List<Area> levelSorted = new ArrayList<Area>(); for (; a.hasMoreElements(); ) levelSorted.add(a.nextElement()); Collections.sort(levelSorted, new Comparator<Area>() { @Override public int compare(Area arg0, Area arg1) { final int lvl1 = arg0.getAreaIStats()[Stats.MED_LEVEL.ordinal()]; final int lvl2 = arg1.getAreaIStats()[Stats.MED_LEVEL.ordinal()]; if (lvl1 == lvl2) return 1; return Integer.valueOf(lvl1).compareTo(Integer.valueOf(lvl2)); } }); a = new IteratorEnumeration<Area>(levelSorted.iterator()); append = " (sorted by level)"; addStat = Stats.MED_LEVEL.ordinal(); commands.remove(i); i--; } else if (s.toUpperCase().startsWith("SORT=AUTH")) { final List<Area> levelSorted = new ArrayList<Area>(); for (; a.hasMoreElements(); ) levelSorted.add(a.nextElement()); Collections.sort(levelSorted, new Comparator<Area>() { @Override public int compare(Area arg0, Area arg1) { return arg0.getAuthorID().compareTo(arg1.getAuthorID()); } }); a = new IteratorEnumeration<Area>(levelSorted.iterator()); append = " (sorted by author)"; commands.remove(i); addStat = -999; numCols = 2; i--; } else if (s.toUpperCase().startsWith("SORT=")) { int statVal = -1; for (int x = 0; x < Area.Stats.values().length; x++) { if (s.toUpperCase().endsWith("=" + Area.Stats.values()[x].name())) statVal = x; } if (statVal < 0) { mob.tell(L("There was an error in your SORT= qualifier: '@x1' is unknown.", s.substring(5))); return false; } final int sortStat = statVal; final List<Area> levelSorted = new ArrayList<Area>(); for (; a.hasMoreElements(); ) levelSorted.add(a.nextElement()); Collections.sort(levelSorted, new Comparator<Area>() { @Override public int compare(Area arg0, Area arg1) { final int lvl1 = arg0.getAreaIStats()[sortStat]; final int lvl2 = arg1.getAreaIStats()[sortStat]; if (lvl1 == lvl2) return 1; return Integer.valueOf(lvl1).compareTo(Integer.valueOf(lvl2)); } }); a = new IteratorEnumeration<Area>(levelSorted.iterator()); append = " (sorted by " + Area.Stats.values()[statVal].name().toLowerCase() + ")"; addStat = sortStat; commands.remove(i); i--; } } StringBuffer msg = new StringBuffer(L("^HComplete areas list@x1:^?^N\n\r", append)); if (commands.size() > 1) { expression = CMParms.combineQuoted(commands, 1); msg = new StringBuffer(L("^HFiltered areas list@x1:^?^N\n\r", append)); } final Vector<String> areasVec = new Vector<String>(); final boolean sysop = (mob != null) && CMSecurity.isASysOp(mob); final int colWidth = CMLib.lister().fixColWidth(66.0 / numCols, mob); for (; a.hasMoreElements(); ) { final Area A = a.nextElement(); if (CMLib.flags().canAccess(mob, A) && (!CMath.bset(A.flags(), Area.FLAG_INSTANCE_CHILD)) && (!(A instanceof SpaceObject))) { String levelStr = (addStat >= 0 ? (Integer.toString(A.getAreaIStats()[addStat]) + ":") : ""); if (addStat == -999) levelStr = CMStrings.padRight(A.getAuthorID(), 10) + ":"; String name = levelStr + ((!CMLib.flags().isHidden(A)) ? " " + A.name() : "(" + A.name() + ")"); if (sysop) switch (A.getAreaState()) { case ACTIVE: name = "^w" + name + "^?"; break; case PASSIVE: name = "^W" + name + "^?"; break; case FROZEN: name = "^b" + name + "^?"; break; case STOPPED: name = "^r" + name + "^?"; break; } if (expression != null) { final int[] stats = A.getAreaIStats(); if (stats != null) { final Map<String, Object> H = new Hashtable<String, Object>(); for (int i = 0; i < stats.length; i++) H.put(Area.Stats.values()[i].name(), Integer.toString(stats[i])); try { if (!CMStrings.parseStringExpression(expression, H, false)) continue; } catch (final Exception e) { if (mob != null) mob.tell(L("There was an error in your AREA qualifier parameters. See help on AREA for more information. The error was: @x1", e.getMessage())); return false; } } } areasVec.add(name); } } int col = 0; for (int i = 0; i < areasVec.size(); i++) { if ((++col) > numCols) { msg.append("\n\r"); col = 1; } msg.append(CMStrings.padRight(areasVec.get(i), colWidth) + "^N"); } msg.append(L("\n\r\n\r^HEnter 'HELP (AREA NAME) for more information.^?")); if ((mob != null) && (!mob.isMonster())) mob.session().colorOnlyPrintln(msg.toString()); return false; } @Override public boolean canBeOrdered() { return true; } }
44.47549
175
0.48716
fbc3004e6745eda2ce4b2e62784eadc1ef24dfd4
5,339
package com.google.android.mms; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ public class ContentType { // Fields public static final java.lang.String MMS_MESSAGE = "application/vnd.wap.mms-message"; public static final java.lang.String MMS_GENERIC = "application/vnd.wap.mms-generic"; public static final java.lang.String MULTIPART_MIXED = "application/vnd.wap.multipart.mixed"; public static final java.lang.String MULTIPART_RELATED = "application/vnd.wap.multipart.related"; public static final java.lang.String MULTIPART_ALTERNATIVE = "application/vnd.wap.multipart.alternative"; public static final java.lang.String TEXT_PLAIN = "text/plain"; public static final java.lang.String TEXT_HTML = "text/html"; public static final java.lang.String TEXT_VCALENDAR = "text/x-vCalendar"; public static final java.lang.String TEXT_VCARD = "text/x-vCard"; public static final java.lang.String IMAGE_UNSPECIFIED = "image/*"; public static final java.lang.String IMAGE_JPEG = "image/jpeg"; public static final java.lang.String IMAGE_JPG = "image/jpg"; public static final java.lang.String IMAGE_GIF = "image/gif"; public static final java.lang.String IMAGE_WBMP = "image/vnd.wap.wbmp"; public static final java.lang.String IMAGE_PNG = "image/png"; public static final java.lang.String AUDIO_UNSPECIFIED = "audio/*"; public static final java.lang.String AUDIO_AAC = "audio/aac"; public static final java.lang.String AUDIO_AMR = "audio/amr"; public static final java.lang.String AUDIO_IMELODY = "audio/imelody"; public static final java.lang.String AUDIO_MID = "audio/mid"; public static final java.lang.String AUDIO_MIDI = "audio/midi"; public static final java.lang.String AUDIO_MP3 = "audio/mp3"; public static final java.lang.String AUDIO_MPEG3 = "audio/mpeg3"; public static final java.lang.String AUDIO_MPEG = "audio/mpeg"; public static final java.lang.String AUDIO_MPG = "audio/mpg"; public static final java.lang.String AUDIO_MP4 = "audio/mp4"; public static final java.lang.String AUDIO_X_MID = "audio/x-mid"; public static final java.lang.String AUDIO_X_MIDI = "audio/x-midi"; public static final java.lang.String AUDIO_X_MP3 = "audio/x-mp3"; public static final java.lang.String AUDIO_X_MPEG3 = "audio/x-mpeg3"; public static final java.lang.String AUDIO_X_MPEG = "audio/x-mpeg"; public static final java.lang.String AUDIO_X_MPG = "audio/x-mpg"; public static final java.lang.String AUDIO_3GPP = "audio/3gpp"; public static final java.lang.String AUDIO_OGG = "application/ogg"; public static final java.lang.String VIDEO_UNSPECIFIED = "video/*"; public static final java.lang.String VIDEO_3GPP = "video/3gpp"; public static final java.lang.String VIDEO_3G2 = "video/3gpp2"; public static final java.lang.String VIDEO_H263 = "video/h263"; public static final java.lang.String VIDEO_MP4 = "video/mp4"; public static final java.lang.String APP_SMIL = "application/smil"; public static final java.lang.String APP_WAP_XHTML = "application/vnd.wap.xhtml+xml"; public static final java.lang.String APP_XHTML = "application/xhtml+xml"; public static final java.lang.String APP_DRM_CONTENT = "application/vnd.oma.drm.content"; public static final java.lang.String APP_DRM_MESSAGE = "application/vnd.oma.drm.message"; // Constructors private ContentType(){ } // Methods public static boolean isImageType(java.lang.String arg1){ return false; } public static boolean isAudioType(java.lang.String arg1){ return false; } public static boolean isVideoType(java.lang.String arg1){ return false; } public static boolean isTextType(java.lang.String arg1){ return false; } public static boolean isSupportedType(java.lang.String arg1){ return false; } public static boolean isSupportedImageType(java.lang.String arg1){ return false; } public static boolean isSupportedAudioType(java.lang.String arg1){ return false; } public static boolean isSupportedVideoType(java.lang.String arg1){ return false; } public static boolean isDrmType(java.lang.String arg1){ return false; } public static boolean isUnspecified(java.lang.String arg1){ return false; } public static java.util.ArrayList<java.lang.String> getImageTypes(){ return (java.util.ArrayList) null; } public static java.util.ArrayList<java.lang.String> getAudioTypes(){ return (java.util.ArrayList) null; } public static java.util.ArrayList<java.lang.String> getVideoTypes(){ return (java.util.ArrayList) null; } public static java.util.ArrayList<java.lang.String> getSupportedTypes(){ return (java.util.ArrayList) null; } }
31.97006
107
0.739277
f0d69488ac70070b837c16a7628435004fd55f32
901
package mantra.symbols; import org.antlr.v4.runtime.tree.ParseTree; public abstract class ScopedSymbol extends BaseScope implements Symbol, Scope { public String name; // All symbols at least have a name // public Type type; public Scope scope; // All symbols know what scope contains them. public ParseTree def; // points at ID node in tree public ScopedSymbol(String name, Scope enclosingScope) { super(enclosingScope); this.name = name; } @Override public String getName() { return name; } @Override public Scope getScope() { return scope; } public Scope getParentScope() { return getEnclosingScope(); } public Scope getEnclosingScope() { return enclosingScope; } public String getScopeName() { return name; } public String getQualifiedName() { if ( scope instanceof PackageSymbol ) { return scope+"::"+name; } return scope+"."+name; } }
29.064516
79
0.710322
728c87629bf51526165f453ca9716ee22bba0526
1,537
/* * 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.progenia.sigdep01_01.systeme.data.business; import com.progenia.sigdep01_01.systeme.data.entity.SystemePeriodiciteRemboursement; import com.progenia.sigdep01_01.systeme.data.repository.SystemePeriodiciteRemboursementRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; /** * * @author Jamâl-Dine DISSOU */ @Service public class SystemePeriodiciteRemboursementBusiness { @Autowired private final SystemePeriodiciteRemboursementRepository repository; public SystemePeriodiciteRemboursementBusiness(SystemePeriodiciteRemboursementRepository repository) { this.repository = repository; } public Optional<SystemePeriodiciteRemboursement> findById(String codePeriodicite) { return this.repository.findById(codePeriodicite); } public List<SystemePeriodiciteRemboursement> findAll() { return this.repository.findAll(); } public SystemePeriodiciteRemboursement save(SystemePeriodiciteRemboursement periodiciteRemboursement) { return this.repository.save(periodiciteRemboursement); } public void delete(SystemePeriodiciteRemboursement periodiciteRemboursement) { this.repository.delete(periodiciteRemboursement); } }
32.702128
107
0.785947
b438e5eaf258d65470902501d356e4f38ae1c63f
1,281
package me.kareluo.imaging.gallery.model; import android.net.Uri; /** * Created by felix on 2017/12/26 上午11:21. */ public class IMGImageViewModel { private Uri uri; private boolean isSelected; private boolean isOriginal; private int width; private int height; private long size; public IMGImageViewModel(Uri uri) { this.uri = uri; } public Uri getUri() { return uri; } public void setUri(Uri uri) { this.uri = uri; } public boolean isOriginal() { return isOriginal; } public void setOriginal(boolean original) { isOriginal = original; } public boolean isSelected() { return isSelected; } public void setSelected(boolean selected) { isSelected = selected; } public void toggleSelected() { isSelected = !isSelected; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } }
16.21519
47
0.58548
7d7c49e435cbdd13997c46cd0e776da7c801f0c4
2,657
import org.jbox2d.collision.shapes.CircleShape; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.dynamics.*; import java.awt.geom.Rectangle2D; /** * CG2D * Class PhysicsBody * Created by Stefan Mermans on 23/03/2016. */ class PhysicsBody { private BodyDef bodyDef; private Body body; private ShapeType2D shapeType2D; /** * Constructor for a circular PhysicsBody * @param x starting X position for the circle From the center of the body * @param y starting y position for the circle From the center of the body * @param radius The radius of the circle * @param bodyType The bodyType the circle will use * @param world The world in which the body will be placed */ PhysicsBody(int x, int y, float radius, BodyType bodyType, World world){ shapeType2D = ShapeType2D.CIRCLE; bodyDef = new BodyDef(); bodyDef.type = bodyType; bodyDef.position.set(x,y); CircleShape circleShape = new CircleShape(); circleShape.m_radius = radius; body = world.createBody(bodyDef); FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = circleShape; fixtureDef.density = 100 * (float)(radius*radius*Math.PI); fixtureDef.friction = 5.0f; body.createFixture(fixtureDef); } /** * Constructor for a rectangular PhysicsBody * @param x starting X position for the rectangle From the center of the body * @param y starting y position for the rectangle From the center of the body * @param rectangle2D The rectangle to be used * @param bodyType The bodyType the rectangle will use * @param world The world in which the body will be placed */ PhysicsBody(int x, int y, Rectangle2D rectangle2D, BodyType bodyType, World world){ shapeType2D = ShapeType2D.RECTANGLE; bodyDef = new BodyDef(); bodyDef.type = bodyType; bodyDef.position.set(x,y); PolygonShape polygonShape = new PolygonShape(); polygonShape.setAsBox((float)(rectangle2D.getWidth() * 0.5f),(float)(rectangle2D.getHeight() * 0.5f)); body = world.createBody(bodyDef); FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = polygonShape; fixtureDef.density = 100 * (float)(rectangle2D.getWidth()*rectangle2D.getHeight()); fixtureDef.friction = 5.0f; body.createFixture(fixtureDef); } ShapeType2D getShapeType2D() { return shapeType2D; } Body getBody() { return body; } }
32.802469
110
0.645841
dbcf20ee73e533c125d87039c7452a4626a16beb
4,727
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/type/dayofweek.proto package com.google.type; /** * <pre> * Represents a day of week. * </pre> * * Protobuf enum {@code google.type.DayOfWeek} */ public enum DayOfWeek implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * The unspecified day-of-week. * </pre> * * <code>DAY_OF_WEEK_UNSPECIFIED = 0;</code> */ DAY_OF_WEEK_UNSPECIFIED(0), /** * <pre> * The day-of-week of Monday. * </pre> * * <code>MONDAY = 1;</code> */ MONDAY(1), /** * <pre> * The day-of-week of Tuesday. * </pre> * * <code>TUESDAY = 2;</code> */ TUESDAY(2), /** * <pre> * The day-of-week of Wednesday. * </pre> * * <code>WEDNESDAY = 3;</code> */ WEDNESDAY(3), /** * <pre> * The day-of-week of Thursday. * </pre> * * <code>THURSDAY = 4;</code> */ THURSDAY(4), /** * <pre> * The day-of-week of Friday. * </pre> * * <code>FRIDAY = 5;</code> */ FRIDAY(5), /** * <pre> * The day-of-week of Saturday. * </pre> * * <code>SATURDAY = 6;</code> */ SATURDAY(6), /** * <pre> * The day-of-week of Sunday. * </pre> * * <code>SUNDAY = 7;</code> */ SUNDAY(7), UNRECOGNIZED(-1), ; /** * <pre> * The unspecified day-of-week. * </pre> * * <code>DAY_OF_WEEK_UNSPECIFIED = 0;</code> */ public static final int DAY_OF_WEEK_UNSPECIFIED_VALUE = 0; /** * <pre> * The day-of-week of Monday. * </pre> * * <code>MONDAY = 1;</code> */ public static final int MONDAY_VALUE = 1; /** * <pre> * The day-of-week of Tuesday. * </pre> * * <code>TUESDAY = 2;</code> */ public static final int TUESDAY_VALUE = 2; /** * <pre> * The day-of-week of Wednesday. * </pre> * * <code>WEDNESDAY = 3;</code> */ public static final int WEDNESDAY_VALUE = 3; /** * <pre> * The day-of-week of Thursday. * </pre> * * <code>THURSDAY = 4;</code> */ public static final int THURSDAY_VALUE = 4; /** * <pre> * The day-of-week of Friday. * </pre> * * <code>FRIDAY = 5;</code> */ public static final int FRIDAY_VALUE = 5; /** * <pre> * The day-of-week of Saturday. * </pre> * * <code>SATURDAY = 6;</code> */ public static final int SATURDAY_VALUE = 6; /** * <pre> * The day-of-week of Sunday. * </pre> * * <code>SUNDAY = 7;</code> */ public static final int SUNDAY_VALUE = 7; public final int getNumber() { if (this == UNRECOGNIZED) { throw new IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @Deprecated public static DayOfWeek valueOf(int value) { return forNumber(value); } public static DayOfWeek forNumber(int value) { switch (value) { case 0: return DAY_OF_WEEK_UNSPECIFIED; case 1: return MONDAY; case 2: return TUESDAY; case 3: return WEDNESDAY; case 4: return THURSDAY; case 5: return FRIDAY; case 6: return SATURDAY; case 7: return SUNDAY; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<DayOfWeek> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< DayOfWeek> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<DayOfWeek>() { public DayOfWeek findValueByNumber(int number) { return DayOfWeek.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.type.DayOfWeekProto.getDescriptor().getEnumTypes().get(0); } private static final DayOfWeek[] VALUES = values(); public static DayOfWeek valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private DayOfWeek(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.type.DayOfWeek) }
20.915929
80
0.591073
888c400ff101c6efb442155b9f20fabe5a541bcf
3,148
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ package org.unitime.timetable.onlinesectioning.model; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Date; import org.infinispan.commons.marshall.Externalizer; import org.infinispan.commons.marshall.SerializeWith; import org.unitime.timetable.model.ClassWaitList; import org.unitime.timetable.onlinesectioning.OnlineSectioningHelper; /** * @author Tomas Muller */ @SerializeWith(XWaitListedSection.XWaitListedSectionSerializer.class) public class XWaitListedSection extends XSection { private static final long serialVersionUID = 1L; private Long iWaitListId = null; private Date iTimeStamp = null; private ClassWaitList.Type iType = null; public XWaitListedSection() {} public XWaitListedSection(ObjectInput in) throws IOException, ClassNotFoundException { readExternal(in); } public XWaitListedSection(ClassWaitList clw, OnlineSectioningHelper helper) { super(clw.getClazz(), helper); iWaitListId = clw.getUniqueId(); iTimeStamp = clw.getTimestamp(); iType = ClassWaitList.Type.values()[clw.getType()]; } public Long getWaitListId() { return iWaitListId; } public ClassWaitList.Type getType() { return iType; } public Date getTimeStamp() { return iTimeStamp; } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); iWaitListId = in.readLong(); if (iWaitListId < 0) iWaitListId = null; iTimeStamp = (in.readBoolean() ? new Date(in.readLong()) : null); iType = ClassWaitList.Type.values()[in.readInt()]; } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeLong(iWaitListId == null ? -1l : iWaitListId); out.writeBoolean(iTimeStamp != null); if (iTimeStamp != null) out.writeLong(iTimeStamp.getTime()); out.writeInt(iType.ordinal()); } public static class XWaitListedSectionSerializer implements Externalizer<XWaitListedSection> { private static final long serialVersionUID = 1L; @Override public void writeObject(ObjectOutput output, XWaitListedSection object) throws IOException { object.writeExternal(output); } @Override public XWaitListedSection readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new XWaitListedSection(input); } } }
34.217391
102
0.769695
17ad4a57e32b6c5a3936c95ef39ea8416775e162
1,124
package com.yuenov.open.fragments.baseInfo; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import butterknife.ButterKnife; public abstract class BaseFragment extends Fragment { public View viewContent; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (viewContent == null) { if (getLayoutId() > 0) viewContent = View.inflate(getContext(), getLayoutId(), null); ButterKnife.bind(this,viewContent); initExtra(); initLayout(); initListener(); initData(); } return viewContent; } protected abstract int getLayoutId(); protected abstract void initLayout(); protected abstract void initExtra(); protected abstract void initListener(); protected abstract void initData(); }
22.48
132
0.685053
58dad24b63894dc85f282eed54734cd01513ecf2
322
package edu.diegod5000.itopapps; import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; /** * Created by diego-d on 16/02/16. */ public class MApplication extends Application { @Override public void onCreate() { super.onCreate(); Fresco.initialize(this); } }
18.941176
52
0.692547
8cf7af0dd811039cde8471cd20fb740d72f5d1c6
3,645
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sis.feature.builder; import java.util.Set; import java.util.EnumSet; import org.apache.sis.feature.FeatureOperations; /** * Roles that can be associated to some attributes for instructing {@code FeatureTypeBuilder} * how to generate pre-defined operations. Those pre-defined operations are: * * <ul> * <li>A {@linkplain FeatureOperations#compound compound operation} for generating a unique identifier * from an arbitrary amount of attribute values.</li> * <li>A {@linkplain FeatureOperations#link link operation} for referencing a geometry to be used as the * <em>default</em> geometry.</li> * <li>An {@linkplain FeatureOperations#envelope operation} for computing the bounding box of all geometries * found in the feature. This operation is automatically added if the feature contains a default geometry.</li> * </ul> * * This enumeration allows user code to specify which feature attribute to use for creating those operations. * * @author Johann Sorel (Geomatys) * @author Martin Desruisseaux (Geomatys) * @version 0.8 * * @see AttributeTypeBuilder#addRole(AttributeRole) * * @since 0.8 * @module */ public enum AttributeRole { /** * Attribute value will be part of a unique identifier for the feature instance. * An arbitrary amount of attributes can be flagged as identifier components: * * <ul> * <li>If no attribute has this role, then no attribute is marked as feature identifier.</li> * <li>If exactly one attribute has this role, then a synthetic attribute named {@code "sis:identifier"} * will be created as a {@linkplain FeatureOperations#link link} to the flagged attribute.</li> * <li>If more than one attribute have this role, then a synthetic attribute named {@code "sis:identifier"} * will be created as a {@linkplain FeatureOperations#compound compound key} made of all flagged * attributes. The separator character can be modified by a call to * {@link FeatureTypeBuilder#setIdentifierDelimiters(String, String, String)}</li> * </ul> * * @see FeatureTypeBuilder#setIdentifierDelimiters(String, String, String) */ IDENTIFIER_COMPONENT, /** * Attribute value will be flagged as the <em>default</em> geometry. * Feature can have an arbitrary amount of geometry attributes, * but only one can be flagged as the default geometry. */ DEFAULT_GEOMETRY; /** * Returns the union of the given set of attribute roles. */ static Set<AttributeRole> merge(final Set<AttributeRole> oldValue, final Set<AttributeRole> newValue) { final EnumSet<AttributeRole> union = EnumSet.copyOf(oldValue); return union.addAll(newValue) ? union : oldValue; } }
43.392857
117
0.710014
6807574548c5e418dca46d81fc47210d61eaf08e
540
package cracking_the_coding_interview.chapter_01.exercise_01; import java.util.Arrays; class SolutionFollowUp { private static final int NUMBER_OF_CHARS = 128; boolean isUnique(final String s) { if (s.length() > NUMBER_OF_CHARS) { return false; } final char[] chars = s.toCharArray(); Arrays.sort(chars); for (int i = 1; i < chars.length; i++) { if (chars[i] == chars[i - 1]) { return false; } } return true; } }
20.769231
61
0.55
e88b0c3ba3ac1dc68fa1ef792b40f10326f9ffd1
1,649
package artifality.block; import artifality.block.base.BuddingCrystalBlock; import artifality.block.base.CrystalBlock; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import java.util.Random; public class BuddingLunarCrystalBlock extends BuddingCrystalBlock { public BuddingLunarCrystalBlock(Settings settings) { super(settings); } @Override public void randomTick(BlockState state, ServerWorld world, BlockPos pos, Random random) { if (random.nextInt(4) == 0) { Direction direction = DIRECTIONS[random.nextInt(DIRECTIONS.length)]; BlockPos blockPos = pos.offset(direction); BlockState blockState = world.getBlockState(blockPos); Block block = null; if (blockState.isAir()) { block = ArtifalityBlocks.SMALL_LUNAR_CRYSTAL_CLUSTER; } else if (blockState.isOf(ArtifalityBlocks.SMALL_LUNAR_CRYSTAL_CLUSTER) && blockState.get(CrystalBlock.FACING) == direction) { block = ArtifalityBlocks.MEDIUM_LUNAR_CRYSTAL_CLUSTER; } else if (blockState.isOf(ArtifalityBlocks.MEDIUM_LUNAR_CRYSTAL_CLUSTER) && blockState.get(CrystalBlock.FACING) == direction) { block = ArtifalityBlocks.LUNAR_CRYSTAL_CLUSTER; } if (block != null) { BlockState crystal = block.getDefaultState().with(CrystalBlock.FACING, direction); world.setBlockState(blockPos, crystal); } } } }
40.219512
140
0.690115
7cf17dc1e8b572d16b0dc926e9f2ec08b1f0f1fc
4,070
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.metrics.test; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.annotation.Nonnull; import com.google.common.base.Function; import com.google.common.base.Predicate; import org.apache.gobblin.metrics.GobblinTrackingEvent; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.metrics.notification.EventNotification; import org.apache.gobblin.metrics.notification.Notification; /** * A class to help with testing metrics. It provides asserts on a {@link MetricContext} */ public class MetricsAssert implements Function<Notification, Void> { private final MetricContext _metricContext; private final LinkedBlockingQueue<GobblinTrackingEvent> _events = new LinkedBlockingQueue<>(); public MetricsAssert(MetricContext metricContext) { _metricContext = metricContext; _metricContext.addNotificationTarget(this); } /** {@inheritDoc} */ @Override public Void apply(Notification input) { if (input instanceof EventNotification) { _events.offer(((EventNotification)input).getEvent()); } return null; } public MetricContext getMetricContext() { return _metricContext; } public void assertEvent(Predicate<GobblinTrackingEvent> predicate, long timeout, TimeUnit timeUnit) throws TimeoutException, InterruptedException { GobblinTrackingEvent gte = timeout > 0 ? _events.poll(timeout, timeUnit) : _events.take(); if (null == gte) { throw new TimeoutException(); } if (!predicate.apply(gte)) { throw new AssertionError("Event predicate mismatch: " + gte); } } public void assertEvent(Predicate<GobblinTrackingEvent> predicate) throws InterruptedException { try { assertEvent(predicate, 0, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { throw new Error("This should never happen"); } } public static Predicate<GobblinTrackingEvent> eqEventName(final String expectedName) { return new Predicate<GobblinTrackingEvent>() { @Override public boolean apply(@Nonnull GobblinTrackingEvent input) { return input.getName().equals(expectedName); } }; } public static Predicate<GobblinTrackingEvent> eqEventNamespace(final String expectedNamespace) { return new Predicate<GobblinTrackingEvent>() { @Override public boolean apply(@Nonnull GobblinTrackingEvent input) { return input.getNamespace().equals(expectedNamespace); } }; } public static Predicate<GobblinTrackingEvent> eqEventMetdata(final String metadataKey, final String metadataValue) { return new Predicate<GobblinTrackingEvent>() { @Override public boolean apply(@Nonnull GobblinTrackingEvent input) { return input.getMetadata().get(metadataKey).equals(metadataValue); } }; } public static Predicate<GobblinTrackingEvent> hasEventMetdata(final String metadataKey) { return new Predicate<GobblinTrackingEvent>() { @Override public boolean apply(@Nonnull GobblinTrackingEvent input) { return input.getMetadata().containsKey(metadataKey); } }; } }
37
98
0.732924
4b10a8499e6c363965e16e68a570b6fd34bc67d5
16,941
/* * Copyright 2010 MIT Strategic Engineering Research Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.mit.spacenet.gui.event; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Set; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.ListSelectionModel; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreeSelectionModel; import edu.mit.spacenet.domain.element.I_Element; import edu.mit.spacenet.domain.element.PropulsiveVehicle; import edu.mit.spacenet.domain.network.edge.Burn; import edu.mit.spacenet.domain.network.edge.BurnType; import edu.mit.spacenet.gui.component.CheckBoxNode; import edu.mit.spacenet.gui.component.CheckBoxTree; import edu.mit.spacenet.gui.component.CheckBoxTreeModel; import edu.mit.spacenet.gui.component.UnitsWrapper; import edu.mit.spacenet.simulator.event.BurnEvent; import edu.mit.spacenet.simulator.event.BurnStageItem; import edu.mit.spacenet.util.Formulae; /** * A panel for viewing and editing a burn event. * * @author Paul Grogan */ public class BurnEventPanel extends AbstractEventPanel { private static final long serialVersionUID = 769918023169742283L; private BurnEvent event; private JComboBox ddlBurnType; private SpinnerNumberModel burnDeltaVModel; private JSpinner burnDeltaVSpinner; private JButton btnAddBurn, btnAddStage, btnClear; private DefaultListModel sequenceModel; private JList sequenceList; private JProgressBar deltaV; private JLabel stackMassLabel; private CheckBoxTreeModel elementModel; private CheckBoxTree elementTree; /** * Instantiates a new burn event panel. * * @param eventDialog the event dialog * @param event the event */ public BurnEventPanel(EventDialog eventDialog, BurnEvent event) { super(eventDialog, event); this.event = event; buildPanel(); initialize(); } private void buildPanel() { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(2,2,2,2); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_END; c.fill = GridBagConstraints.NONE; add(new JLabel("Burn Type: "), c); c.gridy++; add(new JLabel("Required Delta-V: "), c); c.gridx = 1; c.anchor = GridBagConstraints.LINE_START; c.gridy = 0; ddlBurnType = new JComboBox(); for(BurnType t : BurnType.values()) ddlBurnType.addItem(t); add(ddlBurnType, c); c.gridy++; burnDeltaVModel = new SpinnerNumberModel(0, 0, 10000, 1.0); burnDeltaVSpinner = new JSpinner(burnDeltaVModel); add(new UnitsWrapper(burnDeltaVSpinner, "m/s"), c); c.gridx = 0; c.gridy = 2; c.gridwidth = 1; c.anchor = GridBagConstraints.FIRST_LINE_END; c.fill = GridBagConstraints.NONE; add(new JLabel("Elements: "), c); c.gridy+=2; c.anchor = GridBagConstraints.LINE_END; add(new JLabel("Delta-V: "), c); c.gridy++; add(new JLabel("Stack Mass: "), c); c.gridy++; c.anchor = GridBagConstraints.FIRST_LINE_END; add(new JLabel("Sequence: "), c); c.gridy = 2; c.gridx = 1; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; elementModel = new CheckBoxTreeModel(); elementTree = new CheckBoxTree(elementModel); elementTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); elementTree.setRootVisible(false); elementTree.setShowsRootHandles(true); JScrollPane elementScroll = new JScrollPane(elementTree); elementScroll.setPreferredSize(new Dimension(200,100)); add(elementScroll, c); c.gridy++; c.weighty = 0; c.weightx = 0; c.anchor = GridBagConstraints.LINE_END; c.fill = GridBagConstraints.NONE; JPanel sequenceButtonPanel = new JPanel(); sequenceButtonPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 3, 0)); btnAddBurn = new JButton("Burn"); btnAddBurn.setToolTipText("Burn the selected propulsive vehicles"); btnAddBurn.setIcon(BurnStageItem.BURN_ICON); btnAddBurn.setMargin(new Insets(3,3,3,3)); sequenceButtonPanel.add(btnAddBurn); btnAddStage = new JButton("Stage"); btnAddStage.setToolTipText("Stage the selected elements"); btnAddStage.setIcon(BurnStageItem.STAGE_ICON); btnAddStage.setMargin(new Insets(3,3,3,3)); sequenceButtonPanel.add(btnAddStage); add(sequenceButtonPanel, c); c.gridy++; c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.HORIZONTAL; deltaV = new JProgressBar(0, 100); deltaV.setStringPainted(true); add(deltaV, c); c.gridy++; c.fill = GridBagConstraints.NONE; stackMassLabel = new JLabel(); add(new UnitsWrapper(stackMassLabel, "kg"), c); c.gridy++; c.weighty = 1; c.weightx = 1; c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.BOTH; sequenceModel = new DefaultListModel(); sequenceList = new JList(sequenceModel); sequenceList.setCellRenderer(new DefaultListCellRenderer() { private static final long serialVersionUID = 1271331296677711150L; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = (JLabel)super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if(((BurnStageItem)value).getBurnStage().equals(BurnStageItem.BURN)) { label.setIcon(BurnStageItem.BURN_ICON); } else { label.setIcon(BurnStageItem.STAGE_ICON); } return label; } }); sequenceList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); JScrollPane sequenceScroll = new JScrollPane(sequenceList); sequenceScroll.setPreferredSize(new Dimension(200,100)); add(sequenceScroll, c); c.gridy++; c.weighty = 0; c.weightx = 0; c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.LINE_END; btnClear = new JButton("Clear"); btnClear.setToolTipText("Clear the selected burns or stages"); btnClear.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/cross.png"))); btnClear.setMargin(new Insets(3,3,3,3)); add(btnClear, c); } private void initialize() { ddlBurnType.setSelectedItem(event.getBurn().getBurnType()); burnDeltaVModel.setValue(event.getBurn().getDeltaV()); for(BurnStageItem i : event.getBurnStageSequence()) { BurnStageItem bs = new BurnStageItem(); bs.setBurnStage(i.getBurnStage()); bs.setElement(getEventDialog().getSimElement(i.getElement().getUid())); sequenceModel.addElement(bs); } ddlBurnType.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { BurnEvent event = (BurnEvent)getEvent(); if(!ddlBurnType.getSelectedItem().equals(event.getBurn().getBurnType())) { event.getBurn().setBurnType(BurnType.getInstance(ddlBurnType.getSelectedItem().toString())); updateView(); } } }); burnDeltaVSpinner.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { ((BurnEvent)getEvent()).getBurn().setDeltaV(burnDeltaVModel.getNumber().doubleValue()); updateView(); } }); elementModel = new CheckBoxTreeModel(getEventDialog().getSimNode()); elementTree.setModel(elementModel); elementModel.setCheckedElements(event.getElements()); elementModel.addTreeModelListener(new TreeModelListener() { public void treeNodesChanged(TreeModelEvent e) { updateView(); updateButtons(); } public void treeNodesInserted(TreeModelEvent e) { } public void treeNodesRemoved(TreeModelEvent e) { } public void treeStructureChanged(TreeModelEvent e) { } }); elementTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { if(!elementTree.isSelectionEmpty()) { sequenceList.clearSelection(); } updateButtons(); } }); btnAddBurn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sequenceModel.addElement(new BurnStageItem(BurnStageItem.BURN, ((CheckBoxNode)elementTree.getSelectionPath().getLastPathComponent()).getElement())); updateView(); } }); btnAddStage.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sequenceModel.addElement(new BurnStageItem(BurnStageItem.STAGE, ((CheckBoxNode)elementTree.getSelectionPath().getLastPathComponent()).getElement())); updateView(); } }); sequenceList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if(!sequenceList.isSelectionEmpty()) { elementTree.clearSelection(); } updateButtons(); } }); btnClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for(Object o : sequenceList.getSelectedValues()) sequenceModel.removeElement(o); updateView(); } }); } /* (non-Javadoc) * @see edu.mit.spacenet.gui.event.AbstractEventPanel#getEvent() */ @Override public BurnEvent getEvent() { return event; } /* (non-Javadoc) * @see edu.mit.spacenet.gui.event.AbstractEventPanel#saveEvent() */ @Override public void saveEvent() { event.setBurn(new Burn(0, BurnType.getInstance(ddlBurnType.getSelectedItem().toString()), burnDeltaVModel.getNumber().doubleValue())); event.getElements().clear(); for(I_Element element : elementModel.getTopCheckedElements()) { event.getElements().add(getEventDialog().getElement(element.getUid())); } ArrayList<BurnStageItem> sequence = new ArrayList<BurnStageItem>(); for(Object o : sequenceModel.toArray()) { BurnStageItem i = new BurnStageItem(); i.setBurnStage(((BurnStageItem)o).getBurnStage()); i.setElement(getEventDialog().getElement(((BurnStageItem)o).getElement().getUid())); sequence.add(i); } event.setBurnStateSequence(sequence); } /* (non-Javadoc) * @see edu.mit.spacenet.gui.event.AbstractEventPanel#updateView() */ @Override public void updateView() { Set<I_Element> checkedElements = elementModel.getTopCheckedElements(); int[] selectionRows = elementTree.getSelectionRows(); elementModel = new CheckBoxTreeModel(getEventDialog().getSimNode()); elementTree.setModel(elementModel); elementModel.setCheckedElements(checkedElements); elementTree.setSelectionRows(selectionRows); elementModel.addTreeModelListener(new TreeModelListener() { public void treeNodesChanged(TreeModelEvent e) { updateView(); updateButtons(); } public void treeNodesInserted(TreeModelEvent e) { } public void treeNodesRemoved(TreeModelEvent e) { } public void treeStructureChanged(TreeModelEvent e) { } }); for(Object o : sequenceModel.toArray()) { boolean isFound = false; for(I_Element element : elementModel.getTopCheckedElements()) { if(element.equals(((BurnStageItem)o).getElement())) isFound = true; } if(!isFound) sequenceModel.clear(); } updateDeltaV(); } private void updateButtons() { if(elementTree.getSelectionCount() > 0) { if(elementTree.getSelectionCount() == 1 && ((CheckBoxNode)elementTree.getSelectionPath().getLastPathComponent()).isChecked() && elementModel.getTopCheckedElements().contains(((CheckBoxNode)elementTree.getSelectionPath().getLastPathComponent()).getElement())) { boolean isStaged = false; for(Object o : sequenceModel.toArray()) { if(((BurnStageItem)o).getElement().equals(((CheckBoxNode)elementTree.getSelectionPath().getLastPathComponent()).getElement()) && ((BurnStageItem)o).getBurnStage().equals(BurnStageItem.STAGE)) { isStaged = true; break; } } if(isStaged) { btnAddStage.setEnabled(false); btnAddBurn.setEnabled(false); } else { btnAddStage.setEnabled(true); if(((CheckBoxNode)elementTree.getSelectionPath().getLastPathComponent()).getElement() instanceof PropulsiveVehicle) { PropulsiveVehicle v = (PropulsiveVehicle)((CheckBoxNode)elementTree.getSelectionPath().getLastPathComponent()).getElement(); BurnEvent event = (BurnEvent)this.event; if((event.getBurn().getBurnType().equals(BurnType.OMS) && v.getOmsFuelTank() != null) ||(event.getBurn().getBurnType().equals(BurnType.RCS) && v.getRcsFuelTank() != null)) btnAddBurn.setEnabled(true); else btnAddBurn.setEnabled(false); } else { btnAddBurn.setEnabled(false); } } } else { btnAddStage.setEnabled(false); btnAddBurn.setEnabled(false); } } else { btnAddStage.setEnabled(false); btnAddBurn.setEnabled(false); } if(sequenceList.getSelectedIndices().length > 0) { btnClear.setEnabled(true); } else { btnClear.setEnabled(false); } } private void updateDeltaV() { double stackMass = 0; double deltaVReq = burnDeltaVModel.getNumber().doubleValue(); //System.out.println("deltaVReq: " + deltaVReq); for(I_Element e : elementModel.getTopCheckedElements()) stackMass += e.getTotalMass(); for(Object o : sequenceModel.toArray()) { BurnStageItem i = (BurnStageItem)o; if(i.getBurnStage().equals(BurnStageItem.STAGE)) { // staged elements are no longer in the contents model stackMass += i.getElement().getTotalMass(); } } //System.out.println("stackMass: " + stackMass); for(Object o : sequenceModel.toArray()) { BurnStageItem i = (BurnStageItem)o; if(i.getBurnStage().equals(BurnStageItem.STAGE)) { //System.out.println("stage: " + i.getElement().getName()); stackMass -= i.getElement().getTotalMass(); } else if(i.getBurnStage().equals(BurnStageItem.BURN)) { //System.out.println("burn: " + i.getElement().getName()); PropulsiveVehicle v = (PropulsiveVehicle)i.getElement(); if(((BurnType)ddlBurnType.getSelectedItem()).equals(BurnType.OMS)) { if(Formulae.getRequiredFuelMass(stackMass, deltaVReq, v.getOmsIsp()) > v.getOmsFuelTank().getAmount()) { double deltaVAchieved = Formulae.getAchievedDeltaV(stackMass, v.getOmsIsp(), v.getOmsFuelTank().getAmount()); //System.out.println("dv achieved: " + deltaVAchieved); deltaVReq -= deltaVAchieved; stackMass -= v.getOmsFuelTank().getAmount(); } else { //System.out.println("dv achieved: " + deltaVReq); stackMass -= Formulae.getRequiredFuelMass(stackMass, deltaVReq, v.getOmsIsp()); deltaVReq = 0; } } else { if(Formulae.getRequiredFuelMass(stackMass, deltaVReq, v.getRcsIsp()) > v.getRcsFuelTank().getAmount()) { double deltaVAchieved = Formulae.getAchievedDeltaV(stackMass, v.getRcsIsp(), v.getRcsFuelTank().getAmount()); //System.out.println("dv achieved: " + deltaVAchieved); deltaVReq -= deltaVAchieved; stackMass -= v.getRcsFuelTank().getAmount(); } else { //System.out.println("dv achieved: " + deltaVReq); stackMass -= Formulae.getRequiredFuelMass(stackMass, deltaVReq, v.getRcsIsp()); deltaVReq = 0; } } } } if(deltaVReq == 0) { deltaV.setForeground(new Color(0, 153, 0)); getEventDialog().setOkButtonEnabled(true); } else { deltaV.setForeground(new Color(153, 0, 0)); getEventDialog().setOkButtonEnabled(false); } DecimalFormat format = new DecimalFormat("0.0"); stackMassLabel.setText(format.format(stackMass)); deltaV.setValue((int)(100*((burnDeltaVModel.getNumber().doubleValue() - deltaVReq)/burnDeltaVModel.getNumber().doubleValue()))); deltaV.setString(format.format(burnDeltaVModel.getNumber().doubleValue() - deltaVReq) + " / " + burnDeltaVModel.getNumber() + " m/s"); } }
36.044681
140
0.729886
995abc01048fca63f3a7b7770a87ed945b387c02
3,366
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.core.query.aggregation.function; /** * No-op base class for aggregation function visitor */ // Keeping this base class (instead of interface) makes // it easy to create multiple visitors overriding for specific methods public class AggregationFunctionVisitorBase { public void visit(AggregationFunction function) { visitFunction(function); } public void visit(AvgAggregationFunction function) { visitFunction(function); } public void visit(AvgMVAggregationFunction function) { visitFunction(function); } public void visit(CountAggregationFunction function) { visitFunction(function); } public void visit(CountMVAggregationFunction function) { visitFunction(function); } public void visit(DistinctCountAggregationFunction function) { visitFunction(function); } public void visit(DistinctCountHLLAggregationFunction function) { visitFunction(function); } public void visit(DistinctCountHLLMVAggregationFunction function) { visitFunction(function); } public void visit(DistinctCountMVAggregationFunction function) { visitFunction(function); } public void visit(FastHLLAggregationFunction function) { visitFunction(function); } public void visit(MaxAggregationFunction function) { visitFunction(function); } public void visit(MaxMVAggregationFunction function) { visitFunction(function); } public void visit(MinAggregationFunction function) { visitFunction(function); } public void visit(MinMaxRangeAggregationFunction function) { visitFunction(function); } public void visit(MinMaxRangeMVAggregationFunction function) { visitFunction(function); } public void visit(MinMVAggregationFunction function) { visitFunction(function); } public void visit(PercentileAggregationFunction function) { visitFunction(function); } public void visit(PercentileMVAggregationFunction function) { visitFunction(function); } public void visit(PercentileEstAggregationFunction function) { visitFunction(function); } public void visit(PercentileEstMVAggregationFunction function) { visitFunction(function); } public void visit(PercentileTDigestAggregationFunction function) { visitFunction(function); } public void visit(SumAggregationFunction function) { visitFunction(function); } public void visit(SumMVAggregationFunction function) { visitFunction(function); } public void visitFunction(AggregationFunction function) { // non-op } }
26.928
70
0.756982
628b36aeb7af0f312ae6466d40f0496504bdc5a5
480
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}.pe.processor.${packageName}; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.util.Collector; import org.apache.streampipes.model.runtime.Event; public class ${classNamePrefix} implements FlatMapFunction<Event, Event> { @Override public void flatMap(Event in, Collector<Event> out) throws Exception { out.collect(in); } }
24
74
0.727083
4c1f38cebed4438da5a808694906da48078d7b2c
282
package org.corywixom.cache.business.mapping; import org.corywixom.cache.core.base.IMapper; import org.corywixom.cache.common.entities.CacheItem; import org.corywixom.cache.common.model.CacheItemDTO; public interface ICacheItemMapper extends IMapper<CacheItem, CacheItemDTO> { }
31.333333
77
0.833333
7d79a89d349980988c6036704d336ebf45f3830f
2,809
package com.sap.olingo.jpa.processor.cb.impl; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; class InheritanceInfo { private static final Log LOGGER = LogFactory.getLog(InheritanceInfo.class); private final Optional<InheritanceType> inType; private final Optional<Class<?>> baseClass; private final Optional<String> discriminatorColumn; InheritanceInfo(final JPAEntityType type) { baseClass = Optional.ofNullable(determineBaseClass(type)); inType = Optional.ofNullable(baseClass.map(this::determineInType).orElse(null)); discriminatorColumn = Optional.ofNullable(baseClass.map(this::determineColumn).orElse(null)); } Optional<Class<?>> getBaseClass() { return baseClass; } Optional<String> getDiscriminatorColumn() { return discriminatorColumn; } Optional<InheritanceType> getInheritanceType() { return inType; } boolean hasInheritance() { return inType.isPresent(); } @CheckForNull private Class<?> determineBaseClass(final JPAEntityType et) { if (et != null && et.getTypeClass().getSuperclass() != null) { final Class<?> superClass = et.getTypeClass().getSuperclass(); return determineInheritanceByClass(et, superClass); } return null; } private String determineColumn(@Nonnull final Class<?> clazz) { return inType.filter(t -> t.equals(InheritanceType.SINGLE_TABLE)) .map(t -> clazz.getDeclaredAnnotation(DiscriminatorColumn.class).name()) .orElse(null); } @CheckForNull private Class<?> determineInheritanceByClass(final JPAEntityType et, final Class<?> clazz) { final Entity jpaEntity = clazz.getDeclaredAnnotation(Entity.class); if (jpaEntity != null) { final Inheritance inheritance = clazz.getDeclaredAnnotation(Inheritance.class); if (inheritance != null) { return clazz; } else { final Class<?> superClass = clazz.getSuperclass(); if (superClass != null) { return determineInheritanceByClass(et, superClass); } else { LOGGER.debug("Cloud not find InheritanceType for " + et.getInternalName()); } } } return null; } private InheritanceType determineInType(@Nonnull final Class<?> baseClass) { final Inheritance inheritance = baseClass.getDeclaredAnnotation(Inheritance.class); return inheritance.strategy(); } }
33.843373
98
0.705233
970c61856e63b1c22ff4a9b0a09c5ff86ad7b082
2,800
package it.unibo.bmbman.model.utilities; import it.unibo.bmbman.model.TerrainFactoryImpl; import it.unibo.bmbman.view.utilities.ScreenToolUtils; /** * Class to manage the position of entities. */ public class Position { private int x; private int y; private static final int TILEDIM = TerrainFactoryImpl.CELL_DIMENSION * ScreenToolUtils.SCALE; private static final int HALFTILEDIM = TILEDIM / 2; /** * Create a new position in the specified coordinate. * @param x coordinate * @param y coordinate */ public Position(final int x, final int y) { this.x = x; this.y = y; } /** * Create a new position in the specified coordinate. * @param pos a {@link Position} */ public Position(final Position pos) { this.x = pos.getX(); this.y = pos.getY(); } /** * Method to get the x coordinate. * @return x coordinate */ public int getX() { return x; } /** * Method to set the x coordinate of the position. * @param x new x coordinate */ public void setX(final int x) { this.x = x; } /** * Method to get the y coordinate. * @return y coordinate */ public int getY() { return y; } /** * Method to set the y coordinate of the position. * @param y new y coordinate */ public void setY(final int y) { this.y = y; } /** * {@inheritDoc} */ @Override public String toString() { return "Position [x=" + this.getX() + "y=" + this.getY() + "]"; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Position other = (Position) obj; if (x != other.x) { return false; } if (y != other.y) { return false; } return true; } /** * Method used to get the centered position of a cell. * @param position actual position of an entity * @return a new centered position */ public static Position getCenteredPosition(final Position position) { Position newPosition = new Position(((position.getX() + HALFTILEDIM) / TILEDIM) * TILEDIM, ((position.getY() + HALFTILEDIM) / TILEDIM) * TILEDIM); return newPosition; } }
25
99
0.541071
9f2ffd702a4babc3ba9b9c214e8bf8e67686635c
1,924
/** * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at the following location: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.portal.utils.cache.resource; import java.io.IOException; import org.springframework.core.io.Resource; /** * A utility for loading resources from files, URLs or similar locations and building/compiling a * domain object from the resource. The domain object is cached and automatically re-loaded if the * underlying {@link Resource} changes. * * Clients should call {@link #getResource(Resource, Loader)} every time they need the * object and rely on the {@link CachingResourceLoader} implementation to manage caching and reloading. * * @author Eric Dalquist * @version $Revision$ */ public interface CachingResourceLoader { /** * Same as {@link #getResource(Resource, Loader, long)} with a 60 second check interval */ public <T> CachedResource<T> getResource(Resource resource, Loader<T> builder) throws IOException; /** * Get the {@link Resource} using the {@link Loader} to compile it if needed using the specified options. */ public <T> CachedResource<T> getResource(Resource resource, Loader<T> builder, long checkInterval) throws IOException; }
40.93617
122
0.743243
23b47b1523dfea707babbb956244040425594e47
1,018
package com.situjunjie.gulimall.ware.exception; import com.situjunjie.common.exception.BizCodeEnum; public class NoStockException extends RuntimeException{ private Long skuId; private Integer require; private Integer currentStock; public NoStockException(Long skuId, Integer require, Integer currentStock) { super(BizCodeEnum.NO_STOCK_EXCEPTION.getMessage()+"商品id = "+skuId+" 需求量 = "+require+" 现有库存量 ="+currentStock); this.skuId = skuId; this.require = require; this.currentStock = currentStock; } public Long getSkuId() { return skuId; } public void setSkuId(Long skuId) { this.skuId = skuId; } public Integer getRequire() { return require; } public void setRequire(Integer require) { this.require = require; } public Integer getCurrentStock() { return currentStock; } public void setCurrentStock(Integer currentStock) { this.currentStock = currentStock; } }
24.238095
117
0.666994
ea355c4545b15e08cf8caeb0aeb8ee09af64ea94
2,744
/* * Copyright 2002-2006 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.jpa; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.OptimisticLockException; import junit.framework.TestCase; import org.easymock.MockControl; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.DefaultTransactionDefinition; /** * * @author Costin Leau * */ public class DefaultJpaDialectTests extends TestCase { JpaDialect dialect; protected void setUp() throws Exception { dialect = new DefaultJpaDialect(); } protected void tearDown() throws Exception { dialect = null; } public void testDefaultTransactionDefinition() throws Exception { DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); try { dialect.beginTransaction(null, definition); fail("expected exception"); } catch (TransactionException e) { // ok } } public void testDefaultBeginTransaction() throws Exception { TransactionDefinition definition = new DefaultTransactionDefinition(); MockControl entityControl = MockControl.createControl(EntityManager.class); EntityManager entityManager = (EntityManager) entityControl.getMock(); MockControl txControl = MockControl.createControl(EntityTransaction.class); EntityTransaction entityTx = (EntityTransaction) txControl.getMock(); entityControl.expectAndReturn(entityManager.getTransaction(), entityTx); entityTx.begin(); entityControl.replay(); txControl.replay(); dialect.beginTransaction(entityManager, definition); entityControl.verify(); txControl.verify(); } public void testTranslateException() { OptimisticLockException ex = new OptimisticLockException(); assertEquals( EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex).getCause(), dialect.translateExceptionIfPossible(ex).getCause()); } }
31.906977
82
0.75984
6b88a061689d2ee2cc51f5f5525e458f97d9bebc
5,642
/* * Copyright (C) 2020 Beijing Yishu Technology Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.growingio.autotest.autotracker.webservices; import android.content.Intent; import android.net.Uri; import androidx.test.core.app.ActivityScenario; import androidx.test.espresso.action.ViewActions; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import com.gio.test.R; import com.gio.test.three.DemoApplication; import com.gio.test.three.autotrack.activity.ClickTestActivity; import com.google.common.truth.Truth; import com.growingio.autotest.TestTrackConfiguration; import com.growingio.autotest.help.BeforeAppOnCreate; import com.growingio.autotest.help.DataHelper; import com.growingio.autotest.help.Uninterruptibles; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.TimeUnit; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; @RunWith(AndroidJUnit4.class) @LargeTest public class DebuggerServiceTest { private static final String TAG = "DebuggerServiceTest"; private MockWebServer mMockWebServer; private WebSocket mWebSocket; @Before public void setup() { mMockWebServer = new MockWebServer(); } @BeforeAppOnCreate public static void beforeAppOnCreate() { DataHelper.deleteEventsDatabase(); DemoApplication.setConfiguration(TestTrackConfiguration.getTestConfig("growing.d80871b41ef40518")); } protected String getWsUrl() { String hostName = mMockWebServer.getHostName(); int port = mMockWebServer.getPort(); return "ws://" + hostName + ":" + port + "/"; } @Test public void debuggerServiceTest() throws JSONException { MockResponse ready = new MockResponse().withWebSocketUpgrade(new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) { mWebSocket = webSocket; sendMessage("ready"); } @Override public void onMessage(WebSocket webSocket, String text) { try { JSONObject message = new JSONObject(text); String msgType = message.getString("msgType"); switch (msgType) { case "ready": ActivityScenario.launch(ClickTestActivity.class); onView(withId(R.id.test_input)).perform(ViewActions.typeText(msgType)); sendMessage("logger_open"); onView(withId(R.id.test_input)).perform(ViewActions.typeText("logger_open")); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); break; case "refreshScreenshot": break; case "logger_data": onView(withText("测试Button点击")).perform(click()); onView(withId(R.id.test_input)).perform(ViewActions.replaceText(text)); sendMessage("logger_close"); onView(withText("Android")).perform(click()); break; case "debugger_data": onView(withText("Android")).perform(click()); onView(withId(R.id.test_input)).perform(ViewActions.replaceText(text)); onView(withId(R.id.test_input)).perform(ViewActions.typeText("结束测试")); sendMessage("quit"); break; default: //Truth.assertWithMessage("Unknown msgType = " + msgType).fail(); break; } } catch (JSONException e) { e.printStackTrace(); Truth.assertWithMessage(e.getMessage()).fail(); } } }); mMockWebServer.enqueue(ready); String uri = "growing.d80871b41ef40518://growingio/webservice?serviceType=debugger&wsUrl=" + Uri.encode(getWsUrl()); Intent intent = new Intent(); intent.setData(Uri.parse(uri)); ActivityScenario.launch(intent); Uninterruptibles.sleepUninterruptibly(8, TimeUnit.SECONDS); } private void sendMessage(String message) { try { mWebSocket.send(new JSONObject().put("msgType", message).toString()); } catch (JSONException exception) { exception.printStackTrace(); } } }
38.643836
124
0.629387
4d9d3a6f19c3e5af3a3d959f00fc4784dd36b5ff
289
package jp.crestmuse.cmx.sound; import javax.sound.midi.Receiver; import javax.sound.midi.Track; public interface SequenceGeneratable { /** * 続く場合trueを返す */ public boolean changeMeasure(Track track, long measureTick); public void sendInitializingMessages(Receiver r); }
18.0625
62
0.754325
ac7ab06cffd8d4b3b50ccd27ee1466db98068fb2
3,913
/* * Copyright (c) 2019-2020 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */ package org.geysermc.connector.network.session.cache; import com.github.steveice10.mc.protocol.data.game.chunk.Chunk; import com.github.steveice10.mc.protocol.data.game.chunk.Column; import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position; import com.github.steveice10.mc.protocol.data.game.world.block.BlockState; import lombok.Getter; import org.geysermc.connector.network.session.GeyserSession; import org.geysermc.connector.network.translators.world.block.BlockTranslator; import org.geysermc.connector.network.translators.world.chunk.ChunkPosition; import java.util.HashMap; import java.util.Map; public class ChunkCache { private boolean cache; private final GeyserSession session; @Getter private Map<ChunkPosition, Column> chunks = new HashMap<>(); public ChunkCache(GeyserSession session) { this.session = session; this.cache = session.getConnector().getConfig().isCacheChunks(); } public void addToCache(Column chunk) { if (!cache) { return; } ChunkPosition position = new ChunkPosition(chunk.getX(), chunk.getZ()); chunks.put(position, chunk); } public void updateBlock(Position position, BlockState block) { if (!cache) { return; } ChunkPosition chunkPosition = new ChunkPosition(position.getX() >> 4, position.getZ() >> 4); if (!chunks.containsKey(chunkPosition)) return; Column column = chunks.get(chunkPosition); Chunk chunk = column.getChunks()[position.getY() >> 4]; Position blockPosition = chunkPosition.getChunkBlock(position.getX(), position.getY(), position.getZ()); if (chunk != null) { chunk.set(blockPosition.getX(), blockPosition.getY(), blockPosition.getZ(), block); } } public BlockState getBlockAt(Position position) { if (!cache) { return BlockTranslator.AIR; } ChunkPosition chunkPosition = new ChunkPosition(position.getX() >> 4, position.getZ() >> 4); if (!chunks.containsKey(chunkPosition)) return BlockTranslator.AIR; Column column = chunks.get(chunkPosition); Chunk chunk = column.getChunks()[position.getY() >> 4]; Position blockPosition = chunkPosition.getChunkBlock(position.getX(), position.getY(), position.getZ()); if (chunk != null) { return chunk.get(blockPosition.getX(), blockPosition.getY(), blockPosition.getZ()); } return BlockTranslator.AIR; } public void removeChunk(ChunkPosition position) { if (!cache) { return; } chunks.remove(position); } }
38.362745
112
0.693841
12cef86f0e4259da80bc8da51aa1a29764728008
436
package com.food.services.Menu; import java.util.List; import com.food.domain.MenuVO; public interface MenuService { public void insert(MenuVO vo)throws Exception; public List<MenuVO> select(String u_id)throws Exception; public void update(MenuVO vo)throws Exception; public void updateState(MenuVO vo)throws Exception; public List<MenuVO> list() throws Exception; public void delete(MenuVO vo)throws Exception; }
19.818182
57
0.775229
ee20b40b33b0871d602e2187b6aaf39f282aa545
528
package dependencies; import org.springframework.context.annotation.DependsOn; import org.springframework.stereotype.Component; /** * @author yihuier * @Date 2020/11/26 10:19 * @Description */ @Component //@DependsOn({"simpleBean2"}) public class SimpleBean1 { // private SimpleBean2 simpleBean2; public SimpleBean1() { System.out.println("simpleBean1 creating..."); } // public SimpleBean1(SimpleBean2 simpleBean2) { // System.out.println("simpleBean1 creating..."); // this.simpleBean2 = simpleBean2; // } }
20.307692
56
0.727273
118981ba6b30feec9982d7c12f44ce59ec112533
5,498
package org.ffmpeg.avformat57; import com.sun.jna.Callback; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.LongByReference; import org.ffmpeg.avcodec57.AVPacket; import org.ffmpeg.avdevice57.AVDeviceCapabilitiesQuery; import org.ffmpeg.avdevice57.AVDeviceInfoList; import java.util.Arrays; import java.util.List; /** * <i>native declaration : libavformat\avformat.h:149</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class AVInputFormat extends Structure { /** C type : const char* */ public Pointer name; /** C type : const char* */ public Pointer long_name; public int flags; /** C type : const char* */ public Pointer extensions; /** C type : AVCodecTag** */ public Pointer codec_tag; /** * < AVClass for the private context<br> * C type : const AVClass* */ public Pointer priv_class; /** C type : const char* */ public Pointer mime_type; /** C type : AVInputFormat* */ public ByReference next; public int raw_codec_id; public int priv_data_size; /** C type : read_probe_callback* */ public read_probe_callback read_probe; /** C type : read_header_callback* */ public read_header_callback read_header; /** C type : read_packet_callback* */ public read_packet_callback read_packet; /** C type : read_close_callback* */ public read_close_callback read_close; /** C type : read_seek_callback* */ public read_seek_callback read_seek; /** C type : read_timestamp_callback* */ public read_timestamp_callback read_timestamp; /** C type : read_play_callback* */ public read_play_callback read_play; /** C type : read_pause_callback* */ public read_pause_callback read_pause; /** C type : read_seek2_callback* */ public read_seek2_callback read_seek2; /** C type : get_device_list_callback* */ public get_device_list_callback get_device_list; /** C type : create_device_capabilities_callback* */ public create_device_capabilities_callback create_device_capabilities; /** C type : free_device_capabilities_callback* */ public free_device_capabilities_callback free_device_capabilities; /** <i>native declaration : libavformat\avformat.h:137</i> */ public interface read_probe_callback extends Callback { int apply(AVProbeData AVProbeDataPtr1); }; /** <i>native declaration : libavformat\avformat.h:138</i> */ public interface read_header_callback extends Callback { int apply(AVFormatContext AVFormatContextPtr1); }; /** <i>native declaration : libavformat\avformat.h:139</i> */ public interface read_packet_callback extends Callback { int apply(AVFormatContext AVFormatContextPtr1, AVPacket pkt); }; /** <i>native declaration : libavformat\avformat.h:140</i> */ public interface read_close_callback extends Callback { int apply(AVFormatContext AVFormatContextPtr1); }; /** <i>native declaration : libavformat\avformat.h:141</i> */ public interface read_seek_callback extends Callback { int apply(AVFormatContext AVFormatContextPtr1, int stream_index, long timestamp, int flags); }; /** <i>native declaration : libavformat\avformat.h:142</i> */ public interface read_timestamp_callback extends Callback { long apply(AVFormatContext s, int stream_index, LongByReference pos, long pos_limit); }; /** <i>native declaration : libavformat\avformat.h:143</i> */ public interface read_play_callback extends Callback { int apply(AVFormatContext AVFormatContextPtr1); }; /** <i>native declaration : libavformat\avformat.h:144</i> */ public interface read_pause_callback extends Callback { int apply(AVFormatContext AVFormatContextPtr1); }; /** <i>native declaration : libavformat\avformat.h:145</i> */ public interface read_seek2_callback extends Callback { int apply(AVFormatContext s, int stream_index, long min_ts, long ts, long max_ts, int flags); }; /** <i>native declaration : libavformat\avformat.h:146</i> */ public interface get_device_list_callback extends Callback { int apply(AVFormatContext s, AVDeviceInfoList device_list); }; /** <i>native declaration : libavformat\avformat.h:147</i> */ public interface create_device_capabilities_callback extends Callback { int apply(AVFormatContext s, AVDeviceCapabilitiesQuery caps); }; /** <i>native declaration : libavformat\avformat.h:148</i> */ public interface free_device_capabilities_callback extends Callback { int apply(AVFormatContext s, AVDeviceCapabilitiesQuery caps); }; public AVInputFormat() { super(); } protected List<String> getFieldOrder() { return Arrays.asList("name", "long_name", "flags", "extensions", "codec_tag", "priv_class", "mime_type", "next", "raw_codec_id", "priv_data_size", "read_probe", "read_header", "read_packet", "read_close", "read_seek", "read_timestamp", "read_play", "read_pause", "read_seek2", "get_device_list", "create_device_capabilities", "free_device_capabilities"); } public AVInputFormat(Pointer peer) { super(peer); } public static class ByReference extends AVInputFormat implements Structure.ByReference { }; public static class ByValue extends AVInputFormat implements Structure.ByValue { }; }
43.291339
356
0.754274
2cc24cabf20d5658c02222220aff3bcf60271c76
2,489
/** * Project: com.dianping.zebra.zebra-client-0.1.0 * <p/> * File Created at 2011-6-15 * $Id$ * <p/> * Copyright 2010 dianping.com. * All rights reserved. * <p/> * This software is the confidential and proprietary information of * Dianping Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with dianping.com. */ package com.dianping.zebra.shard.router.rule.engine; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import com.dianping.zebra.exception.ZebraConfigException; import com.dianping.zebra.shard.router.rule.dimension.AbstractDimensionRule; import com.dianping.zebra.shard.router.rule.dimension.DimensionRule; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyObject; /** * * @author danson.liu, Dozer */ public class GroovyRuleEngine implements RuleEngine { private final GroovyObject engineObj; private static final Map<String, Class<?>> RULE_CLASS_CACHE = new ConcurrentHashMap<String, Class<?>>(); public GroovyRuleEngine(String rule) { try { engineObj = getGroovyObject(rule); } catch (Exception e) { throw new ZebraConfigException("Construct groovy rule engine failed, cause: ", e); } } @SuppressWarnings("resource") private static final GroovyObject getGroovyObject(String rule) throws IllegalAccessException, InstantiationException { if (!RULE_CLASS_CACHE.containsKey(rule)) { synchronized (GroovyRuleEngine.class) { if (!RULE_CLASS_CACHE.containsKey(rule)) { Matcher matcher = DimensionRule.RULE_COLUMN_PATTERN.matcher(rule); StringBuilder engineClazzImpl = new StringBuilder(200) .append("class RuleEngineBaseImpl extends " + RuleEngineBase.class.getName() + "{") .append("Object execute(Map context) {").append(matcher.replaceAll("context.get(\"$1\")")) .append("}").append("}"); GroovyClassLoader loader = new GroovyClassLoader(AbstractDimensionRule.class.getClassLoader()); Class<?> engineClazz = loader.parseClass(engineClazzImpl.toString()); RULE_CLASS_CACHE.put(rule, engineClazz); } } } return (GroovyObject) RULE_CLASS_CACHE.get(rule).newInstance(); } @Override public Object eval(Map<String, Object> valMap) { return engineObj.invokeMethod("execute", valMap); } }
34.569444
106
0.723182
180d1c484a285bc4c3ddd2095dde2ebb1f3d95fb
2,054
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.linkis.cli.core.interactor.execution.jobexec; import org.apache.linkis.cli.common.entity.execution.jobexec.JobExec; public abstract class JobManExec implements JobExec, Cloneable { Exception exception; /** * ID for client itself */ private String cid; /** * ID generated by server */ private String jobID; private boolean success; private String message; @Override public final String getCid() { return cid; } @Override public void setCid(String cid) { this.cid = cid; } @Override public final String getJobID() { return this.jobID; } @Override public void setJobID(String jobID) { this.jobID = jobID; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public Exception getException() { return exception; } @Override public void setException(Exception exception) { this.exception = exception; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } }
25.358025
75
0.67186
aaf94df485daf004fee9a0b1bd299d1690685d25
11,254
/* * Copyright (c) 2010-2020 Tencent Cloud. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.tencent.qcloud.core.http; import com.tencent.qcloud.core.auth.QCloudSigner; import com.tencent.qcloud.core.common.QCloudClientException; import com.tencent.qcloud.core.util.QCloudStringUtils; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.CacheControl; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; public class HttpRequest<T> { protected final Request.Builder requestBuilder; protected final Map<String, List<String>> headers; protected final Set<String> noSignHeaders; protected final RequestBody requestBody; protected final String method; protected final Object tag; protected final URL url; protected final ResponseBodyConverter<T> responseBodyConverter; protected final boolean calculateContentMD5; HttpRequest(Builder<T> builder) { requestBuilder = builder.requestBuilder; responseBodyConverter = builder.responseBodyConverter; headers = builder.headers; noSignHeaders = builder.noSignHeaderKeys; method = builder.method; calculateContentMD5 = builder.calculateContentMD5; if (builder.tag == null) { tag = toString(); } else { tag = builder.tag; } url = builder.httpUrlBuilder.build().url(); if (builder.requestBodySerializer != null) { requestBody = builder.requestBodySerializer.body(); } else { requestBody = null; } requestBuilder.method(builder.method, requestBody); } public Map<String, List<String>> headers() { return headers; } public Set<String> getNoSignHeaders() { return noSignHeaders; } public String header(String name) { List<String> values = headers.get(name); return values != null ? values.get(0) : null; } public Object tag() { return tag; } public void setOkHttpRequestTag(String tag) { requestBuilder.tag(tag); } public void addHeader(String name, String value) { List<String> values = headers.get(name); if (values == null || values.size() < 1) { requestBuilder.addHeader(name, value); addHeaderNameValue(headers, name, value); } } public void setUrl(String url){ requestBuilder.url(url); } public void removeHeader(String name) { requestBuilder.removeHeader(name); headers.remove(name); } public boolean shouldCalculateContentMD5() { return calculateContentMD5 && QCloudStringUtils.isEmpty(header(HttpConstants.Header.CONTENT_MD5)); } public String method() { return method; } public String host() { return url.getHost(); } public String contentType() { if (requestBody == null) { return null; } MediaType mediaType = requestBody.contentType(); return mediaType != null ? mediaType.toString() : null; } public long contentLength() throws IOException { if (requestBody == null) { return -1; } return requestBody.contentLength(); } public URL url() { return url; } public ResponseBodyConverter<T> getResponseBodyConverter() { return responseBodyConverter; } public RequestBody getRequestBody() { return requestBody; } public Request buildRealRequest() { return requestBuilder.build(); } QCloudSigner getQCloudSigner() throws QCloudClientException { return null; } private static void addHeaderNameValue(Map<String, List<String>> headers, String name, String value) { List<String> values = headers.get(name); if (values == null) { values = new ArrayList<>(2); headers.put(name, values); } values.add(value.trim()); } public static class Builder<T> { Object tag; String method; Request.Builder requestBuilder; HttpUrl.Builder httpUrlBuilder; Map<String, List<String>> headers = new HashMap<>(10); Set<String> noSignHeaderKeys = new HashSet<>(); // 不签名的 header RequestBodySerializer requestBodySerializer; ResponseBodyConverter<T> responseBodyConverter; boolean calculateContentMD5; boolean isCacheEnabled = true; public Builder() { httpUrlBuilder = new HttpUrl.Builder(); requestBuilder = new Request.Builder(); } public Builder<T> url(URL url) { HttpUrl httpUrl = HttpUrl.get(url); if (httpUrl == null) { throw new IllegalArgumentException("url is not legal : " + url); } httpUrlBuilder = httpUrl.newBuilder(); return this; } public Builder<T> scheme(String scheme) { httpUrlBuilder.scheme(scheme); return this; } public Builder<T> tag(Object tag) { this.tag = tag; return this; } public Builder<T> host(String host) { httpUrlBuilder.host(host); return this; } public Builder<T> port(int port) { httpUrlBuilder.port(port); return this; } public Builder<T> path(String path) { if (path.startsWith("/")) { path = path.substring(1); } // if (path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } if (path.length() > 0) { httpUrlBuilder.addPathSegments(path); } return this; } public Builder<T> method(String method) { this.method = method; return this; } public Builder<T> query(String key, String value) { if (key != null) { httpUrlBuilder.addQueryParameter(key, value); } return this; } public Builder<T> encodedQuery(String key, String value) { if (key != null) { httpUrlBuilder.addEncodedQueryParameter(key, value); } return this; } public Builder<T> query(Map<String, String> nameValues) { if (nameValues != null) { for (Map.Entry<String, String> entry : nameValues.entrySet()) { String name = entry.getKey(); if (name != null) { httpUrlBuilder.addQueryParameter(name, entry.getValue()); } } } return this; } public Builder<T> encodedQuery(Map<String, String> nameValues) { if (nameValues != null) { for (Map.Entry<String, String> entry : nameValues.entrySet()) { String name = entry.getKey(); if (name != null) { httpUrlBuilder.addEncodedQueryParameter(name, entry.getValue()); } } } return this; } public Builder<T> contentMD5() { calculateContentMD5 = true; return this; } public Builder<T> addHeader(String name, String value) { if (name != null && value != null) { requestBuilder.addHeader(name, value); addHeaderNameValue(headers, name, value); } return this; } public Builder<T> addHeaders(Map<String, List<String>> headers) { if (headers != null) { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String name = entry.getKey(); for (String value : entry.getValue()) { if (name != null && value != null) { requestBuilder.addHeader(name, value); addHeaderNameValue(this.headers, name, value); } } } } return this; } public Builder<T> removeHeader(String name) { requestBuilder.removeHeader(name); headers.remove(name); return this; } public Builder<T> addNoSignHeaderKeys(List<String> keys) { noSignHeaderKeys.addAll(keys); return this; } public Set<String> getNoSignHeaderKeys() { return noSignHeaderKeys; } public Builder<T> userAgent(String userAgent) { requestBuilder.addHeader(HttpConstants.Header.USER_AGENT, userAgent); addHeaderNameValue(this.headers, HttpConstants.Header.USER_AGENT, userAgent); return this; } public Builder<T> setUseCache(boolean cacheEnabled) { isCacheEnabled = cacheEnabled; return this; } public Builder<T> body(RequestBodySerializer bodySerializer) { requestBodySerializer = bodySerializer; return this; } public Builder<T> converter(ResponseBodyConverter<T> responseBodyConverter) { this.responseBodyConverter = responseBodyConverter; return this; } protected void prepareBuild() { requestBuilder.url(httpUrlBuilder.build()); if (!isCacheEnabled) { requestBuilder.cacheControl(CacheControl.FORCE_NETWORK); } if (responseBodyConverter == null) { // default use string converter responseBodyConverter = (ResponseBodyConverter<T>) ResponseBodyConverter.string(); } } public HttpRequest<T> build() { prepareBuild(); return new HttpRequest<>(this); } } }
30.748634
106
0.585303
94cb1308c0b6fb24544f118b9374a75c1fff5d6c
279
package com.qianmi.open.api.qmcs.endpoint; import java.util.Map; public interface MessageHandler { public void onMessage(EndpointContext context) throws Exception; // just got msg that can not reply public void onMessage(Map<String, Object> message, Identity messageFrom); }
31
74
0.795699
1f054ac3bc02c5870a9ce8dfdd43403f276717c0
2,805
package com.ramasolutions.petagramins.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.ramasolutions.petagramins.R; import com.ramasolutions.petagramins.db.Database; import com.ramasolutions.petagramins.pojo.FavItem; import com.squareup.picasso.Picasso; import java.util.List; public class FavAdapter extends RecyclerView.Adapter<FavAdapter.ViewHolder> { private Context context; private List<FavItem> favItemsList; private Database database; public FavAdapter(Context context, List<FavItem> favItemsList) { this.context = context; this.favItemsList = favItemsList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_favoritos, parent, false); database = new Database(context); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.tvFavPetName.setText(favItemsList.get(position).getFavName()); //holder.ivFavPetPic.setImageResource(favItemsList.get(position).getFavPic()); Picasso.with(context) .load(favItemsList.get(position).getFavPic()) .resize(100, 100) .centerCrop() .into(holder.ivFavPetPic); } @Override public int getItemCount() { return favItemsList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { private ImageView ivFavPetPic; private TextView tvFavPetName; private Button favBtn; public ViewHolder(View itemView) { super(itemView); ivFavPetPic = itemView.findViewById(R.id.ivFavPetPic); tvFavPetName = itemView.findViewById(R.id.tvFavPetName); favBtn = itemView.findViewById(R.id.favBtn); //remove from fav after click favBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int position = getAdapterPosition(); final FavItem favItem = favItemsList.get(position); database.remove_fav(favItem.getKey_id()); removeItem(position); } }); } private void removeItem(int position) { favItemsList.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, favItemsList.size()); } } }
31.875
113
0.662745
e0555efd3b13258557be3b4dafb9f25876254e42
3,220
package org.jbehave.core.configuration; import com.thoughtworks.paranamer.NullParanamer; import com.thoughtworks.paranamer.Paranamer; import org.jbehave.core.embedder.StoryControls; import org.jbehave.core.failures.FailureStrategy; import org.jbehave.core.failures.PassingUponPendingStep; import org.jbehave.core.failures.PendingStepStrategy; import org.jbehave.core.failures.RethrowingFailure; import org.jbehave.core.i18n.LocalizedKeywords; import org.jbehave.core.io.LoadFromClasspath; import org.jbehave.core.io.StoryLoader; import org.jbehave.core.parsers.RegexPrefixCapturingPatternParser; import org.jbehave.core.parsers.RegexStoryParser; import org.jbehave.core.parsers.StepPatternParser; import org.jbehave.core.parsers.StoryParser; import org.jbehave.core.reporters.ConsoleOutput; import org.jbehave.core.reporters.FreemarkerViewGenerator; import org.jbehave.core.reporters.PrintStreamStepdocReporter; import org.jbehave.core.reporters.StepdocReporter; import org.jbehave.core.reporters.ViewGenerator; import org.jbehave.core.steps.MarkUnmatchedStepsAsPending; import org.jbehave.core.steps.ParameterControls; import org.jbehave.core.steps.SilentStepMonitor; import org.jbehave.core.steps.StepCollector; import org.jbehave.core.steps.StepFinder; import org.jbehave.core.steps.StepMonitor; /** * The configuration that works for most situations that users are likely to encounter. * The elements configured are: * <ul> * <li>{@link Keywords}: {@link LocalizedKeywords}</li> * <li>{@link StoryParser}: {@link RegexStoryParser}</li> * <li>{@link StoryLoader}: {@link LoadFromClasspath}</li> * <li>{@link StoryControls}: {@link StoryControls}</li> * <li>{@link FailureStrategy}: {@link RethrowingFailure}</li> * <li>{@link PendingStepStrategy}: {@link PassingUponPendingStep}</li> * <li>{@link DefaultStoryReporter}: {@link ConsoleOutput}</li> * <li>{@link StepCollector}: {@link MarkUnmatchedStepsAsPending}</li> * <li>{@link StepFinder}: {@link StepFinder}</li> * <li>{@link StepPatternParser}: {@link RegexPrefixCapturingPatternParser}</li> * <li>{@link StepdocReporter}: {@link PrintStreamStepdocReporter}</li> * <li>{@link StepMonitor}: {@link SilentStepMonitor} * <li>{@link Paranamer}: {@link NullParanamer}</li> * <li>{@link ParameterControls}: {@link ParameterControls}</li> * <li>{@link ViewGenerator}: {@link FreemarkerViewGenerator}</li> * </ul> */ public class MostUsefulConfiguration extends Configuration { public MostUsefulConfiguration() { useKeywords(new LocalizedKeywords()); useStoryControls(new StoryControls()); useStoryLoader(new LoadFromClasspath()); useParameterControls(new ParameterControls()); useFailureStrategy(new RethrowingFailure()); usePendingStepStrategy(new PassingUponPendingStep()); useStepFinder(new StepFinder()); useStepCollector(new MarkUnmatchedStepsAsPending(stepFinder(), keywords())); useStepPatternParser(new RegexPrefixCapturingPatternParser()); useStepMonitor(new SilentStepMonitor()); useStepdocReporter(new PrintStreamStepdocReporter()); useParanamer(new NullParanamer()); useViewGenerator(new FreemarkerViewGenerator()); } }
46
87
0.770807
2bdabe9cf076ef673ea5e1f9278926e942da271c
3,223
package mage.cards.g; import java.util.UUID; import mage.MageObject; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.effects.RedirectionEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.Zone; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.stack.Spell; import mage.players.Player; import mage.target.TargetSource; import mage.target.common.TargetControlledCreaturePermanent; /** * * @author L_J */ public final class GeneralsRegalia extends CardImpl { public GeneralsRegalia(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{3}"); // {3}: The next time a source of your choice would deal damage to you this turn, that damage is dealt to target creature you control instead. Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new GeneralsRegaliaEffect(), new GenericManaCost(3)); ability.addTarget(new TargetControlledCreaturePermanent()); this.addAbility(ability); } private GeneralsRegalia(final GeneralsRegalia card) { super(card); } @Override public GeneralsRegalia copy() { return new GeneralsRegalia(this); } } class GeneralsRegaliaEffect extends RedirectionEffect { private final TargetSource damageSource; public GeneralsRegaliaEffect() { super(Duration.EndOfTurn, Integer.MAX_VALUE, UsageType.ONE_USAGE_ABSOLUTE); staticText = "The next time a source of your choice would deal damage to you this turn, that damage is dealt to target creature you control instead"; this.damageSource = new TargetSource(); } public GeneralsRegaliaEffect(final GeneralsRegaliaEffect effect) { super(effect); this.damageSource = effect.damageSource.copy(); } @Override public GeneralsRegaliaEffect copy() { return new GeneralsRegaliaEffect(this); } @Override public void init(Ability source, Game game) { this.damageSource.choose(Outcome.PreventDamage, source.getControllerId(), source.getSourceId(), game); super.init(source, game); } @Override public boolean applies(GameEvent event, Ability source, Game game) { // check source MageObject object = game.getObject(event.getSourceId()); if (object == null) { game.informPlayers("Couldn't find source of damage"); return false; } if (!object.getId().equals(damageSource.getFirstTarget()) && (!(object instanceof Spell) || !((Spell) object).getSourceId().equals(damageSource.getFirstTarget()))) { return false; } this.redirectTarget = source.getTargets().get(0); // check player Player player = game.getPlayer(event.getTargetId()); if (player != null) { if (player.getId().equals(source.getControllerId())) { return true; } } return false; } }
32.23
157
0.68942
1926e944bcd79d9fc724fa3c9071c79b4b8f6509
24,851
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gct.idea.debugger.ui; import com.google.api.services.clouddebugger.Clouddebugger.Debugger; import com.google.api.services.clouddebugger.model.Debuggee; import com.google.api.services.clouddebugger.model.ListDebuggeesResponse; import com.google.common.base.Strings; import com.google.gct.idea.debugger.CloudDebugProcessState; import com.google.gct.idea.debugger.CloudDebuggerClient; import com.google.gct.idea.debugger.ProjectRepositoryState; import com.google.gct.idea.debugger.ProjectRepositoryValidator; import com.google.gct.idea.debugger.SyncResult; import com.google.gct.idea.elysium.ProjectSelector; import com.google.gct.idea.util.GctBundle; import com.google.gct.idea.util.GctTracking; import com.google.gct.login.CredentialedUser; import com.google.gct.login.GoogleLogin; import com.google.gct.stats.UsageTrackerProvider; import com.intellij.dvcs.DvcsUtil; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.JBColor; import com.intellij.ui.components.JBCheckBox; import com.intellij.ui.components.JBLabel; import com.intellij.util.containers.HashMap; import git4idea.actions.BasicAction; import git4idea.branch.GitBrancher; import git4idea.commands.GitCommand; import git4idea.commands.GitHandlerUtil; import git4idea.commands.GitLineHandler; import git4idea.i18n.GitBundle; import git4idea.repo.GitRepository; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.event.DocumentEvent; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import java.awt.Dimension; import java.awt.Font; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.text.DateFormat; import java.util.Collections; import java.util.Date; import java.util.Map; /** * CloudAttachDialog shows a dialog allowing the user to select a module and debug. */ public class CloudAttachDialog extends DialogWrapper { private static final Logger LOG = Logger.getInstance(CloudAttachDialog.class); private final Project myProject; private final ProjectDebuggeeBinding myWireup; private JComboBox myDebuggeeTarget; // Module selector private ProjectSelector myElysiumProjectId; // Project combo box private JBLabel myInfoPanel; private String myOriginalBranchName; private JPanel myPanel; private CloudDebugProcessState myProcessResultState; private GitRepository mySourceRepository; private String myStashMessage = null; private SyncResult mySyncResult; private JBCheckBox mySyncStashCheckbox; private JBLabel myWarningLabel; private JBLabel myWarningLabel2; public CloudAttachDialog(@NotNull Project project) { super(project, true); myProject = project; init(); initValidation(); setTitle(GctBundle.getString("clouddebug.attachtitle")); setOKButtonText(GctBundle.getString("clouddebug.attach")); mySyncStashCheckbox.setVisible(false); mySyncStashCheckbox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (mySyncStashCheckbox.isVisible()) { myWarningLabel.setVisible(!mySyncStashCheckbox.isSelected()); myWarningLabel2.setVisible(!mySyncStashCheckbox.isSelected()); myInfoPanel.setVisible(mySyncStashCheckbox.isSelected()); if (mySyncStashCheckbox.isSelected()) { setOKButtonText(isContinued() ? GctBundle.getString("clouddebug.continuesession") : GctBundle.getString("clouddebug.attach")); } else { setOKButtonText(isContinued() ? GctBundle.getString("clouddebug.continueanyway") : GctBundle.getString("clouddebug.attach.anyway")); } } } }); myWarningLabel.setVisible(false); myWarningLabel.setFont(new Font(myWarningLabel.getFont().getName(), Font.BOLD, myWarningLabel.getFont().getSize() - 1)); myWarningLabel.setForeground(JBColor.RED); myWarningLabel2.setVisible(false); myWarningLabel2.setFont(new Font(myWarningLabel2.getFont().getName(), Font.PLAIN, myWarningLabel.getFont().getSize() - 1)); myWarningLabel2.setText(GctBundle.getString("clouddebug.sourcedoesnotmatch")); myInfoPanel.setFont(new Font(myWarningLabel2.getFont().getName(), Font.PLAIN, myWarningLabel.getFont().getSize() - 1)); Border paddingBorder = BorderFactory.createEmptyBorder(2, 0, 2, 0); myInfoPanel.setBorder(paddingBorder); Window myWindow = getWindow(); if (myWindow != null) { myWindow.setPreferredSize(new Dimension(355, 175)); } BasicAction.saveAll(); myWireup = new ProjectDebuggeeBinding(myElysiumProjectId, myDebuggeeTarget); myDebuggeeTarget.setEnabled(false); myDebuggeeTarget.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(myDebuggeeTarget.isEnabled()) { buildResult(); checkSyncStashState(); } else { myWarningLabel.setVisible(false); myWarningLabel2.setVisible(false); } } }); toggleOKActionButton(); } @Nullable @Override protected JComponent createCenterPanel() { return myPanel; } @Override protected void doOKAction() { if (getOKAction().isEnabled()) { UsageTrackerProvider.getInstance() .trackEvent(GctTracking.CATEGORY, GctTracking.CLOUD_DEBUGGER, "start.session", null); // TODO : add source context tracking info if (mySyncStashCheckbox.isSelected()) { syncOrStash(); } else { buildResult(); close(OK_EXIT_CODE); // We close before kicking off the update so it doesn't interfere with // the output window coming to focus. } } } @Override protected ValidationInfo doValidate() { // These should not normally occur. if (!GoogleLogin.getInstance().isLoggedIn()) { return new ValidationInfo(GctBundle.getString("clouddebug.nologin")); } if (Strings.isNullOrEmpty(myElysiumProjectId.getText())) { return new ValidationInfo(GctBundle.getString("clouddebug.noprojectid"), myElysiumProjectId); } if (!myDebuggeeTarget.isEnabled()) {// && myDebuggeeTarget.getItemCount() > 0) { return new ValidationInfo(GctBundle.getString("clouddebug.selectvalidproject"), myElysiumProjectId); } if (myDebuggeeTarget.getSelectedItem() == null) {// && myDebuggeeTarget.getItemCount() > 0) { return new ValidationInfo(GctBundle.getString("clouddebug.nomoduleselected"), myDebuggeeTarget); } return null; } @Nullable public CloudDebugProcessState getResultState() { return myProcessResultState; } public void setInputState(@Nullable CloudDebugProcessState inputState) { myWireup.setInputState(inputState); } private void toggleOKActionButton() { setOKActionEnabled(isContinued() || doValidate() == null); } private void buildResult() { myProcessResultState = myWireup.buildResult(myProject); ProjectRepositoryState repositoryState = ProjectRepositoryState.fromProcessState(myProcessResultState); repositoryState.setStashMessage(myStashMessage); repositoryState.setSourceRepository(mySourceRepository); repositoryState.setOriginalBranchName(myOriginalBranchName); } /** * Checks whether a stash or sync is needed based on the chosen target and local state. */ private void checkSyncStashState() { if (myProcessResultState == null) { LOG.error("unexpected result state during a check sync stash state"); return; } mySyncResult = new ProjectRepositoryValidator(myProcessResultState).checkSyncStashState(); if (mySyncResult.needsStash() && mySyncResult.needsSync()) { setOKButtonText(isContinued() ? GctBundle.getString("clouddebug.continuesession") : GctBundle.getString("clouddebug.attach")); mySyncStashCheckbox.setVisible(true); assert mySyncResult.getTargetSyncSHA() != null; mySyncStashCheckbox.setText( GctBundle.getString("clouddebug.stash.local.changes.and.sync", mySyncResult.getTargetSyncSHA().substring(0, 7))); mySyncStashCheckbox.setSelected(true); myWarningLabel.setVisible(false); myWarningLabel2.setVisible(false); myInfoPanel.setVisible(true); } else if (mySyncResult.needsStash()) { setOKButtonText(isContinued() ? GctBundle.getString("clouddebug.continuesession") : GctBundle.getString("clouddebug.attach")); mySyncStashCheckbox.setVisible(true); mySyncStashCheckbox.setText(GctBundle.getString("clouddebug.stashbuttontext")); mySyncStashCheckbox.setSelected(true); myWarningLabel.setVisible(false); myWarningLabel2.setVisible(false); myInfoPanel.setVisible(true); } else if (mySyncResult.needsSync()) { setOKButtonText(isContinued() ? GctBundle.getString("clouddebug.continuesession") : GctBundle.getString("clouddebug.attach")); mySyncStashCheckbox.setVisible(true); assert mySyncResult.getTargetSyncSHA() != null; mySyncStashCheckbox.setText("Sync to " + mySyncResult.getTargetSyncSHA().substring(0, 7)); mySyncStashCheckbox.setSelected(true); myWarningLabel.setVisible(false); myWarningLabel2.setVisible(false); myInfoPanel.setVisible(true); } else if (mySyncResult.needsSync() && mySyncResult.getTargetSyncSHA() == null) { setOKButtonText(isContinued() ? GctBundle.getString("clouddebug.continueanyway") : GctBundle.getString("clouddebug.attach.anyway")); myWarningLabel.setVisible(true); myWarningLabel2.setVisible(true); myInfoPanel.setVisible(true); myWarningLabel2.setText(GctBundle.getString("clouddebug.no.matching.sha")); } else if (!mySyncResult.hasRemoteRepository()) { setOKButtonText(isContinued() ? GctBundle.getString("clouddebug.continueanyway") : GctBundle.getString("clouddebug.attach.anyway")); myWarningLabel.setVisible(true); myWarningLabel2.setVisible(true); myInfoPanel.setVisible(true); if (mySyncResult.getRepositoryType() != null) { myWarningLabel2.setText(GctBundle.getString("clouddebug.repositories.are.not.supported", mySyncResult.getRepositoryType())); } else { myWarningLabel2.setText(GctBundle.getString("clouddebug.no.remote.repository")); } } else { setOKButtonText(isContinued() ? GctBundle.getString("clouddebug.continuesession") : GctBundle.getString("clouddebug.attach")); mySyncStashCheckbox.setVisible(false); myWarningLabel.setVisible(false); myWarningLabel2.setVisible(false); myInfoPanel.setVisible(true); } } private boolean isContinued() { CloudDebugProcessState state = myWireup.getInputState(); return state != null && state.getCurrentServerBreakpointList().size() > 0; } private void refreshAndClose() { buildResult(); close(OK_EXIT_CODE); } private boolean stash() { if (!mySyncResult.hasLocalRepository()) { LOG.error("unexpected null local repro in call to stash"); return false; } final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); if (changeListManager.isFreezedWithNotification("Can not stash changes now")) return false; final GitLineHandler handler = new GitLineHandler(myProject, mySourceRepository.getRoot(), GitCommand.STASH); handler.addParameters("save"); handler.addParameters("--keep-index"); String date = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date()); myStashMessage = "Cloud Debugger saved changes from branch " + myOriginalBranchName + " at " + date; handler.addParameters(myStashMessage); AccessToken token = DvcsUtil.workingTreeChangeStarted(myProject); try { GitHandlerUtil.doSynchronously(handler, GitBundle.getString("stashing.title"), handler.printableCommandLine()); } finally { DvcsUtil.workingTreeChangeFinished(myProject, token); } return true; } /** * Performs the actual sync/stash needed before attaching. */ private void syncOrStash() { // When the user edits a document in intelliJ, there are spurious updates to the timestamp of // the document for an unspecified amount of time (even though there are no real edits). // So, we save-all right before we stash to (help) ensure we don't get a conflict dialog. // The conflict dialog happens when the timestamps of the document and file are mismatched. // So when we do the git operations, we want the document and file timestamps to match exactly. BasicAction.saveAll(); mySourceRepository = mySyncResult.getLocalRepository(); if (mySyncResult.needsStash() || mySyncResult.needsSync()) { if (mySourceRepository.getCurrentBranch() != null) { myOriginalBranchName = mySourceRepository.getCurrentBranch().getName(); } else { myOriginalBranchName = mySourceRepository.getCurrentRevision(); } } if (mySyncResult.needsStash()) { if (!stash()) { return; } } if (!Strings.isNullOrEmpty(mySyncResult.getTargetSyncSHA())) { //try to check out that revision. final GitBrancher brancher = ServiceManager.getService(myProject, GitBrancher.class); if (mySourceRepository == null) { LOG.error("unexpected null source repo with a target SHA."); return; } assert mySyncResult.getTargetSyncSHA() != null; brancher.checkout(mySyncResult.getTargetSyncSHA(), false, Collections.singletonList(mySourceRepository), new Runnable() { @Override public void run() { refreshAndClose(); } }); } else { refreshAndClose(); } } /** * This binding between the project and debuggee is refactored out to make it reusable in the future. */ private class ProjectDebuggeeBinding { private final JComboBox myDebugeeTarget; private final ProjectSelector myElysiumProjectId; private Debugger myCloudDebuggerClient = null; private CredentialedUser myCredentialedUser = null; private CloudDebugProcessState myInputState; public ProjectDebuggeeBinding(@NotNull ProjectSelector elysiumProjectId, @NotNull JComboBox debugeeTarget) { myElysiumProjectId = elysiumProjectId; myDebugeeTarget = debugeeTarget; myElysiumProjectId.getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { refreshDebugTargetList(); } }); myElysiumProjectId.addModelListener(new TreeModelListener() { @Override public void treeNodesChanged(TreeModelEvent e) { } @Override public void treeNodesInserted(TreeModelEvent e) { } @Override public void treeNodesRemoved(TreeModelEvent e) { } @Override public void treeStructureChanged(TreeModelEvent e) { refreshDebugTargetList(); } }); } @NotNull public CloudDebugProcessState buildResult(Project project) { Long number = myElysiumProjectId.getProjectNumber(); String projectNumberString = number != null ? number.toString() : null; ProjectDebuggeeBinding.DebugTarget selectedItem = (ProjectDebuggeeBinding.DebugTarget)myDebugeeTarget.getSelectedItem(); String savedDebuggeeId = selectedItem != null ? selectedItem.getId() : null; String savedProjectDescription = myElysiumProjectId.getText(); return new CloudDebugProcessState(myCredentialedUser != null ? myCredentialedUser.getEmail() : null, savedDebuggeeId, savedProjectDescription, projectNumberString, project); } @Nullable public Debugger getCloudDebuggerClient() { CredentialedUser credentialedUser = myElysiumProjectId.getSelectedUser(); if (myCredentialedUser == credentialedUser) { return myCloudDebuggerClient; } myCredentialedUser = credentialedUser; myCloudDebuggerClient = myCredentialedUser != null ? CloudDebuggerClient.getLongTimeoutClient(myCredentialedUser.getEmail()) : null; return myCloudDebuggerClient; } @Nullable public CloudDebugProcessState getInputState() { return myInputState; } public void setInputState(@Nullable CloudDebugProcessState inputState) { myInputState = inputState; if (myInputState != null) { myElysiumProjectId.setText(myInputState.getProjectName()); } } /** * Refreshes the list of attachable debug targets based on the project selection. */ @SuppressWarnings("unchecked") private void refreshDebugTargetList() { myDebugeeTarget.removeAllItems(); // myDebuggeeTarget.addItem("Loading..."); // TODO implement a loading state in the modules dropdown ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { try { if (myElysiumProjectId.getProjectNumber() != null && getCloudDebuggerClient() != null) { final ListDebuggeesResponse debuggees = getCloudDebuggerClient().debuggees().list() .setProject(myElysiumProjectId.getProjectNumber().toString()) .execute(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { DebugTarget targetSelection = null; // myDebugeeTarget.removeAllItems(); if (debuggees == null || debuggees.getDebuggees() == null || debuggees.getDebuggees().isEmpty()) { myDebugeeTarget.setEnabled(false); myDebugeeTarget.addItem(GctBundle.getString("clouddebug.nomodulesfound")); } else { myDebugeeTarget.setEnabled(true); Map<String, DebugTarget> perModuleCache = new HashMap<String, DebugTarget>(); for (Debuggee debuggee : debuggees.getDebuggees()) { DebugTarget item = new DebugTarget(debuggee, myElysiumProjectId.getText()); if (!Strings.isNullOrEmpty(item.getModule()) && !Strings.isNullOrEmpty(item.getVersion())) { //If we already have an existing item for that module+version, compare the minor // versions and only use the latest minor version. String key = String.format("%s:%s", item.getModule(), item.getVersion()); DebugTarget existing = perModuleCache.get(key); if (existing != null && existing.getMinorVersion() > item.getMinorVersion()) { continue; } if (existing != null) { myDebugeeTarget.removeItem(existing); } perModuleCache.put(key, item); } if (myInputState != null && !Strings.isNullOrEmpty(myInputState.getDebuggeeId())) { assert myInputState.getDebuggeeId() != null; if (myInputState.getDebuggeeId().equals(item.getId())) { targetSelection = item; } } myDebugeeTarget.addItem(item); CloudAttachDialog.this.toggleOKActionButton(); } } if (targetSelection != null) { myDebugeeTarget.setSelectedItem(targetSelection); } } }); } } catch (IOException ex) { LOG.error("Error listing debuggees from Cloud Debugger API", ex); } } }); } public class DebugTarget { private static final String MODULE = "module"; private final Debuggee myDebuggee; private String myDescription; private long myMinorVersion = 0; private String myModule; private String myVersion; public DebugTarget(@NotNull Debuggee debuggee, @NotNull String projectName) { myDebuggee = debuggee; if (myDebuggee.getLabels() != null) { myDescription = ""; myModule = ""; myVersion = ""; String minorVersion = ""; //Get the module name, major version and minor version strings. for (Map.Entry<String, String> entry : myDebuggee.getLabels().entrySet()) { if (entry.getKey().equalsIgnoreCase(MODULE)) { myModule = entry.getValue(); } else if (entry.getKey().equalsIgnoreCase("minorversion")) { minorVersion = entry.getValue(); } else if (entry.getKey().equalsIgnoreCase("version")) { myVersion = entry.getValue(); } else { //This is fallback logic where we dump the labels verbatim if they //change from underneath us. myDescription += String.format("%s:%s", entry.getKey(),entry.getValue()); } } //Build a description from the strings. if (!Strings.isNullOrEmpty(myModule)) { myDescription = GctBundle.getString("clouddebug.version.with.module.format", myModule, myVersion); } else if (!Strings.isNullOrEmpty(myVersion)) { myDescription = GctBundle.getString("clouddebug.versionformat", myVersion); } //Record the minor version. We only show the latest minor version. try { if (!Strings.isNullOrEmpty(minorVersion)) { myMinorVersion = Long.parseLong(minorVersion); } } catch(NumberFormatException ex) { LOG.warn("unable to parse minor version: " + minorVersion); } } //Finally if nothing worked (maybe labels aren't enabled?), we fall //back to the old logic of using description with the project name stripped out. if (Strings.isNullOrEmpty(myDescription)) { myDescription = myDebuggee.getDescription(); if (myDescription != null && !Strings.isNullOrEmpty(projectName) && myDescription.startsWith(projectName + "-")) { myDescription = myDescription.substring(projectName.length() + 1); } } } public String getId() { return myDebuggee.getId(); } @Override public String toString() { return myDescription; } public long getMinorVersion() { return myMinorVersion; } public String getModule() { return myModule; } public String getVersion() { return myVersion; } } } }
38.648523
127
0.664199
071c2a977882b2099b4a85670272c5437e1c4105
2,943
//package com.demo.security; // //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; //import org.springframework.core.annotation.Order; //import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; //import org.springframework.security.config.annotation.web.builders.HttpSecurity; //import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; //import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; //import org.springframework.security.core.userdetails.UserDetailsService; //import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; // //@Configuration //@EnableWebSecurity //public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // // @Bean // public UserDetailsService customUserService() { // return new CustomUserService(); // } // // @Bean // public BCryptPasswordEncoder bCryptPasswordEncoder() { // return new BCryptPasswordEncoder(); // } // // @Configuration // @Order(1) // public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { // protected void configure(HttpSecurity http) throws Exception { // http // .antMatcher("/reception/**") // .authorizeRequests() // .anyRequest() // .permitAll() // .and() // .httpBasic(); // } // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // //任何用户都可以访问以下URI // http.authorizeRequests() // .antMatchers("/login", "/register", "/user/user_add") // .permitAll(); // // //其他URI均需要权限校验 // http.authorizeRequests() // .anyRequest() // .hasAnyRole("administrator", "admin"); // // //启用记住密码 // http.authorizeRequests() // .and() // .rememberMe(); // // //关闭CSRF跨站请求伪造 // http.csrf().disable(); // // //登录界面设置 // http.formLogin() // .loginPage("/login") // .successForwardUrl("/index") // .failureForwardUrl("/login?error"); // // //注销设置 // http.logout() // .logoutUrl("/logout") // .logoutSuccessUrl("/login"); // } // // @Autowired // public void configureGlobal(AuthenticationManagerBuilder auth) { // try { // auth.userDetailsService(customUserService()).passwordEncoder(bCryptPasswordEncoder()); // } catch (Exception e) { // e.printStackTrace(); // } // } //}
35.457831
110
0.595311
12391b1c928c06b27517131fd727bdb7ef07d8d5
595
package org.gwoplock.scheduledepo; import java.io.File; import java.io.IOException; import org.gwoplock.scheduledepo.dateAndTime.Appointment; public class App { public static void main(String[] args) { System.out.println(Appointment.getCurrentTime()); File toRead = null; if (args.length == 0) { toRead = new File("sched.html"); } else { toRead = new File(args[0]); } try { SchedulePage page = new SchedulePage(toRead); } catch (IOException e) { e.printStackTrace(); } } }
25.869565
57
0.586555
db3eb62d0cf9b75b0c134b1a0f3b7e552f7bddcb
1,226
package org.spring.classscanner; /* * Copyright [2015] [Jeff Lee] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.annotation.Annotation; import java.util.List; /** * 类扫描器 * * @author BYSocket * @since 2016-01-07 19:36:00 */ public interface ClassScanner { public final static String CLASS_SCANNER = "org.jeff.class_scanner"; /** * 获取指定包名中的所有类 * @param packageName 包名 * @return */ List<Class<?>> getClassList(String packageName); /** * 获取指定包名中的所有类 * @param packageName 包名 * @param annotationClass 注解类 * @return */ List<Class<?>> getClassListByAnnotation(String packageName, Class<? extends Annotation> annotationClass); }
28.511628
109
0.696574
9debe86158949c0e80692a7c418906bb3c2e5332
2,117
package org.apache.xpath; import org.apache.xml.utils.QName; import org.apache.xpath.objects.XObject; public class Arg { private QName m_qname; private XObject m_val; private String m_expression; private boolean m_isFromWithParam; private boolean m_isVisible; public final QName getQName() { return this.m_qname; } public final void setQName(QName name) { this.m_qname = name; } public final XObject getVal() { return this.m_val; } public final void setVal(XObject val) { this.m_val = val; } public void detach() { if (null != this.m_val) { this.m_val.allowDetachToRelease(true); this.m_val.detach(); } } public String getExpression() { return this.m_expression; } public void setExpression(String expr) { this.m_expression = expr; } public boolean isFromWithParam() { return this.m_isFromWithParam; } public boolean isVisible() { return this.m_isVisible; } public void setIsVisible(boolean b) { this.m_isVisible = b; } public Arg() { this.m_qname = new QName(""); this.m_val = null; this.m_expression = null; this.m_isVisible = true; this.m_isFromWithParam = false; } public Arg(QName qname, String expression, boolean isFromWithParam) { this.m_qname = qname; this.m_val = null; this.m_expression = expression; this.m_isFromWithParam = isFromWithParam; this.m_isVisible = !isFromWithParam; } public Arg(QName qname, XObject val) { this.m_qname = qname; this.m_val = val; this.m_isVisible = true; this.m_isFromWithParam = false; this.m_expression = null; } public boolean equals(Object obj) { return obj instanceof QName ? this.m_qname.equals(obj) : super.equals(obj); } public Arg(QName qname, XObject val, boolean isFromWithParam) { this.m_qname = qname; this.m_val = val; this.m_isFromWithParam = isFromWithParam; this.m_isVisible = !isFromWithParam; this.m_expression = null; } }
22.763441
81
0.645253
b49c1fcc222af6ca966701859bc4b575a1d98862
4,654
package io.ona.kujaku.utils; import com.mapbox.mapboxsdk.geometry.LatLng; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import io.ona.kujaku.BaseTest; import io.ona.kujaku.location.clients.SphericalUtil; public class SphericalUtilTest extends BaseTest { private static final double EARTH_RADIUS = SphericalUtil.EARTH_RADIUS; // The vertices of an octahedron, for testing private final LatLng up = new LatLng(90, 0); private final LatLng down = new LatLng(-90, 0); private final LatLng front = new LatLng(0, 0); private final LatLng right = new LatLng(0, 90); private final LatLng back = new LatLng(0, -180); private final LatLng left = new LatLng(0, -90); private static void expectEq(Object expected, Object actual) { Assert.assertEquals(expected, actual); } private static void expectNearNumber(double actual, double expected, double epsilon) { Assert.assertTrue(String.format("Expected %f to be near %f", actual, expected), Math.abs(expected - actual) <= epsilon); } @Test public void testAngles() { // Same vertex expectNearNumber(SphericalUtil.computeAngleBetween(up, up), 0, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(down, down), 0, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(left, left), 0, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(right, right), 0, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(front, front), 0, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(back, back), 0, 1e-6); // Adjacent vertices expectNearNumber(SphericalUtil.computeAngleBetween(up, front), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(up, right), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(up, back), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(up, left), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(down, front), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(down, right), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(down, back), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(down, left), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(back, up), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(back, right), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(back, down), Math.PI / 2, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(back, left), Math.PI / 2, 1e-6); // Opposite vertices expectNearNumber(SphericalUtil.computeAngleBetween(up, down), Math.PI, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(front, back), Math.PI, 1e-6); expectNearNumber(SphericalUtil.computeAngleBetween(left, right), Math.PI, 1e-6); } @Test public void testDistances() { expectNearNumber(SphericalUtil.computeDistanceBetween(up, down), Math.PI * EARTH_RADIUS, 1e-6); } @Test public void testComputeLength() { List<LatLng> latLngs; expectNearNumber(SphericalUtil.computeLength(Collections.emptyList()), 0, 1e-6); expectNearNumber(SphericalUtil.computeLength(Arrays.asList(new LatLng(0, 0))), 0, 1e-6); latLngs = Arrays.asList(new LatLng(0, 0), new LatLng(0.1, 0.1)); expectNearNumber(SphericalUtil.computeLength(latLngs), Math.toRadians(0.1) * Math.sqrt(2) * EARTH_RADIUS, 1); latLngs = Arrays.asList(new LatLng(0, 0), new LatLng(90, 0), new LatLng(0, 90)); expectNearNumber(SphericalUtil.computeLength(latLngs), Math.PI * EARTH_RADIUS, 1e-6); } @Test public void testComputeArea() { expectNearNumber(SphericalUtil.computeArea(Arrays.asList(right, up, front, down, right)), Math.PI * EARTH_RADIUS * EARTH_RADIUS, .4); expectNearNumber(SphericalUtil.computeArea(Arrays.asList(right, down, front, up, right)), Math.PI * EARTH_RADIUS * EARTH_RADIUS, .4); } @Test public void testComputeSignedArea() { List<LatLng> path = Arrays.asList(right, up, front, down, right); List<LatLng> pathReversed = Arrays.asList(right, down, front, up, right); expectEq(-SphericalUtil.computeSignedArea(path), SphericalUtil.computeSignedArea(pathReversed)); } }
44.32381
104
0.692952
ff8f14add721ea172831c63cd9280ed5af6a8475
1,311
/* * Copyright 2008-2009 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.consistency.utils.serialization; import voldemort.consistency.utils.ByteUtils; /** * A Serializer that serializes strings * * */ public class StringSerializer implements Serializer<String> { private String encoding; public StringSerializer() { this("UTF-8"); } public StringSerializer(String encoding) { this.encoding = encoding; } public byte[] toBytes(String string) { if(string == null) return null; return ByteUtils.getBytes(string, encoding); } public String toObject(byte[] bytes) { if(bytes == null) return null; return ByteUtils.getString(bytes, encoding); } }
25.705882
80
0.683448
880540fad6baac36fb69b5ced09f14fc1fff4669
428
package uk.co.codelity.event.sourcing.common.exceptions; /** * Thrown when an error occurred while persisting events. */ public class EventPersistenceException extends Exception { public EventPersistenceException() { } public EventPersistenceException(String message) { super(message); } public EventPersistenceException(String message, Throwable cause) { super(message, cause); } }
23.777778
71
0.719626
309166d15f96ffc8e9fdc7b6376cbee1c0573293
2,209
package com.lechucksoftware.proxy.proxysettings.db; import android.os.Parcel; import android.os.Parcelable; import java.util.UUID; /** * Created by Marco on 13/09/13. */ public class TagEntity extends BaseEntity implements Parcelable { private String tag; private Integer tagColor; public TagEntity() { super(); } public TagEntity(TagEntity t) { super(); this.setTag(t.getTag()); this.setTagColor(t.getTagColor()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("%s-%d", getTag(), getTagColor())); return sb.toString(); } @Override public boolean equals(Object another) { Boolean result = false; if ((another instanceof TagEntity)) { TagEntity anotherTag = (TagEntity) another; if (this.isPersisted() && anotherTag.isPersisted()) { return anotherTag.getId() == this.getId(); } else { return anotherTag.getTag().equalsIgnoreCase(this.getTag()); } } return result; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public Integer getTagColor() { return tagColor; } public void setTagColor(Integer tagColor) { this.tagColor = tagColor; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest,flags); dest.writeString(this.tag); dest.writeValue(this.tagColor); } private TagEntity(Parcel in) { super(in); this.tag = in.readString(); this.tagColor = (Integer) in.readValue(Integer.class.getClassLoader()); } public static final Creator<TagEntity> CREATOR = new Creator<TagEntity>() { public TagEntity createFromParcel(Parcel source) {return new TagEntity(source);} public TagEntity[] newArray(int size) {return new TagEntity[size];} }; }
21.038095
88
0.584427
e2b4fa4dea0fc7d8497dd16b43b61b49dcb46a64
1,736
package io.stringx; import android.content.Context; import android.preference.Preference; import android.util.AttributeSet; import io.stringx.sdk.R; /** * Stores {@link StringX} settings */ public class StringXPreference extends android.preference.CheckBoxPreference { public StringXPreference(final Context context, AttributeSet attrs) { super(context, attrs); final StringX stringX = StringX.get(getContext()); if (stringX == null) { setChecked(false); setEnabled(false); return; } try { boolean enabled = stringX.isEnabled(); boolean translationAvailable = stringX.isTranslationAvailable() && !stringX.isForcingLocale(); setChecked(enabled); setEnabled(translationAvailable); } catch (UnsupportedLanguageException e) { setEnabled(false); } setTitle(R.string.sX_preference_title); setSummary(R.string.sX_preference_summary); setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { Boolean isOptedIn = (Boolean) o; stringX.setEnabled(isOptedIn); stringX.restart(); return true; } }); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { try { StringX stringX = StringX.get(getContext()); if (stringX != null) { super.onSetInitialValue(stringX.isEnabled(), false); } } catch (UnsupportedLanguageException ignored) { } } }
31
106
0.615207