text
stringlengths
10
2.72M
/* * 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 uuu.totalbuy.test; import uuu.totalbuy.domain.Outlet; import uuu.totalbuy.domain.Product; /** * * @author PattyTai */ public class TestOutlet { public static void main(String[] args) { Outlet o = new Outlet(); o.setId(2); o.setName("Apple iPhone 4S 16GB"); o.setUnitPrice(16500); System.out.println("名稱:"+o.getName()); // System.out.println("折扣:"+o.getDiscount()); System.out.println("售價:"+o.getUnitPrice()); System.out.println("原價:"+o.getListPrice()); System.out.println(o); System.out.println(o.toString()); //System.out.println("Hello".toString()); } }
package com.santander.bi.model; import java.sql.Timestamp; import java.util.Set; import javax.persistence.*; import com.santander.bi.utils.Constants; @Entity @Table(name = "BI_HI_PRIV_BY_MOD", schema=Constants.SCHEMA_GEN) @SequenceGenerator(name="priv_mod_seq",sequenceName="BI_HI_PRIV_BY_MOD_SEQ", allocationSize = 1) public class PrivilegioModulo { @Id @Column(name="ID_PRIV_BY_MOD") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="priv_mod_seq") private Integer idPrivByMod; @Column(name="ID_MODULO") private Integer idModulo; @Column(name="CODIGO_PRIV") private String codigoPriv; @Column(name="PRIVILEGIO") private String privilegio; //CAMPOS SEGUIMIENTO @Column(name="HABILITADO") private String habilitado="H"; @Column(name="FECHA_CREACION") private Timestamp fechaCreacion; @Column(name="USUARIO_CREADOR") private String usuarioCreador; @Column(name="FECHA_MODIFICACION") private Timestamp fechaModificacion; @Column(name="USUARIO_MODIFICA") private String usuarioModifica; @ManyToMany(cascade = {CascadeType.ALL}, mappedBy="privilegios", fetch=FetchType.LAZY) private Set<Rol> roles; public Integer getIdPrivByMod() { return idPrivByMod; } public void setIdPrivByMod(Integer idPrivByMod) { this.idPrivByMod = idPrivByMod; } public Integer getIdModulo() { return idModulo; } public void setIdModulo(Integer idModulo) { this.idModulo = idModulo; } public String getCodigoPriv() { return codigoPriv; } public void setCodigoPriv(String codigoPriv) { this.codigoPriv = codigoPriv; } public String getPrivilegio() { return privilegio; } public void setPrivilegio(String privilegio) { this.privilegio = privilegio; } public String getHabilitado() { return habilitado; } public void setHabilitado(String habilitado) { this.habilitado = habilitado; } public Timestamp getFechaCreacion() { return fechaCreacion; } public void setFechaCreacion(Timestamp fechaCreacion) { this.fechaCreacion = fechaCreacion; } public String getUsuarioCreador() { return usuarioCreador; } public void setUsuarioCreador(String usuarioCreador) { this.usuarioCreador = usuarioCreador; } public Timestamp getFechaModificacion() { return fechaModificacion; } public void setFechaModificacion(Timestamp fechaModificacion) { this.fechaModificacion = fechaModificacion; } public String getUsuarioModifica() { return usuarioModifica; } public void setUsuarioModifica(String usuarioModifica) { this.usuarioModifica = usuarioModifica; } public Set<Rol> getRoles() { return roles; } public void setRoles(Set<Rol> roles) { this.roles = roles; } }
package pe.gob.trabajo.domain; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.time.Instant; import java.util.Objects; /** * LISTA DE LAS DIRECCIONES DE LAS PERSONAS JURIDICAS */ @ApiModel(description = "LISTA DE LAS DIRECCIONES DE LAS PERSONAS JURIDICAS") @Entity @Table(name = "glmvd_dirperjuri") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName = "glmvd_dirperjuri") public class Dirperjuri implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") @Column(name = "n_codpjudir", nullable = false) private Long id; /** * CODIGO DEL DEPARTAMENTO. */ @ApiModelProperty(value = "CODIGO DEL DEPARTAMENTO.") @Column(name = "n_coddepto") private Integer nCoddepto; /** * CODIGO DE LA PROVINCIA. */ @ApiModelProperty(value = "CODIGO DE LA PROVINCIA.") @Column(name = "n_codprov") private Integer nCodprov; /** * CODIGO DEL DISTRITO. */ @ApiModelProperty(value = "CODIGO DEL DISTRITO.") @Column(name = "n_coddist") private Integer nCoddist; /** * DIRECCION COMPLETA */ @NotNull @Size(max = 200) @ApiModelProperty(value = "DIRECCION COMPLETA", required = true) @Column(name = "v_dircomple", length = 200, nullable = false) private String vDircomple; /** * REFERENCIA DE LA DIRECCION. */ @Size(max = 500) @ApiModelProperty(value = "REFERENCIA DE LA DIRECCION.") @Column(name = "v_referen", length = 500) private String vReferen; /** * BANDERA QUE INDICA QUE SE PUEDE NOTIFICAR EN LA DIRECCION (ACTIVO = 1, INACTIVO = 0) */ @NotNull @ApiModelProperty(value = "BANDERA QUE INDICA QUE SE PUEDE NOTIFICAR EN LA DIRECCION (ACTIVO = 1, INACTIVO = 0)", required = true) @Column(name = "n_flgnotifi", nullable = false) private Boolean nFlgnotifi; /** * CODIGO DEL USUARIO QUE REGISTRA. */ @NotNull @ApiModelProperty(value = "CODIGO DEL USUARIO QUE REGISTRA.", required = true) @Column(name = "n_usuareg", nullable = false) private Integer nUsuareg; /** * FECHA Y HORA DEL REGISTRO. */ @NotNull @ApiModelProperty(value = "FECHA Y HORA DEL REGISTRO.", required = true) @Column(name = "t_fecreg", nullable = false) private Instant tFecreg; /** * ESTADO ACTIVO DEL REGISTRO (1=ACTIVO, 0=INACTIVO) */ @NotNull @ApiModelProperty(value = "ESTADO ACTIVO DEL REGISTRO (1=ACTIVO, 0=INACTIVO)", required = true) @Column(name = "n_flgactivo", nullable = false) private Boolean nFlgactivo; /** * CODIGO DE LA SEDE QUE REGISTRA. */ @NotNull @ApiModelProperty(value = "CODIGO DE LA SEDE QUE REGISTRA.", required = true) @Column(name = "n_sedereg", nullable = false) private Integer nSedereg; /** * CODIGO DEL USUARIO QUE MODIFICA EL REGISTRO. */ @ApiModelProperty(value = "CODIGO DEL USUARIO QUE MODIFICA EL REGISTRO.") @Column(name = "n_usuaupd") private Integer nUsuaupd; /** * FECHA Y HORA DE LA MODIFICACION DEL REGISTRO. */ @ApiModelProperty(value = "FECHA Y HORA DE LA MODIFICACION DEL REGISTRO.") @Column(name = "t_fecupd") private Instant tFecupd; /** * CODIGO DE LA SEDE DONDE SE MODIFICA EL REGISTRO. */ @ApiModelProperty(value = "CODIGO DE LA SEDE DONDE SE MODIFICA EL REGISTRO.") @Column(name = "n_sedeupd") private Integer nSedeupd; @ManyToOne @JoinColumn(name = "n_codperjur") private Perjuridica perjuridica; // jhipster-needle-entity-add-field - Jhipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getnCoddepto() { return nCoddepto; } public Dirperjuri nCoddepto(Integer nCoddepto) { this.nCoddepto = nCoddepto; return this; } public void setnCoddepto(Integer nCoddepto) { this.nCoddepto = nCoddepto; } public Integer getnCodprov() { return nCodprov; } public Dirperjuri nCodprov(Integer nCodprov) { this.nCodprov = nCodprov; return this; } public void setnCodprov(Integer nCodprov) { this.nCodprov = nCodprov; } public Integer getnCoddist() { return nCoddist; } public Dirperjuri nCoddist(Integer nCoddist) { this.nCoddist = nCoddist; return this; } public void setnCoddist(Integer nCoddist) { this.nCoddist = nCoddist; } public String getvDircomple() { return vDircomple; } public Dirperjuri vDircomple(String vDircomple) { this.vDircomple = vDircomple; return this; } public void setvDircomple(String vDircomple) { this.vDircomple = vDircomple; } public String getvReferen() { return vReferen; } public Dirperjuri vReferen(String vReferen) { this.vReferen = vReferen; return this; } public void setvReferen(String vReferen) { this.vReferen = vReferen; } public Boolean isnFlgnotifi() { return nFlgnotifi; } public Dirperjuri nFlgnotifi(Boolean nFlgnotifi) { this.nFlgnotifi = nFlgnotifi; return this; } public void setnFlgnotifi(Boolean nFlgnotifi) { this.nFlgnotifi = nFlgnotifi; } public Integer getnUsuareg() { return nUsuareg; } public Dirperjuri nUsuareg(Integer nUsuareg) { this.nUsuareg = nUsuareg; return this; } public void setnUsuareg(Integer nUsuareg) { this.nUsuareg = nUsuareg; } public Instant gettFecreg() { return tFecreg; } public Dirperjuri tFecreg(Instant tFecreg) { this.tFecreg = tFecreg; return this; } public void settFecreg(Instant tFecreg) { this.tFecreg = tFecreg; } public Boolean isnFlgactivo() { return nFlgactivo; } public Dirperjuri nFlgactivo(Boolean nFlgactivo) { this.nFlgactivo = nFlgactivo; return this; } public void setnFlgactivo(Boolean nFlgactivo) { this.nFlgactivo = nFlgactivo; } public Integer getnSedereg() { return nSedereg; } public Dirperjuri nSedereg(Integer nSedereg) { this.nSedereg = nSedereg; return this; } public void setnSedereg(Integer nSedereg) { this.nSedereg = nSedereg; } public Integer getnUsuaupd() { return nUsuaupd; } public Dirperjuri nUsuaupd(Integer nUsuaupd) { this.nUsuaupd = nUsuaupd; return this; } public void setnUsuaupd(Integer nUsuaupd) { this.nUsuaupd = nUsuaupd; } public Instant gettFecupd() { return tFecupd; } public Dirperjuri tFecupd(Instant tFecupd) { this.tFecupd = tFecupd; return this; } public void settFecupd(Instant tFecupd) { this.tFecupd = tFecupd; } public Integer getnSedeupd() { return nSedeupd; } public Dirperjuri nSedeupd(Integer nSedeupd) { this.nSedeupd = nSedeupd; return this; } public void setnSedeupd(Integer nSedeupd) { this.nSedeupd = nSedeupd; } public Perjuridica getPerjuridica() { return perjuridica; } public Dirperjuri perjuridica(Perjuridica perjuridica) { this.perjuridica = perjuridica; return this; } public void setPerjuridica(Perjuridica perjuridica) { this.perjuridica = perjuridica; } // jhipster-needle-entity-add-getters-setters - Jhipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Dirperjuri dirperjuri = (Dirperjuri) o; if (dirperjuri.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), dirperjuri.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Dirperjuri{" + "id=" + getId() + ", nCoddepto='" + getnCoddepto() + "'" + ", nCodprov='" + getnCodprov() + "'" + ", nCoddist='" + getnCoddist() + "'" + ", vDircomple='" + getvDircomple() + "'" + ", vReferen='" + getvReferen() + "'" + ", nFlgnotifi='" + isnFlgnotifi() + "'" + ", nUsuareg='" + getnUsuareg() + "'" + ", tFecreg='" + gettFecreg() + "'" + ", nFlgactivo='" + isnFlgactivo() + "'" + ", nSedereg='" + getnSedereg() + "'" + ", nUsuaupd='" + getnUsuaupd() + "'" + ", tFecupd='" + gettFecupd() + "'" + ", nSedeupd='" + getnSedeupd() + "'" + "}"; } }
package config; public class NetConfig { public static final int NIO_SEND_BUFF_SIZE = 1024; public static final int NIO_RECV_BUFF_SIZE = 1024; public static final int ALLOC_RECV_BUFF_SIZE = 1024; }
//package com.goodhealth.framework.config; // //import com.goodhealth.framework.interceptor.EcoSessionInterceptor; //import com.goodhealth.framework.interceptor.LoginInterceptor; //import com.goodhealth.framework.interceptor.RefererInterceptor; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.web.servlet.config.annotation.InterceptorRegistration; //import org.springframework.web.servlet.config.annotation.InterceptorRegistry; //import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; // ///** // * 配置多个拦截器又存在多种开启情况的拦截器写法----建立拦截器配置抽象类 // * 例如:配置了拦截器A B C // * 情况1 开启AB // * 情况2 开启BC // * .... // * 控制是否开启情况只需实现此抽象类并且合理实现isOpenxxxx方法 // */ //public abstract class AbstractInterceptorConfig extends WebMvcConfigurerAdapter { // // /** // * 登录拦截 // */ // @Autowired // private LoginInterceptor loginInterceptor; // // @Autowired // private EcoSessionInterceptor ecoSessionInterceptor; // // @Autowired // private RefererInterceptor refererInterceptor; // // /** // * 是否开启EcoSession拦截器 // * @return // */ // public abstract boolean isOpenEcoSessionInterceptor(); // // /** // * 是否开启login拦截器 // * @return // */ // public abstract boolean isOpenLoginInterceptor(); // // /** // * 排除EcoSession拦截的地址 // * // * @return // */ // public abstract String[] ecoSessionExcludePathPatterns(); // // @Override // public void addInterceptors(InterceptorRegistry registry) { // // // before // this.addInterceptorsPre(registry); // // // 开启创建EcoSession // if(isOpenEcoSessionInterceptor()){ // // InterceptorRegistration registration = registry.addInterceptor(ecoSessionInterceptor) // .addPathPatterns("/eco/**"); // if(ecoSessionExcludePathPatterns()!=null){ // registration.excludePathPatterns(ecoSessionExcludePathPatterns()); // } // } // // // 登录状态拦截 // if(isOpenLoginInterceptor()){ // // // 开启了登录拦截,则必须要做referer拦截 // registry.addInterceptor(refererInterceptor).addPathPatterns(GlobalConstants.INTERCEPTOR_PATH_LOGIN); // // // 登录拦截 // registry.addInterceptor(loginInterceptor).addPathPatterns(GlobalConstants.INTERCEPTOR_PATH_LOGIN); // } // // // after // this.addInterceptorsAfter(registry); // // super.addInterceptors(registry); // } // // /** // * 添加拦截,在默认拦截器之前 // * @param registry // */ // public abstract void addInterceptorsPre(InterceptorRegistry registry); // // /** // * 添加拦截,在默认拦截器之后 // * @param registry // */ // public abstract void addInterceptorsAfter(InterceptorRegistry registry); //}
package com.wshoto.user.anyong.Bean; public class CalendarDetailBean { /** * code : 1 * message : {"status":"success"} * data : {"id":"50","title":"Outdoor barbecue","province":"江苏","city":"无锡市","start_time":"2018-12-01 00:00:00","end_time":"2018-12-24 00:00:00","thumb":"https://anyong.wshoto.com/uploads/thumbnail/2018121213424960425.jpeg","content":"<p>Outdoor barbecues will be held this Sunday. You can bring your family to participate in the event.<\/p><p>Time: September 9, 2018<\/p>","type":"有时效","is_join":"1","created":"2018-12-12 13:43:04","updated":"2018-12-12 13:43:04","published":"2018-12-12 00:00:00","qrcode":"https://anyong.wshoto.com/uploads/qrcode/2018121213430449081.png","is_today":1} */ private int code; private MessageBean message; private DataBean data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public MessageBean getMessage() { return message; } public void setMessage(MessageBean message) { this.message = message; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class MessageBean { /** * status : success */ private String status; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } public static class DataBean { /** * id : 50 * title : Outdoor barbecue * province : 江苏 * city : 无锡市 * start_time : 2018-12-01 00:00:00 * end_time : 2018-12-24 00:00:00 * thumb : https://anyong.wshoto.com/uploads/thumbnail/2018121213424960425.jpeg * content : <p>Outdoor barbecues will be held this Sunday. You can bring your family to participate in the event.</p><p>Time: September 9, 2018</p> * type : 有时效 * is_join : 1 * created : 2018-12-12 13:43:04 * updated : 2018-12-12 13:43:04 * published : 2018-12-12 00:00:00 * qrcode : https://anyong.wshoto.com/uploads/qrcode/2018121213430449081.png * is_today : 1 */ private String id; private String title; private String province; private String city; private String start_time; private String end_time; private String thumb; private String content; private String type; private String is_join; private String created; private String updated; private String published; private String qrcode; private int is_today; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStart_time() { return start_time; } public void setStart_time(String start_time) { this.start_time = start_time; } public String getEnd_time() { return end_time; } public void setEnd_time(String end_time) { this.end_time = end_time; } public String getThumb() { return thumb; } public void setThumb(String thumb) { this.thumb = thumb; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getIs_join() { return is_join; } public void setIs_join(String is_join) { this.is_join = is_join; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public String getUpdated() { return updated; } public void setUpdated(String updated) { this.updated = updated; } public String getPublished() { return published; } public void setPublished(String published) { this.published = published; } public String getQrcode() { return qrcode; } public void setQrcode(String qrcode) { this.qrcode = qrcode; } public int getIs_today() { return is_today; } public void setIs_today(int is_today) { this.is_today = is_today; } } }
package com.tsm.template.dto; import com.tsm.template.model.Message; import lombok.Getter; import lombok.Setter; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import static com.tsm.template.util.ErrorCodes.*; public class MessageDTO implements BaseDTO { public static final String EMAIL = "^\\w+([-+._]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"; @Getter @Setter private Long id; @Getter @Setter @NotNull(message = REQUIRED_MESSAGE) @Size(min = 2, max = Message.MESSAGE_MAX_LENGTH, message = INVALID_MESSAGE_SIZE) private String message; @Getter @Setter @NotNull(message = REQUIRED_SUBJECT) @Size(min = 2, max = 30, message = INVALID_SUBJECT_SIZE) private String subject; @Getter @Setter @NotNull(message = REQUIRED_SENDER_NAME) @Size(min = 2, max = 30, message = INVALID_SENDER_NAME_SIZE) private String senderName; @Getter @Setter @NotNull(message = REQUIRED_SENDER_EMAIL) @Pattern(regexp = EMAIL, message = INVALID_EMAIL) private String senderEmail; @Getter @Setter private String status; }
/* * Copyright 2002-2013 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.integration.aws.s3.config.xml; import org.springframework.integration.aws.s3.core.AmazonS3Object; import org.springframework.integration.aws.s3.core.AmazonS3Operations; import org.springframework.integration.aws.s3.core.PaginatedObjectsView; /** * The dummy {@link AmazonS3Operations} for tests * * @author Amol Nayak * * @since 0.5 * */ public class AmazonS3DummyOperations implements AmazonS3Operations { @Override public PaginatedObjectsView listObjects(String bucketName, String folder, String nextMarker, int pageSize) { return null; } @Override public void putObject(String bucketName, String folder, String objectName, AmazonS3Object s3Object) { } @Override public AmazonS3Object getObject(String bucketName, String folder, String objectName) { return null; } @Override public boolean removeObject(String bucketName, String folder, String objectName) { return false; } }
package com.module.controllers.veterandialog.tables; import com.module.model.entity.HelpEntity; import javafx.fxml.FXML; import javafx.scene.control.DatePicker; import javafx.scene.control.TextField; import javafx.stage.Stage; import org.springframework.stereotype.Component; @Component public class AddHelpController { @FXML private TextField organizationName; @FXML private TextField helpType; @FXML private DatePicker helpDate; @FXML private TextField baseToHelp; private Stage dialogStage; private HelpEntity helpEntity; private boolean saveClicked = false; @FXML public void initialize() { } public boolean isSaveClicked() { return saveClicked; } public void setDialogStage(Stage dialogStage) { this.dialogStage = dialogStage; } public void setHelpEntity(HelpEntity helpEntity) { this.helpEntity = helpEntity; organizationName.setText(this.helpEntity.getOrganizationName()); helpType.setText(this.helpEntity.getHelpType()); helpDate.setValue(this.helpEntity.getHelpDate()); baseToHelp.setText(this.helpEntity.getBaseToHelp()); } @FXML private void cancelButtonClick() { dialogStage.close(); } @FXML private void saveButtonClick() { setNewHelpEntity(); saveClicked = true; dialogStage.close(); } private void setNewHelpEntity() { this.helpEntity.setOrganizationName(organizationName.getText()); this.helpEntity.setHelpType(helpType.getText()); this.helpEntity.setHelpDate(helpDate.getValue()); this.helpEntity.setBaseToHelp(baseToHelp.getText()); } }
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component; import android.view.View; import android.view.View.OnClickListener; class l$4 implements OnClickListener { final /* synthetic */ l nDI; l$4(l lVar) { this.nDI = lVar; } public final void onClick(View view) { this.nDI.bzZ(); this.nDI.bAb(); } }
package br.ufla.lemaf.ti.lemaf4j; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class AbstractLongValueObjectTest { @Test public void testEqualsHashCode() { EqualsVerifier.forClass(TestLongVO.class).withRedefinedSuperclass() .withPrefabValues(AbstractLongValueObject.class, new TestLongVO(1L), new TestLongVO(2L)) .suppress(Warning.NULL_FIELDS).verify(); } @Test public void testBaseType() { var testeVO = new TestLongVO(1L); assertThat(testeVO.getBaseType()).isEqualTo(Long.class); } /** Implementation for tests. */ public static final class TestLongVO extends AbstractLongValueObject { private static final long serialVersionUID = 1L; private final Long value; public TestLongVO(final Long value) { super(); this.value = value; } @Override public Long asBaseType() { return value; } } /** Implementation for tests. */ public static final class TestLongVO2 extends AbstractLongValueObject { private static final long serialVersionUID = 1L; private final Long value; public TestLongVO2(final Long value) { super(); this.value = value; } @Override public Long asBaseType() { return value; } } }
package moe.vergo.seasonalseiyuuapi.application.port.out; import moe.vergo.seasonalseiyuuapi.domain.Anime; import moe.vergo.seasonalseiyuuapi.domain.Season; import org.springframework.cache.annotation.Cacheable; import java.util.List; public interface SeasonalAnimePort { List<Anime> getSeasonalAnime(int year, Season season); }
package day06nestedifternaryswitchstringmethods; import java.util.Scanner; public class NestedTernary01IntegerDigits { /* Ask user to enter an integer if the integer is not negative then check if it is less than 10 return "The integer is digit" I the integer is negative return "Negative cannot be a digit" */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter an integer"); int a = scan.nextInt(); String result = (a>=0) ? (a<10? "The integer is digit" : "The integer is not a digit") : ("Negative cannot be a digit"); System.out.println(result); scan.close(); } }
package com.mimi.mimigroup.api; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class APINet { //GET network request public static String GET(OkHttpClient client, String url) throws IOException { try { Request request = new Request.Builder() .url(url) .build(); client=new OkHttpClient.Builder().connectTimeout(10,TimeUnit.SECONDS).writeTimeout(3600,TimeUnit.SECONDS).readTimeout(3600,TimeUnit.SECONDS).build(); Response response = client.newCall(request).execute(); return response.body().string(); }catch (IOException e){ e.printStackTrace(); Log.v("GET_HTTP_ERR",e.toString()); } return null ; } //POST network request public static String POST(OkHttpClient client, String url, RequestBody body) throws IOException { try{ Request request = new Request.Builder() .url(url) .post(body) .build(); client=new OkHttpClient.Builder().connectTimeout(10,TimeUnit.SECONDS).writeTimeout(3600,TimeUnit.SECONDS).readTimeout(3600,TimeUnit.SECONDS).build(); Response response = client.newCall(request).execute(); return response.body().string(); }catch (IOException e) { e.printStackTrace(); Log.v("POST_HTTP_ERR:",e.toString()); } return null; } public static boolean isNetworkAvailable(Context c) { try { ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnectedOrConnecting(); }catch (Exception ex){return false;} } }
package com.wit.getaride; import java.io.ByteArrayOutputStream; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseUser; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Spinner; import android.widget.Switch; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; /** * A simple {@link Fragment} subclass. * */ public class FrSettings extends Fragment{ private Intent mRequestFileIntent; private ParcelFileDescriptor mInputPFD; private ImageView imgView; private ImageView uploadImage; private EditText et; private EditText etPhone; private String imgDecodableString=""; private Spinner spRadius; private Switch swt; private int radiusKm; private Double searchRad; private GetArideApp app = new GetArideApp(); public FrSettings() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fr_settings, container, false); mRequestFileIntent = new Intent(Intent.ACTION_PICK); mRequestFileIntent.setType("image/jpg"); imgView = (ImageView) v.findViewById(R.id.profileImage); et = (EditText)v.findViewById(R.id.editUserName); etPhone=(EditText)v.findViewById(R.id.phone); spRadius= (Spinner)v.findViewById(R.id.spinner1); uploadImage = (ImageView)v.findViewById(R.id.uploadImage); // ImageButton b1 = (ImageButton)v.findViewById(R.id.imageButton1); // ImageButton b2 = (ImageButton)v.findViewById(R.id.imageButton2); Button svChangs = (Button)v.findViewById(R.id.button2); swt = (Switch)v.findViewById(R.id.switch1); // b1.setOnClickListener(this); // b2.setOnClickListener(this); svChangs.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { ParseUser currUser = app.currentParseUser; String newUsername = et.getText().toString(); if(newUsername.equals("")){ Toast.makeText(getActivity(), "Username cannot be empty", Toast.LENGTH_SHORT).show(); return; }else{ if(swt.isChecked()){ currUser.put("hasCar", true); app.thisUser.hasCar=true; } else{ app.thisUser.hasCar=false; currUser.put("hasCar", false);} currUser.put("name",et.getText().toString()); currUser.put("phone", etPhone.getText().toString()); currUser.put("radius", ""+searchRad); } currUser.saveInBackground(); app.searchRadius = searchRad; // Show a simple toast message Toast.makeText(getActivity(), "changes saved", Toast.LENGTH_SHORT).show(); Log.v("search radius", ""+app.searchRadius); } }); uploadImage.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { startActivityForResult(mRequestFileIntent, 0); } }); if(app.currentParseUser.getString("name")!=null) { et.setText(app.currentParseUser.getString("name"));} if(app.currentParseUser.getString("phone")!=null){ etPhone.setText(app.currentParseUser.getString("phone"));} if(app.currentParseUser.getBoolean("hasCar")){ swt.setChecked(true); }else{swt.setChecked(false);} if(app.currentParseUser.getString("radius")==null){ spRadius.setSelection(0); //app.searchRadius = 0.02; } else{ String rd = app.currentParseUser.getString("radius"); switch(rd){ case "0.02": spRadius.setSelection(0); break; case "0.04": spRadius.setSelection(1); break; case "0.06": spRadius.setSelection(2); break; } } spRadius.setOnItemSelectedListener(new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch(position){ case 0: radiusKm = 1; searchRad=0.02; break; case 1: radiusKm = 2; searchRad=0.04; break; case 2: radiusKm = 3; searchRad=0.06; } } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub }}); // et.setEnabled(false); // etPhone.setEnabled(false); // bitmap = imgView.getDrawingCache(); try { app.putDp(imgView,""); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return v; } @Override public void onActivityResult(int requestCode, int resultCode, Intent returnIntent) { // If the selection didn't work if (resultCode != getActivity().RESULT_OK) { // Exit without doing anything else return; } else { // Get the file's content URI from the incoming Intent Uri returnUri = returnIntent.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; // Get the cursor Cursor cursor = getActivity().getContentResolver().query(returnUri, filePathColumn, null, null, null); // Move to first row cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); imgDecodableString = cursor.getString(columnIndex); cursor.close(); Bitmap bitmap = BitmapFactory.decodeFile(imgDecodableString); float scaleWidth = (float) 0.5; float scaleHeight = (float) 0.5; Matrix matrix = new Matrix(); // matrix.postRotate(45); matrix.postScale(scaleWidth, scaleHeight); Bitmap resized = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); // Bitmap resized= Bitmap.createScaledBitmap(bitmap, 250, 250, true); // Convert it to byte ByteArrayOutputStream stream = new ByteArrayOutputStream(); // Compress image to lower quality scale 1 - 100 resized.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] image = stream.toByteArray(); // Create the ParseFile ParseFile file = new ParseFile("profile.jpg", image); // Upload the image into Parse Cloud file.saveInBackground(); ParseUser currUser = ParseUser.getCurrentUser(); // Create a column named "ImageName" and set the string currUser.put("photo", file); currUser.saveInBackground(); // Set the Image in ImageView after decoding the String imgView.setImageBitmap(BitmapFactory .decodeFile(imgDecodableString)); } } // @Override // public void onClick(View v) { // switch(v.getId()){ // case R.id.imageButton1: // et.setEnabled(true); // etPhone.setEnabled(false); // break; // case R.id.imageButton2: // etPhone.setEnabled(true); // et.setEnabled(false); // break; // // } // // } }
package bookexercises.chapter1.fundamentals.two; import java.util.stream.IntStream; import edu.princeton.cs.algs4.StdOut; /** * Develop an implementation SmartDate of our Date API that raises an excep- * tion if the date is not legal. * * @author atlednolispe * @email atlednolispe@gmail.com * @date 2018/7/2 */ public class Eleven { private int month; private int day; private int year; public Eleven(int month, int day, int year) { boolean legal = legalDateOrNot(month, day, year); this.month = month; this.day = day; this.year = year; } public Eleven(String date) { String[] mmddyyyy = date.split("/"); int month = Integer.parseInt(mmddyyyy[0]); int day = Integer.parseInt(mmddyyyy[1]); int year = Integer.parseInt(mmddyyyy[2]); boolean legal = legalDateOrNot(month, day, year); this.month = month; this.day = day; this.year = year; } private boolean legalDateOrNot(int month, int day, int year) { int[] longMonth = new int[]{1, 3, 5, 7, 8, 10, 12}; int[] shortMonth = new int[]{4, 6, 9, 11}; boolean legal = day > 0 && ( (IntStream.of(longMonth).anyMatch(x -> x == month) && day < 32) || (IntStream.of(shortMonth).anyMatch(x -> x == month) && day < 31) || month == 2 && day < 29 || (year % 100 == 0 && year % 400 == 0 || year % 100 != 0 && year % 4 == 0) && day == 29 ); if (!legal) { throw new IllegalArgumentException(); } return legal; } public int month() { return this.month; } public int day() { return this.day; } public int year() { return this.year; } @Override public String toString() { return String.format("%02d/%02d/%4d", month, day, year); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (this.getClass() != that.getClass()) { return false; } Eleven x = (Eleven) that; if (this.month != x.month) { return false; } if (this.day != x.day) { return false; } if (this.year != x.year) { return false; } return true; } public int compareTo(Eleven that) { String formatThis = String.format("%4d/%02d/%02d", this.year, this.month, this.day); String formatThat = String.format("%4d/%02d/%02d", that.year, that.month, that.day); return formatThis.compareTo(formatThat); } @Override public int hashCode() { // what is it? return super.hashCode(); } public static void main(String[] args) { Eleven date1 = new Eleven(7, 1, 2009); Eleven date2 = new Eleven("6/7/2012"); StdOut.println(date1); StdOut.printf("month: %d, day: %d, year: %d\n", date1.month(), date1.day(), date1.year()); StdOut.println(date1.compareTo(date2)); // Eleven date3 = new Eleven("02/29/2100"); } }
package com.appbusters.robinpc.constitutionofindia.model; public class Data { public String Title; public String subTitle; public String Desc; public Data(String Title, String subTitle, String Desc){ this.Title = Title; this.subTitle = subTitle; this.Desc = Desc; } //getters and setters public String getTitle() { return Title; } public void setTitle(String title) { Title = title; } public String getSubTitle() { return subTitle; } public void setSubTitle(String subTitle) { this.subTitle = subTitle; } public String getDesc() { return Desc; } public void setDesc(String Desc) { this.Desc = Desc; } }
package org.jvnet.jaxb2_commons.xml.bind.model.concrete; import org.jvnet.jaxb2_commons.lang.Validate; import org.jvnet.jaxb2_commons.xml.bind.model.MClassInfo; import org.jvnet.jaxb2_commons.xml.bind.model.MSingleTypePropertyInfo; import org.jvnet.jaxb2_commons.xml.bind.model.MTypeInfo; import org.jvnet.jaxb2_commons.xml.bind.model.origin.MPropertyInfoOrigin; public abstract class CMSingleTypePropertyInfo<T, C extends T> extends CMPropertyInfo<T, C> implements MSingleTypePropertyInfo<T, C> { private final MTypeInfo<T, C> typeInfo; public CMSingleTypePropertyInfo(MPropertyInfoOrigin origin, MClassInfo<T, C> classInfo, String privateName, boolean collection, MTypeInfo<T, C> typeInfo, boolean required) { super(origin, classInfo, privateName, collection, required); Validate.notNull(typeInfo); this.typeInfo = typeInfo; } public MTypeInfo<T, C> getTypeInfo() { return typeInfo; } }
package vc.lang.impl.deck; import java.util.Arrays; final class CardIdentifier { public final byte[] symbol; public CardIdentifier(byte[] symbol) { this.symbol = symbol; } @Override public boolean equals(Object other) { return Arrays.equals(symbol, ((CardIdentifier) other).symbol); } @Override public int hashCode() { return Arrays.hashCode(symbol); } public String toString() { return new String(symbol); } }
package com.van.common.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; /** * @author : yangjunqing / yangjunqing@zhimadi.cn * @version : 1.0 */ public class JacksonUtil { /** * om */ private static ObjectMapper om = new ObjectMapper(); /** * Bean to json string. * * @param obj the obj * @return the string * @throws JsonProcessingException the json processing exception * @author : yangjunqing / 2018-05-18 */ public static String beanToJson(Object obj) throws JsonProcessingException { return om.writeValueAsString(obj); } /** * Json to bean t. * * @param <T> the type parameter * @param json the json * @param objClass the obj class * @return the t * @throws IOException the io exception * @author : yangjunqing / 2018-05-18 */ public static <T> T jsonToBean(String json, Class<T> objClass) throws IOException { return om.readValue(json, objClass); } }
package unalcol.types.real.array.sparse; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * @author jgomez */ public class SparseRealVectorCosineSimilarity extends NormalizedSparseRealVectorCosineSimilarity { @Override public double apply(SparseRealVector x, SparseRealVector y) { return super.apply(x, y) / (prod.norm(x) * prod.norm(y)); } }
package org.adv25.ADVNTRIP.Clients.Authentication; import org.adv25.ADVNTRIP.Clients.Client; public class None implements Authentication { @Override public boolean start(Client client) { return true; } @Override public String toString() { return "None"; } }
import org.springframework.data.jpa.repository.JpaRepository; import com.trushil.springBootREST.entity.Product; interface ProductRepository extends JpaRepository<Product,Integer> { }
/* * 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.blood.controller; import java.sql.*; import com.blood.view.Login; import com.jtattoo.plaf.graphite.GraphiteLookAndFeel; import java.util.Properties; import javax.swing.UIManager; /** * * @author shahr */ public class DBConnection { Statement st; ResultSet rs; Connection con; String url; public DBConnection() { new Login().setVisible(true); try { url = "jdbc:ucanaccess://blood.mdb"; con = DriverManager.getConnection(url); System.out.println("Database Ok"); } catch (Exception e) { System.out.println("Could Not Connect to Database" + e); } try { rs.next(); } catch (Exception e) { } } public static void LookAndFeel() { Properties props = new Properties(); props.put("logoString", ""); GraphiteLookAndFeel.setCurrentTheme(props); try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { UIManager.setLookAndFeel("com.jtattoo.plaf.graphite.GraphiteLookAndFeel"); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } } public static void main(String[] args) { LookAndFeel(); DBConnection dbConnection = new DBConnection(); } }
package ro.redeul.google.go.lang.psi.impl.declarations; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import org.jetbrains.annotations.NotNull; import ro.redeul.google.go.lang.parser.GoElementTypes; import ro.redeul.google.go.lang.psi.declarations.GoVarDeclaration; import ro.redeul.google.go.lang.psi.declarations.GoVarDeclarations; import ro.redeul.google.go.lang.psi.impl.GoPsiElementBase; import ro.redeul.google.go.lang.psi.utils.GoPsiUtils; /** * Author: Toader Mihai Claudiu <mtoader@gmail.com> * <p/> * Date: 7/16/11 * Time: 3:22 AM */ public class GoVarDeclarationsImpl extends GoPsiElementBase implements GoVarDeclarations { public GoVarDeclarationsImpl(@NotNull ASTNode node) { super(node); } @Override public GoVarDeclaration[] getDeclarations() { return findChildrenByClass(GoVarDeclaration.class); } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { PsiElement node = lastParent != null ? lastParent.getPrevSibling() : this.getLastChild(); while ( node != null ) { if ( GoPsiUtils.isNodeOfType(node, GoElementTypes.VAR_DECLARATION) ) { if ( ! processor.execute(node, state) ) { return false; } } node = node.getPrevSibling(); } return true; } }
package com.paytechnologies.cloudacar; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import com.parse.Parse; import com.parse.ParsePush; import com.paytechnologies.cloudacar.AsynTask.SendMessageTask; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Rect; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; public class ManageTripDeadAdapter extends BaseAdapter { LayoutInflater inflator; Context mContext; private List<DeadTripDTO> deadTrip = null; private ArrayList<DeadTripDTO> arrayListDead ; DisplayImageOptions options; private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener(); public ManageTripDeadAdapter(Context context,ArrayList<DeadTripDTO> DeadContact) { this.deadTrip = DeadContact; Log.d("DeadTrip ", ""+deadTrip); mContext = context; inflator = LayoutInflater.from(mContext); this.arrayListDead = new ArrayList<DeadTripDTO>(); this.arrayListDead.addAll(DeadContact); options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.user1) .showImageForEmptyUri(R.drawable.user1) .showImageOnFail(R.drawable.user1) .cacheInMemory(true) .cacheOnDisc(true) .considerExifParams(true) .build(); } public class ViewHolderMainHome { ImageView LiveUserIcon; TextView userType,TripStatus,tripStatus,LiveMathching,LivePickUp,LiveUserName,LiveUserLastName,LiveuserPickUp,LiveuserDrop,LiveDate,LiveMessage,Liveoraganisation,LiveTRavelledBefore,LivePercentage; Button show_info,send_invite,show_map; RatingBar rating; } @Override public int getCount() { // TODO Auto-generated method stub Log.d("Size is:", ""+deadTrip.size()); return deadTrip.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return deadTrip.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(final int arg0, View arg1, ViewGroup arg2) { // TODO Auto-generated method stub ImageLoader imageLoader = ImageLoader.getInstance(); final ViewHolderMainHome holderMain; if(arg1 == null) { holderMain = new ViewHolderMainHome(); arg1 = inflator.inflate(R.layout.custom_dead_match, null); holderMain.LiveUserIcon = (ImageView)arg1.findViewById(R.id.imageViewUserPhoto); holderMain.LiveUserName = (TextView)arg1.findViewById(R.id.textViewDeadMatchUsername); holderMain.LiveUserLastName = (TextView)arg1.findViewById(R.id.textViewDeadMatchUserlastname); holderMain.LiveuserPickUp =(TextView)arg1.findViewById(R.id.textViewPickUpLocation); holderMain.LiveuserDrop =(TextView)arg1.findViewById(R.id.textViewDropLocation); holderMain.LiveDate =(TextView)arg1.findViewById(R.id.textViewDateTime); // holderMain.LiveMessage =(TextView)arg1.findViewById(R.id.textViewMessage); holderMain.Liveoraganisation =(TextView)arg1.findViewById(R.id.textViewuserOraganisation); holderMain.LiveTRavelledBefore =(TextView)arg1.findViewById(R.id.textViewTravelledBefore); holderMain.LiveMathching = (TextView)arg1.findViewById(R.id.textViewUserRatingDate); holderMain.userType = (TextView)arg1.findViewById(R.id.userType); // holderMain.LivePickUp =(TextView)arg1.findViewById(R.id.textViewDeadPickUpPoint); holderMain.tripStatus = (TextView)arg1.findViewById(R.id.textViewtripStatus); holderMain.TripStatus = (TextView)arg1.findViewById(R.id.textViewtripMessage); holderMain.send_invite =(Button)arg1.findViewById(R.id.buttonSendInvite); holderMain.show_info = (Button)arg1.findViewById(R.id.buttonSendTripRequest); holderMain.show_map=(Button)arg1.findViewById(R.id.buttonShowMap); holderMain.rating = (RatingBar)arg1.findViewById(R.id.ratingDeadBarRateTrip); arg1.setTag(holderMain); }else { holderMain = (ViewHolderMainHome)arg1.getTag(); } holderMain.LiveUserName.setText(DeadTripDTO.matchedUser.get(arg0).up_FirstName); holderMain.LiveUserLastName.setText(DeadTripDTO.matchedUser.get(arg0).up_LastName); holderMain.LiveuserPickUp.setText(DeadTripDTO.matchedUser.get(arg0).up_StartLocation); holderMain.LiveuserDrop.setText(DeadTripDTO.matchedUser.get(arg0).up_EndLocation); //holderMain.LivePickUp.setText(DeadTripDTO.tripList.get(arg0).pickUplocation); holderMain.Liveoraganisation.setText(DeadTripDTO.matchedUser.get(arg0).up_Company); holderMain.LiveTRavelledBefore.setText(DeadTripDTO.matchedUser.get(arg0).up_TravelledBefore); holderMain.LiveMathching.setText(DeadTripDTO.matchedUser.get(arg0).up_RouteMatcch); holderMain.rating.setRating(Integer.parseInt(DeadTripDTO.matchedUser.get(arg0).up_Rating)); if(DeadTripDTO.matchedUser.get(arg0).up_Type==1){ holderMain.userType.setText("D"); }else if(DeadTripDTO.matchedUser.get(arg0).up_Type==0){ holderMain.userType.setText("P"); }else if(DeadTripDTO.matchedUser.get(arg0).up_Type==2){ holderMain.userType.setText("P/D"); } /* if(Integer.parseInt(DeadTripDTO.tripList.get(arg0).TripMsg)==Constants.DEFAULT_INTEREST_STATUS){ holderMain.tripStatus.setVisibility(View.VISIBLE); holderMain.TripStatus.setVisibility(View.VISIBLE); holderMain.TripStatus.setText("Request Alreday Sent"); }else if(Integer.parseInt(DeadTripDTO.tripList.get(arg0).TripMsg)==Constants.ACCEPTED_INTEREST_STATUS){ holderMain.tripStatus.setVisibility(View.VISIBLE); holderMain.TripStatus.setVisibility(View.VISIBLE); holderMain.TripStatus.setText("Request Accepted"); }else if(Integer.parseInt(DeadTripDTO.tripList.get(arg0).TripMsg)==Constants.DECLINE_INTEREST_STATUS){ holderMain.tripStatus.setVisibility(View.VISIBLE); holderMain.TripStatus.setVisibility(View.VISIBLE); holderMain.TripStatus.setText("Request Declined"); }*/ if(DeadTripDTO.matchedUser.get(arg0).up_TripMsg!=null){ // holderMain.LiveMessage.setVisibility(View.VISIBLE); // holderMain.LiveMessage.setText(DeadTripDTO.matchedUser.get(arg0).up_TripMsg); } if(DeadTripDTO.matchedUser.get(arg0).up_TripMsg.equalsIgnoreCase("Request Already Sent")){ holderMain.send_invite.setEnabled(false); //holderMain.LiveMessage.setVisibility(View.VISIBLE); //holderMain.LiveMessage.setText("Request Already Sent"); holderMain.send_invite.setText("Request Already Sent"); } if(DeadTripDTO.matchedUser.get(arg0).up_TripMsg.equalsIgnoreCase("Send Interest Request")){ // holderMain.LiveMessage.setVisibility(View.VISIBLE); } String imageString = DeadTripDTO.matchedUser.get(arg0).up_Image; if(!DeadTripDTO.matchedUser.get(arg0).up_Image.equalsIgnoreCase("null")){ imageLoader.displayImage("http://www.cloudacar.com/"+DeadTripDTO.matchedUser.get(arg0).up_Image, holderMain.LiveUserIcon, options, animateFirstListener); }else{ holderMain.LiveUserIcon.setImageResource(R.drawable.user1); } holderMain.send_invite.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent bookeTrip = new Intent(mContext,PotentialInviteUser.class); Log.d("cac", "Postiotion"+arg0); // Log.d("cac", "Validuser"+DeadTripDTO.countryList.get(arg0).validUser); bookeTrip.putExtra("position", arg0); // bookeTrip.putExtra("valid", DeadTripDTO.countryList.get(arg0).validUser); bookeTrip.putExtra("fromdashboard",1002); mContext.startActivity(bookeTrip); } }); holderMain.show_info.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Log.d("Arg0 is:", ""+arg0); Intent ShowInfoUser = new Intent(mContext,ShowInformationnRequestedUser.class); ShowInfoUser.putExtra("position", arg0); mContext.startActivity(ShowInfoUser); } private void ShowPopup(final int arg0) { // TODO Auto-generated method stub final Dialog dialog = new Dialog(mContext); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // Include dialog.xml file dialog.setContentView(R.layout.activity_send_message); TextView fullname = (TextView)dialog.findViewById(R.id.text_view_fullname); TextView routeMatch = (TextView)dialog.findViewById(R.id.text_view_routeMatch); TextView ageRange = (TextView)dialog.findViewById(R.id.text_view_ageRange); TextView Gender = (TextView)dialog.findViewById(R.id.text_view_gender); TextView pickUpLocation = (TextView)dialog.findViewById(R.id.text_view_pickupLocation); TextView dropLocation = (TextView)dialog.findViewById(R.id.text_view_dropLocation); final EditText comments= (EditText)dialog.findViewById(R.id.text_view_comments); Button sendRequest = (Button)dialog.findViewById(R.id.buttonSendRequest); Button declineRequest = (Button)dialog.findViewById(R.id.buttonDecline); System.out.println("Arg0 is "+arg0); fullname.setText(DeadTripDTO.countryList.get(arg0).liveFirstName + " " +DeadTripDTO.countryList.get(arg0).liveLastName); if(Integer.parseInt(DeadTripDTO.countryList.get(arg0).liveGender) == 1){ Gender.setText("Male"); }else if(Integer.parseInt(DeadTripDTO.countryList.get(arg0).liveGender) == 2){ Gender.setText("Female"); } pickUpLocation.setText(DeadTripDTO.tripList.get(arg0).pickUplocation); dropLocation.setText(DeadTripDTO.tripList.get(arg0).DropLocation); // tripDetails.setText(DeadTripDTO.tripList.get(arg0).traveldays); routeMatch.setText(SendMessageDeadDTO.userListInfo.get(arg0).Routematch); ageRange.setText(DeadTripDTO.countryList.get(arg0).liveAge); // prefernceMatch.setText(SendMessageDeadDTO.userListInfo.get(arg0).RequestedNeddDriver); routeMatch.setText(String.valueOf(SendMessageDeadDTO.userListInfo.get(arg0).Routematch)+"%"); sendRequest.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // int ValidUser=DeadTripDTO.countryList.get(arg0).validUser; // Log.d("Valid User is:", ""+ValidUser); String UserId = SendMessageDeadDTO.userListInfo.get(arg0).RequestedUserId; //String requestedUserId="userId-"+UserId; String requestedUserId="userId-"+SendMessageDeadDTO.userListInfo.get(arg0).RequestedUserId; Log.d("Requesteduserid", ""+UserId); String comments1 = comments.getText().toString(); String UserName = SendMessageDeadDTO.userListInfo.get(arg0).RequestorFirstName; Log.d("From whom", ""+UserName); Log.d("To send", ""+requestedUserId); //if(ValidUser==1){ Toast.makeText(mContext, "Send invitation", Toast.LENGTH_LONG).show(); JSONObject obj; try { obj = new JSONObject("{\"header\": \"Join Trip\" , \"action\": \"com.paytechnologies.cloudacar.UPDATE_STATUS\", \"from\": \""+UserName+"\" }"); ParsePush push = new ParsePush(); //push.setChannel(requestedUserId); push.setChannel(requestedUserId); push.setData(obj); push.sendInBackground(); Parse.setLogLevel(Parse.LOG_LEVEL_VERBOSE); Toast.makeText(mContext, "Message has been posted", Toast.LENGTH_LONG).show(); new SendMessageTask(mContext).execute(String.valueOf(arg0),comments1); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /*else if(ValidUser == 2){ // JSONObject obj; // try { // obj = new JSONObject("{\"header\": \"Join Trip\" , \"action\": \"com.paytechnologies.cloudacar.UPDATE_STATUS\", \"from\": \""+UserName+"\" }"); // // ParsePush push = new ParsePush(); // push.setChannel(requestedUserId); // push.setData(obj); // push.sendInBackground(); // Parse.setLogLevel(Parse.LOG_LEVEL_VERBOSE); // Toast.makeText(mContext, "Message has been posted", Toast.LENGTH_LONG).show(); // // } catch (JSONException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // new SendMessageTask(mContext).execute(String.valueOf(arg0),comments1); // // Intent activatePlans = new Intent(mContext,BuyCarClouds.class); // activatePlans.putExtra("fromSendInvite", 1001); // mContext.startActivity(activatePlans); }*///change it to 3 // if(ValidUser == 3){ // // // Intent activatePlans = new Intent(mContext,MonthlySubscription.class); // activatePlans.putExtra("fromSendInvite", 1001); // mContext.startActivity(activatePlans); // // // } /*else if(ValidUser == 4){ Intent activatePlans = new Intent(mContext,NewModifiedCacPlans.class); activatePlans.putExtra("fromSendInvite", 1001); mContext.startActivity(activatePlans); } }*/ }); dialog.show(); } }); holderMain.show_map.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent showMap = new Intent(mContext,ShowMap.class); showMap.putExtra("startLocation", DeadTripDTO.matchedUser.get(arg0).up_StartLocation); showMap.putExtra("endLocation", DeadTripDTO.matchedUser.get(arg0).up_EndLocation); showMap.putExtra("pickupLocation", DeadTripDTO.matchedUser.get(arg0).up_pickUpLocation); mContext.startActivity(showMap); } }); return arg1; } private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener { static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>()); @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); displayedImages.add(imageUri); } } } } }
package com.cricmania.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.cricmania.comman.BowlingType; import com.cricmania.comman.PlayerType; import com.cricmania.comman.PlayingStyle; import com.cricmania.models.Address; import com.cricmania.models.Player; import com.cricmania.models.PlayerMetaData; import com.cricmania.models.Team; import com.cricmania.models.Tournament; import com.cricmania.models.Tournament.TournamentStatus; import com.cricmania.models.Umpire; import com.cricmania.vms.PlayerVM; import com.cricmania.vms.TournamentVM; import com.cricmania.vms.UmpireVM; import com.fasterxml.jackson.databind.JsonNode; public class Mapper { public static PlayerVM mapJsonNodeToPlayerVM(JsonNode node) { if(node != null) { PlayerVM playerVM = new PlayerVM(); playerVM.setId(node.get("id")!=null ? node.get("id").asText() : null); try { playerVM.setBattingStyle(node.get("battingStyle") != null ? PlayingStyle.valueOf(node.get("battingStyle").asText()) : null); } catch(Exception e) { playerVM.setBattingStyle(null); } try { playerVM.setBowlingStyle(node.get("bowlingStyle") != null ? PlayingStyle.valueOf(node.get("bowlingStyle").asText()) : null); } catch(Exception e) { playerVM.setBattingStyle(null); } if(node.get("bowlingTypes") != null) { System.out.println(node.get("bowlingTypes").size()); playerVM.setBowlingTypes(new ArrayList<BowlingType>(node.get("bowlingTypes").size())); for(JsonNode n : node.get("bowlingTypes")) { try { if(n != null) { playerVM.getBowlingTypes().add(BowlingType.valueOf(n.asText())); } } catch(Exception e) { } } } playerVM.setCity(node.get("city") != null ? node.get("city").asText() : null); playerVM.setContactNumber(node.get("contactNumber") != null ? node.get("contactNumber").asText() : null); playerVM.setCountry(node.get("country") != null ? node.get("country").asText() : null); playerVM.setDob(node.get("dob") != null ? node.get("dob").asText() : null); playerVM.setEmail(node.get("email") != null ? node.get("email").asText() : null); playerVM.setFirstName(node.get("firstName") != null ? node.get("firstName").asText() : null); playerVM.setIsKeeper(node.get("isKeeper") != null ? node.get("isKeeper").asBoolean() : null); playerVM.setLastName(node.get("lastName") != null ? node.get("lastName").asText() : null); playerVM.setMiddleName(node.get("middleName") != null ? node.get("middleName").asText() : null); try { playerVM.setPlayerType(node.get("playerType") != null ? PlayerType.valueOf(node.get("playerType").asText()) : null); } catch(Exception e) { playerVM.setPlayerType(null); } playerVM.setState(node.get("state") != null ? node.get("state").asText() : null); playerVM.setStreet(node.get("street") != null ? node.get("street").asText() : null); playerVM.setZipcode(node.get("zipcode") != null ? node.get("zipcode").asText() : null); return playerVM; } else { return null; } } public static UmpireVM mapJsonNodeToUmpireVM(JsonNode node) { if(node != null) { UmpireVM umpireVM = new UmpireVM(); umpireVM.setId(node.get("id")!=null ? node.get("id").asText() : null); umpireVM.setCity(node.get("city") != null ? node.get("city").asText() : null); umpireVM.setContactNumber(node.get("contactNumber") != null ? node.get("contactNumber").asText() : null); umpireVM.setCountry(node.get("country") != null ? node.get("country").asText() : null); umpireVM.setDob(node.get("dob") != null ? node.get("dob").asText() : null); umpireVM.setEmail(node.get("email") != null ? node.get("email").asText() : null); umpireVM.setFirstName(node.get("firstName") != null ? node.get("firstName").asText() : null); umpireVM.setLastName(node.get("lastName") != null ? node.get("lastName").asText() : null); umpireVM.setMiddleName(node.get("middleName") != null ? node.get("middleName").asText() : null); umpireVM.setState(node.get("state") != null ? node.get("state").asText() : null); umpireVM.setStreet(node.get("street") != null ? node.get("street").asText() : null); umpireVM.setZipcode(node.get("zipcode") != null ? node.get("zipcode").asText() : null); return umpireVM; } else { return null; } } public static TournamentVM mapJsonToTournamentVM(JsonNode node) { if(node != null) { TournamentVM tournamentVM = new TournamentVM(); tournamentVM.setCity(node.get("city") != null ? node.get("city").asText() : null); tournamentVM.setCountry(node.get("country") != null ? node.get("country").asText() : null); tournamentVM.setId(node.get("id")!=null ? node.get("id").asText() : null); tournamentVM.setName(node.get("name") != null ? node.get("name").asText() : null); tournamentVM.setOrganizedBy(node.get("organizedBy") != null ? node.get("organizedBy").asText() : null); tournamentVM.setStartDate(node.get("startDate") != null ? node.get("startDate").asText() : null); tournamentVM.setState(node.get("state") != null ? node.get("state").asText() : null); tournamentVM.setZipcode(node.get("zipcode") != null ? node.get("zipcode").asText() : null); return tournamentVM; } return null; } public static Tournament mapTournamentVMToTournament(TournamentVM tournamentVM) { if(tournamentVM == null) return null; Tournament tournament = new Tournament(); tournament.setName(tournamentVM.getName()); tournament.setOrganizedBy(tournamentVM.getOrganizedBy()); DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); try { tournament.setStartDate(df.parse(tournamentVM.getStartDate())); if(tournament.getStartDate().getTime() < new Date().getTime()) { tournament.setTournamentStatus(TournamentStatus.RUNNING); } } catch(Exception e) {} Address address = new Address(); address.setCity(tournamentVM.getCity()); address.setCountry(tournamentVM.getCountry()); address.setState(tournamentVM.getState()); address.setZipcode(tournamentVM.getZipcode()); tournament.setAddress(address); return tournament; } public static TournamentVM mapTournamentToTournamentVM(Tournament tournament) { if(tournament == null) return null; TournamentVM tournamentVM = new TournamentVM(); tournamentVM.setId(tournament.getId()); tournamentVM.setName(tournament.getName()); tournamentVM.setOrganizedBy(tournament.getOrganizedBy()); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); if(tournament.getStartDate() != null) { tournamentVM.setStartDate(df.format(tournament.getStartDate())); } if(tournament.getAddress() != null) { tournamentVM.setCity(tournament.getAddress().getCity()); tournamentVM.setCountry(tournament.getAddress().getCountry()); tournamentVM.setState(tournament.getAddress().getState()); tournamentVM.setZipcode(tournament.getAddress().getZipcode()); } return tournamentVM; } public static Umpire mapUmpireVMToUmpire(UmpireVM umpireVM) { if(umpireVM == null) return null; Address address = new Address(); address.setCity(umpireVM.getCity()); address.setCountry(umpireVM.getCountry()); address.setState(umpireVM.getState()); address.setStreet(umpireVM.getStreet()); address.setZipcode(umpireVM.getZipcode()); Umpire umpire = new Umpire(); umpire.setAddress(address); umpire.setContactNumber(umpireVM.getContactNumber()); umpire.setDeletedOn(null); DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); try { umpire.setDob(df.parse(umpireVM.getDob())); } catch (ParseException e) { } umpire.setEmail(umpireVM.getEmail()); umpire.setFirstName(umpireVM.getFirstName()); umpire.setLastName(umpireVM.getLastName()); umpire.setMiddleName(umpireVM.getMiddleName()); umpire.setUpdatedOn(null); return umpire; } public static Player mapPlayerVMToPlayer(PlayerVM playerVM) { if(playerVM == null) return null; Player player = new Player(); Address address = new Address(); address.setCity(playerVM.getCity()); address.setCountry(playerVM.getCountry()); address.setState(playerVM.getState()); address.setStreet(playerVM.getStreet()); address.setZipcode(playerVM.getZipcode()); player.setAddress(address); player.setBattingStyle(playerVM.getBattingStyle()); player.setBowlingStyle(playerVM.getBowlingStyle()); player.setContactNumber(playerVM.getContactNumber()); player.setDeletedOn(null); DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); try { player.setDob(df.parse(playerVM.getDob())); } catch (ParseException e) { } player.setEmail(playerVM.getEmail()); player.setFirstName(playerVM.getFirstName()); player.setIsKeeper(playerVM.getIsKeeper()); player.setLastName(playerVM.getLastName()); player.setMiddleName(playerVM.getMiddleName()); player.setPlayerType(playerVM.getPlayerType()); player.setUpdatedOn(null); return player; } public static Team mapJsonNodeToTeam(JsonNode node) { if(node == null) return null; Team team = new Team(); team.setContactNumber(node.get("contactNumber")!=null ?node.get("contactNumber").asText() : null); team.setContactPerson(node.get("contactPerson")!=null ? node.get("contactPerson").asText() : null); team.setEmail(node.get("email") != null ? node.get("email").asText() : null); team.setName(node.get("name") != null ? node.get("name").asText() : null); team.setSponsoredBy(node.get("sponsoredBy") != null ? node.get("sponsoredBy").asText() : null); Address address = new Address(); address.setCity(node.get("city") != null ? node.get("city").asText() : null); address.setCountry(node.get("country") != null ? node.get("country").asText() : null); address.setState(node.get("state") != null ? node.get("state").asText() : null); address.setZipcode(node.get("zipcode") != null ? node.get("zipcode").asText() : null); team.setAddress(address); if(node.get("players") != null) { List<PlayerMetaData> datas = new ArrayList<PlayerMetaData>(node.get("players").size()); for(JsonNode player : node.get("players")) { PlayerMetaData data = new PlayerMetaData(); data.setBatsman(player.get("isBatsman") != null ?player.get("isBatsman").asBoolean() : null); data.setBowler(player.get("isBowler") != null ? player.get("isBowler").asBoolean() : null); data.setCaptain(player.get("isCaptain") != null ? player.get("isCaptain").asBoolean() : null); data.setKeeper(player.get("isKeeper")!=null ? player.get("isKeeper").asBoolean() : false); data.setPlayer(player.get("player") != null ? player.get("player").asText() : null); data.setViceCaptain(player.get("isViceCaptain")!=null ? player.get("isViceCaptain").asBoolean() : false); datas.add(data); } team.setPlayers(datas); } return team; } }
package com.service; import com.pojo.User; public interface ILoginService { public User Login(String name,String password); }
package com.se.details.util; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; import java.util.Map; import java.util.Set; import static org.junit.Assert.*; @SpringBootTest public class MultipliersTest { @Test public void specialUnitsShouldNotBeEmpty() { Multipliers.intializeSpecialUnits(); Set<String> specialUnits = Multipliers.getSpecialunits(); boolean expected = !specialUnits.isEmpty(); assertTrue(expected); } @Test public void multipliersMapShouldNotBeEmpty() { Multipliers.initializeMultipliersMap(); Map<String, Integer> multipliersMap = Multipliers.getMultipliersmap(); boolean expected = !multipliersMap.isEmpty(); assertTrue(expected); } @Test public void multiplierHasValuePower() { Integer multiplierPower = Multipliers.getMultiplierValue("m"); assertNotNull(multiplierPower); } @Test public void multiplierHasNoValuePower() { Integer multiplierPower = Multipliers.getMultiplierValue("mBgg"); assertNull(multiplierPower); } }
package in.hocg.app.controller; import in.hocg.app.bean.DictateBean; import in.hocg.app.services.DictateService; import in.hocg.defaults.base.controller.BaseController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by hocgin on 16-12-19. */ @RequestMapping("/dictate") @Controller public class DictateController extends BaseController { @Autowired DictateService dictateService; @RequestMapping(value = "/i") @ResponseBody public Object i() { DictateBean dictateBean = new DictateBean(); dictateBean.setCmd("#文章"); dictateBean.setContent("内容"); dictateBean.setType("URL"); dictateService.insert(dictateBean); return dictateBean; } }
package main.java.model.solarsetup; // Author: Alexander Larnemo Ask, Jonatan Bunis, Vegard Landrö, Mohamad Melhem, Alexander Larsson Vahlberg // Responsibility: Abstract representation of a single solar panel. // Used by: SolarSetup, ModelAggregate. // Uses: Holds data common to a solarpanel. Implementations have more specific data. public abstract class SolarPanel { private final double size; private final double retailPrice; private final double wattage; // in KW private double annualOperationCost; private double lifeExpectancy; private double efficiency; private double performanceRatio; public SolarPanel(double size, double retailPrice, double wattage) { this.size = size; this.retailPrice = retailPrice; this.wattage = wattage; this.lifeExpectancy = 20; } //Getters public double getSize() { return this.size; } public double getLifeExpectancy() { return this.lifeExpectancy; } public double getRetailPrice() { return this.retailPrice; } public double getWattage() { return this.wattage; } public double getEfficiency() { return efficiency; } public double getAnnualOperationCost() { return annualOperationCost; } public double getPerformanceRatio() { return performanceRatio; } //Setters public void setAnnualOperationCost(double annualOperationCost) { this.annualOperationCost = annualOperationCost; } public void setEfficiency(double efficiency) { this.efficiency = efficiency; } public void setLifeExpectancy(double lifeExpectancy) { this.lifeExpectancy = lifeExpectancy; } public void setPerformanceRatio(double performanceRatio) { this.performanceRatio = performanceRatio; } }
/* * 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 threads; /** * * @author irolg_000 */ public class FloorSemaphore { private Object lock = new Object(); private boolean repairing = false; public void beginRepair() { synchronized (lock) { while (repairing) { try { lock.wait(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } repairing = false; lock.notifyAll(); } } public void endRepair() { repairing = true; synchronized (lock) { lock.notifyAll(); } } public void beginClean() { synchronized (lock) { while (!repairing) { try { lock.wait(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } repairing = true; lock.notifyAll(); } } public void endClean() { repairing = false; synchronized (lock) { lock.notifyAll(); } } }
package com.rx.rxmvvmlib.ui.binding.viewadapter.view; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.jakewharton.rxbinding2.view.RxView; import com.rx.rxmvvmlib.ui.binding.command.BindingCommand; import java.util.concurrent.TimeUnit; import androidx.databinding.BindingAdapter; import androidx.recyclerview.widget.RecyclerView; import io.reactivex.functions.Consumer; /** * Created by wuwei * 2019/12/6 * 佛祖保佑 永无BUG */ public class ViewAdapter { //防重复点击间隔(毫秒) public static final int CLICK_INTERVAL = 500;//ms /** * requireAll 是意思是是否需要绑定全部参数, false为否 * View的onClick事件绑定 * onClickCommand 绑定的命令, * isThrottleFirst 是否开启防止过快点击 */ @BindingAdapter(value = {"onClickCommand", "isThrottleFirst"}, requireAll = false) public static void onClickCommand(View view, final BindingCommand clickCommand, final boolean isThrottleFirst) { if (isThrottleFirst) { RxView.clicks(view) .subscribe(new Consumer<Object>() { @Override public void accept(Object object) throws Exception { if (clickCommand != null) { clickCommand.execute(); } } }); } else { RxView.clicks(view) .throttleFirst(CLICK_INTERVAL, TimeUnit.MILLISECONDS)//500ms内只允许点击1次 .subscribe(new Consumer<Object>() { @Override public void accept(Object object) throws Exception { if (clickCommand != null) { clickCommand.execute(); } } }); } } @BindingAdapter(value = {"onScalTouchCommand"}, requireAll = false) public static void onScalTouchCommand(final View view, final BindingCommand clickCommand) { view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: view.setPivotX(view.getWidth() / 2); view.setPivotY(view.getHeight() / 2); ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1, 0.9f); ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1, 0.9f); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(scaleX, scaleY); animatorSet.setDuration(100); animatorSet.start(); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: view.setPivotX(view.getWidth() / 2); view.setPivotY(view.getHeight() / 2); ObjectAnimator scaleX2 = ObjectAnimator.ofFloat(view, "scaleX", 0.9f, 1.03f); ObjectAnimator scaleY2 = ObjectAnimator.ofFloat(view, "scaleY", 0.9f, 1.03f); AnimatorSet animatorSet2 = new AnimatorSet(); animatorSet2.playTogether(scaleX2, scaleY2); animatorSet2.setDuration(100); animatorSet2.start(); animatorSet2.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ObjectAnimator scaleX3 = ObjectAnimator.ofFloat(view, "scaleX", 1.03f, 1); ObjectAnimator scaleY3 = ObjectAnimator.ofFloat(view, "scaleY", 1.03f, 1); AnimatorSet animatorSet3 = new AnimatorSet(); animatorSet3.playTogether(scaleX3, scaleY3); animatorSet3.setDuration(100); animatorSet3.start(); animatorSet3.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (clickCommand != null) { clickCommand.execute(); } } }); } }); break; } return true; } }); } /** * view的onLongClick事件绑定 */ @BindingAdapter(value = {"onLongClickCommand"}, requireAll = false) public static void onLongClickCommand(View view, final BindingCommand clickCommand) { RxView.longClicks(view) .subscribe(new Consumer<Object>() { @Override public void accept(Object object) throws Exception { if (clickCommand != null) { clickCommand.execute(); } } }); } /** * 回调控件本身 * * @param currentView * @param bindingCommand */ @BindingAdapter(value = {"currentView"}, requireAll = false) public static void replyCurrentView(View currentView, BindingCommand bindingCommand) { if (bindingCommand != null) { bindingCommand.execute(currentView); } } /** * view是否需要获取焦点 */ @BindingAdapter({"requestFocus"}) public static void requestFocusCommand(View view, final Boolean needRequestFocus) { if (needRequestFocus) { view.setFocusableInTouchMode(true); view.requestFocus(); } else { view.clearFocus(); } } /** * view的焦点发生变化的事件绑定 */ @BindingAdapter({"onFocusChangeCommand"}) public static void onFocusChangeCommand(View view, final BindingCommand<Boolean> onFocusChangeCommand) { view.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (onFocusChangeCommand != null) { onFocusChangeCommand.execute(hasFocus); } } }); } /** * view的显示隐藏 */ @BindingAdapter(value = {"isVisible"}, requireAll = false) public static void isVisible(View view, final Boolean visibility) { if (visibility) { view.setVisibility(View.VISIBLE); } else { view.setVisibility(View.GONE); } } @BindingAdapter(value = {"layout_width", "layout_height"}, requireAll = false) public static void setLayoutWidth(View view, float width, float height) { if (width != 0) { ViewGroup.LayoutParams params = view.getLayoutParams(); params.width = (int) width; view.setLayoutParams(params); } if (height != 0) { ViewGroup.LayoutParams params = view.getLayoutParams(); params.height = (int) height; view.setLayoutParams(params); } } @BindingAdapter("selected") public static void setSeleted(View view, boolean selected) { view.setSelected(selected); } @BindingAdapter("enable") public static void setEnable(View view, boolean enable) { view.setEnabled(enable); } @BindingAdapter(value = {"margin_top", "margin_bottom", "margin_left", "margin_right"}, requireAll = false) public static void setLayoutMargins(View view, int marginTop, int marginBottom, int marginLeft, int marginRight) { ViewGroup.LayoutParams params = view.getLayoutParams(); if (params instanceof LinearLayout.LayoutParams) { ((LinearLayout.LayoutParams) params).topMargin = marginTop; ((LinearLayout.LayoutParams) params).bottomMargin = marginBottom; ((LinearLayout.LayoutParams) params).leftMargin = marginLeft; ((LinearLayout.LayoutParams) params).rightMargin = marginRight; } else if (params instanceof RelativeLayout.LayoutParams) { ((RelativeLayout.LayoutParams) params).topMargin = marginTop; ((RelativeLayout.LayoutParams) params).bottomMargin = marginBottom; ((RelativeLayout.LayoutParams) params).leftMargin = marginLeft; ((RelativeLayout.LayoutParams) params).rightMargin = marginRight; } else if (params instanceof FrameLayout.LayoutParams) { ((FrameLayout.LayoutParams) params).topMargin = marginTop; ((FrameLayout.LayoutParams) params).bottomMargin = marginBottom; ((FrameLayout.LayoutParams) params).leftMargin = marginLeft; ((FrameLayout.LayoutParams) params).rightMargin = marginRight; } else if (params instanceof RecyclerView.LayoutParams) { ((RecyclerView.LayoutParams) params).topMargin = marginTop; ((RecyclerView.LayoutParams) params).bottomMargin = marginBottom; ((RecyclerView.LayoutParams) params).leftMargin = marginLeft; ((RecyclerView.LayoutParams) params).rightMargin = marginRight; } view.setLayoutParams(params); } }
package dataManagement; import java.util.ArrayList; import java.util.List; import dataStructures.Permutation; public class WordSquares { private Permutation permutation; private List<WordSquare> wordSquares; public WordSquares(Permutation permutation) { this.permutation = permutation; wordSquares = new ArrayList<WordSquare>(); makeWordSquare(); } public void makeWordSquare() { for (String word : permutation.getListOfWords()) { WordSquare wordSquare = new WordSquare(); wordSquare.addWord(word); wordSquareRecursive(1, wordSquare); } } public List<WordSquare> getWordSqaures() { return wordSquares; } public boolean wordSquareRecursive(int index, WordSquare wordSquare) { boolean check = false; if (wordSquare.getSizeOfList() == wordSquare.getLengthOfWord()) { wordSquares.add(cloneWordSqaure(wordSquare)); return true; } String prefix = ""; for (String wordForPrefix : wordSquare.getWordSquare()) { prefix += wordForPrefix.charAt(index); } for (String wordFromPrefix : getWordsFromPrefix(prefix)) { wordSquare.addWord(wordFromPrefix); wordSquareRecursive(index + 1, wordSquare); wordSquare.pop(); } return check; } public List<String> getWordsFromPrefix(String prefix) { List<String> wordsFromPrefix = new ArrayList<String>(); for (String word : permutation.getListOfWords()) { if (word.startsWith(prefix)) wordsFromPrefix.add(word); } return wordsFromPrefix; } public String toString() { String toString = ""; if (wordSquares.isEmpty()) toString += "No word squares can be generated."; else { toString += "WordSqaures:\n"; for (WordSquare wordSquare : wordSquares) { toString += wordSquare.toString() + "\n"; } } return toString; } private WordSquare cloneWordSqaure(WordSquare wordSquare) { WordSquare clone = new WordSquare(); for (String word : wordSquare.getWordSquare()) { clone.addWord(word); } return clone; } }
package vn.m2m.utils; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.Random; public class SecretUtil { public static String getRandomHexString(int numchars){ Random r = new Random(); StringBuffer sb = new StringBuffer(); while(sb.length() < numchars){ sb.append(Integer.toHexString(r.nextInt())); } return sb.toString().substring(0, numchars); } public static String keyGen256() throws NoSuchAlgorithmException { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); // create new key SecretKey secretKey = keyGen.generateKey(); // get base64 encoded version of the key String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded()); return encodedKey; } public static String keyGenHex256() throws NoSuchAlgorithmException, UnsupportedEncodingException { return getRandomHexString(88); } public static String keyGenHex512() throws NoSuchAlgorithmException, UnsupportedEncodingException { return getRandomHexString(128); } public static String get_SHA_512_SecurePassword(String passwordToHash, String salt) throws UnsupportedEncodingException{ String generatedPassword = null; try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(salt.getBytes("UTF-8")); byte[] bytes = md.digest(passwordToHash.getBytes("UTF-8")); StringBuilder sb = new StringBuilder(); for(int i=0; i< bytes.length ;i++){ sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } generatedPassword = sb.toString(); } catch (NoSuchAlgorithmException e){ e.printStackTrace(); } return generatedPassword; } public static String secretKeyToString(SecretKey secretKey){ String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded()); return encodedKey; } public static SecretKey stringToSecretKey(String encodedKey){ byte[] decodedKey = Base64.getDecoder().decode(encodedKey); // rebuild key using SecretKeySpec SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); return originalKey; } }
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.qq.packets.out; import java.nio.ByteBuffer; import edu.tsinghua.lumaqq.qq.QQ; import edu.tsinghua.lumaqq.qq.beans.QQUser; import edu.tsinghua.lumaqq.qq.packets.BasicOutPacket; import edu.tsinghua.lumaqq.qq.packets.PacketParseException; /** * <pre> * 高级搜索用户的请求包: * * *********** 格式1 ************** * 头部 * --------- 加密开始(会话密钥)------------ * 用户类型,1字节,0x01表示普通用户 * 页数,从0开始,2字节 * 在线与否,1字节,0x01表示在线,0x00表示不在线 * 是否有摄像头,1字节,0x01表示有,0x00表示无,TX QQ 2004中的处理是如果要查找有摄像头的用户,则必须查找在线用户,不知道不这样行不行 * 年龄,1字节,表示在下拉框中的索引 * 性别,1字节,表示在下拉框中的索引 * 省份,2字节,表示在下拉框中的索引 * 城市,2字节,表示在下拉框中的索引 * --------- 加密结束 ------------- * 尾部 * </pre> * * @author luma */ public class AdvancedSearchUserPacket extends BasicOutPacket { private byte userType; private boolean searchOnline; private boolean hasCam; private char page; private byte ageIndex; private byte genderIndex; private char provinceIndex; private char cityIndex; /** * @param buf * @param length * @throws PacketParseException */ public AdvancedSearchUserPacket(ByteBuffer buf, int length, QQUser user) throws PacketParseException { super(buf, length, user); } /** * 构造一个缺省包,缺省包查找在线用户,其他条件都不限 */ public AdvancedSearchUserPacket(QQUser user) { super(QQ.QQ_CMD_ADVANCED_SEARCH, true, user); searchOnline = true; hasCam = false; page = provinceIndex = cityIndex = 0; ageIndex = genderIndex = 0; userType = QQ.QQ_USER_TYPE_NORMAL; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.packets.OutPacket#getPacketName() */ @Override public String getPacketName() { return "Advanced Search Packet"; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.packets.OutPacket#putBody(java.nio.ByteBuffer) */ @Override protected void putBody(ByteBuffer buf) { // 用户类型 buf.put(userType); // 2. 页数,从0开始 buf.putChar(page); // 3. 在线与否,1字节,0x01表示在线,0x00表示不在线 buf.put(searchOnline ? (byte)0x01 : (byte)0x00); // 4. 是否有摄像头,1字节,0x01表示有,0x00表示无,TX QQ 2004中的处理是如果要查找 // 有摄像头的用户,则必须查找在线用户,不知道不这样行不行 buf.put(hasCam ? (byte)0x01 : (byte)0x00); // 5. 年龄,1字节,表示在下拉框中的索引 buf.put(ageIndex); // 6. 性别,1字节,表示在下拉框中的索引 buf.put(genderIndex); // 7. 省份,2字节,表示在下拉框中的索引 buf.putChar(provinceIndex); // 8. 城市,2字节,表示在下拉框中的索引 buf.putChar(cityIndex); } /** * @return Returns the ageIndex. */ public byte getAgeIndex() { return ageIndex; } /** * @param ageIndex The ageIndex to set. */ public void setAgeIndex(byte ageIndex) { this.ageIndex = ageIndex; } /** * @return Returns the genderIndex. */ public byte getGenderIndex() { return genderIndex; } /** * @param genderIndex The genderIndex to set. */ public void setGenderIndex(byte genderIndex) { this.genderIndex = genderIndex; } /** * @return Returns the hasCam. */ public boolean isHasCam() { return hasCam; } /** * @param hasCam The hasCam to set. */ public void setHasCam(boolean hasCam) { this.hasCam = hasCam; } /** * @return Returns the page. */ public char getPage() { return page; } /** * @param page The page to set. */ public void setPage(char page) { this.page = page; } /** * @return Returns the searchOnline. */ public boolean isSearchOnline() { return searchOnline; } /** * @param searchOnline The searchOnline to set. */ public void setSearchOnline(boolean searchOnline) { this.searchOnline = searchOnline; } /** * @return Returns the cityIndex. */ public char getCityIndex() { return cityIndex; } /** * @param cityIndex The cityIndex to set. */ public void setCityIndex(char cityIndex) { this.cityIndex = cityIndex; } /** * @return Returns the provinceIndex. */ public char getProvinceIndex() { return provinceIndex; } /** * @param provinceIndex The provinceIndex to set. */ public void setProvinceIndex(char provinceIndex) { this.provinceIndex = provinceIndex; } public byte getUserType() { return userType; } public void setUserType(byte userType) { this.userType = userType; } }
package game.app.convert; import org.springframework.core.convert.converter.Converter; import game.app.dtos.response.GameResponse; import game.app.entities.Game; public class GameToGameResponseConverter implements Converter<Game,GameResponse>{ @Override public GameResponse convert(Game game) { GameResponse gameResponse = new GameResponse(); gameResponse.setTitle(game.getTitle()); gameResponse.setDescription(game.getDescription()); gameResponse.setRelease(game.getRelease()); gameResponse.setPrice(game.getPrice()); return gameResponse; } }
package net.minecraft.item; import net.minecraft.block.Block; public class ItemAnvilBlock extends ItemMultiTexture { public ItemAnvilBlock(Block block) { super(block, block, new String[] { "intact", "slightlyDamaged", "veryDamaged" }); } public int getMetadata(int damage) { return damage << 2; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\item\ItemAnvilBlock.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.design.strategy.flyrun; public interface MotionType { }
package ar.com.corpico.appcorpico.login; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import ar.com.corpico.appcorpico.R; import ar.com.corpico.appcorpico.login.data.SessionsCloudStore; import ar.com.corpico.appcorpico.login.data.SessionsPrefsStore; import ar.com.corpico.appcorpico.login.data.SessionsRepository; import ar.com.corpico.appcorpico.login.domain.usecase.LoginUser; import ar.com.corpico.appcorpico.login.presentation.LoginFragment; import ar.com.corpico.appcorpico.login.presentation.LoginPresenter; /** * A login screen that offers login via email/password. */ public class LoginActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); /** <<create> LoginFragment **/ LoginFragment loginView; loginView = (LoginFragment) getSupportFragmentManager() .findFragmentById(R.id.login_view_container); if (loginView == null) { loginView = LoginFragment.newInstance(null, null); getSupportFragmentManager() .beginTransaction() .add(R.id.login_view_container, loginView) .commit(); } /** * <<create>> Almacénes */ SessionsPrefsStore prefsStore = SessionsPrefsStore.get(); SessionsCloudStore restStore = new SessionsCloudStore(); /** * <<create>> SessionsRepository */ SessionsRepository repository = new SessionsRepository(prefsStore, restStore); /** * <<create>> LoginUser */ LoginUser loginUser = new LoginUser(repository); /** * <<create>> LoginPresenter */ LoginPresenter loginPresenter = new LoginPresenter(loginView, loginUser); } }
package com.codelaxy.qwertpoiuy.Models; import java.util.ArrayList; public class MessageResponse { private boolean error; private ArrayList<Message> messages; public MessageResponse(boolean error, ArrayList<Message> messages) { this.error = error; this.messages = messages; } public boolean isError() { return error; } public ArrayList<Message> getMessages() { return messages; } }
package com.joy.http.qyer; import com.joy.http.ReqFactory; import com.joy.http.utils.ParamsUtil; import com.joy.http.volley.Request.Method; import java.util.HashMap; import java.util.Map; /** * Created by Daisw on 16/9/14. */ public class QyerReqFactory { private static Map<String, String> mDefaultParams; public static void setDefaultParams(Map<String, String> defaultParams) { mDefaultParams = defaultParams; } public static Map<String, String> getDefaultParams() { Map<String, String> params = new HashMap<>(); if (mDefaultParams != null && !mDefaultParams.isEmpty()) { params.putAll(mDefaultParams); } return params; } public static boolean isDefaultParamsEmpty() { return mDefaultParams == null || mDefaultParams.isEmpty(); } public static void clearDefaultParams() { if (mDefaultParams != null) { mDefaultParams.clear(); mDefaultParams = null; } } public static Map<String, String> generateParams(Map<String, String> params) { if (mDefaultParams != null && !mDefaultParams.isEmpty()) { params.putAll(mDefaultParams); } return params; } /** * @param baseUrl * @param clazz * @param params length = [0,2] * @param <T> * @return */ public static <T> QyerRequest<T> newGet(String baseUrl, Class<?> clazz, Map<String, String>... params) { ReqFactory.checkParamsIsValid(params); StringBuilder sb = new StringBuilder(baseUrl); if (ReqFactory.isParamsSingle(params)) { sb.append('?').append(ParamsUtil.createUrl(generateParams(params[0]))); } else if (ReqFactory.isParamsDouble(params)) { String fullUrl = baseUrl; final Map<String, String> p = params[0]; if (p != null && !p.isEmpty()) { fullUrl = sb.append('?').append(ParamsUtil.createUrl(generateParams(p))).toString(); } QyerRequest<T> req = new QyerRequest(Method.GET, fullUrl, clazz); req.setHeaders(params[1]); return req; } return new QyerRequest(Method.GET, sb.toString(), clazz); } /** * @param baseUrl * @param clazz * @param params length = [0,2] * @param <T> * @return */ public static <T> QyerRequest<T> newPost(String baseUrl, Class<?> clazz, Map<String, String>... params) { ReqFactory.checkParamsIsValid(params); QyerRequest<T> req = new QyerRequest(Method.POST, baseUrl, clazz); if (ReqFactory.isParamsSingle(params)) { req.setParams(generateParams(params[0])); } else if (ReqFactory.isParamsDouble(params)) { req.setParams(generateParams(params[0])); req.setHeaders(params[1]); } return req; } }
package com.example.myapplication; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.FirebaseApp; import com.google.firebase.ml.vision.FirebaseVision; import com.google.firebase.ml.vision.common.FirebaseVisionImage; import com.google.firebase.ml.vision.face.FirebaseVisionFace; import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetector; import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions; import java.util.List; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.DialogFragment; public class MainActivity extends AppCompatActivity { private Button cameraButton; private final static int REQUEST_IMAGE_CAPTURE=124; private FirebaseVisionImage image; private FirebaseVisionFaceDetector detector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FirebaseApp.initializeApp(this); cameraButton=findViewById(R.id.camera_button); cameraButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent takePictureIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(takePictureIntent.resolveActivity(getPackageManager()) != null){ startActivityForResult(takePictureIntent,REQUEST_IMAGE_CAPTURE); } } }); } /** * Dispatch incoming result to the correct fragment. * * @param requestCode * @param resultCode * @param data */ @SuppressLint("MissingSuperCall") @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if(requestCode == REQUEST_IMAGE_CAPTURE && requestCode == RESULT_OK){ Bundle extras=data.getExtras(); Bitmap bitmap=(Bitmap) extras.get("data"); detectFace(bitmap); } } private void detectFace(Bitmap bitmap) { FirebaseVisionFaceDetectorOptions highAccuracyOpts = new FirebaseVisionFaceDetectorOptions.Builder() .setModeType(FirebaseVisionFaceDetectorOptions.ACCURATE_MODE) .setClassificationType(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS) .setClassificationType(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS) .setMinFaceSize(0.15f) .setTrackingEnabled(true) .build(); try { image=FirebaseVisionImage.fromBitmap(bitmap); detector= FirebaseVision.getInstance() .getVisionFaceDetector(highAccuracyOpts); } catch (Exception e) { e.printStackTrace(); } detector.detectInImage(image).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionFace>>() { @Override public void onSuccess(List<FirebaseVisionFace> firebaseVisionFaces) { String resultText=""; int i=1; for(FirebaseVisionFace face : firebaseVisionFaces){ resultText =resultText.concat("\n" + i + ".") .concat("\nSmile :"+face.getSmilingProbability()*100+ "%") .concat("\nLeft Eye :"+face.getLeftEyeOpenProbability()*100+ "%") .concat("\nRight Eye :"+face.getRightEyeOpenProbability()*100+"%"); i++; } if(firebaseVisionFaces.size()==0){ Toast.makeText(MainActivity.this,"No Faces Detected",Toast.LENGTH_SHORT).show(); }else{ Bundle bundle=new Bundle(); bundle.putString(FaceApp.RESULT_TEXT,resultText); DialogFragment resultDialog = new ResultDialog(); resultDialog.setArguments(bundle); resultDialog.setCancelable(false); resultDialog.show(getSupportFragmentManager(),FaceApp.RESULT_DIALOG); } } }); } }
package pt.ipbeja.estig.po2.boulderdash.model; import java.io.File; import java.util.List; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import javafx.scene.control.Alert; /** * @author Tomás Jorge, 20436 * @author Luiz Felhberg, 20347 * @version 21/05/2021 * --------------------- * Class that has a method that allows reading a file to * a 2D String array, also lets you get information about * this is what is in the file, like the number of columns * the board will have */ public class ReadFile { // Global Variables private final String PATH = "src/resources/files"; private final String filename; private final String separator; // End of the Global Variables /** * Constructor to save the filename and the separator * --------------------------------- * @param filename -> file level name to be read * @param separator -> how do you want to split the file */ public ReadFile(String filename, String separator) { this.filename = filename; this.separator = separator; } /** * Method used and given by professors in the last semester's project in * "Introdução à Programação" * --------------------------------- * @param filename -> file level name to be read * @param separator -> how do you want to split the file * @return String array in 2D */ public String[][] readFileToStringArray2D(String filename, String separator) { filename = this.PATH + filename; try { List<String> linesNumber = Files.readAllLines(Paths.get(filename)); String[][] allData = new String[linesNumber.size()][]; for(int i = 0; i < linesNumber.size(); ++i) { allData[i] = ((String) linesNumber.get(i)).split(separator); } return allData; } catch (IOException exception) { String errorMessage = "Error reading file " + filename; showError(errorMessage); System.out.println(errorMessage + " - Exception " + exception.toString()); return new String[0][]; } } /** * Method used and given by professors in the last semester's project in * "Introdução à Programação" * -------------- * @param message -> message to be displayed when path or filename is wrong */ public void showError(String message) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setContentText(message); alert.showAndWait(); } /** * Method to get the number of lines on the board * -------------- * @return number of lines on the board */ public int getLines() { String[][] s = this.readFileToStringArray2D(this.filename, " "); return Integer.parseInt(s[0][0]); } /** * Method to get the number of columns on the board * -------------- * @return number of columns on the board */ public int getCols() { String[][] s = this.readFileToStringArray2D(this.filename, " "); return Integer.parseInt(s[0][1]); } /** * * get the number of levels in the path * -------------- * @return number of levels */ public int getNumberOfLevels() { File file = new File(this.PATH); File[] files = file.listFiles(); int count = 0; if(files != null) { for (File f : files) { count++; } } return count; } }
package com.flute.atp.common; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data @NoArgsConstructor @AllArgsConstructor public class DateInterval { Date from; Date to; public boolean within(Date date){ return date.after(from) && date.before(to); } }
package exercicios.exercicio03; public class ContaPoupanca extends Conta{ private static double taxaDeSaque; public ContaPoupanca(int conta, double saldo){ super(conta, saldo); } public static void setTaxaDeSaque(double taxa){ if(taxa > 0){ taxaDeSaque = taxa; } } @Override public boolean saque(double valor) { if( getSaldo() >= valor+taxaDeSaque ){ return super.saque(valor + taxaDeSaque); } return false; } }
package com.cloudogu.smeagol.wiki.domain; import com.google.common.base.MoreObjects; import java.time.Instant; import java.util.Objects; import java.util.Optional; import static com.google.common.base.Preconditions.checkNotNull; /** * Commit of a source code management system such as git. */ public class Commit { private Optional<CommitId> id; private Instant date; private Author author; private Message message; public Commit(CommitId id, Instant date, Author author, Message message) { this(date, author, message); this.id = Optional.of(id); } public Commit(Instant date, Author author, Message message) { this.id = Optional.empty(); this.date = checkNotNull(date, "date is required"); this.author = checkNotNull(author, "author is required"); this.message = checkNotNull(message, "message is required"); } public Optional<CommitId> getId() { return id; } public Instant getDate() { return date; } public Author getAuthor() { return author; } public Message getMessage() { return message; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Commit commit = (Commit) o; return Objects.equals(id, commit.id); } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("id", id) .add("date", date) .add("author", author) .add("message", message) .toString(); } }
package com.codeclan.example.BookingSystem.repositories.CourseRepository; import com.codeclan.example.BookingSystem.models.Course; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface CourseRepository extends JpaRepository<Course, Long>, CourseRepositoryCustom { List<Course> findCoursesByRating(int rating); // List<Course> findAllCoursesByCustomerName(String name); }
import java.util.*; /** * Colgate University COSC 290 Labs * Version 0.1, 2017 * * @author Michael Hay */ public class BoardCounting { public static int numRecursiveCalls = 0; public static int numRecursiveCallsDistinct = 0; /** * DLN 9.100 * @return number of leaves in game tree (when you play til board is completely filled in) */ public static int countFilledIn() { return countFilledIn(new Board()); } /** * Variation on DLN 9.100 * @param b current board * @return number of leaves in game subtree whose root is board b */ public static int countFilledIn(Board b) { if (b.isFull()) { return 1; } // System.out.println(b); int sum =0; for (int i=0; i<b.size(); i++ ) { for (int j=0; j<b.size(); j++) { if (b.isOpen(i,j)) { b.placeMark(i,j,b.nextPlayer()); sum += countFilledIn(b); b.removeMark(i,j); } } } return sum; // throw new UnsupportedOperationException("implement me!"); } /** * DLN 9.101 * @return number of distinct leaves in game tree (when you play til board is completely filled in) */ public static int countDistinctFilledIn() { return countDistinctFilledIn(new Board()); } /** * Variation on DLN 9.101 * @param b current board * @return number of distinct leaves in game subtree whose root is board b */ public static int countDistinctFilledIn(Board b) { // System.out.println(distinctBoards(b, new HashSet<Board>())); return distinctBoards(b, new HashSet<Board>()).size(); } public static Set distinctBoards(Board b, Set<Board> boards) { if (b.isFull()) { Board newBoard = b.copy(); boards.add(newBoard); return boards; } for (int i=0; i<b.size(); i++ ) { for (int j=0; j<b.size(); j++) { if (b.isOpen(i,j)) { b.placeMark(i,j,b.nextPlayer()); distinctBoards(b, boards); b.removeMark(i,j); } } } return boards; } /** * DLN 9.102 * @return number of boards in game tree (when you play til board is completely filled in) */ public static int countBoardsInTree() { return countBoardsInTree(new Board()); } /** * Variation on DLN 9.102 * @param b current board * @return number of boards in game subtree whose root is board b */ public static int countBoardsInTree(Board b) { // int numRecursiveCalls = 0; if (b.isFull()) { return 1; } // System.out.println(b); int sum =0; for (int i=0; i<b.size(); i++ ) { for (int j=0; j<b.size(); j++) { if (b.isOpen(i,j)) { b.placeMark(i,j,b.nextPlayer()); numRecursiveCalls += countBoardsInTree(b); numRecursiveCalls++; b.removeMark(i,j); } } } return numRecursiveCalls; } /** * DLN 9.103 * @return number of distinct boards in game tree (when you play til board is completely filled in) */ public static int countDistinctBoardsInTree() { return countDistinctBoardsInTree(new Board()); } /** * Variation on DLN 9.103 * @param b current board * @return number of distinct boards in game subtree whose root is board b */ public static int countDistinctBoardsInTree(Board b) { //throw new UnsupportedOperationException("implement me!"); // System.out.println(distinctBoardsInTree(b,new HashSet<Board>())); return distinctBoardsInTree(b,new HashSet<Board>()).size(); } public static Set distinctBoardsInTree(Board b, Set<Board> boards) { if (b.isFull()) { Board newBoard = b.copy(); boards.add(newBoard); return boards; } for (int i=0; i<b.size(); i++ ) { for (int j=0; j<b.size(); j++) { if (b.isOpen(i,j)) { b.placeMark(i,j,b.nextPlayer()); Board board = b.copy(); boards.add(board); // Board board = b.copy(); // boards.add(board); // System.out.println(boards.contains(board)); // System.out.println(board); // System.out.println(boards); distinctBoardsInTree(b, boards); b.removeMark(i,j); } } } return boards; } /** * DLN 9.104 * @return number of unique boards, accounting for symmetry, in game tree (when you play til board is completely filled in) */ public static int countWithSymmetry() { return countWithSymmetry(new Board()); } /** * Variation on DLN 9.104 * @param b current board * @return number of number of unique boards, accounting for symmetry, in game subtree whose root is board b */ public static int countWithSymmetry(Board b) { throw new UnsupportedOperationException("implement me!"); } /** * DLN 9.105 * @return number of unique boards, accounting for symmetry and wins, in game tree (when you play til board is completely filled in) */ public static int countWithSymmetryWins() { return countWithSymmetryWins(new Board()); } /** * Variation on DLN 9.105 * @param b current board * @return number of number of unique boards, accounting for symmetry and wins, in game subtree whose root is board b */ public static int countWithSymmetryWins(Board b) { throw new UnsupportedOperationException("implement me!"); } public static void main(String[] args) { // example: System.out.println("Problem 9.100: the number of filled-in boards is: " + countFilledIn()); System.out.println("Problem 9.101: the number of distinct filled-in boards is: " + countDistinctFilledIn()); System.out.println("Problem 9.102: the number of total boards: " + countBoardsInTree()); System.out.println("Problem 9.103: the number of total boards for distinct: " + countDistinctBoardsInTree()); // feel free to test your methods here } }
package com.redhat.middleware.keynote; import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.handler.CorsHandler; /** * @author <a href="http://escoffier.me">Clement Escoffier</a> */ public class TrafficServerVerticle extends AbstractVerticle { private Buffer buffer = Buffer.buffer(); @Override public void start(Future<Void> future) throws Exception { int port = config().getInteger("trafficPort", 9003); long period = config().getLong("trafficPingInterval", 2000L); Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.route().handler(CorsHandler.create("*")); router.get("/health").handler(this::ping); router.post("/record").handler(this::addTraffic); vertx.createHttpServer() .requestHandler(router::accept) .websocketHandler(socket -> { switch (socket.path()) { case "/stream": // Push traffic data. MessageConsumer consumer = vertx.eventBus() .<JsonObject>consumer("traffic") .handler(m -> socket.writeFinalTextFrame(new JsonArray().add(m.body()).encode())); // Keep the socket open. long task = vertx.setPeriodic(period, l -> socket.writeFinalTextFrame("[]")); socket.closeHandler(v -> { vertx.cancelTimer(task); consumer.unregister(); }); break; case "/record": socket.frameHandler(frame -> { buffer.appendString(frame.textData()); if (!frame.isFinal()) { System.out.println("Non final frame sent from javascript ! " + frame); } else { vertx.eventBus().publish("traffic", buffer.toJsonObject()); buffer = Buffer.buffer(); } }); break; default: socket.reject(); } } ).listen(port, done -> { if (done.succeeded()) { future.complete(); } else { future.fail(done.cause()); } } ); } private void addTraffic(RoutingContext routingContext) { JsonObject json = routingContext.getBodyAsJson(); vertx.eventBus().publish("traffic", json); routingContext.response().end(); } private void ping(RoutingContext routingContext) { routingContext.response().end("OK"); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edufarming; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.scene.image.ImageView; import javafx.scene.text.Text; import javafx.stage.Stage; /** * FXML Controller class * * @author Frederick */ public class QuizController implements Initializable { @FXML private Button btn_next; @FXML private ImageView logo; @FXML private Button btn_logOut; @FXML private ToggleGroup one; @FXML private ToggleGroup two; @FXML private ToggleGroup three; @FXML private ToggleGroup four; @FXML private Button btn_back; @FXML private RadioButton rb1; @FXML private RadioButton rb2; @FXML private RadioButton rb3; @FXML private RadioButton rb4; @FXML private RadioButton rb5; @FXML private RadioButton rb6; @FXML private RadioButton rb7; @FXML private RadioButton rb8; @FXML private RadioButton rb9; @FXML private RadioButton rb10; @FXML private RadioButton rb11; @FXML private RadioButton rb12; int score=0; String firName=""; String lasName=""; @FXML private Text txt_DisplayName; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } @FXML private void next(ActionEvent event) throws IOException { if(rb2.isSelected()){ score++; } if(rb6.isSelected()){ score++; } if(rb8.isSelected()){ score++; } if(rb11.isSelected()){ score++; } Stage stage=(Stage) btn_next.getScene().getWindow(); FXMLLoader fxmlloader = new FXMLLoader(getClass().getResource("Quiz1.fxml")); Parent root2 = (Parent)fxmlloader.load(); Scene scene1 = new Scene(root2); stage.setScene(scene1); Quiz1Controller q1c=fxmlloader.<Quiz1Controller>getController(); q1c.passOn(score); q1c.passOnInfo(firName, lasName); q1c.setUsername(); stage.show(); } @FXML private void logOut(ActionEvent event) throws IOException, IOException { Stage stage=(Stage) btn_logOut.getScene().getWindow(); Parent root2 = FXMLLoader.load(getClass().getResource("LogOut.fxml")); Scene scene1 = new Scene(root2); stage.setScene(scene1); stage.show(); } @FXML private void back(ActionEvent event) throws IOException { Stage stage=(Stage) btn_back.getScene().getWindow(); FXMLLoader fxmlloader = new FXMLLoader(getClass().getResource("after_log_In.fxml")); Parent root2 = (Parent)fxmlloader.load(); Scene scene1 = new Scene(root2); stage.setScene(scene1); After_log_InController al=fxmlloader.<After_log_InController>getController(); al.passOnInfo(firName, lasName); al.setUsername(); stage.show(); } public void passOnInfo(String fName, String lName){ lasName = lName; firName = fName; } public void setUsername(){ txt_DisplayName.setText(firName+"."+lasName.charAt(0)); } }
package com.ibeiliao.pay.impl.dao; import com.ibeiliao.pay.impl.DeviceSource; import com.ibeiliao.pay.impl.entity.PayRecordPO; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Date; /** * PayRecordDao 测试 * @author linyi 2016/7/10 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:spring-context.xml") public class PayRecordDaoTest { @Autowired private PayRecordDao payRecordDao; /** * 测试增、改、查 * @throws Exception */ @Test public void testInsert() throws Exception { PayRecordPO po = new PayRecordPO(); long payId = System.currentTimeMillis(); long orderNo = System.currentTimeMillis(); Date now = new Date(); po.setPlatformId(1); po.setCreateTime(now); po.setUpdateTime(now); po.setAmount(100); po.setBuyerId(2); po.setBuyerName("buyer test"); po.setBuyerType((short)1); po.setCompositePay((short)0); po.setCurrencyType((short)1); po.setItemDesc("购买牛奶1瓶"); po.setItemName("牛奶"); po.setNotifyOrder((short)0); po.setStatus((short)1); po.setPayType((short)1); po.setSellerId(1001); po.setSellerName("seller test"); po.setSellerType((short)2); po.setPayTime(null); po.setPayId(payId); po.setOrderNo(orderNo); po.setReferencePayId(0L); po.setUserIp("127.0.0.1"); po.setDeviceSource(DeviceSource.H5.getSource()); // 测试读取 PayRecordPO current = payRecordDao.get(payId); if (current == null) { // 测试保存 payRecordDao.insert(po); current = payRecordDao.get(payId); Assert.assertNotNull(current); Assert.assertTrue(current.getDeviceSource() == po.getDeviceSource()); Assert.assertEquals(po.getBuyerName(), current.getBuyerName()); Assert.assertTrue(current.getAmount() == po.getAmount()); Assert.assertTrue(current.getOriginAmount() == po.getOriginAmount()); } else { // 测试更新 current.setItemDesc("购买牛奶1瓶: " + System.currentTimeMillis()); current.setUpdateTime(now); payRecordDao.update(current); PayRecordPO updated = payRecordDao.get(payId); Assert.assertEquals(current.getItemDesc(), updated.getItemDesc()); } } }
package micronaut.starter.kit; import org.dom4j.Element; import org.dom4j.Node; import javax.inject.Singleton; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; @Singleton public class VariablesNode { HashMap<String, VariableBean> map; public VariablesNode() { this.map = new HashMap<String, VariableBean>(); } public void parse(Element el) { VariableBean bn = new VariableBean(el); this.map.put(bn.name, bn); } public Set<String> keySet() { return (Set<String>) this.map.keySet(); } public List<VariableBean> values() { return new ArrayList<VariableBean>(this.map.values()); } public VariableBean findBean(String key) throws ClassNotFoundException { if (this.map.containsKey(key)){ return this.map.get(key); } throw new ClassNotFoundException("Variables with name: " + key + " not found"); } }
package com.example.cs246.medtracker; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.List; import java.util.ArrayList; import java.util.Date; /** * MyPrescriptionHandler * <p>Extended from MyDBHandler. This class facilitates creating, retrieving, * and editing Prescription objects inside SQLite Database</p> * Created by Tim on 3/12/2016. * @author Tim * @version 1.0 */ public class MyPrescriptionHandler extends MyDBHandler { /** * QUERY_BY_ID * Static string containing a formatted SQL query for searching by ID. */ public final static String QUERY_BY_ID = String.format("Select * FROM %s WHERE %s = ", MyDBContract.TABLE_PRESCRIPTIONS, MyDBContract.COLUMN_PRESCRIPTION_ID); /** * MyPrescriptionHandler() * <p>Builds a MyPrescriptionHandler object when provided with the required * parameters</p> * @param context : Context object * @param name : Blank String to satisfy Override reqs * @param factory : CursorFactory object * @param version : Blank Int to satisfy Override reqs */ public MyPrescriptionHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } /** * createPrescription(String name) * <p>Create a new Prescription object and table row inside the Database</p> * @param name : String containing the intended name of the Prescription * @return : Returns a Prescription object containing a unique reference ID * to its corresponding data inside the Database */ public Prescription createPrescription(String name) { ContentValues values = new ContentValues(); values.put(MyDBContract.COLUMN_NAMEPRESCRIPTION, name); SQLiteDatabase db = this.getWritableDatabase(); long id = db.insert(MyDBContract.TABLE_PRESCRIPTIONS, null, values); Log.i(MyPrescriptionHandler.class.getSimpleName(), "Prescription Created: " + id + " Name: " + name); return new Prescription(id, this); } /** * @param id The id of the prescription to delete */ public void deletePrescription(long id) { String query = "DELETE FROM " + MyDBContract.TABLE_DOSES + " WHERE " + MyDBContract.COLUMN_PRESCRIPTION_REFID + " = " + id; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(query); query = "DELETE FROM " + MyDBContract.TABLE_PRESCRIPTIONS + " WHERE " + MyDBContract.COLUMN_PRESCRIPTION_ID + " = " + id; db.execSQL(query); Log.i(MyDBHandler.class.getSimpleName(), "Prescription & Doses Deleted: " + id); db.close(); } /** * findPrescription(String name) * <p>Fetch a Prescription object by name</p> * @param name : String containing the name of the prescription you are trying to find * @return : Returns a Prescription object containing a unique reference ID * to its corresponding data inside the Database */ public Prescription findPrescription (String name) { String query = "Select * FROM " + MyDBContract.TABLE_PRESCRIPTIONS + " WHERE " + MyDBContract.COLUMN_NAMEPRESCRIPTION + " = \"" + name + "\""; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); Prescription prescription; if (cursor.moveToFirst()) { cursor.moveToFirst(); prescription = new Prescription(cursor.getLong(cursor.getColumnIndex(MyDBContract.COLUMN_PRESCRIPTION_ID)), this); } else { prescription = null; } cursor.close(); db.close(); return prescription; } public Prescription findPrescription (Long id) { String query = "Select * FROM " + MyDBContract.TABLE_PRESCRIPTIONS + " WHERE " + MyDBContract.COLUMN_PRESCRIPTION_ID + " = \"" + id + "\""; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); Prescription prescription; if (cursor.moveToFirst()) { cursor.moveToFirst(); prescription = new Prescription(cursor.getLong(cursor.getColumnIndex(MyDBContract.COLUMN_PRESCRIPTION_ID)), this); } else { prescription = null; } cursor.close(); db.close(); return prescription; } /** * getAllPrescriptions() * <p>Return an ArrayList containing all the Prescription objects * in the Database</p> * @return : An ArrayList of Prescription objects */ public ArrayList<Prescription> getAllPrescriptions () { String query = "Select * FROM " + MyDBContract.TABLE_PRESCRIPTIONS; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); ArrayList<Prescription> allPrescriptions = new ArrayList<Prescription>(); if (cursor.moveToFirst()) { do { Prescription prescription = new Prescription(cursor.getLong(cursor.getColumnIndex(MyDBContract.COLUMN_PRESCRIPTION_ID)), this); allPrescriptions.add(prescription); Log.d(MyPrescriptionHandler.class.getSimpleName(), "Prescription Fetched: " + Long.toString(prescription.getID())); } while (cursor.moveToNext()); } else allPrescriptions = null; cursor.close(); db.close(); return allPrescriptions; } /** * queryNamePrescription(long id) * <p>Fetch the name of a Prescription object from the database</p> * @param id : A valid unique Prescription id number (long int) * @return : Returns a String containing the name of the referenced Prescription */ public String queryNamePrescription(long id) { String name; String query = QUERY_BY_ID + id; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { cursor.moveToFirst(); name = cursor.getString(cursor.getColumnIndex(MyDBContract.COLUMN_NAMEPRESCRIPTION)); } else { name = null; } cursor.close(); db.close(); return name; } /** * queryAmountMedication(long id) * <p>Fetch the Amount Medication of a Prescription object from the database</p> * @param id : A valid unique Prescription id number (long int) * @return : Returns an int containing the amount medication of the referenced Prescription */ public double queryAmountMedication(long id) { double amount; String query = QUERY_BY_ID + id; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { cursor.moveToFirst(); amount = cursor.getDouble(cursor.getColumnIndex(MyDBContract.COLUMN_AMOUNTMEDICATION)); } else { amount = -1; } cursor.close(); db.close(); return amount; } /** * queryAmountPerDose(long id) * <p>Fetch the Amount Per Dose of a Prescription object from the database</p> * @param id : A valid unique Prescription id number (long int) * @return : Returns an int containing the amount per dose of the referenced Prescription */ public double queryAmountPerDose(long id) { double amount; String query = QUERY_BY_ID + id; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { cursor.moveToFirst(); amount = cursor.getDouble(cursor.getColumnIndex(MyDBContract.COLUMN_AMOUNTPERDOSE)); } else { amount = -1; } cursor.close(); db.close(); return amount; } /** * queryDailyMax(long id) * <p>Fetch the Amount Medication of a Prescription object from the database</p> * @param id : A valid unique Prescription id number (long int) * @return : Returns an int containing the daily max of the referenced Prescription */ public double queryDailyMax(long id) { double amount; String query = QUERY_BY_ID + id; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { cursor.moveToFirst(); amount = cursor.getDouble(cursor.getColumnIndex(MyDBContract.COLUMN_DAILYMAXDOSE)); } else { amount = -1; } cursor.close(); db.close(); return amount; } /** * queryRefillDate(long id) * <p>Fetch the Refill Date of a Prescription object from the database</p> * @param id : A valid unique Prescription id number (long int) * @return : Returns an int containing the Refill Date of the referenced Prescription */ public Date queryRefillDate(long id) { String query = QUERY_BY_ID + id; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); Date date = new Date(); if (cursor.moveToFirst()) { cursor.moveToFirst(); date.setTime(cursor.getLong(cursor.getColumnIndex(MyDBContract.COLUMN_REFILLDATE))); } else { date = null; } cursor.close(); db.close(); return date; } /** * queryExpirationDate(long id) * <p>Fetch the Amount Medication of a Prescription object from the database</p> * @param id : A valid unique Prescription id number (long int) * @return : Returns an int containing the Expiration Date of the referenced Prescription */ public Date queryExpirationDate(long id) { String query = QUERY_BY_ID + id; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); Date date = new Date(); if (cursor.moveToFirst()) { cursor.moveToFirst(); date.setTime(cursor.getLong(cursor.getColumnIndex(MyDBContract.COLUMN_EXPIRATIONDATE))); } else { date = null; } cursor.close(); db.close(); return date; } /** * queryDirections(long id) * <p>Fetch the Amount Medication of a Prescription object from the database</p> * @param id : A valid unique Prescription id number (long int) * @return : Returns an String containing the description of the referenced Prescription */ public String queryDirections(long id) { String directions; String query = QUERY_BY_ID + id; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { cursor.moveToFirst(); directions = cursor.getString(cursor.getColumnIndex(MyDBContract.COLUMN_DIRECTIONS)); } else { directions = null; } cursor.close(); db.close(); return directions; } public String queryUnits(long id) { String units; String query = QUERY_BY_ID + id; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { cursor.moveToFirst(); units = cursor.getString(7); } else { units = null; } cursor.close(); db.close(); return units; } /** * editNamePrescription(long id, String name) * <p>Submit a new name for a Prescription referenced by ID</p> * @param id : Unique integer for identifying a prescription * @param name : String containing the new Name for a Prescription referenced by ID */ public void editNamePrescription(long id, String name) { String query = "UPDATE " + MyDBContract.TABLE_PRESCRIPTIONS + " SET " + MyDBContract.COLUMN_NAMEPRESCRIPTION + " = \"" + name + "\" WHERE " + MyDBContract.COLUMN_PRESCRIPTION_ID + " = " + id; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(query); db.close(); } /** * editAmountMedication(long id, double amount) * <p>Submit a new Amount Medication for a Prescription referenced by ID</p> * @param id : Unique integer for identifying a prescription * @param amount : Double containing the new Amount Medication for a Prescription referenced by ID */ public void editAmountMedication( long id, double amount ) { String query = "UPDATE " + MyDBContract.TABLE_PRESCRIPTIONS + " SET " + MyDBContract.COLUMN_AMOUNTMEDICATION + " = " + amount + " WHERE " + MyDBContract.COLUMN_PRESCRIPTION_ID + " = " + id; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(query); db.close(); } /** * editAmountPerDose(long id, double amount) * <p>Submit a new name for a Prescription referenced by ID</p> * @param id : Unique integer for identifying a prescription * @param amount : double containing the new Amount Per Dose for a Prescription referenced by ID */ public void editAmountPerDose( long id, double amount ) { String query = "UPDATE " + MyDBContract.TABLE_PRESCRIPTIONS + " SET " + MyDBContract.COLUMN_AMOUNTPERDOSE + " = " + amount + " WHERE " + MyDBContract.COLUMN_PRESCRIPTION_ID + " = " + id; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(query); db.close(); } /** * editDailyMax(long id, double amount) * <p>Submit a new Daily Max for a Prescription referenced by ID</p> * @param id : Unique integer for identifying a prescription * @param amount : Double containing the new Daily Max for a Prescription referenced by ID */ public void editDailyMax( long id, double amount ) { String query = "UPDATE " + MyDBContract.TABLE_PRESCRIPTIONS + " SET " + MyDBContract.COLUMN_DAILYMAXDOSE + " = " + amount + " WHERE " + MyDBContract.COLUMN_PRESCRIPTION_ID + " = " + id; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(query); db.close(); } /** * editRefillDate(long id, Date date) * <p>Submit a new Refill Date for a Prescription referenced by ID</p> * @param id : Unique integer for identifying a prescription * @param date : Date containing the new Refill Date for a Prescription referenced by ID */ public void editRefillDate( long id, Date date ) { String query = "UPDATE " + MyDBContract.TABLE_PRESCRIPTIONS + " SET " + MyDBContract.COLUMN_REFILLDATE + " = " + date.getTime() + " WHERE " + MyDBContract.COLUMN_PRESCRIPTION_ID + " = " + id; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(query); db.close(); } /** * editExpirationDate(long id, String name) * <p>Submit a new Expiration Date for a Prescription referenced by ID</p> * @param id : Unique integer for identifying a prescription * @param date : Date containing the new Expiration Date for a Prescription referenced by ID */ public void editExpirationDate( long id, Date date ) { String query = "UPDATE " + MyDBContract.TABLE_PRESCRIPTIONS + " SET " + MyDBContract.COLUMN_EXPIRATIONDATE + " = " + date.getTime() + " WHERE " + MyDBContract.COLUMN_PRESCRIPTION_ID + " = " + id; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(query); db.close(); } /** * editDirections(long id, String name) * <p>Submit new Directions for a Prescription referenced by ID</p> * @param id : Unique integer for identifying a prescription * @param directions : String containing the new Directions for a Prescription referenced by ID */ public void editDirections( long id, String directions ) { String query = "UPDATE " + MyDBContract.TABLE_PRESCRIPTIONS + " SET " + MyDBContract.COLUMN_DIRECTIONS + " = \"" + directions + "\" WHERE " + MyDBContract.COLUMN_PRESCRIPTION_ID + " = " + id; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(query); db.close(); } public void editUnits( long id, String units ) { String query = "UPDATE " + MyDBContract.TABLE_PRESCRIPTIONS + " SET " + MyDBContract.COLUMN_UNITS + " = \"" + units + "\" WHERE " + MyDBContract.COLUMN_PRESCRIPTION_ID + " = " + id; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(query); db.close(); } }
package org.fuserleer.console; import java.io.PrintStream; import java.util.Collection; import java.util.Date; import java.util.stream.Collectors; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.fuserleer.Context; import org.fuserleer.crypto.Hash; import org.fuserleer.ledger.Block; import org.fuserleer.ledger.PendingAtom; import org.fuserleer.ledger.PendingState; import org.fuserleer.ledger.ShardMapper; import org.fuserleer.ledger.StateCertificate; import org.fuserleer.ledger.StateVote; import org.fuserleer.time.Time; public class Ledger extends Function { private final static Options options = new Options().addOption("pending", false, "Return pending ledger information") .addOption("states", false, "Return hash list of all pending states") .addOption(Option.builder("snapshot").desc("Outputs current state info of ledger").optionalArg(true).numberOfArgs(1).build()) .addOption("block", true, "Return block at specified height") .addOption("branches", false, "Return pending branches"); public Ledger() { super("ledger", options); } @Override public void execute(Context context, String[] arguments, PrintStream printStream) throws Exception { CommandLine commandLine = Function.parser.parse(options, arguments); if (commandLine.hasOption("pending") == true) { if (commandLine.hasOption("branches") == true) { context.getLedger().getBlockHandler().getPendingBranches().forEach(pb -> printStream.println(pb.toString())); } else if (commandLine.hasOption("states") == true) { Collection<PendingState> pendingStates = context.getLedger().getStateHandler().getAll(); pendingStates.forEach(ps -> printStream.println(ps.toString())); printStream.println(pendingStates.size()+" pending states"); } } else if (commandLine.hasOption("block") == true) { Block block = context.getLedger().getBlock(Long.parseLong(commandLine.getOptionValue("block"))); printStream.println("Block: "+block.getHeader().toString()); } else if (commandLine.hasOption("snapshot") == true) { boolean verbose = false; String option = commandLine.getOptionValue("snapshot"); if (option != null && option.compareToIgnoreCase("verbose") == 0) verbose = true; Collection<PendingAtom> atomHandlerPending = context.getLedger().getAtomHandler().getAll(); if (verbose) atomHandlerPending.forEach(pa -> printStream.println(pa.getHash())); printStream.println(atomHandlerPending.size()+" pending in atom handler "+atomHandlerPending.stream().map(PendingAtom::getHash).reduce((a, b) -> Hash.from(a,b))); Collection<PendingAtom> atomPoolPending = context.getLedger().getAtomPool().getAll(); if (verbose) atomPoolPending.forEach(pa -> printStream.println(pa.getHash())); printStream.println(atomPoolPending.size()+" pending in atom pool "+atomPoolPending.stream().map(PendingAtom::getHash).reduce((a, b) -> Hash.from(a,b))); Collection<PendingState> stateHandlerPending = context.getLedger().getStateHandler().getAll(); if (verbose) stateHandlerPending.forEach(ps -> printStream.println(ps.getHash())); printStream.println(stateHandlerPending.size()+" pending in state handler "+stateHandlerPending.stream().map(ps -> ps.getHash()).reduce((a, b) -> Hash.from(a,b))); Collection<StateCertificate> stateHandlerCertificates = context.getLedger().getStateHandler().getAll().stream().filter(ps -> ps.getCertificate() != null).map(ps -> ps.getCertificate()).collect(Collectors.toList()); if (verbose) stateHandlerCertificates.forEach(sc -> printStream.println(sc.getHash())); printStream.println(stateHandlerCertificates.size()+" certificates in state handler "+stateHandlerCertificates.stream().map(sc -> sc.getHash()).reduce((a, b) -> Hash.from(a,b))); Collection<StateVote> stateHandlerVotes = context.getLedger().getStateHandler().getAll().stream().flatMap(ps -> ps.votes().stream()).collect(Collectors.toList()); if (verbose) stateHandlerVotes.forEach(sv -> printStream.println(sv.getHash())); printStream.println(stateHandlerVotes.size()+" votes in state pool "+stateHandlerVotes.stream().map(sv -> sv.getHash()).reduce((a, b) -> Hash.from(a,b))); Collection<Hash> stateAccumulatorExclusiveLocked = context.getLedger().getStateAccumulator().locked(true); if (verbose) stateAccumulatorExclusiveLocked.forEach(p -> printStream.println(p.toString())); printStream.println(stateAccumulatorExclusiveLocked.size()+" exclusive locks in accumulator "+stateAccumulatorExclusiveLocked.stream().reduce((a, b) -> Hash.from(a,b))); Collection<Hash> stateAccumulatorNonExclusiveLocked = context.getLedger().getStateAccumulator().locked(false); if (verbose) stateAccumulatorNonExclusiveLocked.forEach(p -> printStream.println(p.toString())); printStream.println(stateAccumulatorNonExclusiveLocked.size()+" non-exclusive locks in accumulator "+stateAccumulatorNonExclusiveLocked.stream().reduce((a, b) -> Hash.from(a,b))); printStream.println("Current head: "+context.getLedger().getHead()); } else { printStream.println("Synced: "+context.getLedger().isSynced()); printStream.println("Identity: S-"+(ShardMapper.toShardGroup(context.getNode().getIdentity(), context.getLedger().numShardGroups()))+" <- "+context.getNode().getIdentity()); printStream.println("Current head: "+context.getLedger().getHead()); printStream.println("Ledger timestamp: "+Time.getLedgerTimeSeconds()+" / "+new Date(Time.getLedgerTimeMS())); // TODO only accurate for simulated time printStream.println("Atoms (P/L/T): "+context.getLedger().getAtomHandler().getAll().size()+"/"+context.getMetaData().get("ledger.processed.atoms.local", 0l)+"/"+context.getMetaData().get("ledger.processed.atoms.total", 0l)); printStream.println("Certificates (A/R/T): "+context.getMetaData().get("ledger.commits.certificates.accept", 0l)+"/"+context.getMetaData().get("ledger.commits.certificates.reject", 0l)+"/"+context.getMetaData().get("ledger.commits.certificates", 0l)); printStream.println("Accumulation (I/A/T): "+context.getMetaData().get("ledger.accumulator.iterations", 0l)+"/"+(context.getMetaData().get("ledger.accumulator.duration", 0l) / Math.max(1, context.getMetaData().get("ledger.accumulator.iterations", 0l)))+"/"+context.getMetaData().get("ledger.accumulator.duration", 0l)); printStream.println("Block size avg: "+(context.getMetaData().get("ledger.blocks.bytes", 0l)/(context.getLedger().getHead().getHeight()+1))); printStream.println("Block throughput: "+context.getMetaData().get("ledger.throughput.blocks", 0l)); printStream.println("Atom throughput: "+context.getMetaData().get("ledger.throughput.atoms.local", 0l)+"/"+context.getMetaData().get("ledger.throughput.atoms.total", 0l)); printStream.println("Commit latency: "+context.getMetaData().get("ledger.throughput.latency", 0l)); printStream.println("Atom pool (S/A/R/C/Q): "+context.getLedger().getAtomPool().size()+" / "+context.getMetaData().get("ledger.pool.atoms.added", 0l)+" / "+context.getMetaData().get("ledger.pool.atoms.removed", 0l)+" / "+context.getMetaData().get("ledger.pool.atoms.agreed", 0l)+" / "+context.getMetaData().get("ledger.pool.atom.certificates", 0l)); printStream.println("State pool (S/A/R/V/C): "+context.getLedger().getStateHandler().size()+" / "+context.getMetaData().get("ledger.pool.state.added", 0l)+" / "+context.getMetaData().get("ledger.pool.state.removed", 0l)+" / "+context.getMetaData().get("ledger.pool.state.votes", 0l)+" / "+context.getMetaData().get("ledger.pool.state.certificates", 0l)); printStream.println("Block pool: "+context.getLedger().getBlockHandler().size()+" / "+context.getMetaData().get("ledger.pool.blocks.added", 0l)+" / "+context.getMetaData().get("ledger.pool.blocks.removed", 0l)); printStream.println("Shard (G/A): "+context.getLedger().numShardGroups()+"/"+context.getMetaData().get("ledger.throughput.shards.touched", 0l)); printStream.println("Gossip Req (A/AV/SV/SC/BH/BV): "+context.getMetaData().get("gossip.requests.atom", 0l)+"/"+context.getMetaData().get("gossip.requests.atomvote", 0l)+"/"+ context.getMetaData().get("gossip.requests.statevote", 0l)+"/"+context.getMetaData().get("gossip.requests.statecertificate", 0l)+"/"+ context.getMetaData().get("gossip.requests.blockheader", 0l)+"/"+context.getMetaData().get("gossip.requests.blockvote", 0l)+"/"+context.getMetaData().get("gossip.requests.total", 0l)); } } }
package com.tencent.mm.plugin.profile.ui; import com.tencent.mm.R; import com.tencent.mm.plugin.profile.ui.NormalUserFooterPreference.a; import com.tencent.mm.ui.base.l; import com.tencent.mm.ui.base.n.c; class NormalUserFooterPreference$a$4 implements c { final /* synthetic */ a lXy; NormalUserFooterPreference$a$4(a aVar) { this.lXy = aVar; } public final void a(l lVar) { lVar.ak(2, R.l.app_field_voip, R.k.sharemore_videovoip); lVar.ak(1, R.l.app_field_voipaudio, R.k.sharemore_voipvoice); } }
package com.lin.paper.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.lin.paper.bean.UserInfo; /** * 登录拦截器 * @ * @date 2018年2月7日下午7:27:00 * @version 1.0 */ public class LoginInterceptor implements HandlerInterceptor{ /** * Handler执行之前调用这个方法 * @param request * @param response * @param handler * @return * @throws Exception * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //获取请求的URL String url = request.getRequestURI(); if(url.indexOf("/login.html")>=0 //登录界面 || url.indexOf("/column/show/")==0 //栏目 || url.indexOf("/notice/show/")==0 //公告浏览 || url.indexOf("/notice/download/")==0 //公告下载 || url.indexOf("/notice/search")==0 //搜索 || url.indexOf("/user/vcode")==0 //验证码 || url.indexOf("/index.html")==0 //主页 ||(url.indexOf("/")==0&&url.lastIndexOf("/")==0&&url.indexOf("/main.html")==-1)){ //前台主页 return true; } //获取Session HttpSession session = request.getSession(); UserInfo userInfo = (UserInfo)session.getAttribute("session_user"); if(userInfo != null){ return true; } //不符合条件的,跳转到登录界面 request.getRequestDispatcher("/login.html").forward(request, response); return false; } /** * Handler执行之后,ModelAndView返回之前调用这个方法 * @param request * @param response * @param handler * @param modelAndView * @throws Exception * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub } /** * Handler执行完成之后调用这个方法 * @param request * @param response * @param handler * @param ex * @throws Exception * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub } }
package com.sdk4.boot.controller.log; import com.google.common.collect.Lists; import com.sdk4.boot.apiengine.ApiFactory; import com.sdk4.boot.apiengine.ApiService; import com.sdk4.boot.common.BaseResponse; import com.sdk4.boot.common.PageResponse; import com.sdk4.boot.domain.ApiLog; import com.sdk4.boot.service.LogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; /** * @author sh */ @RestController("BootApiLogController") @RequestMapping("/ops") public class ApiLogController { @Autowired LogService logService; @RequestMapping(value = { "apinames" }, produces = "application/json;charset=UTF-8" ) public BaseResponse<List<String>> apinames(@RequestBody Map reqMap) { Map<String, ApiService> apis = ApiFactory.getAllApi(); List<String> names = Lists.newArrayList(); for (Map.Entry<String, ApiService> entry : apis.entrySet()) { names.add(entry.getValue().method()); } BaseResponse<List<String>> ret = new BaseResponse(0, "获取成功", names); return ret; } @RequestMapping(value = { "apilog" }, produces = "application/json;charset=UTF-8" ) public PageResponse apilog(@RequestBody Map reqMap) { PageResponse<ApiLog> pageResponse = logService.queryApiLog(reqMap); return pageResponse; } }
package listeners.comprables; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JLabel; import GUI.Gui; import juego.Juego; import state.Estado; import visitor.Visitor; import visitor.VisitorBuff; public abstract class ComprablePowerUp extends MouseAdapter { protected Gui gui; protected JLabel sprite; protected ComprablePowerUp(Gui gui) { this.gui = gui; } public void mousePressed(MouseEvent e) { Estado pu = crearPowerUp(); if (Juego.getJuego().getMonedas()>=pu.getCoste()) { Visitor v = getVisitor(pu); Juego.getJuego().visitarEntidades(v); Juego.getJuego().sumarMonedas(-1*pu.getCoste()); } } protected Visitor getVisitor(Estado e) { return new VisitorBuff(e); } protected abstract Estado crearPowerUp(); }
package com.acme.paymentserver.exception; public class PaymentExistsException extends RuntimeException { }
package com.cryfish.myalomatika; import java.util.HashMap; public interface Constants { HashMap<Integer, String> colors = new HashMap<>() {{ put(0, "#b20000"); //red put(1, "#a000b5"); //purple put(2, "#3600af"); //blue put(3, "#00a4ad"); //aqua put(4, "#0caa00"); //green put(5, "#ff7f00"); //orange }}; }
package com.kvapps.kyle.tripeaks; import java.util.ArrayList; import java.util.Iterator; /** * class to model the cards that have been dealt out into the tripeak formation. */ public class Dealt { private ArrayList<Card> dealt = new ArrayList<>(); /** * Creates the doubly linked list of cards that are connected by cards they are covering and the cards they are covered by. * @param deck Deck of 52 cards */ public void start(Deck deck){ for(int i=0; i<28; i++){ dealt.add(deck.flip()); } int count = 0; for(int i=1; i<4; i++){ for(int j=0; j<i*3; j++){ Card indexCard = dealt.get(count); if (i<3) { indexCard.addCovered(dealt.get((j / i) + (i * 3) + count), dealt.get((j / i) + (i * 3) + count + 1)); } else { indexCard.addCovered(dealt.get((i * 3) + count), dealt.get((i * 3) + count + 1)); } ArrayList<Card> cards = indexCard.getCovered(); for(Card c : cards){ c.addCovering(indexCard); } count++; } } } /** * Getter returning the card at the specified index * @param index the index of the dealt card to return * @return Card The card being asked for */ public Card get(int index){ return dealt.get(index); } }
package org.sang.config; import org.sang.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.util.DigestUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * Created by albert on 2019/12/20. */ // WebSecurity(WEB安全) @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserService userService; // AuthenticationManagerBuilder(身份验证管理生成器) @Override // 重写了configure参数为AuthenticationManagerBuilder的方法 protected void configure(AuthenticationManagerBuilder auth) throws Exception { //并根据传入的AuthenticationManagerBuilder中的userDetailsService方法来接收我们自定义的认证方法。 //且该方法必须要实现UserDetailsService这个接口。 auth.userDetailsService(userService).passwordEncoder(new PasswordEncoder() { @Override public String encode(CharSequence charSequence) { return DigestUtils.md5DigestAsHex(charSequence.toString().getBytes()); } /** * @param charSequence 明文 * @param s 密文 * @return */ @Override public boolean matches(CharSequence charSequence, String s) { return s.equals(DigestUtils.md5DigestAsHex(charSequence.toString().getBytes())); } }); } @Override protected void configure(HttpSecurity http) throws Exception { // super.configure(http); // 定制请求的授权规则 // http.authorizeRequests()其中这里的意思是指通过authorizeRequests()方法来开始请求权限配置。 //而接着的.anyRequest().authenticated()是对http所有的请求必须通过授权认证才可以访问 // 每个matcher按照他们的声明顺序执行 http.authorizeRequests() // .antMatchers("/register").permitAll() // 用户可任意访问 .antMatchers("/admin/category/all").authenticated() // 用户登录后可以访问 // .antMatchers("/admin/**","/reg").hasRole("超级管理员")///admin/**的URL都需要有超级管理员角色,如果使用.hasAuthority()方法来配置,需要在参数中加上ROLE_,如下.hasAuthority("ROLE_超级管理员") .antMatchers("/admin/user/**", "/admin/roles", "/admin/category/").hasRole("超级管理员") .anyRequest().authenticated() // 其他的路径都是登录后即可访问 .and() .formLogin() // .loginPage("/login") .loginPage("/login_page") // 指定登录页的路径 // 必须允许所有用户访问我们的登录页(例如为验证的用户,否则验证流程就会进入死循环) // 这个formLogin().permitAll()方法允许所有用户基于表单登录访问/login这个page // 登录成功 .successHandler(new AuthenticationSuccessHandler() { @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { httpServletResponse.setContentType("application/json;charset=utf-8"); PrintWriter out = httpServletResponse.getWriter(); out.write("{\"status\":\"success\",\"msg\":\"登录成功\"}"); out.flush(); out.close(); } }) // 登录失败 .failureHandler(new AuthenticationFailureHandler() { @Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { httpServletResponse.setContentType("application/json;charset=utf-8"); PrintWriter out = httpServletResponse.getWriter(); out.write("{\"status\":\"error\",\"msg\":\"登录失败\"}"); out.flush(); out.close(); } }).loginProcessingUrl("/login") /** * 1)HttpSecurity支持cors。 * * 2)默认会启用CRSF,此处因为没有使用thymeleaf模板(会自动注入_csrf参数), * * 要先禁用csrf,否则登录时需要_csrf参数,而导致登录失败。 * * 3)antMatchers:匹配 "/" 路径,不需要权限即可访问,匹配 "/user" 及其以下所有路径, * * 都需要 "USER" 权限 * * 4)配置登录地址和退出地址 */ .usernameParameter("username").passwordParameter("password").permitAll() .and() .logout() // 登出 .permitAll() .and() .csrf().disable() // 禁用csrf,否则登录时需要_csrf参数,而导致登录失败。 .exceptionHandling().accessDeniedHandler(getAccessDeniedHandler()); } // WebSecurity(WEB安全) @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/blogimg/**", "/index.html", "/static/**", "/register"); } @Bean AccessDeniedHandler getAccessDeniedHandler() { return new AuthenticationAccessDeniedHandler(); } }
package game.unit.characters; import game.core.HexTile; import game.items.Armor; import game.items.Weapon; import game.match.Player; import game.unit.Unit; public class NoUnit extends Unit{ public NoUnit(HexTile onTile) { super(Player.EMPTY, onTile, Weapon.EMPTY, Weapon.EMPTY, Armor.EMPTY, ""); } }
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import beans.Auction ; public class AuctionDao { private DAOFactory daoFactory; private static final String SQL_INSERT = "INSERT INTO auction(amount, date,user_id,article_auction_id) Values (?, NOW(), ?,?)"; private static final String SQL_SELECT_PAR_ID = "SELECT * date FROM auction WHERE id = ? " ; private static final String SQL_SELECT_PAR_DATE = "SELECT * FROM auction WHERE date= ? "; public AuctionDao (DAOFactory daoFactory) { this.daoFactory = daoFactory; } public void create (Auction auction) throws DAOException{ Connection connexion = null; PreparedStatement preparedStatement = null; ResultSet valeursAutoGenerees = null; try { connexion = daoFactory.getConnection(); preparedStatement = initialisationRequetePreparee( connexion, SQL_INSERT, true , auction.getAmount(),auction.getBuyer().getId(),auction.getArticle().getId() ); int statut = preparedStatement.executeUpdate();if ( statut == 0 ) { throw new DAOException( "Echec de la creation de l'user, aucune ligne ajoutee dans la table." );} valeursAutoGenerees = preparedStatement.getGeneratedKeys(); if ( valeursAutoGenerees.next() ) { auction.setId( valeursAutoGenerees.getInt( 1 ) ); } else {throw new DAOException( "Echec de la creation de l'user en base, aucun ID auto-genere retourne." ); } } catch ( SQLException e ) { throw new DAOException( e ); } finally { fermeturesSilencieuses( valeursAutoGenerees, preparedStatement, connexion ); } } public static PreparedStatement initialisationRequetePreparee( Connection connexion, String sql, boolean returnGeneratedKeys, Object... objets )throws SQLException{ PreparedStatement preparedStatement = connexion.prepareStatement( sql, returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS ); for ( int i = 0; i < objets.length; i++ ) { preparedStatement.setObject( i + 1, objets[i] ); } return preparedStatement; } public static void fermetureSilencieuse( ResultSet resultSet ) { if ( resultSet != null ) { try { resultSet.close(); } catch ( SQLException e ) { System.out.println( "Echec de la fermeture du ResultSet : " + e.getMessage() ); } } } /* Fermeture silencieuse du statement */ public static void fermetureSilencieuse( Statement statement ) { if ( statement != null ) { try { statement.close(); } catch ( SQLException e ) { System.out.println( "Echec de la fermeture du Statement : " + e.getMessage() ); } } } /* Fermeture silencieuse de la connexion */ public static void fermetureSilencieuse( Connection connexion ) { if ( connexion != null ) { try { connexion.close(); } catch ( SQLException e ) { System.out.println( "Echec de la fermeture de la connexion : " + e.getMessage() ); } } } /* Fermetures silencieuses du statement et de la connexion */ public static void fermeturesSilencieuses( Statement statement, Connection connexion ) { fermetureSilencieuse( statement ); fermetureSilencieuse( connexion ); } /* Fermetures silencieuses du resultset, du statement et de la connexion */ public static void fermeturesSilencieuses( ResultSet resultSet, Statement statement, Connection connexion ) { fermetureSilencieuse( resultSet ); fermetureSilencieuse( statement ); fermetureSilencieuse( connexion ); } private static Auction map( ResultSet resultSet ) throws SQLException { Auction auction = new Auction(); auction.setId(resultSet.getInt("id")); auction.setAmount(resultSet.getInt("amount")); auction.setDate(resultSet.getDate("date")); auction.setArticle(DAOFactory.getInstance().getArticleDao().find_auc(resultSet.getInt("article_auction_id"))); auction.setBuyer(DAOFactory.getInstance().getUserDao().find(resultSet.getInt("user_id"))); return auction;} public Auction find( int id) throws DAOException {Connection connexion = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Auction auction = null; try { connexion = daoFactory.getConnection(); preparedStatement = initialisationRequetePreparee( connexion, SQL_SELECT_PAR_ID, false,id ); resultSet = preparedStatement.executeQuery(); if ( resultSet.next() ) { auction = map(resultSet ); } } catch ( SQLException e ) { throw new DAOException( e ); } finally { fermeturesSilencieuses( resultSet, preparedStatement, connexion ); } return auction ; } public Auction find( String date) throws DAOException {Connection connexion = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Auction auction = null; try { connexion = daoFactory.getConnection(); preparedStatement = initialisationRequetePreparee( connexion, SQL_SELECT_PAR_DATE, false,date ); resultSet = preparedStatement.executeQuery(); if ( resultSet.next() ) { auction = map(resultSet ); } } catch ( SQLException e ) { throw new DAOException( e ); } finally { fermeturesSilencieuses( resultSet, preparedStatement, connexion ); } return auction ; } }
package net.iz44kpvp.kitpvp.Comandos; import org.bukkit.GameMode; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import net.iz44kpvp.kitpvp.Sistemas.API; public class Gamemode implements CommandExecutor { public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) { if (cmd.getName().equalsIgnoreCase("gm") || cmd.getName().equalsIgnoreCase("gamemode")) { if (sender instanceof ConsoleCommandSender) { System.out.println(API.semconsole); return true; } final Player p = (Player) sender; if (args.length == 0) { p.sendMessage(String.valueOf(String.valueOf(API.preffix)) + "§cUse: §8/gm,gamemode 0 | 1 "); } else if (args.length == 1) { if (p.hasPermission("Ninho.gm") || p.isOp()) { if (args[0].equalsIgnoreCase("1") || args[0].equalsIgnoreCase("criativo")) { p.setGameMode(GameMode.CREATIVE); p.sendMessage(String.valueOf(String.valueOf(API.preffix)) + "§bVoce Entrou No Modo §eCriativo"); } else if (args[0].equalsIgnoreCase("0") || args[0].equalsIgnoreCase("sobrevivencia")) { p.setGameMode(GameMode.SURVIVAL); p.sendMessage( String.valueOf(String.valueOf(API.preffix)) + "§bVoce Entrou No Modo §cSobrebivencia"); } else if (args[0].equalsIgnoreCase("2") || args[0].equalsIgnoreCase("aventura")) { p.setGameMode(GameMode.ADVENTURE); p.sendMessage(String.valueOf(String.valueOf(API.preffix)) + "§bVoce Entrou No Modo §aAventura"); } else { p.sendMessage(API.jogadoroff); } } else { p.sendMessage(API.semperm); } } } return false; } }
//package net.cupmouse.minecraft.eplugin.chat.callback; // //import net.cupmouse.minecraft.eplugin.EPluginSession; //import net.objecthunter.exp4j.ExpressionBuilder; //import net.objecthunter.exp4j.function.Function; //import org.spongepowered.api.entity.living.player.Player; // //public final class CalcExpCallback extends CallBack { // // private static final Function FUNC_DISTANCE; // // static { // FUNC_DISTANCE = new Function("dist", 6) { // // @Override // public double apply(double... args) { // double x1 = args[0]; // double y1 = args[1]; // double z1 = args[2]; // double x2 = args[3]; // double y2 = args[4]; // double z2 = args[5]; // return Math.pow((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1), 0.5); // } // }; // } // // private String exp; // // public CalcExpCallback(EPluginSession plugin, Player sendTo, String exp) { // super(plugin, sendTo); // this.exp = exp; // } // // // @Override // public void run() { // sendMessage(ChatColor.GRAY + exp); // try { // double result = new ExpressionBuilder(exp) // // 変数 // .variables("s", "hs", "hhs", "inv", "slot") // .function(FUNC_DISTANCE) // .build() // .setVariable("s", 64) // 1スタック // .setVariable("hs", 32) // ハーフスタック // .setVariable("hhs", 16) // 1/4スタック // .setVariable("inv", 36) // インベントリ全スロット // .setVariable("slot", 9) // スロット(インベントリ最下部) // .evaluate(); // sendMessage(ChatColor.AQUA + " = " + String.format("%f", result)); // } catch (Exception e) { // sendMessage(ChatColor.RED + " = ERROR! - " + e.getLocalizedMessage()); // } // } //}
import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.xml.bind.ParseConversionEvent; import kovaUtils.TextAssist.TextAssist; import kovaUtils.TextAssist.TextAssistContentProvider; import net.miginfocom.swt.MigLayout; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DateTime; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolTip; public class editForm implements FocusListener, KeyListener, VerifyListener { static Group group; static Label lblCateg; static Label lblDatum; static DateTime dtp; static DateTime dtp2; static Label lblBrRata; static Label lblIznosU; static Text txtBrRata; static Text txtUkupRata; static String datum; static TextAssist txtMjesto2; static TextAssist txtSvrha; static Text txtIznos; Label lblTrack; static Label lblNet; static Text txtNet; Label sep; static int optIndex; static ToolTip tip; static Label lbl; static Label lblMess; static Button[] opt; static Button cmdSpremi; static Button cmdExit; static Listener listener; double ukIznos = 0; static double iznNeg = 0; static int IDbroj = 0; static String sTablica = "racuni"; Image icona; static ResultSet rs; static Boolean flgAdmin = false; static Shell shell; static Composite comp; static Shell s; static Display display; private static String SQLquery; MigLayout layout = new MigLayout(""); MigLayout layout2 = new MigLayout(""); MigLayout layoutComp = new MigLayout(""); private TextAssistContentProvider contentProvider2; private ArrayList<String> lista; private ArrayList<String> lista2; private static Color gray; public editForm(Shell parent) { shell = new Shell(parent, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM); display = shell.getDisplay(); shell.setSize(360, 250); icona = new Image(display, "library/icons/Boue.ico"); shell.setImage(icona); shell.addListener(SWT.Close, new Listener() { public void handleEvent(Event event) { DEF.gBroj = 0; } }); shell.setLayout(layout); createWidgets(); createButtons(); // DEF.setLanguage(shell); if (DEF.gBroj != 0) { // ako je uređivanje i ako je broj >0 popunjava // formu fillForm(DEF.gBroj); } else { shell.setText(DEF.getLabel("Edit")); } shell.open(); DEF.CenterScreen(shell, display); shell.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); // Utils.centerDialogOnScreen(comp.getcomp()); if (DEF.gBroj != 0) { // ako je uređivanje i ako je broj >0 popunjava // formu // fillForm(DEF.gBroj); } else { shell.setText("Uređivanje retka?"); } while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } } private void createWidgets() { gray = display.getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW); lblCateg = new Label(shell, SWT.BORDER | SWT.CENTER); lblCateg.setLayoutData("span,width 340px"); lblCateg.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); lblCateg.setText("Nema kategorije"); lblCateg.setForeground(gray); comp = new Composite(shell, SWT.NONE); comp.setLayoutData("width 310px,height 320px"); comp.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); comp.setLayout(layoutComp); listener = new Listener() { public void handleEvent(Event e) { Button bt = (Button) e.widget; for (int i = 0; i < 4; i++) { if (bt.equals(opt[i])) { optIndex = i; break; } } switch (optIndex) { case 0: // System.out.println("0"); // iznNeg=0; // iznNeg=Math.abs(Double.parseDouble(txtIznos.getText())); // System.out.println(iznNeg); // // txtIznos.setText(String.valueOf(iznNeg)); // // txtIznos.setText(DEF.FormatCur(txtIznos.getText())); // txtIznos.setText(DEF.FormatCur2(iznNeg)); lblBrRata.setVisible(false); txtBrRata.setVisible(false); lblIznosU.setVisible(false); txtUkupRata.setVisible(false); txtMjesto2.setSize(265, 20); lblNet.setVisible(false); txtNet.setVisible(false); break; case 1: // System.out.println("1"); // iznNeg=0; // iznNeg=Math.abs(Double.parseDouble(txtIznos.getText())); // // System.out.println(iznNeg); // // iznNeg = (iznNeg * - 1); // // txtIznos.setText(String.valueOf(iznNeg)); // // txtIznos.setText(DEF.FormatCur(txtIznos.getText())); // txtIznos.setText(DEF.FormatCur2(iznNeg)); lblBrRata.setVisible(false); txtBrRata.setVisible(false); lblIznosU.setVisible(false); txtUkupRata.setVisible(false); txtMjesto2.setSize(265, 20); lblNet.setVisible(false); txtNet.setVisible(false); break; case 2: // System.out.println("2"); // iznNeg=0; // iznNeg=Math.abs(Double.parseDouble(txtIznos.getText())); // System.out.println(iznNeg); // iznNeg = (iznNeg * - 1); // // txtIznos.setText(String.valueOf(iznNeg)); // // txtIznos.setText(DEF.FormatCur(txtIznos.getText())); // txtIznos.setText(DEF.FormatCur2(iznNeg)); String sUK = String.valueOf(DEF.Round( DEF.getReal(txtIznos.getText()) / DEF.getReal(txtBrRata.getText()), 2)); txtUkupRata.setText(DEF.FormatCur(sUK)); lblBrRata.setVisible(true); txtBrRata.setVisible(true); lblIznosU.setVisible(true); txtUkupRata.setVisible(true); lblNet.setVisible(false); txtNet.setVisible(false); txtMjesto2.setSize(265, 20); break; case 3: // // System.out.println("3"); // comp.layout(true); // iznNeg=0; // iznNeg=Math.abs(Double.parseDouble(txtIznos.getText())); // System.out.println(iznNeg); // iznNeg = (iznNeg * - 1); // // txtIznos.setText(String.valueOf(iznNeg)); // // txtIznos.setText(DEF.FormatCur(txtIznos.getText())); // txtIznos.setText(DEF.FormatCur2(iznNeg)); txtMjesto2.setSize(155, 20); txtMjesto2.setRedraw(true); lblNet.setLocation(225, 65); lblNet.setVisible(true); txtNet.setLocation(255, 62); txtNet.setVisible(true); lblBrRata.setVisible(false); txtBrRata.setVisible(false); lblIznosU.setVisible(false); txtUkupRata.setVisible(false); // // shell.setSize(shell.computeSize(SWT.DEFAULT, // SWT.DEFAULT)); // comp.update(); // comp.redraw(); // comp.pack(); // shell.update(); // shell.redraw(); // break; } } }; String optText[] = { "Prihodi", "Rashodi", "Rate", "NetBanking" }; opt = new Button[4]; for (int i = 0; i < opt.length; i++) { opt[i] = new Button(comp, SWT.RADIO); opt[i].setText(DEF.getLabel("opt" + i)); opt[i].setLayoutData("width 30px"); opt[i].setBackground(display.getSystemColor(SWT.COLOR_WHITE)); opt[i].addListener(SWT.Selection, listener); } opt[0].setLayoutData("split 4"); opt[3].setLayoutData("wrap"); sep = new Label(comp, SWT.SEPARATOR | SWT.SHADOW_IN | SWT.HORIZONTAL); sep.setLayoutData("width 330px,wrap"); lbl = new Label(comp, SWT.NONE); lbl.setText(DEF.getLabel("lblDatum")); lbl.setLayoutData("width 50px,split2,gapright 6px,gapleft 2px"); lbl.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); dtp = new DateTime(comp, SWT.DROP_DOWN); dtp.setLayoutData("width 100px,wrap"); dtp.setDate(DEF.getToday().getYear(), DEF.getToday().getMonth(), DEF .getToday().getDay()); dtp.setMonth(DEF.getToday().getMonth()); dtp.setYear(DEF.getToday().getYear()); dtp.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: datum = dtp.getYear() + "-" + (dtp.getMonth()) + "-" + dtp.getDay(); } } }); lbl = new Label(comp, SWT.NONE); lbl.setText(DEF.getLabel("lblMjesto")); lbl.setLayoutData("width 50px,split2,gapright 6px,gapleft 2px,span2"); lbl.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); rs = RSet .openRS("select distinct mjesto from racuni where Mjesto is not null "); //$NON-NLS-1$ lista = new ArrayList<String>(); int i = 0; try { while (rs.next()) { lista.add(rs.getString("mjesto")); //$NON-NLS-1$ i++; } } catch (SQLException e2) { e2.printStackTrace(); } contentProvider2 = new TextAssistContentProvider() { // private final String[] EUROZONE = new String[] { // "Austria","Albanija","Australija","Amerika","Azerbejđan","Argentina","BIH","Belgium", // "Cyprus", "Estonia", "Finland", "France", "Germany", "Greece", // "Ireland", "Italy", "Luxembourg", "Malta", "Netherlands", // "Portugal", "Slovakia", "Slovenia", "Spain" }; @Override public List<String> getContent(final String entry) { List<String> returnedList = new ArrayList<String>(); for (String country : lista) { if (country.toLowerCase().startsWith(entry.toLowerCase())) { returnedList.add(country); } } return returnedList; } }; txtMjesto2 = new TextAssist(comp, SWT.BORDER, contentProvider2); // txtMjesto2 // = // new // Text // (comp, // SWT.BORDER); txtMjesto2.setTextLimit(50); txtMjesto2.setLayoutData("width 265px"); // txtMjesto2 = new Text (comp, SWT.BORDER); // txtMjesto2.setTextLimit(50); // txtMjesto2.setLayoutData ("width 265px"); // txtMjesto2.setEditable(true); // txtMjesto2.addFocusListener(this); // txtMjesto2.addKeyListener(this); // // samo za NetBanking lblNet = new Label(comp, SWT.NONE); lblNet.setText(DEF.getLabel("lblNet")); lblNet.setLayoutData("width 30px"); lblNet.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); lblNet.setLocation(190, 65); lblNet.setVisible(false); txtNet = new Text(comp, SWT.BORDER); txtNet.setTextLimit(10); txtNet.setLayoutData("width 75px,wrap"); txtNet.addFocusListener(this); txtNet.addKeyListener(this); txtNet.setLocation(222, 62); txtNet.setVisible(false); lbl = new Label(comp, SWT.NONE); lbl.setText(DEF.getLabel("lblSvrha")); lbl.setLayoutData("width 50px,split2,gapright 7px,gapleft 2px,span"); lbl.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); rs = RSet .openRS("select distinct svrha from racuni where svrha is not null "); //$NON-NLS-1$ lista2 = new ArrayList<String>(); try { while (rs.next()) { lista2.add(rs.getString("svrha")); //$NON-NLS-1$ } } catch (SQLException e2) { e2.printStackTrace(); } contentProvider2 = new TextAssistContentProvider() { // private final String[] EUROZONE = new String[] { // "Austria","Albanija","Australija","Amerika","Azerbejđan","Argentina","BIH","Belgium", // "Cyprus", "Estonia", "Finland", "France", "Germany", "Greece", // "Ireland", "Italy", "Luxembourg", "Malta", "Netherlands", // "Portugal", "Slovakia", "Slovenia", "Spain" }; @Override public List<String> getContent(final String entry) { List<String> returnedList = new ArrayList<String>(); for (String country : lista2) { if (country.toLowerCase().startsWith(entry.toLowerCase())) { returnedList.add(country); } } return returnedList; } }; txtSvrha = new TextAssist(comp, SWT.SINGLE | SWT.BORDER, contentProvider2); txtSvrha.setTextLimit(50); txtSvrha.setLayoutData("width 265px,wrap"); // txtSvrha = new Text (comp, SWT.BORDER); // txtSvrha.setTextLimit(50); // txtSvrha.setLayoutData ("width 265px,wrap"); // txtSvrha.addFocusListener(this); // txtSvrha.addKeyListener(this); lbl = new Label(comp, SWT.NONE); lbl.setText(DEF.getLabel("lblIznos")); lbl.setLayoutData("width 50px,split6,gapright 7px,gapleft 2px,span"); lbl.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); txtIznos = new Text(comp, SWT.BORDER); txtIznos.setText("0,00"); txtIznos.setTextLimit(15); txtIznos.setLayoutData("width 65px,span"); txtIznos.addFocusListener(this); txtIznos.addKeyListener(this); txtIznos.addVerifyListener(this); // samo za rate... // ---------------------------------------------------------------------------------// lblBrRata = new Label(comp, SWT.NONE); lblBrRata.setText(DEF.getLabel("lblBrRata")); lblBrRata.setLayoutData("width 30px"); lblBrRata.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); lblBrRata.setVisible(false); txtBrRata = new Text(comp, SWT.BORDER); txtBrRata.setLayoutData("width 30px"); txtBrRata.setTextLimit(3); txtBrRata.setText("12"); txtBrRata.setVisible(false); txtBrRata.addFocusListener(this); txtBrRata.addKeyListener(this); txtBrRata.addVerifyListener(this); lblIznosU = new Label(comp, SWT.NONE); lblIznosU.setText(DEF.getLabel("lblIznosU")); lblIznosU.setData("L10"); lblIznosU.setLayoutData("width 20px,split2"); lblIznosU.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); lblIznosU.setVisible(false); txtUkupRata = new Text(comp, SWT.BORDER | SWT.READ_ONLY); txtUkupRata.setLayoutData("width 65px,span,wrap"); txtUkupRata.setText("0,00"); txtUkupRata.setVisible(false); txtUkupRata.addFocusListener(this); txtUkupRata.addKeyListener(this); txtUkupRata.addVerifyListener(this); } private void createButtons() { sep = new Label(comp, SWT.SEPARATOR | SWT.SHADOW_IN | SWT.HORIZONTAL); sep.setLayoutData("width 330px,wrap,span2"); cmdSpremi = new Button(comp, SWT.PUSH | SWT.WRAP); cmdSpremi.setText(DEF.getLabel("cmdSpremi")); cmdSpremi.setLayoutData("width 320px,span,wrap"); cmdSpremi.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: lblMess.setText("Spremanje u tijeku!\n Molimo pričekajte..."); if (checkValues() == true) { Spremi(DEF.gBroj); shell.dispose(); } else { lblMess.setText("Nisu unešeni svi potrebni podaci!"); } } } }); // cmdExit = new Button(comp,SWT.PUSH|SWT.WRAP); // cmdExit.setText("Odustani"); // cmdExit.setLayoutData ("width 240px,span 2,wrap"); // // // cmdExit.addListener(SWT.Selection, new Listener() { // public void handleEvent(Event e) { // switch (e.type) { // // case SWT.Selection: // comp.close(); // // } // } // }); lblMess = new Label(comp, SWT.NONE); lblMess.setLayoutData("width 240px,growx"); lblMess.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); lblMess.setForeground(display.getSystemColor(SWT.COLOR_RED)); lblMess.setAlignment(SWT.CENTER); shell.setDefaultButton(cmdSpremi); } private static void fillForm(int broj) { ResultSet rs; // System.out.println("EDIT broja:" + broj); try { SQLquery = "select R.ID,R.Datum,R.Mjesto,R.Svrha,R.Iznos,R.Tip,C.R,C.G,C.B,C.Name,R.Iznos,R.Pintrans from racuni R LEFT OUTER JOIN " + " categories C on R.kategorija=C.ID" + " where R.ID = " + broj; rs = RSet.openRS(SQLquery); while (rs.next()) { if (rs.getString("R") != null) { // System.out.println(rs.getString("R")); lblCateg.setBackground(new Color(shell.getDisplay(), new RGB(rs.getInt("R"), rs.getInt("G"), rs .getInt("B")))); lblCateg.setText(rs.getString("Name")); } else { lblCateg.setForeground(gray); lblCateg.setText(DEF.getLabel("NoCateg")); } txtSvrha.setText(rs.getString("svrha")); txtMjesto2.setText(rs.getString("mjesto")); txtNet.setText(DEF.iNull(rs.getString("PINtrans"))); Double Iznos = rs.getDouble("iznos"); txtIznos.setText(DEF.FormatCur2(Iznos)); // txtIznos.setText("%1$.2f", Iznos); optIndex = rs.getInt("tip"); for (int i = 0; i < 4; i++) { if (i == optIndex) { opt[i].setSelection(true); opt[i].setFocus(); opt[i].notifyListeners(SWT.Selection, new Event()); comp.changed(new Control[] { opt[i] }); comp.layout(); break; } } // System.out.println("dan" + // DEF.getSQLDay(rs.getDate("Datum"))); // System.out.println("mjesec" + // DEF.getSQLMonth(rs.getDate("Datum"))); // System.out.println("godina" + // DEF.getSQLYear(rs.getDate("Datum"))); // dtp.setDay(Integer.parseInt(DEF.getSQLDay(rs.getDate("Datum")))); dtp.setMonth((Integer.parseInt(DEF.getSQLMonth(rs .getDate("Datum"))) - 1)); dtp.setYear(Integer.parseInt(DEF.getSQLYear(rs.getDate("Datum")))); // dtp.setMonth(); // dtp.setYear(); // System.out.println(rs.getDate("datum")); } RSet.closeRS(); txtSvrha.selectAll(); } catch (SQLException e) { System.out.println("fillForm - greška RS!"); logger.loggErr("editForm " + e.getMessage() + " (" + e.getErrorCode() + ")"); e.printStackTrace(); } } private static void Spremi(int broj) { if (broj != 0) { RSet.updateRS("update racuni set mjesto='" + txtMjesto2.getText() + "',svrha='" + txtSvrha.getText() + "',iznos='" + DEF.getReal(txtIznos.getText()) + "',tip='" + optIndex + "',datum='" + dtp.getYear() + "-" + (dtp.getMonth() + 1) + "-" + dtp.getDay() + "' where ID= " + broj); System.out.println("update racuni set mjesto='" + txtMjesto2.getText() + "',svrha='" + txtSvrha.getText() + "',iznos='" + DEF.getReal(txtIznos.getText()) + "',tip='" + optIndex + "',datum='" + dtp.getYear() + "-" + (dtp.getMonth() + 1) + "-" + dtp.getDay() + "' where ID= " + broj); logger.logg("Ažurirane vrijednosti u tablici " + sTablica + " (ID=" + broj + ")"); DEF.gBroj = 0; } else { // System.out.println("ime='"+ txtIme.getText() +"',prezime='"+ // txtPrezime.getText() +"',[user]='"+ txtUser.getText() // +"',pass='"+ txtPass.getText() +"',vrijediOd='"+ dtPoc // +"',vrijediDo='"+ dtKraj +"'"); String col = "iznos,mjesto,svrha,tip,datum"; String val = "'" + txtIznos.getText() + "','" + txtMjesto2.getText() + "','" + txtSvrha.getText() + "','" + optIndex + "','" + dtp.getYear() + "-" + (dtp.getMonth() + 1) + "-" + dtp.getDay() + "'"; RSet.addRS2(sTablica, col, val); logger.logg("Unos novih vrijednosti u tablicu " + sTablica + " (" + txtSvrha.getText() + "," + txtIznos.getText() + ")"); DEF.gBroj = 0; } } @Override public void focusGained(FocusEvent e) { Text t = (Text) e.widget; t.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); t.selectAll(); } @Override public void focusLost(FocusEvent e) { String UK = "0,00"; Text t = (Text) e.widget; t.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); if (e.widget == txtIznos || e.widget == txtBrRata) { if (optIndex == 2) { UK = String.valueOf(DEF.Round(DEF.getReal(txtIznos.getText()) / DEF.getReal(txtBrRata.getText()), 2)); } else if (optIndex != 0 && e.widget == txtIznos) { iznNeg = 0; iznNeg = Math.abs(DEF.getReal(txtIznos.getText())); iznNeg = (iznNeg * -1); txtIznos.setText(String.valueOf(iznNeg)); } else if (optIndex == 0 && e.widget == txtIznos) { iznNeg = 0; iznNeg = Math.abs(DEF.getReal(txtIznos.getText())); iznNeg = Math.abs(iznNeg); txtIznos.setText(String.valueOf(iznNeg)); } txtIznos.setText(DEF.FormatCur(txtIznos.getText())); txtUkupRata.setText(DEF.FormatCur(UK)); } } @Override public void keyPressed(KeyEvent e) { Text t = (Text) e.widget; if (e.keyCode == 16777218) {// dolje t.traverse(SWT.TRAVERSE_TAB_NEXT); } else if (e.keyCode == 16777217) {// gore t.traverse(SWT.TRAVERSE_TAB_PREVIOUS); } } @Override public void verifyText(VerifyEvent e) { // iznos if (e.widget == txtIznos || e.widget == txtUkupRata) { String string = e.text; char[] chars = new char[string.length()]; string.getChars(0, chars.length, chars, 0); for (int i = 0; i < chars.length; i++) { if (!('0' <= chars[i] && chars[i] <= '9' || '.' == chars[i] || '-' == chars[i] || ',' == chars[i])) e.doit = false; return; } } else if (e.widget == txtBrRata) { String string = e.text; char[] chars = new char[string.length()]; string.getChars(0, chars.length, chars, 0); for (int i = 0; i < chars.length; i++) { if (!('0' <= chars[i] && chars[i] <= '9')) e.doit = false; return; } } } private static boolean checkValues() { Boolean flgFields = false; int chk = 0; switch (optIndex) { case 2: if (txtBrRata.getText().length() != 0 || txtBrRata.getText() != "0") chk += 1; case 3: if (txtNet.getText().length() != 0) chk += 1; default: if (txtIznos.getText() != "0,00" || txtIznos.getText() != "-0,00" || txtIznos.getText().length() != 0) chk += 1; if (txtMjesto2.getText().length() != 0 || txtMjesto2.getText() != "") chk += 1; if (txtSvrha.getText().length() != 0 || txtSvrha.getText() != "") chk += 1; } switch (optIndex) { case 2: if (chk == 4) flgFields = true; case 3: if (chk == 4) flgFields = true; default: if (chk == 3) flgFields = true; } return flgFields; } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } }
package mine_mine; public class VendingNestedIfVAR2 { public static void main(String[] args) { String selection = "drink"; String drinkItem = "coke"; String snackItem = "candy"; if(selection.equals("drink")){ System.out.println("Drink option is selected"); if(drinkItem.equals("tea")){ System.out.println("Tea selected"); }else{ System.out.println("Coke selected"); } }else if (selection.equals("snack")){ System.out.println("Snack option is selected"); if(snackItem.equals("chips")){ System.out.println("Chips is selected"); }else{ System.out.println("candy is selected"); } } } }
package com.fancy.ownparking.ui.car; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.fancy.ownparking.R; import com.fancy.ownparking.data.local.entity.Car; import com.fancy.ownparking.ui.base.BaseAdapter; import java.util.ArrayList; import java.util.List; public class CarAdapter extends BaseAdapter<Car, CarAdapter.CarViewHolder> { CarAdapter(OnAdapterItemListener<Car> listener) { super(listener); } @Override public CarViewHolder onCreateRecyclerViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_car, parent, false); return new CarViewHolder(view); } @Override public void onBindRecyclerViewHolder(CarViewHolder holder, int position) { Car car = mItemsList.get(position); holder.bind(car); } @Override public List<Car> search(String query) { List<Car> filteredList = new ArrayList<>(); for (Car car : mItemsList) { if (car.getName().toLowerCase().contains(query.toLowerCase()) || car.getNumber().toLowerCase().contains(query.toLowerCase())) { filteredList.add(car); } } return filteredList; } class CarViewHolder extends RecyclerView.ViewHolder { private TextView mName; private TextView mNumber; CarViewHolder(View itemView) { super(itemView); mName = itemView.findViewById(R.id.text_car_name); mNumber = itemView.findViewById(R.id.text_car_number); } public void bind(Car car) { mName.setText(car.getName()); mNumber.setText(car.getNumber()); if (car.isSelected()) { itemView.setBackgroundColor(itemView.getResources().getColor(R.color.light_gray)); } else { itemView.setBackgroundColor(itemView.getResources().getColor(R.color.white)); } itemView.setOnClickListener(view -> { if (mListener != null) { if (isMultipleSelectionEnabled) { car.setSelected(!car.isSelected()); notifyItemChanged(getAdapterPosition()); mListener.onAdapterSelectionClick(car); return; } mListener.onAdapterItemClick(car); } }); itemView.setOnLongClickListener(view -> { if (mListener != null && !isMultipleSelectionEnabled) { car.setSelected(true); notifyItemChanged(getAdapterPosition()); isMultipleSelectionEnabled = true; mListener.onAdapterItemLongClick(car); return true; } return false; }); } } }
package com.angelhack.mapteam.api.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreType; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; @Generated("com.robohorse.robopojogenerator") @JsonIgnoreProperties(ignoreUnknown = true) public class AccessTokenResponse{ @JsonProperty("access_token") private String accessToken; @JsonProperty("token_type") private String tokenType; public void setAccessToken(String accessToken){ this.accessToken = accessToken; } public String getAccessToken(){ return accessToken; } public void setTokenType(String tokenType){ this.tokenType = tokenType; } public String getTokenType(){ return tokenType; } @Override public String toString(){ return "AccessTokenResponse{" + "access_token = '" + accessToken + '\'' + ",token_type = '" + tokenType + '\'' + "}"; } }
package com.hepsiemlak; import org.apache.log4j.BasicConfigurator; import org.junit.After; import org.junit.Before; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.apache.log4j.Logger; public class Base { WebDriver webDriver; ChromeOptions options = new ChromeOptions(); public Logger log = Logger.getLogger(Base.class); @Before public void setUp() { BasicConfigurator.configure(); log.info("------Web Tesler Başlatıyor-------"); System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver1.exe"); options.addArguments("--start-maximized"); options.addArguments("--disable-notifications"); webDriver = new ChromeDriver(options); webDriver.get("https:/www.hepsiemlak.com"); } @After public void tearDown() { webDriver.quit(); } }
package com.isystk.sample.domain.entity; import java.time.LocalDateTime; import org.seasar.doma.Column; import org.seasar.doma.Entity; import org.seasar.doma.GeneratedValue; import org.seasar.doma.GenerationType; import org.seasar.doma.Id; import org.seasar.doma.Table; import org.seasar.doma.Version; import com.isystk.sample.domain.dto.common.DomaDtoImpl; import lombok.Getter; import lombok.Setter; /** * 自動生成のため原則修正禁止!! */ @Entity @Table(name = "t_post") @Getter @Setter public class TPost extends DomaDtoImpl { /** * serialVersionUID */ private static final long serialVersionUID = 1L; /** * 投稿ID */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "POST_ID") Integer postId; /** * 会員ID */ @Column(name = "USER_ID") Integer userId; /** * タイトル */ @Column(name = "TITLE") String title; /** * 本文 */ @Column(name = "TEXT") String text; /** * 登録日時 */ @Column(name = "REGIST_TIME") LocalDateTime registTime; /** * 更新日時 */ @Column(name = "UPDATE_TIME") LocalDateTime updateTime; /** * 削除フラグ */ @Column(name = "DELETE_FLG") Boolean deleteFlg; /** * 楽観チェック用バージョン */ @Version @Column(name = "VERSION") Long version; }
package Gof.principles.module.proxy.pattern.module; public class ProxyPattern { public static void main(String[] args) { System.out.println("***Proxy Pattern Demo***\n"); Proxy px = new Proxy(); px.doSomeWork(); } }
package custom.classes; import java.util.*; import java.text.*; public class DateFunctions { public static void main(String args[]) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); long convertedDate = 12345678910L; try { String inputDate = "2018-05-18T13:51:15"; if (inputDate.isEmpty()|| inputDate == " "){ Date date = df.parse("1970-01-01T00:00:00+02:00"); convertedDate = date.getTime(); convertedDate = (convertedDate)/1000; } else{ Date date = df.parse(inputDate); convertedDate = date.getTime(); /*double plus2Hours = 7.2e+6; long epoch2Hours = Math.round(plus2Hours); convertedDate = (convertedDate + epoch2Hours)/1000;*/ convertedDate = (convertedDate)/1000; } } catch (ParseException e) { e.printStackTrace(); } //return convertedDate; System.out.println(convertedDate); } }
package com.smxknife.annotation.processor.writer; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import java.io.IOException; import static org.objectweb.asm.Opcodes.ASM4; /** * @author smxknife * 2019-03-28 */ public class DataPointWriter { ClassReader reader; ClassWriter writer; AddAnnotationAdapter addAnnotationAdapter; final static String CLASSNAME = "com.smxknife.annotation.example.DataPoint"; final static String CLONEABLE = "com/smxknife/annotation/example/DataPoint"; public DataPointWriter() { try { reader = new ClassReader(CLASSNAME); writer = new ClassWriter(reader, 0); } catch (IOException e) { e.printStackTrace(); } } public DataPointWriter(byte[] content) { reader = new ClassReader(content); writer = new ClassWriter(reader, 0); } public byte[] addAnnotation(String ann) { addAnnotationAdapter = new AddAnnotationAdapter(ann, writer); reader.accept(addAnnotationAdapter, 0); return writer.toByteArray(); } public class AddAnnotationAdapter extends ClassVisitor { private String annotation; private boolean isPresent; public AddAnnotationAdapter(String annotation, ClassVisitor cv) { super(ASM4, cv); this.cv = cv; this.annotation = annotation; } @Override public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { if (annotation.equals(descriptor)) isPresent = true; return cv.visitAnnotation(descriptor, visible); } @Override public void visitEnd() { if (!isPresent) { AnnotationVisitor av = cv.visitAnnotation(annotation, true); av.visitEnd(); } cv.visitEnd(); } } }
package com.example.spring.mongodb;
package net.minecraft.world; public enum EnumSkyBlock { SKY(15), BLOCK(0); public final int defaultLightValue; EnumSkyBlock(int defaultLightValueIn) { this.defaultLightValue = defaultLightValueIn; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\world\EnumSkyBlock.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package cn.canlnac.onlinecourse.data.entity; import com.google.gson.annotations.SerializedName; import java.util.List; /** * 评论列表. */ public class CommentListEntity { @SerializedName("total") private int total; @SerializedName("comments") private List<CommentEntity> comments; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<CommentEntity> getComments() { return comments; } public void setComments(List<CommentEntity> comments) { this.comments = comments; } }
package com.epf.rentmanager.dao; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; import com.epf.rentmanager.exception.DaoException; import com.epf.rentmanager.model.Reservation; import com.epf.rentmanager.persistence.ConnectionManager; @Repository public class ReservationDao { private static final String CREATE_RESERVATION_QUERY = "INSERT INTO Reservation(client_id, vehicle_id, debut, fin) VALUES(?, ?, ?, ?);"; private static final String DELETE_RESERVATION_QUERY = "DELETE FROM Reservation WHERE id=?;"; private static final String FIND_RESERVATIONS_BY_CLIENT_QUERY = "SELECT id, vehicle_id, debut, fin FROM Reservation WHERE client_id=? ORDER BY vehicle_id;"; private static final String FIND_RESERVATIONS_BY_VEHICLE_QUERY = "SELECT id, client_id, debut, fin FROM Reservation WHERE vehicle_id=? ORDER BY client_id;"; private static final String FIND_RESERVATIONS_QUERY = "SELECT id, client_id, vehicle_id, debut, fin FROM Reservation;"; private static final String FIND_RESERVATION_QUERY = "SELECT client_id, vehicle_id, debut, fin FROM Reservation WHERE id=?;"; private static final String EDIT_RESERVATIONS_QUERY = "UPDATE Reservation SET client_id = ?, vehicle_id = ?, debut = ?, fin = ? WHERE id = ?;"; private static final String COUNT_RESERVATIONS_QUERY = "SELECT COUNT(*) as count FROM Reservation;"; private static final String NB_VEHICLE_BY_CLIENT = "SELECT DISTINCT vehicle_id FROM Reservation WHERE client_id=?;"; private static final String NB_CLIENT_BY_VEHICLE = "SELECT DISTINCT client_id FROM Reservation WHERE vehicle_id=?;"; private static final String FIND_RESERVATIONS_TRIES_QUERY = "SELECT id, client_id, debut, fin FROM Reservation WHERE vehicle_id=? ORDER BY fin;"; /** * Créé une reservation * * @param reservation de la classe Reservation * @return l'id (long) de la reservation créée * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public long create(Reservation reservation) throws DaoException { long id = 0; try { Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(CREATE_RESERVATION_QUERY, Statement.RETURN_GENERATED_KEYS); ps.setLong(1, reservation.getClient_id()); ps.setLong(2, reservation.getVoiture_id()); ps.setDate(3, Date.valueOf(reservation.getDebut())); ps.setDate(4, Date.valueOf(reservation.getFin())); ps.executeUpdate(); ResultSet resultSet = ps.getGeneratedKeys(); if (resultSet.next()) { id = resultSet.getLong(1); } ps.close(); connection.close(); } catch (SQLException e) { throw new DaoException("Erreur lors de la création de la réservation", e); } return id; } /** * Supprime une reservation * * @param id un long identifiant du reservation * @return l'id de la reservation supprimée * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public long delete(long id) throws DaoException { try { Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(DELETE_RESERVATION_QUERY, Statement.RETURN_GENERATED_KEYS); ps.setLong(1, id); ps.executeUpdate(); ResultSet resultSet = ps.getGeneratedKeys(); if (resultSet.next()) { id = resultSet.getLong(1); } ps.close(); connection.close(); } catch (SQLException e) { throw new DaoException("Erreur lors de la suppression de la réservation", e); } return id; } /** * Trouve une réservation via son id * * @param id un long identifiant de la réservation * @return la réservation trouvée * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public Reservation findById(long idr) throws DaoException { Reservation reservation = new Reservation(); try { Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(FIND_RESERVATION_QUERY); ps.setLong(1, idr); ResultSet resultSet = ps.executeQuery(); if (resultSet.next()) { reservation.setClient_id(resultSet.getLong("client_id")); reservation.setVoiture_id(resultSet.getLong("vehicle_id")); reservation.setDebut(resultSet.getDate("debut").toLocalDate()); reservation.setFin(resultSet.getDate("fin").toLocalDate()); reservation.setId(idr); } ps.close(); resultSet.close(); connection.close(); } catch (SQLException e) { throw new DaoException("Erreur lors de la recherche de la réservation", e); } return reservation; } /** * Trouve les réservations d'un client via son id * * @param clientId un long identifiant du client dans la classe réservation * @return la liste des réservations du client * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public List<Reservation> findResaByClientId(long clientId) throws DaoException { List<Reservation> liste_Reservations = new ArrayList<>(); try { Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(FIND_RESERVATIONS_BY_CLIENT_QUERY); ps.setLong(1, clientId); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { Reservation reservation = new Reservation(); reservation.setId(resultSet.getLong("id")); reservation.setVoiture_id(resultSet.getLong("vehicle_id")); reservation.setDebut(resultSet.getDate("debut").toLocalDate()); reservation.setFin(resultSet.getDate("fin").toLocalDate()); liste_Reservations.add(reservation); } ps.close(); connection.close(); } catch (SQLException e) { throw new DaoException("Erreur lors de la génération de la liste des réservations du client", e); } return liste_Reservations; } /** * Trouve les réservations d'un véhicule via son id * * @param vehicleId un long identifiant du véhicule dans la classe réservation * @return la liste des réservations du véhicule * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public List<Reservation> findResaByVehicleId(long vehicleId) throws DaoException { List<Reservation> liste_Reservations = new ArrayList<>(); try { Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(FIND_RESERVATIONS_BY_VEHICLE_QUERY); ps.setLong(1, vehicleId); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { Reservation reservation = new Reservation(); reservation.setId(resultSet.getLong("id")); reservation.setClient_id(resultSet.getLong("client_id")); reservation.setDebut(resultSet.getDate("debut").toLocalDate()); reservation.setFin(resultSet.getDate("fin").toLocalDate()); liste_Reservations.add(reservation); } ps.close(); connection.close(); } catch (SQLException e) { throw new DaoException("Erreur lors de la génération de la liste des réservations du véhicule", e); } return liste_Reservations; } /** * Donne la liste des reservations * * @return la liste des reservations (ArrayList) * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public List<Reservation> findAll() throws DaoException { List<Reservation> liste_Reservations = new ArrayList<>(); try { Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(FIND_RESERVATIONS_QUERY); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { Reservation reservation = new Reservation(); reservation.setClient_id(resultSet.getLong("client_id")); reservation.setVoiture_id(resultSet.getLong("vehicle_id")); reservation.setId(resultSet.getLong("id")); reservation.setDebut(resultSet.getDate("debut").toLocalDate()); reservation.setFin(resultSet.getDate("fin").toLocalDate()); liste_Reservations.add(reservation); } ps.close(); connection.close(); } catch (SQLException e) { throw new DaoException("Erreur lors de la génération de la liste des réservations", e); } return liste_Reservations; } /** * Permet de modifier une reservation * * @param reservation un élément de la classe reservation * @return le nombre de lignes modifiées * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public int edit(Reservation reservation) throws DaoException { try { Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(EDIT_RESERVATIONS_QUERY); ps.setLong(1, reservation.getClient_id()); ps.setLong(2, reservation.getVoiture_id()); ps.setDate(3, Date.valueOf(reservation.getDebut())); ps.setDate(4, Date.valueOf(reservation.getFin())); ps.setLong(5, reservation.getId()); int nb_lignes_modifiees = ps.executeUpdate(); ps.close(); connection.close(); return nb_lignes_modifiees; } catch (SQLException e) { throw new DaoException("Erreur lors de la modification de la réservation", e); } } /** * Compte le nombre de reservations * * @return le nombre de reservations (int) * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public int count() throws DaoException { int nb_reservation = 0; try { Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(COUNT_RESERVATIONS_QUERY); ResultSet rs = ps.executeQuery(); if (rs.next()) { nb_reservation = rs.getInt("count"); } } catch (SQLException e) { throw new DaoException("Erreur lors du compte du nombre de réservations", e); } return nb_reservation; } /** * Compte le nombre de clients de chaque voiture * * @param id L'identifiant de la voiture * @return Le nombre trouvé * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public int NbClientByVehicle(int id) throws DaoException { try (Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(NB_CLIENT_BY_VEHICLE);) { ps.setInt(1, id); ResultSet resultSet = ps.executeQuery(); int count = 0; while (resultSet.next()) { count++; } return count; } catch (SQLException e) { throw new DaoException(); } } /** * Compte le nombre de voitures de chaque client * * @param id L'identifiant du client * @return Le nombre trouvé * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public int NbVehicleByClient(int id) throws DaoException { try (Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(NB_VEHICLE_BY_CLIENT);) { ps.setInt(1, id); ResultSet resultSet = ps.executeQuery(); int count = 0; while (resultSet.next()) { count++; } return count; } catch (SQLException e) { throw new DaoException(); } } /** * La liste des identifiants des voitures utilisées par un client * * @param id L'identifiant du client * @return La liste d'identifiant (ArrayList) * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public List<Integer> vehicleIdByClient(int id) throws DaoException { List<Integer> vehicleListe = new ArrayList<>(); try (Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(NB_VEHICLE_BY_CLIENT);) { ps.setInt(1, id); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { vehicleListe.add(resultSet.getInt("vehicle_id")); } return vehicleListe; } catch (SQLException e) { throw new DaoException(); } } /** * La liste des identifiants des clients ayant réservés la voiture * * @param id L'identifiant de la voiture * @return La liste d'identifiant (ArrayList) * @throws DaoException en cas d'erreur lors de la connexion à la base de donnée * ou dans la requête */ public List<Integer> clientIdByVehicle(int id) throws DaoException { List<Integer> clientListe = new ArrayList<>(); try (Connection connection = ConnectionManager.getConnection(); PreparedStatement ps = connection.prepareStatement(NB_CLIENT_BY_VEHICLE);) { ps.setInt(1, id); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { clientListe.add(resultSet.getInt("client_id")); } return clientListe; } catch (SQLException e) { throw new DaoException(); } } /** * Retourne la liste des réservations associées à un véhicule triée de la plus * ancienne à la plus récente * * @param resa Une réservation dont on veut récupperer l'identifiant du véhicule * dont on souhaite afficher les autres réservations associées * @return Une liste qui contient toutes les réservations du véhicule * @throws DaoException en cas d'erreur lors de la connection à la base de * données ou dans la requête */ public List<Reservation> tri_par_date(Reservation resa) throws DaoException { List<Reservation> reservations_tries = new ArrayList<>(); try (Connection connection = ConnectionManager.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(FIND_RESERVATIONS_TRIES_QUERY);) { preparedStatement.setLong(1, resa.getVoiture_id()); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { if (resultSet.getInt("id") != resa.getId()) { Reservation reservation = new Reservation(); reservation.setId(resultSet.getInt("id")); reservation.setClient_id(resultSet.getInt("client_id")); reservation.setVoiture_id(resa.getVoiture_id()); reservation.setDebut(resultSet.getDate("debut").toLocalDate()); reservation.setFin(resultSet.getDate("fin").toLocalDate()); reservations_tries.add(reservation); } } boolean resa_ajoutee = false; int place = 0; for (Reservation reservation : reservations_tries) { if (resa.getDebut().isBefore(reservation.getDebut())) { reservations_tries.add(place, resa); resa_ajoutee = true; break; } place++; } if (resa_ajoutee == false) { reservations_tries.add(resa); } } catch (SQLException e) { throw new DaoException(e.getMessage()); } return reservations_tries; } }
package com.model; import javax.swing.DefaultListModel; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; import com.view.ProcessList; /** * Contains all entries for the process list */ public class ProcessListModel extends DefaultListModel<Integer> implements ChangeListener { private Model model; public ProcessListModel(Model model) { if (model == null) { throw new NullPointerException(); } this.model = model; ensureCapacity(model.getProcessData().size()); for (Integer processID : model.getProcessData().keySet()) { addElement(processID); } model.addChangeListener(this); } public void stateChanged(ChangeEvent e) { // merge new IDs from model into this ensureCapacity(model.getProcessData().size()); int index = 0; for (Integer processID : model.getProcessData().keySet()) { if (index == size() || processID.compareTo(get(index)) < 0) { add(index, processID); } // the model only adds process IDs, but never removes them assert(processID == get(index)); index++; } // any process may have become (in)active and possibly needs // to be rendered again if (size() > 0) { fireContentsChanged(this, 0, size()-1); } } }
package org.eginez; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Set7 { static void findTarget(double target, Map<String, Double> items, List<String> picked) { if (target == 0) { System.out.println(picked); } if (target < 0) { return; } for (String item : items.keySet()){ double price = items.get(item); Map<String, Double> newItems = new HashMap<>(items); newItems.remove(item); int times = 1; List<String> newList = new ArrayList<String>(picked); while(target - (price * times) >= 0){ newList.add(item); findTarget(target - (price * times), newItems, newList); times++; } } } public static boolean wordBreak(String s, List<String> wordDict) { Set<String> dict = new HashSet<>(wordDict); return wordBreakHelper(s, dict, new HashMap<String, Boolean>()); } public static boolean wordBreakHelper(String rest, Set<String> dict, Map<String, Boolean> cache){ if (cache.containsKey(rest)){ return cache.get(rest); } if(rest.isEmpty()){ return false; } boolean canBreak = false; for(int i = 0; i < rest.length(); i++) { String left = rest.substring(0, i); if (dict.contains(left) && wordBreakHelper(rest.substring(i), dict, cache)) { canBreak = true; break; } } cache.put(rest, canBreak); return canBreak; } public static int maxProduct(int[] nums){ int max = 1; int min = 1; if (nums.length == 0) { return 0; } int res = IntStream.of(nums).max().getAsInt(); for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) { max = 1; min = 1; continue; } int tempMax = max; max = Arrays.asList(max * nums[i], min * nums[i], nums[i] ).stream().max(Integer::compareTo).get(); min = Arrays.asList(tempMax * nums[i], min * nums[i], nums[i]).stream().min(Integer::compareTo).get(); res = Math.max(res, max); } return res; } }
package com.test.mjp.ui.base; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MutableLiveData; import com.test.mjp.entity.aimal.Animal; import com.test.mjp.entity.aimal.AnimalDetail; import com.test.mjp.interact.AnimalDetailsPutInteract; import com.test.mjp.interact.AnimalFetchInteract; public abstract class BaseAnimalViewModel extends BaseViewModel { protected AnimalDetailsPutInteract animalDetailsPutInteract; protected AnimalFetchInteract animalFetchInteract; protected MutableLiveData<Boolean> openedAnimalDetails = new MutableLiveData<>(); private MutableLiveData<Integer> scrollPosition = new MutableLiveData<>(); public void openAnimalDetails(Animal animal, int position) { AnimalDetail animalDetail = new AnimalDetail(position, animal); animalDetailsPutInteract.putAnimalDetails(animalDetail); openedAnimalDetails.postValue(true); } public LiveData<Boolean> animalDetails() { return openedAnimalDetails; } public LiveData<Integer> scrollPosition() { return scrollPosition; } public void updateScrollPosition(int scrollPosition) { this.scrollPosition.postValue(scrollPosition); } }
package com.duanxr.yith.easy; import java.util.HashSet; import java.util.Set; /** * @author Duanran 2019/1/16 0016 */ public class JewelsAndStones { /** * You're given strings J representing the types of stones that are jewels, and S representing the * stones you have. Each character in S is a type of stone you have. You want to know how many * of the stones you have are also jewels. * * The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters * are case sensitive, so "a" is considered a different type of stone from "A". * * Example 1: * * Input: J = "aA", S = "aAAbbbb" Output: 3 * * Example 2: * * Input: J = "z", S = "ZZ" Output: 0 * * Note: * * S and J will consist of letters and have length at most 50. The characters in J are distinct. * * 给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。 * * J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。 * * 示例 1: * * 输入: J = "aA", S = "aAAbbbb" 输出: 3 * * 示例 2: * * 输入: J = "z", S = "ZZ" 输出: 0 * * 注意: * * S 和 J 最多含有50个字母。 J 中的字符不重复。 */ class Solution { public int numJewelsInStones(String J, String S) { char[] stone = S.toCharArray(); int i = 0; Set<Character> gem = new HashSet<>(J.length()); for (char nowCahr : J.toCharArray()) { gem.add(nowCahr); } for (char nowCahr : stone) { if (gem.contains(nowCahr)) { i++; } } return i; } } }
package leetcode.algorithms; import java.util.Arrays; public class _152_MaximumProductSubarray { static int maxProduct(int [] nums) { int result = Integer.MIN_VALUE; int [] pos = new int [nums.length]; int [] neg = new int [nums.length]; Arrays.fill(pos, 1); Arrays.fill(neg, 1); pos[0] = nums[0]; neg[0] = nums[0]; for(int i = 1; i < nums.length; i++) { pos[i] = Math.max(nums[i], Math.max(nums[i] * pos[i-1], nums[i] * neg[i-1])); neg[i] = Math.min(nums[i], Math.min(nums[i] * pos[i-1], nums[i] * neg[i-1])); result = Math.max(result, Math.max(pos[i], neg[i])); } return result; } public static void main(String args[]) { System.out.println(maxProduct(new int []{2, 3, -2, 4, -3, -100})); } }
package com.example.demo; import java.util.Arrays; import java.util.List; import org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions; import com.github.tomakehurst.wiremock.extension.Extension; import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer; public class HandlebarsExtensions implements WireMockExtensions { @Override public List<Extension> extensions() { return Arrays.asList(new ResponseTemplateTransformer(false)); } }
package esir.dom11.nsoc.context.presence; import com.espertech.esper.client.*; import esir.dom11.nsoc.context.calendar.Calendar; import esir.dom11.nsoc.context.calendar.CalendarEvent; import javax.swing.event.EventListenerList; import java.util.Date; import java.util.LinkedList; public class PresenceManager implements PresenceListener { private boolean presence = false; private EPRuntime cepRT; private EPServiceProvider cep; private EPStatement var_presence; private EPStatement var_presence_true; private EPStatement var_presence_false; private EPStatement confirmation; private EPStatement newPresence; private EPStatement endPresence; private EPStatement cancel; protected EventListenerList listenerList; private CalendarChecker calendarChecker; public PresenceManager() { this.listenerList = new EventListenerList(); calendarChecker = new CalendarChecker(); calendarChecker.addCalendarEventListener(new CalendarCheckerListener() { @Override public void eventStart() { getCepRT().sendEvent(new PresenceCalendarEvent("salle", true)); System.out.println("Context::PresenceComp : start calendar event"); } @Override public void eventStop() { getCepRT().sendEvent(new PresenceCalendarEvent("salle", false)); System.out.println("Context::PresenceComp : stop calendar event"); } }); calendarChecker.start(); Configuration cepConfig = new Configuration(); cepConfig.addEventType("PresenceEvent", "esir.dom11.nsoc.context.presence.PresenceEvent"); cepConfig.addEventType("PresenceCalendarEvent", "esir.dom11.nsoc.context.presence.PresenceCalendarEvent"); cep = EPServiceProviderManager.getProvider("myCEPEngine", cepConfig); cepRT = cep.getEPRuntime(); EPAdministrator cepAdm = cep.getEPAdministrator(); var_presence = cepAdm.createEPL("create variable boolean var_presence = false"); var_presence.start(); var_presence_true = cepAdm.createEPL("select * from pattern[every PresenceEvent(presence=true)]"); var_presence_false = cepAdm.createEPL("select * from pattern[every PresenceEvent(presence=false)]"); var_presence_true.addListener(new UpdateListener() { @Override public void update(EventBean[] newData, EventBean[] oldData) { presence = true; } }); var_presence_false.addListener(new UpdateListener() { @Override public void update(EventBean[] newData, EventBean[] oldData) { presence = false; } }); String confirmation_startWindow = "2 sec"; String confirmation_minDuration = "2 sec"; confirmation = cepAdm.createEPL("select * from pattern[" + "every (PresenceCalendarEvent(presence=true) and PresenceEvent(presence=true))where timer:within(" + confirmation_startWindow + ") " + "-> timer:interval(" + confirmation_minDuration + ") and not PresenceEvent(presence=false) ]"); newPresence = cepAdm.createEPL("select * from pattern" + "[every (" + "( (PresenceEvent(presence=true) and not PresenceCalendarEvent(presence=true)) where timer:within(2 sec) " + "-> timer:interval(2 sec) and not PresenceEvent(presence=false) )" + ")]"); endPresence = cepAdm.createEPL("select * from pattern[" + "every PresenceEvent(presence=false) " + "-> timer:interval(2 sec) and not PresenceEvent(presence=true) ]"); cancel = cepAdm.createEPL("select * from pattern[" + "every PresenceCalendarEvent(presence=true) " + "-> timer:interval(2 sec) and not PresenceEvent(presence=true) ]"); confirmation.addListener(new UpdateListener() { @Override public void update(EventBean[] newData, EventBean[] oldData) { System.out.println("Context::PresenceComp : confirmation calendar event"); } }); cancel.addListener(new UpdateListener() { @Override public void update(EventBean[] newData, EventBean[] oldData) { if (!presence) { calendarChecker.getCalendar().getEvents().remove( calendarChecker.getCalendar().getEventByDate(new Date()) ); sendCalendar(calendarChecker.getCalendar()); System.out.println("Context::PresenceComp : cancel calendar event"); } } }); newPresence.addListener(new UpdateListener() { @Override public void update(EventBean[] newData, EventBean[] oldData) { // Date now = new Date(); calendarChecker.getCalendar().getEvents().add( new CalendarEvent(now, new Date(now.getTime() + 900000) // 15 min ) ); sendCalendar(calendarChecker.getCalendar()); System.out.println("Context::PresenceComp : new presence"); } }); endPresence.addListener(new UpdateListener() { @Override public void update(EventBean[] newData, EventBean[] oldData) { System.out.println("Context::PresenceComp : end presence"); } }); } public void setCalendar(LinkedList<CalendarEvent> events) { calendarChecker.getCalendar().getEvents().clear(); calendarChecker.getCalendar().getEvents().addAll(events); } public void stop() { calendarChecker.setActive(false); var_presence.removeAllListeners(); var_presence_true.removeAllListeners(); var_presence_false.removeAllListeners(); confirmation.removeAllListeners(); newPresence.removeAllListeners(); endPresence.removeAllListeners(); cancel.removeAllListeners(); cep.destroy(); } public EPRuntime getCepRT() { return cepRT; } public void addPresenceEventListener(PresenceListener l) { this.listenerList.add(PresenceListener.class, l); } @Override public void sendCalendar(Calendar calendar) { PresenceListener[] listeners = (PresenceListener[]) listenerList.getListeners(PresenceListener.class); for (int i = listeners.length - 1; i >= 0; i--) { listeners[i].sendCalendar(calendar); } } }
package in.ac.kiit.justtalk.models; import java.util.ArrayList; public class AppUser { String roll; String emailID; ArrayList<AppUser> players = new ArrayList<>(); String name; }
package com.tencent.mm.plugin.game.ui; import android.content.Intent; import android.os.Bundle; import com.tencent.mm.bg.d; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.game.a.b; import com.tencent.mm.plugin.game.e.c; import com.tencent.mm.plugin.game.model.an; import com.tencent.mm.plugin.game.model.s; import com.tencent.mm.plugin.game.model.v; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; public abstract class GameCenterBaseUI extends GameCenterActivity { protected int jNv = 0; protected boolean jVe = false; protected s jVf; protected s jVg; protected s jVh; protected boolean jVi = false; private boolean jVj = true; static /* synthetic */ void a(GameCenterBaseUI gameCenterBaseUI) { if (gameCenterBaseUI.jVe) { ((b) g.l(b.class)).aSi(); gameCenterBaseUI.jVf = v.aTX(); if (gameCenterBaseUI.jVf != null) { gameCenterBaseUI.jVf.aTW(); } ((b) g.l(b.class)).aSi(); gameCenterBaseUI.jVg = v.aTZ(); if (gameCenterBaseUI.jVg != null) { gameCenterBaseUI.jVg.aTW(); } } ((b) g.l(b.class)).aSi(); gameCenterBaseUI.jVh = v.aUb(); if (gameCenterBaseUI.jVh != null) { gameCenterBaseUI.jVh.aTW(); } } static /* synthetic */ void b(GameCenterBaseUI gameCenterBaseUI) { if (gameCenterBaseUI.jVg != null && !gameCenterBaseUI.jVg.field_isHidden && !bi.oW(gameCenterBaseUI.jVg.jMI.url)) { gameCenterBaseUI.jVi = true; s sVar = gameCenterBaseUI.jVg; c.a(gameCenterBaseUI.getBaseContext(), sVar, "game_center_h5_floatlayer"); int i = sVar.field_msgType; if (sVar.field_msgType == 100) { i = sVar.jNa; } an.a(gameCenterBaseUI, 10, 1006, 1, 1, 0, sVar.field_appId, 0, i, sVar.field_gameMsgId, sVar.jNb, null); h.mEJ.a(858, 18, 1, false); gameCenterBaseUI.jVg.field_isRead = true; ((com.tencent.mm.plugin.game.a.c) g.l(com.tencent.mm.plugin.game.a.c.class)).aSj().c(gameCenterBaseUI.jVg, new String[0]); } } public void onCreate(Bundle bundle) { super.onCreate(bundle); if (g.Eg().Dx()) { this.jNv = getIntent().getIntExtra("game_report_from_scene", 0); this.jVe = getIntent().getBooleanExtra("from_find_more_friend", false); c.Em().H(new 1(this)); an.a(this, 10, 1000, 0, 1, 0, null, this.jNv, 0, null, null, null); return; } x.e("MicroMsg.GameCenterBaseUI", "account not ready"); finish(); } public void onResume() { super.onResume(); if (g.Eg().Dx()) { if (!this.jVj && a$a.kdf.kdd) { a$a.kdf.kdd = false; x.i("MicroMsg.GameCenterBaseUI", "restart page from country setting"); if (!isFinishing()) { finish(); } sendBroadcast(new Intent("com.tencent.mm.ACTION_EXIT"), "com.tencent.mm.permission.MM_MESSAGE"); Intent intent = new Intent(); intent.putExtra("game_report_from_scene", 901); intent.putExtra("switch_country_no_anim", true); d.b(this, "game", ".ui.GameCenterUI", intent); } this.jVj = false; return; } x.e("MicroMsg.GameCenterBaseUI", "account not ready"); } public final int aUM() { return 10; } public final int aUN() { return 1000; } public final int aUO() { return this.jNv; } }
/* 1: */ package com.kaldin.payment.form; /* 2: */ /* 3: */ import javax.servlet.http.HttpServletRequest; /* 4: */ import org.apache.struts.action.ActionForm; /* 5: */ import org.apache.struts.action.ActionMapping; /* 6: */ /* 7: */ public class PaymentForm /* 8: */ extends ActionForm /* 9: */ { /* 10: */ private static final long serialVersionUID = 1L; /* 11: 15 */ private String myCurrentCreditCard = null; /* 12: 17 */ private String creditcardname = null; /* 13: 19 */ private String fullName = null; /* 14: 21 */ private String creditCardNo = null; /* 15: 23 */ private String cw2 = null; /* 16: 25 */ private String expMonth = null; /* 17: 27 */ private String expYear = null; /* 18: 29 */ private String myCurrentBillingAddress = null; /* 19: 31 */ private String lastname = null; /* 20: 33 */ private String firstname = null; /* 21: 35 */ private String company = null; /* 22: 37 */ private String address = null; /* 23: 39 */ private String address2 = null; /* 24: 41 */ private String city = null; /* 25: 43 */ private String state = null; /* 26: 45 */ private String province = null; /* 27: 47 */ private String zip = null; /* 28: 49 */ private String country = "105"; /* 29: */ private String companyaddress; /* 30: */ private String companyaddress2; /* 31: 55 */ private String companycity = null; /* 32: 57 */ private String companystate = null; /* 33: 59 */ private String companyprovince = null; /* 34: 61 */ private String companyzip = null; /* 35: 63 */ private String companycountry = null; /* 36: 65 */ private String autoCheckPayment = null; /* 37: 67 */ private String serviceMethod = null; /* 38: 69 */ private String serviceStatus = null; /* 39: 71 */ private String nickname = null; /* 40: 73 */ private String act = null; /* 41: 75 */ private String creditcardpaymentid = null; /* 42: 77 */ private String isPrimary = null; /* 43: 79 */ private String gatewayType = null; /* 44: 81 */ private String previousCompany = null; /* 45: 83 */ private String previousFullName = null; /* 46: 85 */ private String previousAddress = null; /* 47: 87 */ private String previousAddress2 = null; /* 48: 89 */ private String previousCity = null; /* 49: 91 */ private String previousState = null; /* 50: 93 */ private String previousProvince = null; /* 51: 95 */ private String previousZip = null; /* 52: 97 */ private String previousCountry = null; /* 53: 99 */ private String operation = null; /* 54:101 */ private String paymentAmount = null; /* 55: */ /* 56: */ public String getMyCurrentCreditCard() /* 57: */ { /* 58:104 */ return this.myCurrentCreditCard; /* 59: */ } /* 60: */ /* 61: */ public void setMyCurrentCreditCard(String myCurrentCreditCard) /* 62: */ { /* 63:108 */ this.myCurrentCreditCard = myCurrentCreditCard; /* 64: */ } /* 65: */ /* 66: */ public String getCreditcardname() /* 67: */ { /* 68:112 */ return this.creditcardname; /* 69: */ } /* 70: */ /* 71: */ public void setCreditcardname(String creditcardname) /* 72: */ { /* 73:116 */ this.creditcardname = creditcardname; /* 74: */ } /* 75: */ /* 76: */ public String getFullName() /* 77: */ { /* 78:120 */ return this.fullName; /* 79: */ } /* 80: */ /* 81: */ public void setFullName(String fullName) /* 82: */ { /* 83:124 */ this.fullName = fullName; /* 84: */ } /* 85: */ /* 86: */ public String getCreditCardNo() /* 87: */ { /* 88:128 */ return this.creditCardNo; /* 89: */ } /* 90: */ /* 91: */ public void setCreditCardNo(String creditCardNo) /* 92: */ { /* 93:132 */ this.creditCardNo = creditCardNo; /* 94: */ } /* 95: */ /* 96: */ public String getCw2() /* 97: */ { /* 98:136 */ return this.cw2; /* 99: */ } /* 100: */ /* 101: */ public void setCw2(String cw2) /* 102: */ { /* 103:140 */ this.cw2 = cw2; /* 104: */ } /* 105: */ /* 106: */ public String getExpMonth() /* 107: */ { /* 108:144 */ return this.expMonth; /* 109: */ } /* 110: */ /* 111: */ public void setExpMonth(String expMonth) /* 112: */ { /* 113:148 */ this.expMonth = expMonth; /* 114: */ } /* 115: */ /* 116: */ public String getExpYear() /* 117: */ { /* 118:152 */ return this.expYear; /* 119: */ } /* 120: */ /* 121: */ public void setExpYear(String expYear) /* 122: */ { /* 123:156 */ this.expYear = expYear; /* 124: */ } /* 125: */ /* 126: */ public String getMyCurrentBillingAddress() /* 127: */ { /* 128:160 */ return this.myCurrentBillingAddress; /* 129: */ } /* 130: */ /* 131: */ public void setMyCurrentBillingAddress(String myCurrentBillingAddress) /* 132: */ { /* 133:164 */ this.myCurrentBillingAddress = myCurrentBillingAddress; /* 134: */ } /* 135: */ /* 136: */ public String getLastname() /* 137: */ { /* 138:168 */ return this.lastname; /* 139: */ } /* 140: */ /* 141: */ public void setLastname(String lastname) /* 142: */ { /* 143:172 */ this.lastname = lastname; /* 144: */ } /* 145: */ /* 146: */ public String getFirstname() /* 147: */ { /* 148:176 */ return this.firstname; /* 149: */ } /* 150: */ /* 151: */ public void setFirstname(String firstname) /* 152: */ { /* 153:180 */ this.firstname = firstname; /* 154: */ } /* 155: */ /* 156: */ public String getCompany() /* 157: */ { /* 158:184 */ return this.company; /* 159: */ } /* 160: */ /* 161: */ public void setCompany(String company) /* 162: */ { /* 163:188 */ this.company = company; /* 164: */ } /* 165: */ /* 166: */ public String getAddress() /* 167: */ { /* 168:192 */ return this.address; /* 169: */ } /* 170: */ /* 171: */ public void setAddress(String address) /* 172: */ { /* 173:196 */ this.address = address; /* 174: */ } /* 175: */ /* 176: */ public String getAddress2() /* 177: */ { /* 178:200 */ return this.address2; /* 179: */ } /* 180: */ /* 181: */ public void setAddress2(String address2) /* 182: */ { /* 183:204 */ this.address2 = address2; /* 184: */ } /* 185: */ /* 186: */ public String getCity() /* 187: */ { /* 188:208 */ return this.city; /* 189: */ } /* 190: */ /* 191: */ public void setCity(String city) /* 192: */ { /* 193:212 */ this.city = city; /* 194: */ } /* 195: */ /* 196: */ public String getState() /* 197: */ { /* 198:216 */ return this.state; /* 199: */ } /* 200: */ /* 201: */ public void setState(String state) /* 202: */ { /* 203:220 */ this.state = state; /* 204: */ } /* 205: */ /* 206: */ public String getProvince() /* 207: */ { /* 208:224 */ return this.province; /* 209: */ } /* 210: */ /* 211: */ public void setProvince(String province) /* 212: */ { /* 213:228 */ this.province = province; /* 214: */ } /* 215: */ /* 216: */ public String getZip() /* 217: */ { /* 218:232 */ return this.zip; /* 219: */ } /* 220: */ /* 221: */ public void setZip(String zip) /* 222: */ { /* 223:236 */ this.zip = zip; /* 224: */ } /* 225: */ /* 226: */ public String getCountry() /* 227: */ { /* 228:240 */ return this.country; /* 229: */ } /* 230: */ /* 231: */ public void setCountry(String country) /* 232: */ { /* 233:244 */ this.country = country; /* 234: */ } /* 235: */ /* 236: */ public String getCompanyaddress() /* 237: */ { /* 238:248 */ return this.companyaddress; /* 239: */ } /* 240: */ /* 241: */ public void setCompanyaddress(String companyaddress) /* 242: */ { /* 243:252 */ this.companyaddress = companyaddress; /* 244: */ } /* 245: */ /* 246: */ public String getCompanyaddress2() /* 247: */ { /* 248:256 */ return this.companyaddress2; /* 249: */ } /* 250: */ /* 251: */ public void setCompanyaddress2(String companyaddress2) /* 252: */ { /* 253:260 */ this.companyaddress2 = companyaddress2; /* 254: */ } /* 255: */ /* 256: */ public String getCompanycity() /* 257: */ { /* 258:264 */ return this.companycity; /* 259: */ } /* 260: */ /* 261: */ public void setCompanycity(String companycity) /* 262: */ { /* 263:268 */ this.companycity = companycity; /* 264: */ } /* 265: */ /* 266: */ public String getCompanystate() /* 267: */ { /* 268:272 */ return this.companystate; /* 269: */ } /* 270: */ /* 271: */ public void setCompanystate(String companystate) /* 272: */ { /* 273:276 */ this.companystate = companystate; /* 274: */ } /* 275: */ /* 276: */ public String getCompanyprovince() /* 277: */ { /* 278:280 */ return this.companyprovince; /* 279: */ } /* 280: */ /* 281: */ public void setCompanyprovince(String companyprovince) /* 282: */ { /* 283:284 */ this.companyprovince = companyprovince; /* 284: */ } /* 285: */ /* 286: */ public String getCompanyzip() /* 287: */ { /* 288:288 */ return this.companyzip; /* 289: */ } /* 290: */ /* 291: */ public void setCompanyzip(String companyzip) /* 292: */ { /* 293:292 */ this.companyzip = companyzip; /* 294: */ } /* 295: */ /* 296: */ public String getCompanycountry() /* 297: */ { /* 298:296 */ return this.companycountry; /* 299: */ } /* 300: */ /* 301: */ public void setCompanycountry(String companycountry) /* 302: */ { /* 303:300 */ this.companycountry = companycountry; /* 304: */ } /* 305: */ /* 306: */ public String getAutoCheckPayment() /* 307: */ { /* 308:304 */ return this.autoCheckPayment; /* 309: */ } /* 310: */ /* 311: */ public void setAutoCheckPayment(String autoCheckPayment) /* 312: */ { /* 313:308 */ this.autoCheckPayment = autoCheckPayment; /* 314: */ } /* 315: */ /* 316: */ public String getServiceMethod() /* 317: */ { /* 318:312 */ return this.serviceMethod; /* 319: */ } /* 320: */ /* 321: */ public void setServiceMethod(String serviceMethod) /* 322: */ { /* 323:316 */ this.serviceMethod = serviceMethod; /* 324: */ } /* 325: */ /* 326: */ public String getServiceStatus() /* 327: */ { /* 328:320 */ return this.serviceStatus; /* 329: */ } /* 330: */ /* 331: */ public void setServiceStatus(String serviceStatus) /* 332: */ { /* 333:324 */ this.serviceStatus = serviceStatus; /* 334: */ } /* 335: */ /* 336: */ public String getNickname() /* 337: */ { /* 338:328 */ return this.nickname; /* 339: */ } /* 340: */ /* 341: */ public void setNickname(String nickname) /* 342: */ { /* 343:332 */ this.nickname = nickname; /* 344: */ } /* 345: */ /* 346: */ public String getAct() /* 347: */ { /* 348:336 */ return this.act; /* 349: */ } /* 350: */ /* 351: */ public void setAct(String act) /* 352: */ { /* 353:340 */ this.act = act; /* 354: */ } /* 355: */ /* 356: */ public String getCreditcardpaymentid() /* 357: */ { /* 358:344 */ return this.creditcardpaymentid; /* 359: */ } /* 360: */ /* 361: */ public void setCreditcardpaymentid(String creditcardpaymentid) /* 362: */ { /* 363:348 */ this.creditcardpaymentid = creditcardpaymentid; /* 364: */ } /* 365: */ /* 366: */ public String getIsPrimary() /* 367: */ { /* 368:352 */ return this.isPrimary; /* 369: */ } /* 370: */ /* 371: */ public void setIsPrimary(String isPrimary) /* 372: */ { /* 373:356 */ this.isPrimary = isPrimary; /* 374: */ } /* 375: */ /* 376: */ public String getGatewayType() /* 377: */ { /* 378:360 */ return this.gatewayType; /* 379: */ } /* 380: */ /* 381: */ public void setGatewayType(String gatewayType) /* 382: */ { /* 383:364 */ this.gatewayType = gatewayType; /* 384: */ } /* 385: */ /* 386: */ public String getPreviousCompany() /* 387: */ { /* 388:368 */ return this.previousCompany; /* 389: */ } /* 390: */ /* 391: */ public void setPreviousCompany(String previousCompany) /* 392: */ { /* 393:372 */ this.previousCompany = previousCompany; /* 394: */ } /* 395: */ /* 396: */ public String getPreviousFullName() /* 397: */ { /* 398:376 */ return this.previousFullName; /* 399: */ } /* 400: */ /* 401: */ public void setPreviousFullName(String previousFullName) /* 402: */ { /* 403:380 */ this.previousFullName = previousFullName; /* 404: */ } /* 405: */ /* 406: */ public String getPreviousAddress() /* 407: */ { /* 408:384 */ return this.previousAddress; /* 409: */ } /* 410: */ /* 411: */ public void setPreviousAddress(String previousAddress) /* 412: */ { /* 413:388 */ this.previousAddress = previousAddress; /* 414: */ } /* 415: */ /* 416: */ public String getPreviousAddress2() /* 417: */ { /* 418:392 */ return this.previousAddress2; /* 419: */ } /* 420: */ /* 421: */ public void setPreviousAddress2(String previousAddress2) /* 422: */ { /* 423:396 */ this.previousAddress2 = previousAddress2; /* 424: */ } /* 425: */ /* 426: */ public String getPreviousCity() /* 427: */ { /* 428:400 */ return this.previousCity; /* 429: */ } /* 430: */ /* 431: */ public void setPreviousCity(String previousCity) /* 432: */ { /* 433:404 */ this.previousCity = previousCity; /* 434: */ } /* 435: */ /* 436: */ public String getPreviousState() /* 437: */ { /* 438:408 */ return this.previousState; /* 439: */ } /* 440: */ /* 441: */ public void setPreviousState(String previousState) /* 442: */ { /* 443:412 */ this.previousState = previousState; /* 444: */ } /* 445: */ /* 446: */ public String getPreviousProvince() /* 447: */ { /* 448:416 */ return this.previousProvince; /* 449: */ } /* 450: */ /* 451: */ public void setPreviousProvince(String previousProvince) /* 452: */ { /* 453:420 */ this.previousProvince = previousProvince; /* 454: */ } /* 455: */ /* 456: */ public String getPreviousZip() /* 457: */ { /* 458:424 */ return this.previousZip; /* 459: */ } /* 460: */ /* 461: */ public void setPreviousZip(String previousZip) /* 462: */ { /* 463:428 */ this.previousZip = previousZip; /* 464: */ } /* 465: */ /* 466: */ public String getPreviousCountry() /* 467: */ { /* 468:432 */ return this.previousCountry; /* 469: */ } /* 470: */ /* 471: */ public void setPreviousCountry(String previousCountry) /* 472: */ { /* 473:436 */ this.previousCountry = previousCountry; /* 474: */ } /* 475: */ /* 476: */ public String getOperation() /* 477: */ { /* 478:440 */ return this.operation; /* 479: */ } /* 480: */ /* 481: */ public void setOperation(String operation) /* 482: */ { /* 483:444 */ this.operation = operation; /* 484: */ } /* 485: */ /* 486: */ public String getPaymentAmount() /* 487: */ { /* 488:448 */ return this.paymentAmount; /* 489: */ } /* 490: */ /* 491: */ public void setPaymentAmount(String paymentAmount) /* 492: */ { /* 493:452 */ this.paymentAmount = paymentAmount; /* 494: */ } /* 495: */ /* 496: */ public void reset(ActionMapping aMapping, HttpServletRequest aR) /* 497: */ { /* 498:456 */ this.myCurrentCreditCard = null; /* 499:457 */ this.creditcardname = null; /* 500:458 */ this.fullName = null; /* 501:459 */ this.creditCardNo = null; /* 502:460 */ this.cw2 = null; /* 503:461 */ this.expMonth = null; /* 504:462 */ this.expYear = null; /* 505:463 */ this.myCurrentBillingAddress = null; /* 506:464 */ this.lastname = null; /* 507:465 */ this.firstname = null; /* 508:466 */ this.company = null; /* 509:467 */ this.address = null; /* 510:468 */ this.address2 = null; /* 511:469 */ this.city = null; /* 512:470 */ this.state = null; /* 513:471 */ this.province = null; /* 514:472 */ this.zip = null; /* 515:473 */ this.country = null; /* 516:474 */ this.autoCheckPayment = null; /* 517:475 */ this.operation = null; /* 518:476 */ this.paymentAmount = null; /* 519: */ } /* 520: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.payment.form.PaymentForm * JD-Core Version: 0.7.0.1 */
package com.liutao.service; import com.liutao.entity.User; /** * 用户服务层接口 * * @author LIUTAO * @version 2017/5/23 * @see * @since */ public interface UserService { User getUserInfo(String username); }
package ru.otus.spring.dao; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.core.io.Resource; import ru.otus.spring.domain.Question; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import static org.junit.jupiter.api.Assertions.*; @DisplayName("Класс QuestionDao") class QuestionDaoCsvImplTest { @DisplayName("конструктор создает корректный объект") @Test void constructorShouldCreateCorrectObject() throws IOException { Resource fileMock = Mockito.mock(Resource.class); String[] row = {"1","Question","1","A","B","C","D"}; Question question = new Question(row); String rawData = "\"№\",\"Question\",\"Right Answer\",\"Answer1\",\"Answer2\",\"Answer3\",\"Answer4\"\n" + "\"1\",\"Question\",\"1\",\"A\",\"B\",\"C\",\"D\""; try (InputStream is = new ByteArrayInputStream(rawData.getBytes())) { Mockito.when(fileMock.getInputStream()).thenReturn(is); QuestionDaoCsv questions = new QuestionDaoCsvImpl(fileMock); assertEquals(question.getRightAnswer(), questions.getQuestionsDaoCsv().get(0).getRightAnswer()); } } }
package com.bluejnr.wiretransfer.web.api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.bluejnr.wiretransfer.model.api.WireTransfer; import com.bluejnr.wiretransfer.service.WireTransferService; @RestController @RequestMapping("/wire-transfer") public class WireTransferController { @Autowired private WireTransferService wireTransferService; @PutMapping("/process") public void process(@RequestBody WireTransfer wireTransfer) { wireTransferService.process(wireTransfer); } }
import com.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Mytest { @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); // 1 beans.xml 开启包注解 // 2 @Component :标注User类 // @Value: 定义值 // 就可以自动装配了 System.out.println(context.getBean("user", User.class).toString()); } }
package display; import javax.swing.ImageIcon; import javax.swing.JPanel; import java.awt.Dimension; import javax.swing.JLabel; import javax.swing.JButton; import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class SplashPanel extends JPanel { private static final long serialVersionUID = 1L; public boolean startGameClicked; /** * Create the panel. */ public SplashPanel() { setSize(new Dimension(1228, 500)); this.setPreferredSize(new Dimension(1228,500)); setLayout(null); startGameClicked = false; JLabel lblSplashScreen = new JLabel(""); lblSplashScreen.setIcon(new ImageIcon("C:\\github-repos\\CSC8540_Hooli\\cfg\\SplashScreen.jpg")); lblSplashScreen.setBounds(0,5,1228,381); add(lblSplashScreen); JButton btnStartGame = new JButton("Start Game"); btnStartGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { startGameClicked = true; } }); btnStartGame.setFont(new Font("Tahoma", Font.PLAIN, 18)); btnStartGame.setBounds(935, 397, 141, 56); add(btnStartGame); JButton btnGameRules = new JButton("Game Rules"); btnGameRules.setFont(new Font("Tahoma", Font.PLAIN, 18)); btnGameRules.setBounds(1088, 397, 141, 56); add(btnGameRules); } }
package yao.service; import yao.bean.Language; import yao.bean.Word; import yao.bean.WordMeaning; import yao.dao.LanguageDAO; import yao.dao.WordDAO; import yao.dao.WordMeaningDAO; import java.util.List; public class LanguageService { private String msg; public Language getLanguage(int languageID){ return new LanguageDAO().findLanguageByLanguageID(languageID); } public boolean addLanguage(Language language){ if(new LanguageDAO().findLanguageByLanguageID(language.getLanguageID()) != null){ msg = "语言已存在"; return false; } else { return new LanguageDAO().addLanguage(language); } } public boolean deleteLanguage(Language language){ WordDAO wordDAO=new WordDAO(); if(wordDAO.existWordsByLanguage(language)){ for(Word word : wordDAO.findWordsByLanguage(language)) { WordMeaningDAO wordMeaningDAO=new WordMeaningDAO(); if(wordMeaningDAO.existWordMeaningsByWord(word)){ for(WordMeaning wordMeaning : wordMeaningDAO.findWordMeaningsByWord(word)) { wordMeaningDAO.deleteWordMeaning(wordMeaning.getWordMeaningID()); } } wordDAO.deleteWord(word.getWordID()); } } return new LanguageDAO().deleteLanguage(language.getLanguageID()); } public List<Language> getAllLanguage(){ return new LanguageDAO().findAllLanguages(); } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
package Swing.Control; import Swing.util.DBConnect; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Created by qiuxin on 15/12/28. */ public class deleteNote { public static void delete(String note) { Connection con = DBConnect.Connect(); String sqlStr = "DELETE FROM notes WHERE " + "notes=\"" + note +"\";"; Statement stat = null; try { stat = con.createStatement(); int rs = stat.executeUpdate(sqlStr); } catch (SQLException e) { e.printStackTrace(); } } }
package com.shagaba.kickstarter.application.init; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import com.shagaba.kickstarter.core.domain.profile.Gender; import com.shagaba.kickstarter.core.domain.profile.PersonalInformation; import com.shagaba.kickstarter.core.domain.security.Authority; import com.shagaba.kickstarter.core.domain.security.Role; import com.shagaba.kickstarter.core.domain.security.account.UserAccount; import com.shagaba.kickstarter.core.domain.security.account.UserAccountRole; import com.shagaba.kickstarter.core.domain.security.account.authentication.AccountAuthenticationStatus; import com.shagaba.kickstarter.core.repository.profile.PersonalInformationRepository; import com.shagaba.kickstarter.core.repository.security.AuthorityRepository; import com.shagaba.kickstarter.core.repository.security.RoleRepository; import com.shagaba.kickstarter.core.repository.security.account.UserAccountRepository; import com.shagaba.kickstarter.core.repository.security.account.authentication.AccountAuthenticationStatusRepository; import com.shagaba.kickstarter.core.security.account.authentication.AccountPasswordAuthenticationManager; public class InitializeMongoDB { @Autowired protected AuthorityRepository authorityRepository; @Autowired protected RoleRepository roleRepository; @Autowired protected UserAccountRepository userAccountRepository; @Autowired protected PersonalInformationRepository personalInformationRepository; @Autowired protected AccountAuthenticationStatusRepository accountAuthenticationStatusRepository; @Autowired protected AccountPasswordAuthenticationManager accountPasswordAuthenticationManager; @PostConstruct public void afterPropertiesSet() { roleRepository.deleteAll(); authorityRepository.deleteAll(); userAccountRepository.deleteAll(); personalInformationRepository.deleteAll(); accountAuthenticationStatusRepository.deleteAll(); // authorityRepository.save(getBasicAuthorities()); // roleRepository.save(getBasicRoles()); userAccountRepository.save(getBasicUsers()); personalInformationRepository.save(getPersonalInformations()); accountAuthenticationStatusRepository.save(getAccountAuthenticationStatus()); } protected List<Authority> getBasicAuthorities() { List<Authority> authorities = new LinkedList<>(); authorities.add(new Authority("ADMIN_AUTHORITY_SERVICE", "ADMIN AUTHORITY SERVICE")); authorities.add(new Authority("ADMIN_ROLE_SERVICE", "ADMIN ROLE SERVICE")); return authorities; } protected List<Role> getBasicRoles() { List<Role> roles = new LinkedList<>(); roles.add(new Role("ROLE_VISITOR", "visitor role", Arrays.asList(new String[]{"ROLE_VISITOR"}), null)); roles.add(new Role("ROLE_USER", "user role", Arrays.asList(new String[]{"ROLE_USER"}), null)); roles.add(new Role("ROLE_ADMIN", "admin role", Arrays.asList(new String[]{"ROLE_ADMIN"}), null)); roles.add(new Role("ROLE_ADMIN_AUTHORITY_SERVICE", "admin role on authority service", Arrays.asList(new String[]{"ADMIN_AUTHORITY_SERVICE"}), null)); roles.add(new Role("ROLE_ADMIN_ROLE_SERVICE", "admin role on role service", Arrays.asList(new String[]{"ADMIN_ROLE_SERVICE"}), null)); return roles; } protected List<UserAccount> getBasicUsers() { List<UserAccount> userAccounts = new LinkedList<>(); List<UserAccountRole> userAccountRoles = new LinkedList<>(); userAccountRoles.add(new UserAccountRole("ROLE_ADMIN", null)); String salt = accountPasswordAuthenticationManager.generateSalt(); String encPassword = accountPasswordAuthenticationManager.encodePassword("admin1", salt); userAccounts.add(new UserAccount("ADMIN_ID_1", "admin1", encPassword, "admin@mycomp.com", null, salt, userAccountRoles)); System.out.println(accountPasswordAuthenticationManager.encodePassword("admin", "5a1T")); return userAccounts; } protected List<PersonalInformation> getPersonalInformations() { List<PersonalInformation> personalInformations = new LinkedList<>(); personalInformations.add(new PersonalInformation("ADMIN_ID_1", "Administrator", "first", "last", Gender.MALE)); return personalInformations; } protected List<AccountAuthenticationStatus> getAccountAuthenticationStatus() { List<AccountAuthenticationStatus> accountAuthenticationStatus = new LinkedList<>(); accountAuthenticationStatus.add(new AccountAuthenticationStatus("ADMIN_ID_1", true, true)); return accountAuthenticationStatus; } }
package com.example.user.test; /** * Created by YUNAHKIM on 2017-10-30. */ import android.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class GoogleActivity extends AppCompatActivity implements OnMapReadyCallback { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.googlemap); getSupportActionBar().setDisplayHomeAsUpEnabled(true); FragmentManager fragmentManager = getFragmentManager(); MapFragment mapFragment = (MapFragment)fragmentManager .findFragmentById(R.id.googlemap); mapFragment.getMapAsync(this); } @Override public void onMapReady(final GoogleMap map) { LatLng SEOUL = new LatLng(37.56, 126.97); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(SEOUL); markerOptions.title("서울"); markerOptions.snippet("한국의 수도"); map.addMarker(markerOptions); map.moveCamera(CameraUpdateFactory.newLatLng(SEOUL)); map.animateCamera(CameraUpdateFactory.zoomTo(10)); } public boolean onOptionsItemSelected(android.view.MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // NavUtils.navigateUpFromSameTask(this); finish(); return true; } return super.onOptionsItemSelected(item); }; }
package com.abay.aml.handler; import com.abay.aml.R; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; /** * * 实现的主要功能。 * @version 1.0.0 * @author Abay Zhuang <br/> * Create at 2014-7-28 */ public class HandlerActivity1 extends Activity { private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // ... } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mHandler.sendMessageDelayed(Message.obtain(), 60000); //just finish this activity finish(); } }