text
stringlengths
10
2.72M
package com.mahendracandi.app.model; public class DetailTransaksi{ private int id; private String noTrans; private String kodeSayur; private double harga; private int qty; private double subtotal; public void setId(int id){ this.id=id; } public int getId(){ return id; } public void setNoTrans(String noTrans){ this.noTrans=noTrans; } public String getNoTrans(){ return noTrans; } public void setKodeSayur(String kodeSayur){ this.kodeSayur=kodeSayur; } public String getKodeSayur(){ return kodeSayur; } public void serHarga(double harga){ this.harga=harga; } public double getHarga(){ return harga; } public void setQty(int qty){ this.qty=qty; } public int getqty(){ return qty; } public void setSubtotal(double subtotal){ this.subtotal=subtotal; } public double getSubtotal(){ return subtotal; } }
package com.xiaoxz.model; import com.fasterxml.jackson.annotation.JsonInclude; import java.io.Serializable; import java.util.List; /** * 客户 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class Custom implements Serializable { private String cid; private String referralCode; private String type; private String source; private String phone; private String name; private String sex; private String ethnic; private String birthday; private String identity; private String nativeplace; private String koseki; private String nowaddress; private String phoneserviceno; private String bankcard; private String bankaddress; private String family_linkone_name; private String family_linkone_sex; private String family_linkone_relation; private String family_linkone_phone; private String family_linkone_address; private String family_linktwo_name; private String family_linktwo_sex; private String family_linktwo_relation; private String family_linktwo_phone; private String family_linktwo_address; private String contacts_ids; private String headimg; private String identity_front; //身份证正面 private String identity_reverse; //身份证反面 private String cus_photo; //个人照 private String company; private String income; private String consume; private String school; private String indatestring; private String studentcard; private Integer family_flg; //是否完善亲属联系人 private Integer link_flg; //是否完善联系人 private Integer identity_flg; //是否完善身份信息 private Integer person_flg; //是否完善个人信息 private Integer taobao_flg; //是否完善淘宝信息 private Integer zhifb_flg; //是否完善支付宝信息 private Integer mobile_flg; //是否完善运营商信息 private Integer student_flg; //是否完善学信网信息 private String email; private String workcard; //工作证 private String zhimfvideo; //芝麻分视频 private String shipname; //收货人 private String shiparea;//收货地区 private String shipphone; //收货电话 private String shipaddress; //收货地址 private List<Cus_Link> linkList; private String link_ids; private String crtuser; private String crtdate; private String recsts; public String getLink_ids() { return link_ids; } public void setLink_ids(String link_ids) { this.link_ids = link_ids; } public String getReferralCode() { return referralCode; } public void setReferralCode(String referralCode) { this.referralCode = referralCode; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getEthnic() { return ethnic; } public void setEthnic(String ethnic) { this.ethnic = ethnic; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getIdentity() { return identity; } public void setIdentity(String identity) { this.identity = identity; } public String getNativeplace() { return nativeplace; } public void setNativeplace(String nativeplace) { this.nativeplace = nativeplace; } public String getKoseki() { return koseki; } public void setKoseki(String koseki) { this.koseki = koseki; } public String getNowaddress() { return nowaddress; } public void setNowaddress(String nowaddress) { this.nowaddress = nowaddress; } public String getPhoneserviceno() { return phoneserviceno; } public void setPhoneserviceno(String phoneserviceno) { this.phoneserviceno = phoneserviceno; } public String getBankcard() { return bankcard; } public void setBankcard(String bankcard) { this.bankcard = bankcard; } public String getBankaddress() { return bankaddress; } public void setBankaddress(String bankaddress) { this.bankaddress = bankaddress; } public String getFamily_linkone_name() { return family_linkone_name; } public void setFamily_linkone_name(String family_linkone_name) { this.family_linkone_name = family_linkone_name; } public String getFamily_linkone_sex() { return family_linkone_sex; } public void setFamily_linkone_sex(String family_linkone_sex) { this.family_linkone_sex = family_linkone_sex; } public String getFamily_linkone_relation() { return family_linkone_relation; } public void setFamily_linkone_relation(String family_linkone_relation) { this.family_linkone_relation = family_linkone_relation; } public String getFamily_linkone_phone() { return family_linkone_phone; } public void setFamily_linkone_phone(String family_linkone_phone) { this.family_linkone_phone = family_linkone_phone; } public String getFamily_linkone_address() { return family_linkone_address; } public void setFamily_linkone_address(String family_linkone_address) { this.family_linkone_address = family_linkone_address; } public String getFamily_linktwo_name() { return family_linktwo_name; } public void setFamily_linktwo_name(String family_linktwo_name) { this.family_linktwo_name = family_linktwo_name; } public String getFamily_linktwo_sex() { return family_linktwo_sex; } public void setFamily_linktwo_sex(String family_linktwo_sex) { this.family_linktwo_sex = family_linktwo_sex; } public String getFamily_linktwo_relation() { return family_linktwo_relation; } public void setFamily_linktwo_relation(String family_linktwo_relation) { this.family_linktwo_relation = family_linktwo_relation; } public String getFamily_linktwo_phone() { return family_linktwo_phone; } public void setFamily_linktwo_phone(String family_linktwo_phone) { this.family_linktwo_phone = family_linktwo_phone; } public String getFamily_linktwo_address() { return family_linktwo_address; } public void setFamily_linktwo_address(String family_linktwo_address) { this.family_linktwo_address = family_linktwo_address; } public String getContacts_ids() { return contacts_ids; } public void setContacts_ids(String contacts_ids) { this.contacts_ids = contacts_ids; } public String getCrtuser() { return crtuser; } public void setCrtuser(String crtuser) { this.crtuser = crtuser; } public String getCrtdate() { return crtdate; } public void setCrtdate(String crtdate) { this.crtdate = crtdate; } public String getHeadimg() { return headimg; } public void setHeadimg(String headimg) { this.headimg = headimg; } public String getRecsts() { return recsts; } public void setRecsts(String recsts) { this.recsts = recsts; } public String getIdentity_front() { return identity_front; } public void setIdentity_front(String identity_front) { this.identity_front = identity_front; } public String getIdentity_reverse() { return identity_reverse; } public void setIdentity_reverse(String identity_reverse) { this.identity_reverse = identity_reverse; } public String getCus_photo() { return cus_photo; } public void setCus_photo(String cus_photo) { this.cus_photo = cus_photo; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getIncome() { return income; } public void setIncome(String income) { this.income = income; } public String getConsume() { return consume; } public void setConsume(String consume) { this.consume = consume; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String getIndatestring() { return indatestring; } public void setIndatestring(String indatestring) { this.indatestring = indatestring; } public String getStudentcard() { return studentcard; } public void setStudentcard(String studentcard) { this.studentcard = studentcard; } public Integer getFamily_flg() { return family_flg; } public void setFamily_flg(Integer family_flg) { this.family_flg = family_flg; } public Integer getLink_flg() { return link_flg; } public void setLink_flg(Integer link_flg) { this.link_flg = link_flg; } public Integer getIdentity_flg() { return identity_flg; } public void setIdentity_flg(Integer identity_flg) { this.identity_flg = identity_flg; } public Integer getPerson_flg() { return person_flg; } public void setPerson_flg(Integer person_flg) { this.person_flg = person_flg; } public Integer getTaobao_flg() { return taobao_flg; } public void setTaobao_flg(Integer taobao_flg) { this.taobao_flg = taobao_flg; } public Integer getZhifb_flg() { return zhifb_flg; } public void setZhifb_flg(Integer zhifb_flg) { this.zhifb_flg = zhifb_flg; } public Integer getMobile_flg() { return mobile_flg; } public void setMobile_flg(Integer mobile_flg) { this.mobile_flg = mobile_flg; } public Integer getStudent_flg() { return student_flg; } public void setStudent_flg(Integer student_flg) { this.student_flg = student_flg; } public List<Cus_Link> getLinkList() { return linkList; } public void setLinkList(List<Cus_Link> linkList) { this.linkList = linkList; } public String getShipaddress() { return shipaddress; } public void setShipaddress(String shipaddress) { this.shipaddress = shipaddress; } public String getWorkcard() { return workcard; } public void setWorkcard(String workcard) { this.workcard = workcard; } public String getZhimfvideo() { return zhimfvideo; } public void setZhimfvideo(String zhimfvideo) { this.zhimfvideo = zhimfvideo; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getShipname() { return shipname; } public void setShipname(String shipname) { this.shipname = shipname; } public String getShipphone() { return shipphone; } public void setShipphone(String shipphone) { this.shipphone = shipphone; } public String getShiparea() { return shiparea; } public void setShiparea(String shiparea) { this.shiparea = shiparea; } @Override public String toString() { return "Custom{" + "cid='" + cid + '\'' + ", type='" + type + '\'' + ", source='" + source + '\'' + ", phone='" + phone + '\'' + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", ethnic='" + ethnic + '\'' + ", birthday='" + birthday + '\'' + ", identity='" + identity + '\'' + ", nativeplace='" + nativeplace + '\'' + ", koseki='" + koseki + '\'' + ", nowaddress='" + nowaddress + '\'' + ", phoneserviceno='" + phoneserviceno + '\'' + ", bankcard='" + bankcard + '\'' + ", bankaddress='" + bankaddress + '\'' + ", family_linkone_name='" + family_linkone_name + '\'' + ", family_linkone_sex='" + family_linkone_sex + '\'' + ", family_linkone_relation='" + family_linkone_relation + '\'' + ", family_linkone_phone='" + family_linkone_phone + '\'' + ", family_linkone_address='" + family_linkone_address + '\'' + ", family_linktwo_name='" + family_linktwo_name + '\'' + ", family_linktwo_sex='" + family_linktwo_sex + '\'' + ", family_linktwo_relation='" + family_linktwo_relation + '\'' + ", family_linktwo_phone='" + family_linktwo_phone + '\'' + ", family_linktwo_address='" + family_linktwo_address + '\'' + ", contacts_ids='" + contacts_ids + '\'' + ", headimg='" + headimg + '\'' + ", identity_front='" + identity_front + '\'' + ", identity_reverse='" + identity_reverse + '\'' + ", cus_photo='" + cus_photo + '\'' + ", company='" + company + '\'' + ", income='" + income + '\'' + ", consume='" + consume + '\'' + ", school='" + school + '\'' + ", indatestring='" + indatestring + '\'' + ", studentcard='" + studentcard + '\'' + ", family_flg=" + family_flg + ", link_flg=" + link_flg + ", identity_flg=" + identity_flg + ", person_flg=" + person_flg + ", taobao_flg=" + taobao_flg + ", zhifb_flg=" + zhifb_flg + ", mobile_flg=" + mobile_flg + ", student_flg=" + student_flg + ", email='" + email + '\'' + ", workcard='" + workcard + '\'' + ", zhimfvideo='" + zhimfvideo + '\'' + ", shipaddress='" + shipaddress + '\'' + ", linkList=" + linkList + ", link_ids='" + link_ids + '\'' + ", crtuser='" + crtuser + '\'' + ", crtdate='" + crtdate + '\'' + ", recsts='" + recsts + '\'' + '}'; } }
package io.ceph.rgw.client.core.subscribe; import io.ceph.rgw.client.SubscribeClient; import io.ceph.rgw.client.action.ActionExecutor; import io.ceph.rgw.client.action.ActionFuture; import io.ceph.rgw.client.action.ActionListener; import io.ceph.rgw.client.action.SubscribeActionFuture; import io.ceph.rgw.client.converter.SubscribeRequestConverter; import io.ceph.rgw.client.converter.SubscribeResponseConverter; import io.ceph.rgw.client.core.Connectors; import io.ceph.rgw.client.model.notification.SubscribeObjectRequest; import io.ceph.rgw.client.model.notification.SubscribeObjectResponse; import io.netty.handler.codec.http.FullHttpResponse; /** * A default implementation of SubscribeClient. * * @author zhuangshuo * Created by zhuangshuo on 2020/6/5. */ public class DefaultSubscribeClient extends SubscribeConnectorAware implements SubscribeClient { public DefaultSubscribeClient(Connectors<SubscribeConnector> connectors, ActionExecutor executor) { super(connectors, executor); } @Override public ActionFuture<Void> subscribeObjectAsync(SubscribeObjectRequest request, ActionListener<SubscribeObjectResponse> listener) { return executor.execute(l -> doSubscribeObject(request, l), httpResponseListener(listener, SubscribeResponseConverter::subscribeObject)); } private SubscribeActionFuture<FullHttpResponse> doSubscribeObject(SubscribeObjectRequest request, ActionListener<FullHttpResponse> listener) { return doAction(request, SubscribeRequestConverter::subscribeObject, listener); } }
package com.git.cloud.tenant.model.po; import com.git.cloud.common.model.base.BaseBO; /** * 租户配额 * @author */ public class QuotaPo extends BaseBO implements java.io.Serializable{ /** * */ private static final long serialVersionUID = 6519577748840786940L; private String id; private String tenantId; private String quotaConfigId; private String projectId; private String dataCnterId; private String value; private String code; /** * 已使用的值 */ private String usedValue; /** * 平台code */ private String platformCode; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getQuotaConfigId() { return quotaConfigId; } public void setQuotaConfigId(String quotaConfigId) { this.quotaConfigId = quotaConfigId; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getDataCnterId() { return dataCnterId; } public void setDataCnterId(String dataCnterId) { this.dataCnterId = dataCnterId; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getUsedValue() { return usedValue; } public void setUsedValue(String usedValue) { this.usedValue = usedValue; } public String getPlatformCode() { return platformCode; } public void setPlatformCode(String platformCode) { this.platformCode = platformCode; } @Override public String getBizId() { // TODO Auto-generated method stub return null; } }
package com.madadata.testjdbi; import com.codahale.metrics.annotation.Timed; import com.google.common.base.Strings; import io.dropwizard.jersey.params.IntParam; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; /** * Created by lixinyi on 16/3/19. * <p> * http://host:port/path?query * <p> * query param: host:port/users?id=1 * path param: host:port/users/1 */ @Path("/database") @Produces(MediaType.APPLICATION_JSON) public class UserResource { private final MyDAO dao; public UserResource(MyDAO dao) { this.dao = dao; } @GET @Timed public UserProfile getUserProfileById(@QueryParam("id") IntParam id) { return dao.findUserProfileById(id.get()); } // // @GET // @Timed // public String findResultById(@PathParam("name") String name,@PathParam("email") String email,@PathParam("gender") String gender) { // Integer integer = id.get(); // if (integer == null) { // throw new WebApplicationException("id cannot be null"); // } // String name = dao.findNameById(id.get()); // if (Strings.isNullOrEmpty(name)) { // throw new WebApplicationException("cannot find name"); // } // return name; // } }
import java.io.IOException; class RunVector { public static void main(String[] args) throws IOException { Vector3 vector1 = new Vector3(1F, 2F, 3F); Vector3 vector2 = new Vector3(0F, -1F, 0F); Vector3 vector3 = new Vector3(2F, 3F, 4F); Vector3 vector4 = new Vector3(5F, 6F, 7F); System.out.println("Dot Product of vectors: " + vector1.dot(vector2)); Entity entity = new Entity(vector1, vector2); Ghost ghost = new Ghost(vector3, vector4); System.out.println("Ghost visible: " + ghost.isVisible(entity)); Vector3 crossVector = vector1.cross(vector2); System.out.println("cross product: " + crossVector.x + "," + crossVector.y + "," + crossVector.z); System.out.println("dot product of cross: " + vector1.dot(vector1.cross(vector2))); } }
package com.min.edu.ctrl; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.min.edu.dto.MemberDTO; import com.min.edu.model.MemberIService; @Controller public class MemberController { private Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired private MemberIService service; @RequestMapping(value = "/loginForm.do") public String loginForm() { log.info("로그인폼으로~~"); return "login"; } @RequestMapping(value = "/login.do",method = RequestMethod.POST) public String login(String id, String pw,HttpSession session) { log.info("login!!"+id+"////"+pw); Map<String,String> map = new HashMap<String,String>(); map.put("id",id); map.put("pw",pw); MemberDTO mdto = service.loginMember(map); log.info(mdto.toString()); session.setAttribute("mdto",mdto); return "redirect:/boardList.do"; } @RequestMapping(value = "/signUpForm.do",method = RequestMethod.GET) public String signUpForm() { log.info("signUpForm"); return "signUp"; } @RequestMapping(value = "/signUp.do",method = RequestMethod.GET) public String signUp(MemberDTO dto) { log.info("signUp"); boolean isc = service.signUpMember(dto); log.info(isc+""); if(isc) { return "login"; }else { return "hello"; } } @ResponseBody @RequestMapping(value = "/idDuplicateCheck.do",method = RequestMethod.POST) public String idDuplicateCheck(String id) { log.info("idDuplicateCheck -> "+id); int n = service.idDuplicateCheck(id); String result=""; if(n==0) { result = "true"; }else { result = "false"; } return result; } }
package com.myvodafone.android.model.service; import com.myvodafone.android.service.ServiceResponse; public class LastBillPDF extends ServiceResponse { private String pdfUrl; public String getPdfUrl() { return pdfUrl; } public void setPdfUrl(String pdfUrl) { this.pdfUrl = pdfUrl; } }
package com.svalero.examen.controller; import com.svalero.examen.domain.Job; import com.svalero.examen.service.JobService; import com.svalero.examen.utils.Alerts; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.Event; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.text.Text; import javafx.scene.web.WebView; import javafx.stage.FileChooser; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import rx.Observable; import rx.schedulers.Schedulers; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.concurrent.Executors; import java.util.stream.Collectors; public class AppController implements Initializable { /* ELEMENTOS DE JAVAFX - SCENE BUILDER */ public ListView lvJobs; public TextField tfDescription; public Button btSearch1, btSearch2, btExport; public ComboBox cbLocation; public Text txtType, txtCompany; public CheckBox checkBoxFullTime; /* ATRIBUTOS DE CLASE PROPIOS */ private ObservableList<Job> observableListAllJobs; private List<Job> arrayListAllJobs; // Para trabajar con streams private JobService jobService; private Job jobSelected; @Override public void initialize(URL url, ResourceBundle resourceBundle) { jobService = new JobService(); arrayListAllJobs = new ArrayList<>(); observableListAllJobs = FXCollections.observableArrayList(); lvJobs.setItems(observableListAllJobs); getAllJobs(); } /* ------------------- MÉTODOS DE FXML ------------------- */ @FXML private void getSelectedJob(Event event) { jobSelected = (Job) lvJobs.getSelectionModel().getSelectedItem(); if (!validateJobSelected()) { return; } addDescriptionOfSelectedJob(jobSelected); } @FXML private void findByDescription(Event event) { String description = tfDescription.getText(); if (description.isBlank()) { Alerts.showErrorAlert("Debes escribir un lenguaje de programación"); return; } getJobsByDescription(description); } @FXML private void findByLocation(Event event) { String location = (String) cbLocation.getSelectionModel().getSelectedItem(); String type; if (location.isBlank()) { Alerts.showErrorAlert("No puedes dejar la localización vacía"); return; } if (checkBoxFullTime.isSelected()){ type = "true"; } else { type = "false"; } getJobsByLocation(location, type); } @FXML private void exportCSV(Event event) { File file = export(); if (file != null) { Alerts.showInfoAlert("Archivo exportado con éxito en: " + file.getAbsolutePath()); } else { Alerts.showErrorAlert("Error al exportar los datos"); } } @FXML private void reset(Event event) { getAllJobs(); } /* --------------------------------------------------------- */ /* --------------------------------------------------------- */ /* --------------------------------------------------------- */ /* ------------------- MÉTODOS PROPIOS DE CLASE ------------------- */ private void getAllJobs() { lvJobs.getItems().clear(); observableListAllJobs.clear(); arrayListAllJobs.clear(); jobService.getAllJobs() .flatMap(Observable::from) .doOnCompleted(() -> { /* Lo pongo en un Platform.runLater para que no de error de hilos */ Platform.runLater(() -> { System.out.println("Se carga listado general"); /* Aprovecho ArrayList que cargo con la llamada inicial y hago stream y mapeo a locations, así cargo el comboBox*/ cbLocation.setItems(arrayListAllJobs.stream() .map(Job::getLocation) .distinct() .collect(Collectors.toCollection(FXCollections::observableArrayList))); cbLocation.getSelectionModel().select(0); }); }) .doOnError(throwable -> System.out.println(throwable.getMessage())) .subscribeOn(Schedulers.from(Executors.newCachedThreadPool())) .subscribe(job -> { Platform.runLater(() -> { observableListAllJobs.add(job); arrayListAllJobs.add(job); }); }); } private void getJobsByDescription(String description) { lvJobs.getItems().clear(); observableListAllJobs.clear(); jobService.getJobsByDescription(description) .flatMap(Observable::from) .doOnCompleted(() -> { Platform.runLater(() -> { System.out.println("Se carga listado con lenguaje: " + description); if (observableListAllJobs.isEmpty()) { Alerts.showInfoAlert("No existen trabajos para el lenguaje: " + description); } }); }) .doOnError(throwable -> System.out.println(throwable.getMessage())) .subscribeOn(Schedulers.from(Executors.newCachedThreadPool())) .subscribe(job -> { Platform.runLater(() -> { observableListAllJobs.add(job); }); }); } private void getJobsByLocation(String location, String type) { lvJobs.getItems().clear(); observableListAllJobs.clear(); jobService.getJobsByLocation(location, type) .flatMap(Observable::from) .doOnCompleted(() ->{ Platform.runLater(() -> { if (type.equals("true")) { System.out.println("Se carga listado con localización: " + location + " y de tipo FULL TIME UNICAMENTE"); } else { System.out.println("Se carga listado con localización: " + location + " de CUALQUIER tipo"); } }); }) .doOnError(throwable -> System.out.println(throwable.getMessage())) .subscribeOn(Schedulers.from(Executors.newCachedThreadPool())) .subscribe(job -> { Platform.runLater(() -> { observableListAllJobs.add(job); }); }); } private boolean validateJobSelected() { if (jobSelected == null) { Alerts.showErrorAlert("Selecciona un trabajo para poder ver los detalles"); return false; } else { return true; } } private void addDescriptionOfSelectedJob(Job selected) { txtType.setText(selected.getType()); txtCompany.setText(selected.getCompany()); } private File export() { File file = null; try { FileChooser fileChooser = new FileChooser(); file = fileChooser.showSaveDialog(null); FileWriter fileWriter = new FileWriter(file + ".csv"); CSVPrinter printer = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withHeader("Título", "Compañia", "Localización")); for (Job job : observableListAllJobs) { printer.printRecord( job.getTitle(), job.getCompany(), job.getLocation() ); } printer.close(); } catch (IOException e) { System.out.println("ERROR " + e.getMessage()); } return file; } }
package springmvc.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Medicine { @Override public String toString() { return "Medicine [MedicineId=" + MedicineId + ", medicine_Name=" + medicine_Name + ", ProviderID=" + ProviderID + ", Company_Name=" + Company_Name + ", mfg_date=" + mfg_date + ", Expiry_date=" + Expiry_date + ", Price=" + Price + ", Dose_per_day=" + Dose_per_day + ", StoreID=" + StoreID + "]"; } @Id @GeneratedValue(strategy=GenerationType.AUTO) public int MedicineId; public String medicine_Name; public int ProviderID; public String Company_Name; public String mfg_date; public String Expiry_date; public int Price; public int Dose_per_day; public int StoreID; public int getStoreID() { return StoreID; } public void setStoreID(int storeID) { this.StoreID = storeID; } public int getMedicineId() { return MedicineId; } public void setMedicineId(int medicineId) { this.MedicineId = medicineId; } public String getMedicine_Name() { return medicine_Name; } public void setMedicine_Name(String medicine_Name) { this.medicine_Name = medicine_Name; } public int getProviderID() { return ProviderID; } public void setProviderID(int ProviderID) { this.ProviderID = ProviderID; } public String getCompany_Name() { return Company_Name; } public void setCompany_Name(String company_Name) { this.Company_Name = company_Name; } public String getMfg_date() { return mfg_date; } public void setMfg_date(String mfg_date) { this.mfg_date = mfg_date; } public String getExpiry_date() { return Expiry_date; } public void setExpiry_date(String expiry_date) { this.Expiry_date = expiry_date; } public int getPrice() { return Price; } public void setPrice(int price) { this.Price = price; } public int getDose_per_day() { return Dose_per_day; } public void setDose_per_day(int dose_per_day) { this.Dose_per_day = dose_per_day; } public Medicine() { super(); // TODO Auto-generated constructor stub } }
package com.tacademy.board.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import com.tacademy.board.vo.Board; public class BoardDAO { private String listSQL = "select * from board order by seq desc"; private String insertSQL = "INSERT INTO BOARD( TITLE, WRITER, CONTENT ) VALUES( ?, ?, ? )"; private String boardSQL ="select * from board where seq = ?"; private String boardReadSQL = "update board set cnt = cnt + 1 where seq = ?"; private String updateSQL = "update board set title = ?, content = ? where seq = ?"; private String deleteSQL = "delete from board where seq = ?"; public void deleteBoard(Board board){ Connection con = null; PreparedStatement stmt = null; try{ con = JDBCUtil.getConnection(); stmt = con.prepareStatement(deleteSQL); stmt.setInt(1, board.getSeq()); int cnt = stmt.executeUpdate(); System.out.println( cnt==1 ? "success" : "fail" ); }catch(SQLException e){ System.out.println("deleteBoard error : " + e); }finally{ JDBCUtil.close(stmt, con); } } public void updateBoard(Board board){ Connection con = null; PreparedStatement stmt = null; try{ con = JDBCUtil.getConnection(); stmt = con.prepareStatement(updateSQL); stmt.setString(1, board.getTitle()); stmt.setString(2, board.getContent()); stmt.setInt(3, board.getSeq()); int cnt = stmt.executeUpdate(); System.out.println( cnt==1 ? "success" : "fail" ); }catch(SQLException e){ System.out.println("updateBoard error : " + e); }finally{ JDBCUtil.close(stmt, con); } } public void getBoard(Board board){ Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; try{ con = JDBCUtil.getConnection(); stmt = con.prepareStatement(boardReadSQL); stmt.setInt(1, board.getSeq()); stmt.executeUpdate(); stmt = con.prepareStatement(boardSQL); stmt.setInt(1, board.getSeq()); rs = stmt.executeQuery(); if( rs.next() ){ board.setTitle(rs.getString(2)); board.setWriter(rs.getString(3)); board.setContent(rs.getString(4)); board.setRegdate(rs.getString(5)); board.setCnt(rs.getInt(6)); } }catch(SQLException e){ System.out.println("getBoard error : " + e); }finally{ JDBCUtil.close(rs, stmt, con); } } public void addBoard(Board board){ Connection con = null; PreparedStatement stmt = null; try{ con = JDBCUtil.getConnection(); stmt = con.prepareStatement(insertSQL); stmt.setString(1, board.getTitle()); stmt.setString(2, board.getWriter()); stmt.setString(3, board.getContent()); int cnt = stmt.executeUpdate(); System.out.println( cnt==1 ? "success" : "fail" ); }catch(SQLException e){ System.out.println("addBoard error : " + e); }finally{ JDBCUtil.close(stmt, con); } } public ArrayList<Board> getBoardList(){ ArrayList<Board> list = new ArrayList<Board>(); Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; Board board ; try{ con = JDBCUtil.getConnection(); stmt = con.prepareStatement(listSQL); rs = stmt.executeQuery(); while( rs.next() ){ board = new Board(); board.setSeq(rs.getInt("seq")); board.setTitle(rs.getString(2)); board.setWriter(rs.getString(3)); board.setContent(rs.getString(4)); board.setRegdate(rs.getString(5)); board.setCnt(rs.getInt(6)); list.add(board); } }catch(SQLException e){ System.out.println("list error : " + e); }finally{ JDBCUtil.close(rs, stmt, con); } return list; } }
package com.github.olly.workshop.imageorchestrator.config; import brave.SpanCustomizer; import com.github.olly.workshop.imageorchestrator.model.Image; import com.github.olly.workshop.imageorchestrator.model.Transformation; import com.github.olly.workshop.imageorchestrator.model.TransformationRequest; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class LogTraceContextUtil { private final SpanCustomizer span; private final Boolean TRACING_TAGS_ENABLED; public LogTraceContextUtil(SpanCustomizer span, @Value("${TRACING_TAGS_ENABLED:true}") Boolean tracingTagsEnabled) { this.span = span; this.TRACING_TAGS_ENABLED = tracingTagsEnabled; } public void put(Transformation transformation) { transformation(transformation); } public void put(Image image) { image(image); } public void put(TransformationRequest transformationRequest) { transformationRequest(transformationRequest); } public void put(Object... objects) { for (Object object : objects) { if (object instanceof Image) { image((Image) object); } else if (object instanceof Transformation) { transformation((Transformation) object); } else if (object instanceof TransformationRequest) { transformationRequest((TransformationRequest) object); } } } private void transformationRequest(TransformationRequest transformationRequest) { if (transformationRequest != null) { put("imageId", transformationRequest.getImageId()); put("imageName", transformationRequest.getName()); put("persist", transformationRequest.getPersist()); put("transformationType", transformationRequest.getTransformationTypes()); transformationRequest.getTransformations().forEach(LogTraceContextUtil::transformationProperties); } } private void transformation(Transformation transformation) { if (transformation != null) { put("transformationType", transformation.getType().name()); transformationProperties(transformation); } } private static void transformationProperties(Transformation transformation) { if (transformation != null && transformation.getProperties() != null) { transformation.getProperties().forEach(MDC::put); } } private void image(Image image) { if (image != null) { put("mimeType", image.getMimeType()); put("imageId", image.getId()); } } private void put(String key, String value) { MDC.put(key, String.valueOf(value)); if (TRACING_TAGS_ENABLED) { span.tag(key, String.valueOf(value)); } } }
public class StackOrQueueException extends RuntimeException{ public StackOrQueueException(String msg) { super(msg); } public StackOrQueueException() { super(); } }
package com.test.app.cacheapi.services; import com.test.app.cacheapi.model.LRUCacheResponse; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class CacheServiceImplTest { CacheServiceImpl cacheService = new CacheServiceImpl(); @Before public void setUp() throws Exception { cacheService.setCapacity(2); } @Test public void shouldReturnNewEntryForGetCacheWithNewKey(){ LRUCacheResponse actualCache = new LRUCacheResponse(1, 400); cacheService.createCache(1, 400); LRUCacheResponse expectedCache = cacheService.getCache(1); Assert.assertNotNull(expectedCache); Assert.assertEquals(expectedCache.getKey() , actualCache.getKey()); Assert.assertEquals(expectedCache.getValue() , actualCache.getValue()); } @Test public void shouldReturnNullWhenNoKeyAddedIntoGetCache(){ LRUCacheResponse expectedCache = cacheService.getCache(1); Assert.assertEquals(expectedCache , null); } @Test public void shouldReturnLRUCacheResponseWithPutCache(){ LRUCacheResponse actualCache = new LRUCacheResponse(1, 400); LRUCacheResponse expectedCache = cacheService.createCache(1, 400); Assert.assertNotNull(expectedCache); Assert.assertEquals(expectedCache.getKey() , actualCache.getKey()); Assert.assertEquals(expectedCache.getValue() , actualCache.getValue()); } }
/* * Copyright (C) 2015 Adrien Guille <adrien.guille@univ-lyon2.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package main.java.fr.ericlab.sondy.algo.eventdetection.mabed; import main.java.fr.ericlab.sondy.core.app.AppParameters; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import org.graphstream.algorithm.ConnectedComponents; import org.graphstream.algorithm.ConnectedComponents.ConnectedComponent; import org.graphstream.graph.Edge; import org.graphstream.graph.Graph; import org.graphstream.graph.Node; import org.graphstream.graph.implementations.SingleGraph; /** * * @author Adrien GUILLE, ERIC Lab, University of Lyon 2 * @email adrien.guille@univ-lyon2.fr */ public class MABEDEventGraph implements Serializable { public Graph graph; public Graph redundancyGraph; public HashMap<String,MABEDEvent> duplicatedEvents; double maximumScore; double sigma; public MABEDEventGraph(double ms, Double sig){ sigma = sig; graph = new SingleGraph(""); redundancyGraph = new SingleGraph(""); maximumScore = ms; duplicatedEvents = new HashMap<>(); } public int addEvent(MABEDEvent event){ int added = 0; boolean redundant = false; if(graph.getNode(event.mainTerm) != null){ for(MABEDWeightedTerm wt : event.relatedTerms.list){ Node wtNode = graph.getNode(wt.term); if(wtNode != null){ if(wtNode.getAttribute("ui.class").equals("mainTerm") && wtNode.hasEdgeFrom(graph.getNode(event.mainTerm).toString())){ MABEDEvent event1 = getEvent(wtNode); double intersection = Math.max(event.I.intersectionProportion(event1.I), event1.I.intersectionProportion(event.I)); if(intersection > sigma){ redundant = true; duplicatedEvents.put(event.mainTerm,event); duplicatedEvents.put(event1.mainTerm,event1); // new way of managing redundancy if(redundancyGraph.getNode(event1.mainTerm) == null){ redundancyGraph.addNode(event1.mainTerm); } if(redundancyGraph.getNode(event.mainTerm) == null){ redundancyGraph.addNode(event.mainTerm); } if(redundancyGraph.getEdge(event.mainTerm+"-"+event1.mainTerm) == null){ redundancyGraph.addEdge(event.mainTerm+"-"+event1.mainTerm, event.mainTerm, event1.mainTerm, false); } } } } } } if(!redundant){ if(event.mainTerm != null){ if(graph.getNode(event.mainTerm) == null){ graph.addNode(event.mainTerm); } graph.getNode(event.mainTerm).addAttributes(event.getMainTermAttributes()); graph.getNode(event.mainTerm).setAttribute("ui.size",20+(event.score/maximumScore)*10); graph.getNode(event.mainTerm).addAttribute("ui.label", "["+AppParameters.dataset.corpus.convertTimeSliceToDay(event.I.timeSliceA)+"::"+AppParameters.dataset.corpus.convertTimeSliceToDay(event.I.timeSliceB)+"]:"+event.mainTerm); graph.getNode(event.mainTerm).addAttribute("anomaly",event.anomaly); for(MABEDWeightedTerm wt : event.relatedTerms.list){ if(wt.term != null){ if(graph.getNode(wt.term)==null){ graph.addNode(wt.term); graph.getNode(wt.term).addAttribute("ui.label", wt.term); graph.getNode(wt.term).setAttribute("ui.class","relatedTerm"); } graph.addEdge("["+event.I.timeSliceA+":"+event.I.timeSliceB+"]"+event.mainTerm+"-"+wt.term,wt.term,event.mainTerm,true); graph.getEdge("["+event.I.timeSliceA+":"+event.I.timeSliceB+"]"+event.mainTerm+"-"+wt.term).addAttribute("weight", wt.weight); } } } added = 1; } return added; } public MABEDEventList identifyConnectedComponents(){ ConnectedComponents ccs = new ConnectedComponents(redundancyGraph); ccs.setCountAttribute("component"); int i = 0; MABEDEventList globalEvents = new MABEDEventList(); for (ConnectedComponent cc : ccs) { MABEDEventList ccEvents = new MABEDEventList(); for(Node node : cc.getEachNode()){ MABEDEvent event = duplicatedEvents.get(node.getId()); ccEvents.add(event); removeEvent(event); } ccEvents.sort(); MABEDEvent mainEvent = ccEvents.list.pop(); MABEDEvent globalEvent = mainEvent.merge(ccEvents); globalEvents.add(globalEvent); addEvent(globalEvent); i++; } return globalEvents; } public void removeEvent(MABEDEvent event){ Node mainNode = graph.getNode(event.mainTerm); if(mainNode != null){ if(mainNode.getAttribute("ui.class").equals("mainTerm")){ Collection<Edge> edges = mainNode.getEnteringEdgeSet(); if(edges != null){ for(Edge edge : edges){ if(edge != null){ // remove obsolete edge graph.removeEdge(edge); if(edge.getSourceNode().getDegree() == 0){ graph.removeNode(edge.getSourceNode().toString()); } } } } if(mainNode.getOutDegree() == 0){ graph.removeNode(mainNode); }else{ mainNode.setAttribute("ui.class", "relatedTerm"); } } } } public void replaceEvent(Node nodeT0, MABEDEvent t1){ nodeT0.setAttribute("ui.class","relatedTerm"); Collection<Edge> edges = nodeT0.getEnteringEdgeSet(); graph.addNode(t1.mainTerm); graph.getNode(t1.mainTerm).addAttributes(t1.getMainTermAttributes()); graph.getNode(t1.mainTerm).setAttribute("ui.size",20+(t1.score/maximumScore)*10); graph.getNode(t1.mainTerm).addAttribute("ui.label", "["+AppParameters.dataset.corpus.convertTimeSliceToDay(t1.I.timeSliceA)+"::"+AppParameters.dataset.corpus.convertTimeSliceToDay(t1.I.timeSliceB)+"]:"+t1.mainTerm); graph.getNode(t1.mainTerm).setAttribute("anomaly",t1.anomaly); if(edges != null){ for(Edge edge : edges){ if(edge != null){ // remove obsolete edge graph.removeEdge(edge); // add edge toward the new main term if(!t1.mainTerm.contains(edge.getSourceNode().getId())){ String edgeId = "["+t1.I.timeSliceA+":"+t1.I.timeSliceB+"]"+t1.mainTerm+"-"+edge.getSourceNode().getId(); graph.addEdge(edgeId,edge.getSourceNode().getId(),t1.mainTerm,true); graph.getEdge(edgeId).addAttribute("weight", edge.getAttribute("weight")); } if(edge.getSourceNode().getDegree() == 0){ graph.removeNode(edge.getSourceNode().toString()); } } } } graph.removeNode(nodeT0); for(MABEDWeightedTerm wt : t1.relatedTerms.list){ if(wt.term != null){ if(graph.getNode(wt.term)==null){ graph.addNode(wt.term); graph.getNode(wt.term).addAttribute("ui.label", wt.term); graph.getNode(wt.term).setAttribute("ui.class","relatedTerm"); } if(graph.getEdge("["+t1.I.timeSliceA+":"+t1.I.timeSliceB+"]"+t1.mainTerm+"-"+wt.term) == null){ graph.addEdge("["+t1.I.timeSliceA+":"+t1.I.timeSliceB+"]"+t1.mainTerm+"-"+wt.term,wt.term,t1.mainTerm,true); } graph.getEdge("["+t1.I.timeSliceA+":"+t1.I.timeSliceB+"]"+t1.mainTerm+"-"+wt.term).addAttribute("weight", wt.weight); } } // if(nodeT0.getDegree() == 0){ // System.out.println(" - "+nodeT0.getId()+" is a leaf node."); // graph.removeNode(nodeT0); // } } public MABEDEvent getEvent(Node mainNode){ MABEDEvent event = new MABEDEvent(); if(mainNode.getAttribute("ui.class")!=null && mainNode.getAttribute("ui.class").equals("mainTerm")){ event = new MABEDEvent(mainNode.getId(), new MABEDTimeInterval((String) mainNode.getAttribute("I")), (double) mainNode.getAttribute("score"), (ArrayList<Double>) mainNode.getAttribute("anomaly")); for(Edge edge : mainNode.getEnteringEdgeSet()){ event.relatedTerms.add(new MABEDWeightedTerm(edge.getSourceNode().getId(), (double) edge.getAttribute("weight"))); } } return event; } public MABEDEventList toEventList(){ MABEDEventList events = new MABEDEventList(); events.timeSliceLength = AppParameters.dataset.corpus.timeSliceLength; events.corpusStart = new Timestamp(AppParameters.dataset.corpus.start.getTime()); for(Node node : graph){ if(node.getAttribute("ui.class")!=null && node.getAttribute("ui.class").equals("mainTerm")){ MABEDEvent event = new MABEDEvent(node.getId(), new MABEDTimeInterval((String) node.getAttribute("I")), (double) node.getAttribute("score"), (ArrayList<Double>) node.getAttribute("anomaly")); for(Edge edge : node.getEnteringEdgeSet()){ event.relatedTerms.add(new MABEDWeightedTerm(edge.getSourceNode().getId(), (double) edge.getAttribute("weight"))); } events.add(event); } } events.sort(); return events; } }
package JavaPackage; import java.util.ArrayList; public class WebPage { //This WebPage is Associated with WebPage String title; String url; ArrayList<String> linksList; final static String logo = "Amazon"; //First Constructor can be create with ONLY Non-Static properties. No Static public WebPage(String title, String url, ArrayList<String> linksList) { this.title = title; this.url = url; this.linksList = linksList; } //Below we create another constructor with only title & url public WebPage(String title, String url) { this.title = title; this.url = url; } }
package com.joalib.controller; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.joalib.DTO.ActionForward; import com.joalib.member.action.*; @WebServlet("*.mem") public class MemberinfoContr extends javax.servlet.http.HttpServlet{ protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String RequestURI=request.getRequestURI(); String contextPath=request.getContextPath(); String command=RequestURI.substring(contextPath.length()); ActionForward forward=null; Action action = null; if(command.equals("/memberInsert.mem")) { //ȸ������ action = new MemberInsertAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/IDCheck.mem")) { //�α��� action = new MemberIDCheck(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/memberLogout.mem")) { //�α׾ƿ� HttpSession session = request.getSession(false); session.invalidate(); // forward = new ActionForward(); forward.setRedirect(true); forward.setPath("home.jsp"); }else if (command.equals("/newMemberPointInsert.mem")) { action = new NewMemberPointAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if (command.equals("/memberDelete.mem")) { action = new MemberDeleteAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if (command.equals("/memberinfoChange.mem")) { action = new MeberinfoChangeAction(); //�������� try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } } else if (command.equals("/memberAlram.mem")) { action = new AlarmMemberAction(); //�������� try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } } if(forward != null){ if(forward.isRedirect()){ response.sendRedirect(forward.getPath()); //��ȯ�ϴ� forward���� ������, 'forward.getPath()'���� �̵��Ѵ�. }else{ RequestDispatcher dispatcher= request.getRequestDispatcher(forward.getPath()); dispatcher.forward(request, response); } } //doProcess END } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request,response); } }
package edu.colostate.cs.cs414.soggyZebras.rollerball.Client.menu; import edu.colostate.cs.cs414.soggyZebras.rollerball.Client.menu.listdisplay.PendingInviteListDisplay; import edu.colostate.cs.cs414.soggyZebras.rollerball.Server.Invite; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; public class PendingInvitesPanel extends MenuPanel { private DefaultListModel<PendingInviteListDisplay> pendingInvitesListModel; private PendingInviteListDisplay selectedInvite; public PendingInvitesPanel(MenuGUI menuGUI) { super("pending_invites", menuGUI); selectedInvite = null; refresh(); } @Override public void refresh() { removeAll(); JLabel title = new JLabel("Pending Invites"); add(title); pendingInvitesListModel = new DefaultListModel(); // get users pending invites if (getMenuGUI().loggedInUser != null) { for (Invite invite : getMenuGUI().loggedInUser.getGotInvites()) { pendingInvitesListModel.add(0, new PendingInviteListDisplay(invite)); } } JList<PendingInviteListDisplay> pendingInvitesList = new JList<>(pendingInvitesListModel); pendingInvitesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); pendingInvitesList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { selectedInvite = pendingInvitesList.getSelectedValue(); } }); // make it so that the selected user doesn't change even if it is refreshed if (selectedInvite != null) { pendingInvitesList.setSelectedValue(selectedInvite, true); } JScrollPane listScroller = new JScrollPane(pendingInvitesList); listScroller.setPreferredSize(new Dimension(250, 100)); add(listScroller); add(createLinkedActionButton("Accept Invite", new AcceptInviteListener(pendingInvitesList))); // to make sure Back is on a new line add(new JLabel(" ")); add(createLinkedButton("Back", "main_menu")); } /** * used for testing * @return get the user id of the first user in the list */ public int getFirstInviteID() { if (pendingInvitesListModel.size() > 0) return pendingInvitesListModel.get(0).invite.getInviteID(); else return -1; } class AcceptInviteListener implements ActionListener { private JList<PendingInviteListDisplay> pendingInvitesList; public AcceptInviteListener(JList<PendingInviteListDisplay> pendingInviteList) { this.pendingInvitesList = pendingInviteList; } @Override public void actionPerformed(ActionEvent e) { PendingInviteListDisplay listInvite = pendingInvitesList.getSelectedValue(); if (listInvite == null) { JOptionPane.showMessageDialog(getMenuGUI(), "No invite was selected."); return; } pendingInvitesListModel.remove(pendingInvitesListModel.indexOf(listInvite)); getMenuGUI().revalidate(); getMenuGUI().repaint(); try { getMenuGUI().client.respondInvite(listInvite.invite.getInviter(), listInvite.invite.getInviteID()); } catch (IOException e1) { e1.printStackTrace(); } // notify user JOptionPane.showMessageDialog(getMenuGUI(), "Game created with user " + listInvite.invite.getInviter() + ".\nGo to the main menu to start the game."); } } }
package headedTests; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.jtimer.Runner; import org.jtimer.Annotations.DisplayName; import org.jtimer.Annotations.Settings; import org.jtimer.Annotations.Time; import org.jtimer.Misc.Setting; import org.junit.jupiter.api.BeforeAll; import logic.BruteForceScheduleMaker; import logic.Globals; import logic.GreedyQuickScheduleMaker; @Settings({ Setting.BEST_FIT }) public class ScheduleTimeTests { static List<String> courses = new ArrayList<>(); long counter = 0; // If you want some variable to keep the repetition that you're on. public static void main(String[] args) throws Throwable { Runner.time(ScheduleTimeTests.class); } @BeforeAll public static void setup() { Globals.init(); courses.clear(); courses.add("EC4050 - Game Theory/Strategic Behavior"); courses.add("AF3020 - Effective Com II - Non AFROTC"); courses.add("BL4450 - Limnology"); courses.add("CH1151 - University Chemistry Lab I Lab"); courses.add("MA1161 - Calculus Plus w/ Technology I Lab"); courses.add("FA3400 - Keweenaw Symphony Orchestra Lab"); courses.add("CEE4507 - Distribution and Collection Lab"); courses.add("CEE5350 - Life Cycle Engineering Lab"); courses.add("CS3311 - Formal Models of Computation"); courses.add("BL4530 - Senior Research Capstone Exp"); courses.add("MA3160 - Multivariable Calc with Tech Lab"); courses.add("BL4752 - Cancer Biology"); courses.add("CH1150 - University Chemistry I"); courses.add("MA1161 - Calculus Plus w/ Technology I"); courses.add("CH1163 - University Chem Recitation II"); courses.add("BL3611 - Phlebotomy Lab"); courses.add("MA2720 - Statistical Methods"); courses.add("MA3160 - Multivariable Calc with Tech"); courses.add("ACC2000 - Accounting Principles I"); courses.add("EE4800 - Antennas"); courses.add("ACC4600 - Advanced Tax Topics"); courses.add("EE2174 - Digital Logic and Lab Lab"); courses.add("ENT1960 - Wireless Communication Lab"); courses.add("PE0121 - Beginning Snowboarding Lab"); courses.add("BL3190 - Evolution"); courses.add("BL5038 - Epigenetics"); courses.add("UN5953 - Graduate Continuous Enrollment"); courses.add("UN5951 - Grad Cont. Enrl't-Special Circ"); courses.add("UN5390 - Scientific Computing"); courses.add("UN5100 - Water and Society Colloquium"); courses.add("UN5004 - Graduate Co-op Education IV"); courses.add("UN5003 - Graduate Co-op Education III"); courses.add("UN5002 - Graduate Co-op Education II"); courses.add("UN5000 - Graduate Co-op Education I"); courses.add("UN3990 - Entrepreneurship Indep. Study"); courses.add("UN3005 - Undergrad Co-op Education IV"); courses.add("UN3004 - Undergrad Co-op Education III"); courses.add("UN3003 - Undergrad Co-op Education II"); courses.add("UN3002 - Undergrad Co-op Education I"); courses.add("UN2600 - Fund Nanoscale Science & Eng"); courses.add("UN1025 - Global Issues"); courses.add("UN1015 - Composition"); courses.add("UN0500 - Effective Scholarship"); courses.add("SU5999 - Thesis Research in IGT"); courses.add("SU5998 - Practical Experience in IGT"); courses.add("SU5800 - Master's Graduate Seminar"); courses.add("SU5541 - Close-range Photogrammetry"); courses.add("SU5023 - Geospatial Positioning"); courses.add("SU5013 - Hydrographic Mapping Lab"); courses.add("SU5013 - Hydrographic Mapping"); courses.add("SU5012 - Geospatial Data MIning Lab"); courses.add("SU5012 - Geospatial Data MIning"); courses.add("SU5010 - Geospatia Concepts, Tech, Data"); courses.add("SU4999 - Professional Practice Review"); courses.add("SU4900 - Capstone Design Project Lab"); courses.add("SU4900 - Capstone Design Project"); courses.add("SU4180 - Land Subdivision Design"); courses.add("SU4060 - Geodesy Lab"); courses.add("SU4060 - Geodesy"); courses.add("SU4013 - Hydrographic Mapping Lab"); courses.add("SU4013 - Hydrographic Mapping"); courses.add("SU4012 - Geospatial Data Mining Lab"); courses.add("SU4012 - Geospatial Data Mining"); courses.add("SU4010 - Geospatia Concepts, Tech, Data"); courses.add("SU3210 - Site Planning and Development Lab"); courses.add("SU3210 - Site Planning and Development"); courses.add("SU2220 - Route/Construction Surveying"); courses.add("SU2000 - Introduction to Surveying Lab"); courses.add("SU2000 - Introduction to Surveying"); courses.add("SS6600 - PhD. Dissertation Research"); courses.add("SS6500 - Directed Reading"); courses.add("SS6002 - Research Design"); courses.add("SS5990 - Graduate Research"); courses.add("SS5950 - Professional Development"); courses.add("SS5502 - Historical Archaeology"); courses.add("SS5015 - VISTA Field Service Lab"); courses.add("SS5010 - Directed Study"); courses.add("SS4990 - Directed Study in Anthropology"); courses.add("SS4920 - Internship Experience"); courses.add("SS4910 - Prof Devel for Soc Sciences"); courses.add("SS4900 - Memory and Heritage"); courses.add("SS4630 - Adv Research in Soc Sci"); courses.add("SS4552 - Historical Archaeology"); } @Time(repeat = 82) @DisplayName("Greedy Scheduler") public void scheduleMaker1() { List<String> courses = this.courses.parallelStream().filter(e -> this.courses.indexOf(e) < counter).collect(Collectors.toList()); GreedyQuickScheduleMaker.build(courses, "202001"); } @Time(repeat = 82) @DisplayName("Brute-Force Scheduler") public void scheduleMaker2() { Set<String> courses = this.courses.parallelStream().filter(e -> this.courses.indexOf(e) < counter).collect(Collectors.toSet()); BruteForceScheduleMaker.build(courses, "202001"); } }
package algo3.fiuba.modelo.cartas.moldes_cartas.cartas_campo; import algo3.fiuba.modelo.Juego; import algo3.fiuba.modelo.Turno; import algo3.fiuba.modelo.cartas.Carta; import algo3.fiuba.modelo.cartas.moldes_cartas.cartas_monstruos.*; import algo3.fiuba.modelo.jugador.Jugador; import algo3.fiuba.modelo.cartas.Monstruo; import algo3.fiuba.modelo.cartas.estados_cartas.BocaArriba; import algo3.fiuba.modelo.jugador.PreInvocacion; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class SogenTest { private Sogen sogen; private Jugador jugador; private Jugador jugador1; private Jugador jugador2; private Juego juego; private Turno turno; @Before public void setUp() { jugador = new Jugador(); jugador.setEstadoJugador(new PreInvocacion()); jugador1 = new Jugador(); jugador2 = new Jugador(); juego = Juego.getInstancia(); juego.inicializar(jugador1, jugador2); turno = Turno.getInstancia(); } @Test public void alActivarElEfectoElMonstruoDeSuLadoDelCampoGana500PuntosDeDefensa() { sogen = new Sogen(jugador1); Monstruo monstruoPropio = new BebeDragon(jugador1); jugador1.colocarCartaEnCampo((Carta) monstruoPropio, new BocaArriba()); Integer defensaInicialDelMonstruo = monstruoPropio.getDefensa(); sogen.setEstado(new BocaArriba()); sogen.activarEfecto(); Integer defensaFinalDelMonstruo = defensaInicialDelMonstruo + 500; Assert.assertEquals(defensaFinalDelMonstruo, monstruoPropio.getDefensa()); } @Test public void alActivarElEfectoTodosLosMonstruosDeSuLadoDelCampoGanan500PuntosDeDefensa() { sogen = new Sogen(jugador1); Monstruo monstruoPropio1 = new BebeDragon(jugador1); Monstruo monstruoPropio2 = new Kuriboh(jugador1); jugador1.colocarCartaEnCampo((Carta) monstruoPropio1, new BocaArriba()); turno.pasarTurno(); turno.pasarTurno(); jugador1.colocarCartaEnCampo((Carta) monstruoPropio2, new BocaArriba()); Integer defensaInicialDelMonstruo1 = monstruoPropio1.getDefensa(); Integer defensaInicialDelMonstruo2 = monstruoPropio2.getDefensa(); sogen.setEstado(new BocaArriba()); sogen.activarEfecto(); Integer defensaFinalDelMonstruo1 = defensaInicialDelMonstruo1 + 500; Assert.assertEquals(defensaFinalDelMonstruo1, monstruoPropio1.getDefensa()); Integer defensaFinalDelMonstruo2 = defensaInicialDelMonstruo2 + 500; Assert.assertEquals(defensaFinalDelMonstruo2, monstruoPropio2.getDefensa()); } @Test public void alActivarElEfectoElMonstruoDelCampoDelOponenteGana200PuntosDeAtaque() { sogen = new Sogen(jugador1); Monstruo monstruoOponente = new BebeDragon(jugador2); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoOponente, new BocaArriba()); Integer ataqueInicialDelMonstruo = monstruoOponente.getAtaque(); sogen.setEstado(new BocaArriba()); sogen.activarEfecto(); Integer ataqueFinalDelMonstruo = ataqueInicialDelMonstruo + 200; Assert.assertEquals(ataqueFinalDelMonstruo, monstruoOponente.getAtaque()); } @Test public void alActivarElEfectoTodosLosMonstruosDelCampoDelOponenteGanan200PuntosDeAtaque() { sogen = new Sogen(jugador1); Monstruo monstruoOponente1 = new BebeDragon(jugador2); Monstruo monstruoOponente2 = new Kuriboh(jugador2); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoOponente1, new BocaArriba()); turno.pasarTurno(); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoOponente2, new BocaArriba()); Integer ataqueInicialDelMonstruo1 = monstruoOponente1.getAtaque(); Integer ataqueInicialDelMonstruo2 = monstruoOponente2.getAtaque(); sogen.setEstado(new BocaArriba()); sogen.activarEfecto(); Integer ataqueFinalDelMonstruo1 = ataqueInicialDelMonstruo1 + 200; Assert.assertEquals(ataqueFinalDelMonstruo1, monstruoOponente1.getAtaque()); Integer ataqueFinalDelMonstruo2 = ataqueInicialDelMonstruo2 + 200; Assert.assertEquals(ataqueFinalDelMonstruo2, monstruoOponente2.getAtaque()); } @Test public void alActivarElEfectoElJugador2TodosLosMonstruosDelJugador1EnCampoGanan200PuntosDeAtaque() { sogen = new Sogen(jugador2); Monstruo monstruo1 = new BebeDragon(jugador1); Monstruo monstruo2 = new Kuriboh(jugador1); jugador1.colocarCartaEnCampo((Carta) monstruo1, new BocaArriba()); turno.pasarTurno(); turno.pasarTurno(); jugador1.colocarCartaEnCampo((Carta) monstruo2, new BocaArriba()); Integer ataqueInicialDelMonstruo1 = monstruo1.getAtaque(); Integer ataqueInicialDelMonstruo2 = monstruo2.getAtaque(); sogen.setEstado(new BocaArriba()); sogen.activarEfecto(); Integer ataqueFinalDelMonstruo1 = ataqueInicialDelMonstruo1 + 200; Assert.assertEquals(ataqueFinalDelMonstruo1, monstruo1.getAtaque()); Integer ataqueFinalDelMonstruo2 = ataqueInicialDelMonstruo2 + 200; Assert.assertEquals(ataqueFinalDelMonstruo2, monstruo2.getAtaque()); } @Test public void alActivarElEfectoElJugador2TodosLosMonstruosDelJugador2EnCampoDelOponenteGanan500PuntosDeDefensa() { sogen = new Sogen(jugador2); Monstruo monstruo1 = new BebeDragon(jugador2); Monstruo monstruo2 = new Kuriboh(jugador2); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruo1, new BocaArriba()); turno.pasarTurno(); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruo2, new BocaArriba()); Integer defensaInicialDelMonstruo1 = monstruo1.getDefensa(); Integer defensaInicialDelMonstruo2 = monstruo2.getDefensa(); sogen.setEstado(new BocaArriba()); sogen.activarEfecto(); Integer defensaFinalDelMonstruo1 = defensaInicialDelMonstruo1 + 500; Assert.assertEquals(defensaFinalDelMonstruo1, monstruo1.getDefensa()); Integer defensaFinalDelMonstruo2 = defensaInicialDelMonstruo2 + 500; Assert.assertEquals(defensaFinalDelMonstruo2, monstruo2.getDefensa()); } @Test public void colocaSogenEnCampoBocaArriba_elEfectoSeActivaAutomaticamente_seMantieneEnElCampo() { sogen = new Sogen(jugador1); jugador1.colocarCartaEnCampo((Carta) sogen, new BocaArriba()); Assert.assertTrue(sogen.estaEnJuego()); Assert.assertTrue(jugador1.cartaEstaEnCampo((Carta) sogen)); Assert.assertFalse(jugador1.cartaEstaEnCementerio(sogen)); } @Test public void colocaSogenEnCampoBocaArriba_elEfectoSeActivaAutomaticamente_losMonstruosDeSuLadoDelCampoGanan500PuntosDeDefensa() { sogen = new Sogen(jugador1); Monstruo monstruoPropio1 = new BebeDragon(jugador1); Monstruo monstruoPropio2 = new Kuriboh(jugador1); jugador1.colocarCartaEnCampo((Carta) monstruoPropio1, new BocaArriba()); turno.pasarTurno(); turno.pasarTurno(); jugador1.colocarCartaEnCampo((Carta) monstruoPropio2, new BocaArriba()); turno.pasarTurno(); turno.pasarTurno(); Integer defensaInicialDelMonstruo1 = monstruoPropio1.getDefensa(); Integer defensaInicialDelMonstruo2 = monstruoPropio2.getDefensa(); jugador1.colocarCartaEnCampo((Carta) sogen, new BocaArriba()); Integer defensaFinalDelMonstruo1 = defensaInicialDelMonstruo1 + 500; Assert.assertEquals(defensaFinalDelMonstruo1, monstruoPropio1.getDefensa()); Integer defensaFinalDelMonstruo2 = defensaInicialDelMonstruo2 + 500; Assert.assertEquals(defensaFinalDelMonstruo2, monstruoPropio2.getDefensa()); } @Test public void seColocaSogenEnCampoBocaArriba_elEfectoSeActivaAutomaticamente_losMonstruosDelLadoDelOponenteGanan200PuntosDeAtaque() { sogen = new Sogen(jugador1); Monstruo monstruoOponente1 = new BebeDragon(jugador2); Monstruo monstruoOponente2 = new Kuriboh(jugador2); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoOponente1, new BocaArriba()); turno.pasarTurno(); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoOponente2, new BocaArriba()); turno.pasarTurno(); Integer ataqueInicialDelMonstruo1 = monstruoOponente1.getAtaque(); Integer ataqueInicialDelMonstruo2 = monstruoOponente2.getAtaque(); jugador1.colocarCartaEnCampo((Carta) sogen, new BocaArriba()); Integer ataqueFinalDelMonstruo1 = ataqueInicialDelMonstruo1 + 200; Assert.assertEquals(ataqueFinalDelMonstruo1, monstruoOponente1.getAtaque()); Integer ataqueFinalDelMonstruo2 = ataqueInicialDelMonstruo2 + 200; Assert.assertEquals(ataqueFinalDelMonstruo2, monstruoOponente2.getAtaque()); } @Test public void seColocaSogenEnCampoYLuegoSeRemueve_losMonstruosDeAmbosLadosDeberianTenerLosPuntosPreviosASerInvocada() { sogen = new Sogen(jugador1); Monstruo monstruoPropio1 = new BebeDragon(jugador1); Monstruo monstruoPropio2 = new Kuriboh(jugador1); Monstruo monstruoOponente1 = new GuerreroCelta(jugador2); Monstruo monstruoOponente2 = new PezDe7Colores(jugador2); jugador1.colocarCartaEnCampo((Carta) monstruoPropio1, new BocaArriba()); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoOponente1, new BocaArriba()); turno.pasarTurno(); jugador1.colocarCartaEnCampo((Carta) monstruoPropio2, new BocaArriba()); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoOponente2, new BocaArriba()); turno.pasarTurno(); Integer defensaInicialDelMonstruoPropio1 = monstruoPropio1.getDefensa(); Integer defensaInicialDelMonstruoPropio2 = monstruoPropio2.getDefensa(); Integer ataqueInicialDelMonstruoOponente1 = monstruoOponente1.getAtaque(); Integer ataqueInicialDelMonstruoOponente2 = monstruoOponente2.getAtaque(); jugador1.colocarCartaEnCampo((Carta) sogen, new BocaArriba()); jugador1.removerCartaDelCampo(sogen); Assert.assertEquals(defensaInicialDelMonstruoPropio1, monstruoPropio1.getDefensa()); Assert.assertEquals(defensaInicialDelMonstruoPropio2, monstruoPropio2.getDefensa()); Assert.assertEquals(ataqueInicialDelMonstruoOponente1, monstruoOponente1.getAtaque()); Assert.assertEquals(ataqueInicialDelMonstruoOponente2, monstruoOponente2.getAtaque()); } }
package com.qumla.domain.answer; public class CountryResult { private String country; private Long count; private Long max; private String countryname; private Long option; private String text; private Float percent; private Long total; private String region; public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Long getCount() { return count; } public void setCount(Long count) { this.count = count; } public Long getMax() { return max; } public void setMax(Long max) { this.max = max; } public String getCountryname() { return countryname; } public void setCountryname(String countryname) { this.countryname = countryname; } public Long getOption() { return option; } public void setOption(Long option) { this.option = option; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Long getTotal() { return total; } public void setTotal(Long total) { this.total = total; } public Float getPercent() { return percent; } public void setPercent(Float percent) { this.percent = percent; } @Override public Object clone() { CountryResult r=new CountryResult(); r.countryname=this.countryname; r.count=this.count; r.country=this.country; r.max=this.max; r.option=this.option; r.total=this.total; r.region=this.region; r.text=this.text; return r; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } }
package com.cloudaping.cloudaping.utils; import com.cloudaping.cloudaping.entity.productType.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; public class ConvertDuplicate { private static Object getFieldValueByFieldName(String fieldName, Object object) { try { Field field = object.getClass().getDeclaredField(fieldName); //设置对象的访问权限,保证对private的属性的访问 field.setAccessible(true); return field.get(object); } catch (Exception e) { return null; } } public static Map<String,Set<Object>> getNotDuplicate(List<ProductType> list,Integer productType){ Class<?> clazz=null; switch (productType){ case 1: clazz= Mobile.class; break; case 2: clazz= AudioVideo.class; break; case 3: clazz= Laptop.class; break; case 4: clazz= Computer.class; break; case 5: clazz= Camera.class; break; default: clazz= Mobile.class; break; } Map<String,Set<Object>> map=new HashMap<>(); Field[] fields=clazz.getDeclaredFields(); for (Field field:fields){ field.setAccessible(true); String name=field.getName(); map.put(name,new HashSet<>()); } for (int i = 0; i < list.size(); i++) { for (Map.Entry<String, Set<Object>> entry : map.entrySet()){ Object o=getFieldValueByFieldName(entry.getKey(),list.get(i)); if (o instanceof String) o=((String) o).toUpperCase(); map.get(entry.getKey()).add(o); } } return map; } public static void main(String[] args){ Laptop productType=new Laptop(); productType.setLaptopBrand("apple"); Laptop productType1=new Laptop(); productType1.setLaptopBrand("apple"); Laptop productType2=new Laptop(); productType2.setLaptopBrand("dell"); List<ProductType> list=new ArrayList<>(); list.add(productType); list.add(productType1); list.add(productType2); getNotDuplicate(list,1); } }
package com.beike.service.impl.user; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.beike.dao.GenericDao; import com.beike.dao.user.UserAddressDao; import com.beike.entity.user.UserAddress; import com.beike.service.impl.GenericServiceImpl; import com.beike.service.user.UserAddressService; /** * project:beiker * Title: * Description: * Copyright:Copyright (c) 2011 * Company:Sinobo * @author qiaowb * @date Mar 16, 2012 10:59:27 AM * @version 1.0 */ @Service("userAddressService") public class UserAddressServiceImpl extends GenericServiceImpl<UserAddress,Long> implements UserAddressService { @Autowired private UserAddressDao userAddressDao; /* (non-Javadoc) * @see com.beike.service.impl.GenericServiceImpl#getDao() */ @Override public GenericDao getDao() { return userAddressDao; } /* (non-Javadoc) * @see com.beike.service.user.UserAddressService#addUserAddress(com.beike.entity.user.UserAddress) */ @Override public Long addUserAddress(UserAddress address) { return userAddressDao.addUserAddress(address); } /* (non-Javadoc) * @see com.beike.service.user.UserAddressService#getUserAddressById(java.lang.Long) */ @Override public List<UserAddress> getUserAddressByUserId(Long userId) { return userAddressDao.getUserAddressByUserId(userId); } /* (non-Javadoc) * @see com.beike.service.user.UserAddressService#updateUserAddress(com.beike.entity.user.UserAddress) */ @Override public int updateUserAddress(UserAddress address) { return userAddressDao.updateUserAddress(address); } /* (non-Javadoc) * @see com.beike.service.GenericService#findById(java.io.Serializable) */ @Override public UserAddress findById(Long id) { return null; } }
package com.pelephone_mobile.mypelephone.ui.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.pelephone_mobile.R; import com.pelephone_mobile.mypelephone.ui.components.ArialTextView; /** * Created by gali.issachar on 12/12/13. */ public class StoreDeviceDetailsListAdapter extends BaseAdapter { private Context context; private String[] list; public StoreDeviceDetailsListAdapter(Context context, String[] list) { this.context = context; this.list = list; } @Override public int getCount() { return list.length; } @Override public Object getItem(int position) { return list[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null){ convertView = LayoutInflater.from(context).inflate(R.layout.store_device_details_list_item, null,false); } ArialTextView textView = (ArialTextView)convertView.findViewById(R.id.textView); textView.setText(list[position]); parent.getLayoutParams().height = parent.getHeight() + convertView.getHeight(); return convertView; } }
package de.varylab.discreteconformal.plugin; import static java.awt.RenderingHints.KEY_ANTIALIASING; import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON; import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Path2D; import javax.swing.JFrame; public class VMCrashReproduction extends JFrame { private static final long serialVersionUID = 1L; public VMCrashReproduction() { setSize(1000, 1000); setDefaultCloseOperation(EXIT_ON_CLOSE); } @Override public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; Path2D path = new Path2D.Float(); path.append(new Ellipse2D.Double(0.2014256547853074, 0.4506075538048867, 0.2779263027163357, 0.2779263027163357), false); path.append(new Ellipse2D.Double(0.5955270094527079, 0.3041804257465449, 0.18761279304214137, 0.18761279304214137), false); path.append(new Ellipse2D.Double(-0.26794919129277944, -0.2679491912927795, 0.5358983825855589, 0.5358983825855589), false); path.append(new Ellipse2D.Double(-0.4793519570516376, 0.45060755990094614, 0.2779262965084575, 0.2779262965084575), false); g2d.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON); g2d.setStroke(new BasicStroke(.01f)); g2d.translate(100, 100); g2d.scale(100.0, 100.0); g2d.draw(path); } public static void main(String[] args) { new VMCrashReproduction().setVisible(true); } }
package com.sys2017.android_app_test; import java.io.Serializable; /** * Created by N552VW on 2017-08-16. */ public class AlbumItem implements Serializable { String id; String img; String memo; String date; public AlbumItem(String id, String imgUrl, String memo, String date) { this.id = id; this.img = imgUrl; this.memo = memo; this.date = date; } public String getImgUrl() { return img; } public void setImgUrl(String imgUrl) { this.img = imgUrl; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
package com.stk123.repository; import com.stk123.entity.StkPeEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; @Repository public interface StkPeRepository extends JpaRepository<StkPeEntity, String> { default StkPeEntity findOrCreateById(String date) { StkPeEntity stkPeEntity = this.findById(date).orElse(null); if(stkPeEntity == null){ stkPeEntity = new StkPeEntity(); } return stkPeEntity; } StkPeEntity findFirstByReportDate(String reportDate); StkPeEntity findTopByOrderByReportDateDesc(); List<StkPeEntity> findAllByReportDateGreaterThanOrderByReportDateDesc(String date); }
package com.cs192.foodwatch; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; public class RecordSubmenu extends Activity { String id; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_records_submenu); Bundle bundle = getIntent().getExtras(); id = bundle.getString("ID"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_records_submenu, menu); return true; } public void records(View view) { Intent intent =new Intent(getApplicationContext(),Record.class); intent.putExtra("ID", id); startActivity(intent); } public void viewRecords(View view) { Intent intent =new Intent(getApplicationContext(),ViewRecords.class); intent.putExtra("ID", id); startActivity(intent); } public void viewCharts(View view) { Intent intent = new Intent(getApplicationContext(),ViewWeightChart.class); intent.putExtra("ID", id); startActivity(intent); } public void viewCalorieChart(View view) { Intent intent = new Intent(getApplicationContext(), ViewCalorieChart.class); intent.putExtra("ID", id); startActivity(intent); } }
package stepDef; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import junit.framework.Assert; import pages.homepageFacebook; public class stepdeffacebook { WebDriver driver; homepageFacebook hpf; @Given("^user is on the facebook home page$") public void user_is_on_the_facebook_home_page() throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\Agile1Tech\\Desktop\\Selenium Testing libraries\\chromedriver.exe"); driver = new ChromeDriver(); hpf = new homepageFacebook(driver); Thread.sleep(2000); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.navigate().to("https://www.facebook.com/"); Thread.sleep(2000); } @When("^user enters first Name$") public void user_enters_first_Name() { hpf.getFirstName().sendKeys("Michael"); } @When("^user enters last name for signup$") public void user_enters_last_name_for_signup() throws Throwable { hpf.getlastName().sendKeys("jordan"); } @When("^user enters email address$") public void user_enters_email_address() throws Throwable { hpf.getemailphone().sendKeys("michael@gmail.com"); } @When("^user enters new password for signup$") public void user_enters_new_password_for_signup() { } @When("^user select birhtday month$") public void user_select_birhtday_month() { } @When("^user select birth date$") public void user_select_birth_date() throws Throwable { } @When("^user select birth year$") public void user_select_birth_year() { } @When("^use clicks on the sign up button$") public void use_clicks_on_the_sign_up_button() { } @Then("^user should have a new account$") public void user_should_have_a_new_account(){ } @Then("^user should be in the new account home page$") public void user_should_be_in_the_new_account_home_page() { } @When("^user enters invalid first name$") public void user_enters_invalid_first_name() { hpf.getFirstName().sendKeys("56788"); } @When("^user enters invalid last name$") public void user_enters_invalid_last_name() throws Throwable { hpf.getlastName().sendKeys("224"); } @Then("^user should not be able to create a login$") public void user_should_not_be_able_to_create_a_login() { } @Then("^close the browser$") public void close_the_browser() { driver.quit(); } }
/** * */ package net.itinajero.app.service; import net.itinajero.app.model.Noticia; /** * @author Jose Alvaro * */ public interface INoticiasService { /** * * @param noticia */ void guardar(Noticia noticia); }
package assignment4; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; /** * Filter consists of methods that filter a list of tweets for those matching a * condition. * * DO NOT change the method signatures and specifications of these methods, but * you should implement their method bodies, and you may add new public or * private methods or classes if you like. */ public class Filter { /** * Find tweets written by a particular user. * * @param tweets * a list of tweets with distinct ids, not modified by this method. * @param username * Twitter username, required to be a valid Twitter username as * defined by Tweet.getAuthor()'s spec. * @return all and only the tweets in the list whose author is username, * in the same order as in the input list. */ public static List<Tweets> writtenBy(List<Tweets> tweets, String username) { List<Tweets> filteredList = new ArrayList<Tweets>(); //Convert username to lowercase username = username.toLowerCase(); for(Tweets tweet : tweets){ try { String author = validName(tweet.getName()); validId(tweet.getId()); if (username.equals(author.toLowerCase())) { filteredList.add(tweet); } } catch (Exception e) { continue; } } return filteredList; } /** * Find tweets that were sent during a particular timespan. * * @param tweets * a list of tweets with distinct ids, not modified by this method. * @param timespan * timespan * @return all and only the tweets in the list that were sent during the timespan, * in the same order as in the input list. */ public static List<Tweets> inTimespan(List<Tweets> tweets, Timespan timespan) { List<Tweets> filteredList = new ArrayList<Tweets>(); for(Tweets tweet : tweets){ try { validDate(tweet.getDate()); Instant date = Instant.parse(tweet.getDate()); validId(tweet.getId()); if (date.isAfter(timespan.getStart()) && date.isBefore(timespan.getEnd())) { filteredList.add(tweet); } } catch(Exception e){ continue; } } return filteredList; } /** * Find tweets that contain certain words. * * @param tweets * a list of tweets with distinct ids, not modified by this method. * @param words * a list of words to search for in the tweets. * A word is a nonempty sequence of nonspace characters. * @return all and only the tweets in the list such that the tweet text (when * represented as a sequence of nonempty words bounded by space characters * and the ends of the string) includes *at least one* of the words * found in the words list. Word comparison is not case-sensitive, * so "Obama" is the same as "obama". The returned tweets are in the * same order as in the input list. */ public static List<Tweets> containing(List<Tweets> tweets, List<String> words) { List<Tweets> filteredList = new ArrayList<Tweets>(); for(Tweets tweet : tweets){ try { String body = validText(tweet.getText()); validId(tweet.getId()); if (compareText(body, words)) { filteredList.add(tweet); } } catch (Exception e) { continue; } } return filteredList; } //Search if any of the given list of words is in the string public static boolean compareText(String text, List<String> words){ text = text.toLowerCase(); ListIterator wordIt = words.listIterator(); while(wordIt.hasNext()){ String word = wordIt.next().toString().toLowerCase(); if(text.contains(word)){ return true; } } return false; } //Tests if name is valid public static String validName(String name) throws Exception { if(name == null){ throw new Exception("illegal name"); } for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); //Valid chars are a-z, A-Z, 0-9, _ if (!Character.isLetter(c) && !Character.isDigit(c) && !(c == '_')) { throw new Exception("illegal name"); } } return name; } //tests if text is valid public static String validText(String text) throws Exception{ if(text == null){ throw new Exception("illegal text"); } if(text.length() > 140){ throw new Exception("illegal text"); } return text; } //Tests if id is valid public static int validId(int id) throws Exception{ if (id < 1 || id > Math.pow(2, 32)) { throw new Exception("illegal id"); } return id; } //Tests if date is valid public static String validDate(String date) throws Exception{ if(date.length() != 20){ throw new Exception("illegal date"); } if(!Character.isDigit(date.charAt(0)) || !Character.isDigit(date.charAt(1)) || !Character.isDigit(date.charAt(2)) || !Character.isDigit(date.charAt(3))){ throw new Exception("illegal date"); } if(date.charAt(4) != '-' || date.charAt(7) != '-'){ throw new Exception("illegal date"); } if(!Character.isDigit(date.charAt(5)) || !Character.isDigit(date.charAt(6))){ throw new Exception("illegal date"); } if(!Character.isDigit(date.charAt(8)) || !Character.isDigit(date.charAt(9)) || !Character.isDigit(date.charAt(11)) || !Character.isDigit(date.charAt(12)) || !Character.isDigit(date.charAt(14)) || !Character.isDigit(date.charAt(15)) || !Character.isDigit(date.charAt(17)) || !Character.isDigit(date.charAt(18))){ throw new Exception("illegal date"); } if(date.charAt(10) != 'T' || date.charAt(13) != ':' || date.charAt(16) != ':' || date.charAt(19) != 'Z'){ throw new Exception("illegal date"); } return date; } }
package com.zhaoyan.ladderball.dao.eventofmatch; import com.zhaoyan.ladderball.domain.eventofmatch.db.EventOfMatch; import java.util.List; public interface EventOfMatchDao { /** * 事件的uuid是否重复 */ boolean isEventUUIDRepeated(String uuid); /** * 添加一个事件 */ void addEvent(EventOfMatch eventOfMatch); /** * 更新事件 */ void updateEvent(EventOfMatch eventOfMatch); /** * 获取球员的一个事件总数 */ int getEventCountByPlayer(int eventCode, long playerId); /** * 获取比赛一小节的事件 */ List<EventOfMatch> getEventPartList(long matchId, long teamId, int partNumber); /** * 删除比赛一小节中的小节结束事件 */ void deleteXiaoJieJieShuEvent(long matchId, long teamId, int partNumber, int eventCode); /** * 根据id获取事件 */ EventOfMatch getEventBy(long eventId); /** * 删除一个事件 */ void deleteEvent(EventOfMatch eventOfMatch); }
// File : Cell.java // PIC : Letivany Aldina - 13514067 /** * * @author Letivany Aldina - 13514067 */ abstract class Cell implements Renderable { private int x; private int y; private String tipeCell; /** * konstruktor sebuah Cell * @param x posisi x sebuah Cell * @param y posisi y sebuah Cell */ public Cell (int x, int y){ this.x = x; this.y = y; } /** * mendapatkan tipe sebuah Cell * @param s simbol dari Cell * @return string tipe Cell */ public abstract String getTipeCell(); /** * mendapatkan posisi x * @return nilai x */ public int getX(){ return x; } /** * mendapatkan posisi y * @return nilai y */ public int getY(){ return y; } /** * set nilai x * @param x nilai x yang diset */ public void setX(int x){ this.x = x; } /** * set nilai y * @param y nilai y yang diset */ public void setY(int y){ this.y = y; } }
package com.qust.mapper; import com.qust.model.tkb_Prorelation; public interface tkb_ProrelationMapper { int deleteByPrimaryKey(Integer id); int insert(tkb_Prorelation record); int insertSelective(tkb_Prorelation record); tkb_Prorelation selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(tkb_Prorelation record); int updateByPrimaryKey(tkb_Prorelation record); }
package com.emiza.exception; import com.emiza.constants.Constant; public class DivideByZero extends RuntimeException { /** * */ private static final long serialVersionUID = 8674526552568884728L; public DivideByZero() { super(Constant.DIVIDE_BY_ZERO); } }
package com.capstone.kidinvest.repositories; import com.capstone.kidinvest.models.Business; import com.capstone.kidinvest.models.Ingredient; import com.capstone.kidinvest.models.Inventory; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface InventoryRepo extends JpaRepository<Inventory, Long> { List<Inventory> findInventoryByBusinessId(long businessId); Inventory getInventoryByBusinessIdAndIngredientId(long business_id, long ingredient_id); @Query(nativeQuery = true, value = "SELECT total FROM inventory WHERE business_id = ?1 && ingredient_id = ?2") long findTotalByBusinessIdAAndIngredientId(long business_id, long ingredient_id); // @Query(nativeQuery = true, value = "SELECT * FROM inventory WHERE business_id = ?1 && ingredient_id = ?2") // Inventory findInventoryByBusinessIdAndIngredientId(long business_id, long ingredient_id); }
package us.gibb.dev.gwt.server.inject; import static com.google.inject.matcher.Matchers.annotatedWith; import static com.google.inject.matcher.Matchers.not; import static com.google.inject.matcher.Matchers.subclassesOf; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import us.gibb.dev.gwt.command.Dispatch; import us.gibb.dev.gwt.server.command.handler.CommandHandler; import us.gibb.dev.gwt.server.command.handler.CommandHandlerRegistry; import com.google.inject.AbstractModule; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; public class DispatchModule extends AbstractModule { private ArrayList<Package> packages; private Set<Class<?>> classes; @Override protected void configure() { requireBinding(CommandHandlerRegistry.class); requireBinding(Dispatch.class); packages = new ArrayList<Package>(); classes = new HashSet<Class<?>>(); configureDispatch(); for (Package pkg : packages) { classes.addAll(Classes.matching(subclassesOf(CommandHandler.class).and(not(annotatedWith(DispatchIgnore.class)))).in(pkg)); } classes.remove(CommandHandler.class); bind(new TypeLiteral<Set<Class<?>>>() {}) .annotatedWith(Names.named("command.handler.classes")) .toInstance(classes); System.out.println(classes); //TODO move to log } protected void configureDispatch() { } protected void scan(Package pkg) { assert pkg != null; packages.add(pkg); } protected <CH extends CommandHandler<?, ?>> void addCommandHandler(Class<CH> clazz) { classes.add(clazz); } }
package com.leetcode; public class ReverseWords { public static void main(String [] args) { ReverseWords t = new ReverseWords(); System.out.println(t.reverseWord(" she is my sin ") + "."); System.out.println(t.reverseWord2(" she is my sin ") + "."); } public String reverseWord(String s) { StringBuffer reversed = new StringBuffer(); int j = s.length(); for (int i = s.length() - 1; i >=0; i--) { if (s.charAt(i) == ' ') { j = i; } else if (i == 0 || s.charAt(i - 1) == ' ') { if (reversed.length() != 0) reversed.append(' '); reversed.append(s.substring(i, j)); } } return reversed.toString(); } public String reverseWord2(String s) { String [] temp = s.split(" +", -1); System.out.println(String.valueOf(temp.length)); String reversed = ""; for (int i = temp.length - 1; i >= 0; i--) { System.out.println(temp[i] + "."); if (temp[i].length() != 0) { if (reversed.length() != 0) reversed = reversed + " " + temp[i]; else reversed = reversed + temp[i]; } } return reversed; } }
package dao; import java.util.List; import enterprise.Personel; public interface PersonelDAO { public void createOlustur1(Personel personel); public void createOlustur2(Personel personel); public Personel readOku1(int id); public Personel readOku2(int id); public void updateGuncelle1(Personel personel, int id); public void updateGuncelle2(Personel personel, int id); public void deleteSil1(int id); public void deleteSil2(int id); public List<Personel> getAllHepsiniGetir1(); public List<Personel> getAllHepsiniGetir2(); }
import java.util.*; public class Main{ public static class Node{ int data; ArrayList<Node> children = new ArrayList<>(); } public static void main(String[] args) { int[] arr = {10,20,50,-1,60,-1,-1,30,70,-1,-1,40,80,-1,90,100,-1,-1,-1,-1}; Stack<Node> st = new Stack<>(); Node root = null; for(int i = 0; i<arr.length; i++){ // if -1 then it means no more children so pop the node if( arr[i] == -1){ st.pop(); } else{ Node t = new Node(); t.data = arr[i]; // if st.size()==0 , it means it is the first node i.e root if(st.size() == 0){ root = t; }else{ st.peek().children.add( t ); } st.push(t); } } display(root); } public static void display(Node root){ System.out.print(root.data + " -> "); for(Node child : root.children){ System.out.print(child.data +", "); } System.out.println("."); for(Node child : root.children){ display(child); } } }
package cn.edu.cugb.information_program.go_test; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MyFragment extends Fragment { private int choice; public MyFragment(int choice) { this.choice = choice; } private void initsumenu() { for (int i = 0; i < 1; i++) { submenu apple = new submenu("个人资料", R.drawable.camera_back_default); submenuList.add(apple); submenu banana = new submenu("修改密码", R.drawable.camera_back_default); submenuList.add(banana); submenu pear = new submenu("通用设置", R.drawable.camera_back_default); submenuList.add(pear); submenu cherry = new submenu("应用反馈", R.drawable.camera_back_default); submenuList.add(cherry); submenu mango = new submenu("切换账号", R.drawable.camera_back_default); submenuList.add(mango); } } private String[] data = {"个人资料", "修改密码", "通用设置", "应用反馈", "切换账号"}; private List<submenu> submenuList = new ArrayList<>(); public EditText origin; public EditText destination; public EditText month; public EditText day; public EditText number; public EditText comment; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /********************************************************************************************/ /********************************************************************************************/ /********************************************************************************************/ switch (choice) { case 1: View view = inflater.inflate(R.layout.mainview1, container, false); /********************************************************/ /********************************************************/ return view; case 2: View view2 = inflater.inflate(R.layout.mainview2, container, false); /********************************************************/ origin = (EditText) view2.findViewById(R.id.editText2); destination = (EditText) view2.findViewById(R.id.editText3); number = (EditText) view2.findViewById(R.id.editText4); month = (EditText) view2.findViewById(R.id.editText5); day = (EditText) view2.findViewById(R.id.editText6); comment = (EditText) view2.findViewById(R.id.editText7); Button button_matching = (Button) view2.findViewById(R.id.button_matching); button_matching.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "正在匹配,请稍等...", Toast.LENGTH_SHORT).show(); Intent intent_matching = new Intent(getActivity(), MatchingActivity.class); String originstr= origin.getText().toString(); String destinationstr= destination.getText().toString(); String numberstr= number.getText().toString(); String monthstr= month.getText().toString(); String daystr= day.getText().toString(); String commentstr=comment.getText().toString(); intent_matching.putExtra("origin",originstr); intent_matching.putExtra("destination",destinationstr); intent_matching.putExtra("number",numberstr); intent_matching.putExtra("month",monthstr); intent_matching.putExtra("day",daystr); intent_matching.putExtra("comment",commentstr); startActivity(intent_matching); } }); /********************************************************/ return view2; case 3: View view3 = inflater.inflate(R.layout.mainview3, container, false); /********************************************************/ /********************************************************/ return view3; case 4: View view4 = inflater.inflate(R.layout.mainview4, container, false); /********************************************************/ initsumenu(); submenuAdapter adapter = new submenuAdapter(getActivity(), R.layout.submenu_item, submenuList); ListView listView = (ListView) view4.findViewById(R.id.list_view); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { submenu submenu = submenuList.get(position); Toast.makeText(getActivity(), submenu.getName(), Toast.LENGTH_SHORT).show(); } }); /********************************************************/ return view4; } View view5 = inflater.inflate(R.layout.mainview_error, container, false); return view5; } /************************************************************************************************/ }
package ru.goodroads.data; import java.io.Serializable; import java.lang.annotation.Retention; import java.util.Date; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") public class Hole implements Serializable { private static final long serialVersionUID = -8606143116953832890L; @SerializedName("lat") private double lat; @SerializedName("lng") private double lon; @SerializedName("holeSize") private double size; @SerializedName("holeType") private int type = Type.Auto.ordinal(); @SerializedName("Aclx") private float aclX; @SerializedName("Acly") private float aclY; @SerializedName("Aclz") private float aclZ; @SerializedName("speed") private float speed; @SerializedName("Date") private long time; public enum Type { Auto, UserDefined; } public Hole() { this.time = new Date().getTime(); } public Hole setSize(double size) { this.size = size; return this; } public double getSize() { return size; } public Hole setType(Type type) { this.type = type.ordinal(); return this; } public Hole setSpeed(float speed) { this.speed = speed; return this; } public Hole setLocation(double lat, double lon) { this.lat = lat; this.lon = lon; return this; } public double getLat() { return lat; } public double getLon() { return lon; } public Hole setAccelerometer(float aclX, float aclY, float aclZ) { this.aclX = aclX; this.aclY = aclY; this.aclZ = aclZ; return this; } }
package com.tyj.venus.service.impl; import com.tyj.venus.entity.UserMsg; import com.tyj.venus.service.UserMsgService; import org.springframework.stereotype.Service; @Service("userMsgService") public class UserMsgServiceImpl extends BaseServiceImpl<UserMsg,Integer> implements UserMsgService { }
import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import processing.video.*; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class lineNoise1 extends PApplet { PImage back ; Movie bk; NoiseyLine [] noises = new NoiseyLine[100]; int[] noisescolors = new int[noises.length]; int z = 0; int b = 0; int ha = 0; int add; int addd; int create = 10; public boolean sketchFullScreen() { return true; } public void setup(){ size(displayWidth, displayHeight); frameRate(30); smooth(); strokeCap(PROJECT); noCursor(); for (int i=0; i<noises.length; i++){ //new noiseyline(start, end, y, tall, steps) noisescolors[i] = color((int)random(100)+100); // noises[i] = new NoiseyLine(width - 2*(int)random(width),width +100, (int)(height/4+ random(1,height/2)),(int)random(1,20),(int)random(7,14)); noises[i] = new NoiseyLine((int)random(width) - 400,width, (int)(height/4+ random(1,height/2)),(int)random(1,20),(int)random(7,40)); } bk = new Movie(this, "garbage.mov"); bk.loop(); bk.speed(0.5f); back = loadImage("background.jpg"); // NoiseyLine one = new NoiseyLine(50,800, height/2, 50, 10); } // Called every time a new frame is available to read public void movieEvent(Movie m) { m.read(); } public void draw(){ // background(z); // bk.jump(random(bk.duration())); image(back, 0, 0, width, height); if(z ==0){ add = 1; } else if (z == 200) { add = -1; } if(frameCount%3 == 0){ z+= add; } for(int i=0; i<noises.length; i++){ stroke(noisescolors[i]); strokeCap(ROUND); strokeWeight(random(1,13)); noises[i].drawRunner(); } // for (int i = 0; i<(noises.length/20); i++){ // strokeCap(ROUND); // strokeWeight(5); // // stroke(255-z, 50+ z/4, 60 + Z/2); // stroke(0,30); // noises[(int)random(noises.length)].drawNoiseyLine(); // } filter(DILATE); tint(100, 155); if (frameCount% 10 == 0){ create += addd; } if (create == 10){ addd = 1; } else if (create == noises.length) { addd = -1; } } class NoiseyLine{ int step, vert, start, end, tall, x; float lastX, lastY; NoiseyLine(int xStart, int xEnd, int why, int talll, int steps){ step = steps; lastX = -999; lastY = -999; vert = why; start = xStart; end = xEnd; tall = talll; x = start; } public void drawNoiseyLine(){ for ( x = start; x <= end; x+=step){ float y = vert + random(-tall,tall); if (lastX> -999){ line(x, y, lastX, lastY); } lastX = x; lastY = y; } if ( x >=end){ x = start; lastX = -999; lastY = -999; } } public void drawRunner(){ float y = vert + noise(random(-tall,tall))*random(1,30); if(lastX> -999){ line(x, y, lastX, lastY); noStroke(); // ellipse(x+random(-100, 100), y + random(-100, 100), 5, 5); } lastX = x; lastY = y; if ( x >=end){ x = start; lastX = -999; lastY = -999; } x+=step; } } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "lineNoise1" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } }
package com.exam.controller; import com.alibaba.fastjson.JSONObject; import com.exam.entity.User; import com.exam.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/index") public class UserController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired @Qualifier("userService") private UserService userService; @RequestMapping(value = "/testController1", method = RequestMethod.GET) @ResponseBody public JSONObject indexTest() { int i = userService.testContoller(); JSONObject jsonObject = new JSONObject(); jsonObject.put("test",i); return jsonObject; } @RequestMapping(value = "/testController2", method = RequestMethod.GET) public String indexTest2() { return "home"; } @RequestMapping("/query") public String query(@RequestParam(value = "username",required = true) String username, Model model) { User user = new User(); user = userService.queryByUserName(username); model.addAttribute("user",user); return "test"; } }
package com.beadhouse.dao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.beadhouse.domen.Contact; @Mapper public interface ContactsMapper { void insertContact(Contact contact); Contact selectBycontacts(Contact contact); List<Contact> selectByLoginUserId(Integer loginUserId); List<Contact> selectByElderUserId(Integer elderUserId); }
package com.jgw.supercodeplatform.trace.common.cache; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.jgw.supercodeplatform.trace.dao.mapper1.TraceFunFieldConfigMapper; import com.jgw.supercodeplatform.trace.exception.SuperCodeTraceException; import com.jgw.supercodeplatform.trace.pojo.TraceFunFieldConfig; @Component public class FunctionFieldCache { private static Logger logger = LoggerFactory.getLogger(FunctionFieldCache.class); public static List<String> defaultCreateFields=new ArrayList<>(Arrays.asList(new String[]{"UserId","ProductId","TraceBatchInfoId","OrganizationId","TraceTemplateId","SysId","Id","SortDateTime","DeleteStatus","ParentId"})); @Autowired private TraceFunFieldConfigMapper traceFunFieldConfigDao; /** * @author czm |fieldCode1-->{fieldType,....} | the map pattern functionId * :|fieldCode2-->{fieldType,....} | |fieldCode3-->{fieldType,....} * */ private static volatile Map<String, Map<String, TraceFunFieldConfig>> functionFieldMap = new HashMap<String, Map<String, TraceFunFieldConfig>>(); /** * 暂时去除缓存 * @param traceTemplateId * @param functionId * @param typeClass * @return * @throws SuperCodeTraceException */ public Map<String, TraceFunFieldConfig> getFunctionIdFields(String traceTemplateId,String functionId,int typeClass) throws SuperCodeTraceException { if (StringUtils.isBlank(functionId)) { throw new SuperCodeTraceException("functionId不能为空", 500); } Map<String, TraceFunFieldConfig> fieldsMap = new LinkedHashMap <String, TraceFunFieldConfig>(); List<TraceFunFieldConfig> fieldConfigList =null; if (1==typeClass) { fieldConfigList =traceFunFieldConfigDao.selectDZFPartFieldsByFunctionId(functionId); }else { fieldConfigList = traceFunFieldConfigDao.selectPartTraceTemplateIdAndNodeFunctionId(traceTemplateId,functionId); } if (null == fieldConfigList || fieldConfigList.isEmpty()) { logger.info("获取功能字段信息无法更加功能id:" + functionId + "查询到字段信息"); return null; } for (TraceFunFieldConfig traceFunFieldConfig : fieldConfigList) { fieldsMap.put(traceFunFieldConfig.getFieldCode(), traceFunFieldConfig); } return fieldsMap; // String mapKey = functionId; // //如果节点类型不为空则表示请求节点字段属性 // if (2==typeClass) { // if (StringUtils.isBlank(traceTemplateId)) { // throw new SuperCodeTraceException("节点获取功能字段必须传模板id", 500); // } // mapKey = traceTemplateId + functionId; // } // logger.info("获取字段信息,traceTemplateId="+traceTemplateId+",functionId="+functionId+",typeClass="+typeClass); // Map<String, TraceFunFieldConfig> fieldsMap = functionFieldMap.get(mapKey); // if (null == fieldsMap) { // synchronized (this) { // // volatile语义保证functionFieldMap写入操作会立即写入主存线程读取也直接从主存读取,当前线程释放锁之后保证functionFieldMap有对应functionId数据除非数据库种无数据 // fieldsMap = functionFieldMap.get(functionId); // if (null == fieldsMap) { // fieldsMap = new LinkedHashMap <String, TraceFunFieldConfig>(); // List<TraceFunFieldConfig> fieldConfigList =null; // if (1==typeClass) { // fieldConfigList =traceFunFieldConfigDao.selectDZFPartFieldsByFunctionId(functionId); // }else { // fieldConfigList = traceFunFieldConfigDao.selectPartTraceTemplateIdAndNodeFunctionId(traceTemplateId,functionId); // } // if (null == fieldConfigList || fieldConfigList.isEmpty()) { // logger.info("获取功能字段信息无法更加功能id:" + functionId + "查询到字段信息"); // return null; // } // for (TraceFunFieldConfig traceFunFieldConfig : fieldConfigList) { // fieldsMap.put(traceFunFieldConfig.getFieldCode(), traceFunFieldConfig); // } // functionFieldMap.put(functionId, fieldsMap); // } // } // } } public void flush(String traceTemplateId,String functionId,int typeClass) throws SuperCodeTraceException { if (StringUtils.isBlank(functionId)) { throw new SuperCodeTraceException("functionId不能为空", 500); } String mapKey = functionId; if (2==typeClass) { if (StringUtils.isBlank(traceTemplateId)) { throw new SuperCodeTraceException("节点获取功能字段必须传模板id", 500); } mapKey = traceTemplateId + functionId; } synchronized (this) { Map<String, TraceFunFieldConfig> fieldsMap = functionFieldMap.get(mapKey); if (null == fieldsMap) { fieldsMap = new HashMap<String, TraceFunFieldConfig>(); } List<TraceFunFieldConfig> fieldConfigList =null; if (1==typeClass) { fieldConfigList =traceFunFieldConfigDao.selectDZFPartFieldsByFunctionId(functionId); }else { fieldConfigList = traceFunFieldConfigDao.selectPartTraceTemplateIdAndNodeFunctionId(traceTemplateId,functionId); } if (null == fieldConfigList || fieldConfigList.isEmpty()) { logger.info("获取功能字段信息无法更加功能id:" + functionId + "查询到字段信息"); return; } for (TraceFunFieldConfig traceFunFieldConfig : fieldConfigList) { fieldsMap.put(traceFunFieldConfig.getFieldCode(), traceFunFieldConfig); } functionFieldMap.put(functionId, fieldsMap); } } }
package com.beike.common.bean.trx.partner; import java.util.Date; import java.util.List; /** * Title : ParT800OrderParam.java <br/> * Description : 800传入信息转换后的参数集<br/> * Company : Sinobo <br/> * Copyright : Copyright (c) 2010-2012 All rights reserved.<br/> * Created : 2012-11-7 上午10:55:13 <br/> * * @author Wenzhong Gu * @version 1.0 */ public class ParT800OrderParam { // 订单同步请求参数 /** * 平台goodsId */ private String goodsId; private String totalPrice; /** * 800支付价格 */ private String payPrice; /** * 商品数量 */ private String prodCount; /** * 订单创建时间 */ private String createDate; /** * 订单支付时间 */ private String payDate; /** * 用户手机号 */ private String mobile; /** * 订单状态 */ private String state; // 退款请求参数 /** * 订单状态 */ private String status; /** * 发货方 */ private String sender; /** * 短信模板 */ private String smsTemplate; /** * 商品订单号 */ private String trxGoodsSn; /** * 第三方券Id(我侧voucherId) * TODO 目前发的是券码 */ private String voucherId; /** * 券码 */ private String voucherCode; /** * 订单号 */ private String orderId; /** * 第三方订单号(流水号) */ private String externalId; /** * 团800订单号 */ private String outRequestId; /** * 团800券开始时间 */ private Date startTime; /** * 团800券失效时间 */ private Date endTime; /** * 分销商对应用户ID */ private Long userId; private String partnerId; private String reason;// 退款原因 private List<Long> userIdList; /** * 商家goodsId */ private String outGoodsId; /** * 客户端IP */ private String clientIp = "";// 客户端IP /** * @return the goodsId */ public String getGoodsId() { return goodsId; } /** * @return the totalPrice */ public String getTotalPrice() { return totalPrice; } /** * @param totalPrice the totalPrice to set */ public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } /** * @param goodsId * the goodsId to set */ public void setGoodsId(String goodsId) { this.goodsId = goodsId; } /** * @return the payPrice */ public String getPayPrice() { return payPrice; } /** * @param payPrice * the payPrice to set */ public void setPayPrice(String payPrice) { this.payPrice = payPrice; } /** * @return the prodCount */ public String getProdCount() { return prodCount; } /** * @param prodCount * the prodCount to set */ public void setProdCount(String prodCount) { this.prodCount = prodCount; } /** * @return the createDate */ public String getCreateDate() { return createDate; } /** * @param createDate * the createDate to set */ public void setCreateDate(String createDate) { this.createDate = createDate; } /** * @return the payDate */ public String getPayDate() { return payDate; } /** * @param payDate * the payDate to set */ public void setPayDate(String payDate) { this.payDate = payDate; } /** * @return the mobile */ public String getMobile() { return mobile; } /** * @param mobile * the mobile to set */ public void setMobile(String mobile) { this.mobile = mobile; } /** * @return the status */ public String getStatus() { return status; } /** * @param status * the status to set */ public void setStatus(String status) { this.status = status; } /** * @return the trxGoodsSn */ public String getTrxGoodsSn() { return trxGoodsSn; } /** * @param trxGoodsSn * the trxGoodsSn to set */ public void setTrxGoodsSn(String trxGoodsSn) { this.trxGoodsSn = trxGoodsSn; } /** * @return the voucherId */ public String getVoucherId() { return voucherId; } /** * @param voucherId * the voucherId to set */ public void setVoucherId(String voucherId) { this.voucherId = voucherId; } /** * @return the orderId */ public String getOrderId() { return orderId; } /** * @param orderId * the orderId to set */ public void setOrderId(String orderId) { this.orderId = orderId; } /** * @return the externalId */ public String getExternalId() { return externalId; } /** * @param externalId * the externalId to set */ public void setExternalId(String externalId) { this.externalId = externalId; } /** * @return the startTime */ public Date getStartTime() { return startTime; } /** * @param startTime * the startTime to set */ public void setStartTime(Date startTime) { this.startTime = startTime; } /** * @return the endTime */ public Date getEndTime() { return endTime; } /** * @param endTime * the endTime to set */ public void setEndTime(Date endTime) { this.endTime = endTime; } /** * @return the userId */ public Long getUserId() { return userId; } /** * @param userId * the userId to set */ public void setUserId(Long userId) { this.userId = userId; } /** * @return the reason */ public String getReason() { return reason; } /** * @param reason * the reason to set */ public void setReason(String reason) { this.reason = reason; } /** * @return the userIdList */ public List<Long> getUserIdList() { return userIdList; } /** * @param userIdList * the userIdList to set */ public void setUserIdList(List<Long> userIdList) { this.userIdList = userIdList; } /** * @return the outGoodsId */ public String getOutGoodsId() { return outGoodsId; } /** * @param outGoodsId * the outGoodsId to set */ public void setOutGoodsId(String outGoodsId) { this.outGoodsId = outGoodsId; } /** * @return the clientIp */ public String getClientIp() { return clientIp; } /** * @param clientIp * the clientIp to set */ public void setClientIp(String clientIp) { this.clientIp = clientIp; } /** * @return the state */ public String getState() { return state; } /** * @param state * the state to set */ public void setState(String state) { this.state = state; } /** * @return the sender */ public String getSender() { return sender; } /** * @param sender * the sender to set */ public void setSender(String sender) { this.sender = sender; } /** * @return the smsTemplate */ public String getSmsTemplate() { return smsTemplate; } /** * @param smsTemplate * the smsTemplate to set */ public void setSmsTemplate(String smsTemplate) { this.smsTemplate = smsTemplate; } /** * @return the voucherCode */ public String getVoucherCode() { return voucherCode; } /** * @param voucherCode * the voucherCode to set */ public void setVoucherCode(String voucherCode) { this.voucherCode = voucherCode; } /** * @return the outRequestId */ public String getOutRequestId() { return outRequestId; } /** * @param outRequestId the outRequestId to set */ public void setOutRequestId(String outRequestId) { this.outRequestId = outRequestId; } /** * @return the partnerId */ public String getPartnerId() { return partnerId; } /** * @param partnerId the partnerId to set */ public void setPartnerId(String partnerId) { this.partnerId = partnerId; } }
package br.com.douglastuiuiu.biometricengine.model.document; import br.com.douglastuiuiu.biometricengine.model.dto.DocumentDTO; import br.com.douglastuiuiu.biometricengine.model.enumeration.DocumentTypeEnum; import org.springframework.data.mongodb.core.mapping.Field; /** * @author douglas * @since 23/03/2017 */ @org.springframework.data.mongodb.core.mapping.Document(collection = "document") public class Document extends File { @Field private DocumentTypeEnum type; public Document(DocumentTypeEnum type) { setType(type); } public static Document parseDocument(DocumentDTO documentDTO) { Document document = new Document(documentDTO.getType()); return document; } public DocumentTypeEnum getType() { return type; } public void setType(DocumentTypeEnum type) { this.type = type; } }
package org.vpontus.vuejs.web.rest; import io.micrometer.core.annotation.Timed; import lombok.extern.log4j.Log4j2; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.bind.annotation.*; import org.vpontus.vuejs.domain.User; import org.vpontus.vuejs.repository.UserRepository; import org.vpontus.vuejs.security.AuthoritiesConstrants; import org.vpontus.vuejs.security.SecurityUtils; import org.vpontus.vuejs.service.UserService; import org.vpontus.vuejs.service.dto.UserDTO; import org.vpontus.vuejs.web.rest.errors.OperationNotAllowedException; import org.vpontus.vuejs.web.rest.errors.UserNotFoundException; import org.vpontus.vuejs.web.rest.util.HeaderUtil; import org.vpontus.vuejs.web.rest.util.PaginationUtil; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * @author vpontus */ @Log4j2 @RestController @RequestMapping("/api") public class UserResource { private final UserService userService; private final UserRepository userRepository; public UserResource(UserService userService, UserRepository userRepository) { this.userService = userService; this.userRepository = userRepository; } @PostMapping("/admin/users") @Timed @PreAuthorize("hasRole(\""+ AuthoritiesConstrants.ADMIN+"\")") public ResponseEntity<UserDTO> createUser(@Valid @RequestBody UserDTO userDTO) throws URISyntaxException { log.debug("Rest request to save user: {}",userDTO); if (userRepository.findUserByUsername(userDTO.getUsername()).isPresent()) { throw new UserNotFoundException("username-" + userDTO.getUsername()); } else { User newUser = userService.createUser(userDTO); return ResponseEntity.created(new URI("/api/users/" + newUser.getId())).headers(HeaderUtil.createAlert("A user is created with id" + newUser.getId(), newUser.getId().toString())).body(new UserDTO(newUser)); } } @PutMapping("/admin/users") @Timed @PreAuthorize("hasRole(\""+ AuthoritiesConstrants.ADMIN+"\")") public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody UserDTO userDTO) { log.debug("Rest request to update User: {}",userDTO.getUsername()); if (!userRepository.findUserByUsername(userDTO.getUsername()).isPresent()) { throw new UsernameNotFoundException("username-"+userDTO.getUsername()); } UserDTO updated = userService.updateUser(userDTO); return new ResponseEntity<>(updated,HttpStatus.ACCEPTED); } @DeleteMapping("/admin/users") @PreAuthorize("hasRole(\""+AuthoritiesConstrants.ADMIN+"\")") @ResponseStatus(HttpStatus.OK) public void deleteUser(@Valid @RequestBody UserDTO userDTO) { log.debug("Rest request to delete User: {}",userDTO.getUsername()); String currentUser = SecurityUtils.getCurrentUserUsername().orElseThrow(()->new UserNotFoundException("Current user not found")); if (userDTO.getUsername().equals(currentUser)) { throw new OperationNotAllowedException("Self delete not allowed"); } userService.deleteUser(userDTO); } @GetMapping("/admin/users") @Timed public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) { log.debug("Rest request to get all managed users"); final Page<UserDTO> page = userService.getAllManagedUsers(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page,"/api/admin/users"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } // TODO: implement Admin change password public ResponseEntity<UserDTO> getUser(@PathVariable Long id) { log.debug("Rest request User: {}",id); Optional<User> user = userService.getUserWithAuthorities(id); if (user.isPresent()) { UserDTO dto = new UserDTO(user.get()); return ResponseEntity.ok(dto); } else throw new UserNotFoundException("id-" + id); } }
package com.gaoshin.stock; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.view.View; import android.widget.LinearLayout; import android.widget.ScrollView; import com.gaoshin.sorma.SORMA; import com.gaoshin.stock.model.ConfigurationServiceImpl; import com.gaoshin.stock.model.GroupItem; import com.gaoshin.stock.model.StockContentProvider; import com.gaoshin.stock.model.StockGroup; public class GroupItemsView extends ScrollView { public static interface SymbolChangedListener { void onSymbolChanged(Integer groupItemId); } private SORMA sorma = null; private List<SymbolView> symViewList = new ArrayList<SymbolView>(); private int current = 0; private LinearLayout container; private SymbolChangedListener symbolChangedListener; private ConfigurationServiceImpl confService; private StockGroup stockGroup; public GroupItemsView(Context context) { super(context); this.setPadding(0, 0, 0, 0); sorma = SORMA.getInstance(context, StockContentProvider.class); confService = new ConfigurationServiceImpl(sorma); setId(Math.abs(this.hashCode())); setBackgroundColor(Color.WHITE); setFadingEdgeLength(0); container = new LinearLayout(context); container.setPadding(0, 0, 0, 0); container.setOrientation(LinearLayout.VERTICAL); addView(container); } public void applyData(StockGroup stockGroup) { symViewList.clear(); current = 0; container.removeAllViews(); this.stockGroup = stockGroup; Integer groupId = stockGroup.getId(); Integer currentItemId = stockGroup.getDefaultItem(); List<GroupItem> items = sorma.select(GroupItem.class, "groupId=?", new String[]{String.valueOf(groupId)}); for(GroupItem item : items) { SymbolView sv = new SymbolView(getContext()); symViewList.add(sv); sv.setGroupItem(item); sv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SymbolView sv = (SymbolView) v; setCurrentSelected(sv.getGroupItem().getId()); } }); sv.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { deleteCurrent(); return true; } }); if(item.getId() == currentItemId) { sv.setSelected(); } container.addView(sv, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); } } public void setCurrentSelected(Integer groupItemId) { symViewList.get(current).setUnselected(); for(int i=0; i<symViewList.size(); i++) { SymbolView sv = symViewList.get(i); if(sv.getGroupItem().getId().equals(groupItemId)) { sv.setSelected(); current = i; stockGroup.setDefaultItem(sv.getId()); } } if(symbolChangedListener != null) { symbolChangedListener.onSymbolChanged(groupItemId); } } public int getCurrentSelected() { return current; } public void addGroupItem(GroupItem groupItem) { SymbolView sv = new SymbolView(getContext()); sv.setGroupItem(groupItem); sv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SymbolView sv = (SymbolView) v; setCurrentSelected(sv.getGroupItem().getId()); } }); sv.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { deleteCurrent(); return true; } }); container.addView(sv, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); symViewList.add(sv); setCurrentSelected(groupItem.getId()); getHandler().post(new Runnable() { @Override public void run() { fullScroll(ScrollView.FOCUS_DOWN); } }); } private void deleteCurrent() { new AlertDialog.Builder(getContext()) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage("Are you sure to delete this symbol " + symViewList.get(current).getGroupItem().getSym() + "?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { sorma.delete(symViewList.get(current).getGroupItem()); container.removeView(symViewList.get(current)); symViewList.remove(current); if(current > (symViewList.size()-1)) { current--; } if(current>=0) { symViewList.get(current).setBackgroundColor(Color.LTGRAY); if(symbolChangedListener != null) { symbolChangedListener.onSymbolChanged(symViewList.get(current).getGroupItem().getId()); } } } }) .setNegativeButton("No", null) .show(); } public SymbolChangedListener getSymbolChangedListener() { return symbolChangedListener; } public void setSymbolChangedListener(SymbolChangedListener symbolChangedListener) { this.symbolChangedListener = symbolChangedListener; } }
package cn.math.fibonacciSequence; import cn.math.arithmeticSeries.ArithmeticSeries; import cn.math.geometricSeries.GeometricSeries; import lombok.extern.slf4j.Slf4j; import javax.swing.*; import java.awt.*; /** * Created by xiaoni on 2019/8/17. * 斐波那契弧线 */ @Slf4j public class FibonacciArc extends JPanel { //初始原点 private final static int WIDTH = 1000; private final static int HEIGHT = 1000; private final static int X0 = WIDTH / 2; private final static int Y0 = HEIGHT / 2; //缩放倍数, 越大,越缩小(看到的螺旋越多) private final static int ZOOM = 1; //画几阶弧线 private final static int N = 30; //画函数类型常量 //斐波纳挈 private final static int FUNCTION_FIBONACCI = 1; //等差级数 private final static int FUNCTION_ARITHMETIC_SERIES = 2; //等比级数 private final static int FUNCTION_GEOMETIRC_SERIES = 3; public FibonacciArc() { //默认斐波纳挈 this.functionTypeId = FUNCTION_FIBONACCI; } public FibonacciArc(int functionTypeId) { this.functionTypeId = functionTypeId; } /** * 画什么类型的曲线 */ private int functionTypeId; @Override protected void paintComponent(Graphics g) { // TODO Auto-generated method stub super.paintComponent(g); //上一个斐波那契数 int lastFibonacciI = 0; //扇形圆心点 int x = X0; int y = Y0; //java画弧线图工具矩形区域左上角坐标 int xArcRec = x; int yArcRec = y; //java画矩形图工具矩形区域左上角坐标 int xRecRec = x; int yRecRec = y; //计算象限 int startAngle = 0; //要画的度数 int arcAngle = 90; ArithmeticSeries arithmeticSeries = new ArithmeticSeries(1, 10); GeometricSeries geometricSeries = new GeometricSeries(1, 2); //因为左上角是坐标原点,所以计算坐标平移量时要反着来 for (int i = 3; i < N; i++) { //计算斐波那契数 int fibonacciI; switch (functionTypeId) { case FUNCTION_FIBONACCI: fibonacciI = FibonacciSequence.f(i); break; case FUNCTION_ARITHMETIC_SERIES: fibonacciI = arithmeticSeries.f(i); break; case FUNCTION_GEOMETIRC_SERIES: fibonacciI = new Long(geometricSeries.f(i)).intValue(); break; default: fibonacciI = FibonacciSequence.f(i); } int change = fibonacciI - lastFibonacciI; switch (i % 4) { case 0: //第一象限 startAngle = 0; x = x - change; xRecRec = x; yRecRec = y - fibonacciI; break; case 1: //第二象限 startAngle = 90; y = y + change; xRecRec = x - fibonacciI; yRecRec = y - fibonacciI; break; case 2: //第三象限 startAngle = 180; x = x + change; xRecRec = x - fibonacciI; yRecRec = y; break; case 3: //第四象限 startAngle = 270; y = y - change; xRecRec = x; yRecRec = y; break; } xArcRec = x - fibonacciI; yArcRec = y - fibonacciI; /** * 绘制一个覆盖指定矩形的圆弧或椭圆弧边框。 得到的弧从 startAngle 开始跨越 arcAngle 度,并使用当前颜色。 对角度的解释如下:0 度角位于 3 点钟位置。正值指示逆时针旋转,负值指示顺时针旋转。 弧的中心是矩形的中心,此矩形的原点为 (x1 = x + width/2, y1 = y + wideth / 2),大小由 width 和 height 参数指定。 得到的弧覆盖 width + 1 像素宽乘以 height + 1 像素高的区域。 角度是相对于外接矩形的非正方形区域指定的,45 度角始终落在从椭圆中心到外接矩形右上角的连线上。 因此,如果外接矩形在一个轴上远远长于另一个轴,则弧段的起点和结束点的角度将沿边框长轴发生更大的偏斜 x - 要绘制弧的左上角的 x 坐标。(矩形的左上角) y - 要绘制弧的左上角的 y 坐标。(矩形的左上角) width - 要绘制弧的宽度。 height - 要绘制弧的高度。 startAngle - 开始角度。 arcAngle - 相对于开始角度而言,弧跨越的角度。 */ int drawWidth = 2 * fibonacciI / ZOOM; int drawHeight = 2 * fibonacciI / ZOOM; int drawArcX = X0 + (xArcRec - X0) / ZOOM; int drawArcY = Y0 + (yArcRec - Y0) / ZOOM; //画矩形 g.setColor(Color.RED); g.drawRect(xRecRec / ZOOM, yRecRec / ZOOM, drawWidth / 2, drawHeight / 2); //画斐波那契弧线 g.setColor(Color.MAGENTA); g.drawArc(drawArcX, drawArcY, drawWidth, drawHeight, startAngle, arcAngle); lastFibonacciI = fibonacciI; } // g2.drawArc(100, 100, 100, 100, 0, 360); // g2.drawArc(100, 100, 50, 50, 0, 360); // g2.drawArc(100, 100, 20, 20, 270, 360); // g2.drawArc(60, 60, 20, 20, 270, 360); } public static void main(String[] args) { JFrame f = new JFrame(); // FibonacciArc fibonacciArc = new FibonacciArc(); // FibonacciArc fibonacciArc = new FibonacciArc(FibonacciArc.FUNCTION_ARITHMETIC_SERIES); FibonacciArc fibonacciArc = new FibonacciArc(FibonacciArc.FUNCTION_GEOMETIRC_SERIES); fibonacciArc.repaint(); f.add(fibonacciArc); //设置画布大小 f.setMinimumSize(new Dimension(FibonacciArc.WIDTH, FibonacciArc.HEIGHT)); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
/* * 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 serverPrgms; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.stage.Stage; import static serverPrgms.TicTaeToeConstants.CONTINUE; import static serverPrgms.TicTaeToeConstants.DRAW; import static serverPrgms.TicTaeToeConstants.PLAYER1; import static serverPrgms.TicTaeToeConstants.PLAYER1_WON; import static serverPrgms.TicTaeToeConstants.PLAYER2; import static serverPrgms.TicTaeToeConstants.PLAYER2_WON; /** * * @author Shivam */ public class TicTaeToeServer extends Application implements TicTaeToeConstants { TextArea ta = new TextArea(); int sessionNo = 1; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Scene myScene = new Scene(new ScrollPane(ta), 450, 200); primaryStage.setTitle("Tic-Tae-Toe Server.."); primaryStage.setScene(myScene); primaryStage.show(); ta.setEditable(false); new Thread(new PlayerInitiator()).start(); } class PlayerInitiator implements Runnable { @Override public void run() { try{ ServerSocket serverSocket = new ServerSocket(8000); Platform.runLater(()-> { ta.appendText(new Date() + " : Server Started.."); }); while (true) { Platform.runLater(()-> { ta.appendText("\n\nSession"+sessionNo+" is Initiated....."); ta.appendText("\nWaiting for Player 1 to connect....."); }); Socket p1Socket = serverSocket.accept(); new DataOutputStream(p1Socket.getOutputStream()).writeInt(PLAYER1); Platform.runLater(()-> { ta.appendText("\nPlayer 1 joined session"+sessionNo); ta.appendText("\nPlayer 1 IP address : "+p1Socket.getInetAddress().getHostAddress()); ta.appendText("\nWaiting for Player 2 to connect.."); }); Socket p2Socket = serverSocket.accept(); new DataOutputStream(p2Socket.getOutputStream()).writeInt(PLAYER2); Platform.runLater(()-> { ta.appendText("\nPlayer 2 joined session"+sessionNo); ta.appendText("\nPlayer 2 IP address : "+p2Socket.getInetAddress().getHostAddress()); ta.appendText("\nStarting the game..............................."); ta.appendText("\nPlz wait..............................."); }); new Thread(new HandleASession(p1Socket,p2Socket)).start(); sessionNo++; } } catch (IOException ex) { System.out.println(ex.toString()); } } } class HandleASession implements Runnable { private Socket p1,p2; private char cell[][] = new char[3][3]; private DataInputStream fromPlayer1,fromPlayer2; private DataOutputStream toPlayer1,toPlayer2; public HandleASession(Socket p1, Socket p2) { this.p1 = p1; this.p2 = p2; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cell[i][j]=' '; } } } @Override public void run() { try { fromPlayer1 = new DataInputStream(p1.getInputStream()); fromPlayer2 = new DataInputStream(p2.getInputStream()); toPlayer1 = new DataOutputStream(p1.getOutputStream()); toPlayer2 = new DataOutputStream(p2.getOutputStream()); toPlayer1.writeInt(1); // toPlayer2.writeInt(2); while (true) { int row = fromPlayer1.readInt(); System.out.println("line 150 row : "+row); int col = fromPlayer1.readInt(); System.out.println("line 152 col : "+col); cell[row][col] = 'X'; System.out.println("line 156"); if(isWon('X')) { toPlayer1.writeInt(PLAYER1_WON); toPlayer2.writeInt(PLAYER1_WON); sendMove(toPlayer2, row, col); break; } else if(isFull()) { toPlayer1.writeInt(DRAW); toPlayer2.writeInt(DRAW); sendMove(toPlayer2, row, col); break; } else { toPlayer2.writeInt(CONTINUE); sendMove(toPlayer2, row, col); } System.out.println("line 173"); row = fromPlayer2.readInt(); System.out.println("line 175"); col = fromPlayer2.readInt(); System.out.println("line 177"); cell[row][col] = '0'; System.out.println("line 181"); if(isWon('0')) { toPlayer1.writeInt(PLAYER2_WON); System.out.println("line 185"); toPlayer2.writeInt(PLAYER2_WON); System.out.println("line 187"); sendMove(toPlayer1, row, col); break; } else { toPlayer1.writeInt(CONTINUE); sendMove(toPlayer1, row, col); } } } catch (IOException ex) { System.out.println(ex.toString()); } } private void sendMove(DataOutputStream out, int row, int col) throws IOException { out.writeInt(row); out.writeInt(col); } private boolean isWon(char tocken) { for (int i = 0; i < 3; i++) { if( cell[i][0] == tocken && cell[i][1] == tocken && cell[i][2] == tocken) //check all rows return true; else if(cell[0][i] == tocken && cell[1][i] == tocken && cell[2][i] == tocken) //check all columns return true; } if(cell[0][0] == tocken && cell[1][1] == tocken && cell[2][2] == tocken) //check major diagonal return true; else if(cell[0][2] == tocken && cell[1][1] == tocken && cell[2][0] == tocken) //check minor diagonal return true; return false; } private boolean isFull() { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if(cell[i][j] == ' ') return false; return true; } } class Restarter implements Runnable { Socket player; public Restarter(Socket player) { this.player = player; } public void run() { try { int status = new DataInputStream(player.getInputStream()).readInt(); if(status == RESTART) { } else if(status == QUIT) { } } catch (IOException ex) { Logger.getLogger(TicTaeToeServer.class.getName()).log(Level.SEVERE, null, ex); } } } }
<<<<<<< HEAD package in.vamsoft.excersise1.shape1; public class Square extends Rectangle { /** Builds a Square with the given side as both its width and its height. */ public Square(double side) { super(side, side); } private void setSides(double side) { super.setWidth(side); super.setHeight(side); } /** Sets BOTH the width and the height. */ @Override public void setHeight(double height) { setSides(height); } /** Sets BOTH the width and the height. */ @Override public void setWidth(double width) { setSides(width); } /** Indirectly sets the area by working backward to the side length. * The resultant area may not be EXACTLY what you set, due to roundoff * error when working with doubles. */ public void setArea(double area) { setSides(Math.sqrt(area)); } /** Prints info about the Square. */ @Override public String toString() { return ("Square (width/height=" + getWidth() + ", area=" + getArea() + ")"); } ======= package in.vamsoft.excersise1.shape1; /* * @author vignesh */ public class Square extends Rectangle { public Square(double side) { super(side, side); } private void setSides(double side) { super.setWidth(side); super.setHeight(side); } public void setHeight(double height) { setSides(height); } public void setWidth(double width) { setSides(width); } public void setArea(double area) { setSides(Math.sqrt(area)); } public String toString() { return("Square (width/height=" + getWidth() + ", area=" + getArea() + ")"); } >>>>>>> 35b1b732e68ed3b6596b2e23d9ec90c62220f54e }
//package com.example.demo.config; // //import org.springframework.context.annotation.Configuration; //import org.springframework.web.servlet.config.annotation.InterceptorRegistry; //import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; // //@Configuration //public class InterceptorBean implements WebMvcConfigurer { // // @Override // public void addInterceptors(InterceptorRegistry registry) { // registry.addInterceptor(new Interceptor()).addPathPatterns("/api/**"); // } //}
package org.cnodejs.android.md.display.adapter; import android.app.Activity; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import org.cnodejs.android.md.R; import org.cnodejs.android.md.display.activity.LoginActivity; import org.cnodejs.android.md.display.activity.UserDetailActivity; import org.cnodejs.android.md.display.widget.CNodeWebView; import org.cnodejs.android.md.display.widget.ToastUtils; import org.cnodejs.android.md.model.api.ApiClient; import org.cnodejs.android.md.model.api.DefaultToastCallback; import org.cnodejs.android.md.model.entity.Reply; import org.cnodejs.android.md.model.entity.Result; import org.cnodejs.android.md.model.storage.LoginShared; import org.cnodejs.android.md.util.FormatUtils; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Response; public class TopicAdapter extends BaseAdapter { public interface OnAtClickListener { void onAt(String loginName); } private final Activity activity; private final LayoutInflater inflater; private final List<Reply> replyList; private final OnAtClickListener onAtClickListener; public TopicAdapter(@NonNull Activity activity, @NonNull List<Reply> replyList, @NonNull OnAtClickListener onAtClickListener) { this.activity = activity; inflater = LayoutInflater.from(activity); this.replyList = replyList; this.onAtClickListener = onAtClickListener; } @Override public int getCount() { return replyList.size(); } @Override public Object getItem(int position) { return replyList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = inflater.inflate(R.layout.activity_topic_item_reply, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.update(position); return convertView; } public class ViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.topic_item_reply_img_avatar) protected ImageView imgAvatar; @Bind(R.id.topic_item_reply_tv_login_name) protected TextView tvLoginName; @Bind(R.id.topic_item_reply_tv_index) protected TextView tvIndex; @Bind(R.id.topic_item_reply_tv_create_time) protected TextView tvCreateTime; @Bind(R.id.topic_item_reply_btn_ups) protected TextView btnUps; @Bind(R.id.topic_item_reply_web_content) protected CNodeWebView webContent; @Bind(R.id.topic_item_reply_icon_deep_line) protected View iconDeepLine; @Bind(R.id.topic_item_reply_icon_shadow_gap) protected View iconShadowGap; private Reply reply; private int position = -1; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } public void update(int position) { this.position = position; reply = replyList.get(position); Glide.with(activity).load(reply.getAuthor().getAvatarUrl()).placeholder(R.drawable.image_placeholder).dontAnimate().into(imgAvatar); tvLoginName.setText(reply.getAuthor().getLoginName()); tvIndex.setText(position + 1 + "楼"); tvCreateTime.setText(FormatUtils.getRecentlyTimeText(reply.getCreateAt())); btnUps.setText(String.valueOf(reply.getUpList().size())); btnUps.setCompoundDrawablesWithIntrinsicBounds(reply.getUpList().contains(LoginShared.getId(activity)) ? R.drawable.ic_thumb_up_theme_24dp : R.drawable.ic_thumb_up_grey600_24dp, 0, 0, 0); iconDeepLine.setVisibility(position == replyList.size() - 1 ? View.GONE : View.VISIBLE); iconShadowGap.setVisibility(position == replyList.size() - 1 ? View.VISIBLE : View.GONE); // 这里直接使用WebView,有性能问题 webContent.loadRenderedContent(reply.getHandleContent()); } @OnClick(R.id.topic_item_reply_img_avatar) protected void onBtnAvatarClick() { UserDetailActivity.startWithTransitionAnimation(activity, reply.getAuthor().getLoginName(), imgAvatar, reply.getAuthor().getAvatarUrl()); } @OnClick(R.id.topic_item_reply_btn_ups) protected void onBtnUpsClick() { if (LoginActivity.startForResultWithAccessTokenCheck(activity)) { if (reply.getAuthor().getLoginName().equals(LoginShared.getLoginName(activity))) { ToastUtils.with(activity).show(R.string.can_not_up_yourself_reply); } else { upReplyAsyncTask(this); } } } @OnClick(R.id.topic_item_reply_btn_at) protected void onBtnAtClick() { if (LoginActivity.startForResultWithAccessTokenCheck(activity)) { onAtClickListener.onAt(reply.getAuthor().getLoginName()); } } } private void upReplyAsyncTask(final ViewHolder holder) { final int position = holder.position; // 标记当时的位置信息 final Reply reply = holder.reply; // 保存当时的回复对象 Call<Result.UpReply> call = ApiClient.service.upReply(holder.reply.getId(), LoginShared.getAccessToken(activity)); call.enqueue(new DefaultToastCallback<Result.UpReply>(activity) { @Override public boolean onResultOk(Response<Result.UpReply> response, Result.UpReply result) { if (!activity.isFinishing()) { if (result.getAction() == Reply.UpAction.up) { reply.getUpList().add(LoginShared.getId(activity)); } else if (result.getAction() == Reply.UpAction.down) { reply.getUpList().remove(LoginShared.getId(activity)); } // 如果位置没有变,则更新界面 if (position == holder.position) { holder.btnUps.setText(String.valueOf(holder.reply.getUpList().size())); holder.btnUps.setCompoundDrawablesWithIntrinsicBounds(holder.reply.getUpList().contains(LoginShared.getId(activity)) ? R.drawable.ic_thumb_up_theme_24dp : R.drawable.ic_thumb_up_grey600_24dp, 0, 0, 0); } } return false; } }); } }
package com.tech.interview.siply.redbus.handlers.exceptions; import java.util.HashMap; import java.util.Map; public class RedBusException extends Exception { private final Map<String, Object> exceptionExtensions = new HashMap<>(); public RedBusException(String errMsg) { super(errMsg); } public RedBusException withType(RedBusErrTypes redBusErrType) { this.exceptionExtensions.put(RedBusExConstants.ERROR_TYPE_KEY.getValue(), redBusErrType); return this; } }
package ch6; public class Ex_Power { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(power(3,0)); System.out.println(power(3,2)); System.out.println(power(3,4)); System.out.println(power(3,3)); } public static double power(double x, int n) { if(n==0) { return 1; }if(n%2==0) { if(n==2) { return Math.pow(x, n); }else { return Math.pow(x, 2)*Math.pow((Math.pow(x, ((n-2)/2))),2); } }else { return x*(Math.pow(x, n-1)); } } }
package product; //concrete product public class Order1 implements Order { // ... }
package com.syntax.class06; import java.util.Scanner; public class Homework037 { public static void main(String[] args) { Scanner input; input = new Scanner(System.in); boolean thirsty; boolean sleep; String drink; System.out.println("Are you thirsty?"); thirsty = input.nextBoolean(); System.out.println("Are you sleepy?"); sleep = input.nextBoolean(); if(thirsty && (!sleep)){ drink ="Water"; }else if(thirsty && sleep){ drink="Coffee"; }else if(!thirsty && !sleep) { drink = "Tea"; }else{ drink = "Nothing"; } System.out.println("Looks like you need to drink " + drink); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.handler; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.springframework.beans.BeansException; import org.springframework.util.CollectionUtils; /** * Implementation of the {@link org.springframework.web.servlet.HandlerMapping} * interface that maps from URLs to request handler beans. Supports both mapping to bean * instances and mapping to bean names; the latter is required for non-singleton handlers. * * <p>The "urlMap" property is suitable for populating the handler map with * bean references, e.g. via the map element in XML bean definitions. * * <p>Mappings to bean names can be set via the "mappings" property, in a form * accepted by the {@code java.util.Properties} class, as follows: * * <pre class="code"> * /welcome.html=ticketController * /show.html=ticketController</pre> * * <p>The syntax is {@code PATH=HANDLER_BEAN_NAME}. If the path doesn't begin * with a slash, one is prepended. * * <p>Supports direct matches (given "/test" -&gt; registered "/test") and "*" * matches (given "/test" -&gt; registered "/t*"). For details on the pattern * options, see the {@link org.springframework.web.util.pattern.PathPattern} * javadoc. * @author Rod Johnson * @author Juergen Hoeller * @author Sam Brannen * @see #setMappings * @see #setUrlMap * @see BeanNameUrlHandlerMapping */ public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping { private final Map<String, Object> urlMap = new LinkedHashMap<>(); /** * Create a {@code SimpleUrlHandlerMapping} with default settings. */ public SimpleUrlHandlerMapping() { } /** * Create a {@code SimpleUrlHandlerMapping} using the supplied URL map. * @param urlMap map with URL paths as keys and handler beans (or handler * bean names) as values * @since 5.2 * @see #setUrlMap(Map) */ public SimpleUrlHandlerMapping(Map<String, ?> urlMap) { setUrlMap(urlMap); } /** * Create a {@code SimpleUrlHandlerMapping} using the supplied URL map and order. * @param urlMap map with URL paths as keys and handler beans (or handler * bean names) as values * @param order the order value for this {@code SimpleUrlHandlerMapping} * @since 5.2 * @see #setUrlMap(Map) * @see #setOrder(int) */ public SimpleUrlHandlerMapping(Map<String, ?> urlMap, int order) { setUrlMap(urlMap); setOrder(order); } /** * Map URL paths to handler bean names. * This is the typical way of configuring this HandlerMapping. * <p>Supports direct URL matches and Ant-style pattern matches. For syntax * details, see the {@link org.springframework.util.AntPathMatcher} javadoc. * @param mappings properties with URLs as keys and bean names as values * @see #setUrlMap */ public void setMappings(Properties mappings) { CollectionUtils.mergePropertiesIntoMap(mappings, this.urlMap); } /** * Set a Map with URL paths as keys and handler beans (or handler bean names) * as values. Convenient for population with bean references. * <p>Supports direct URL matches and Ant-style pattern matches. For syntax * details, see the {@link org.springframework.util.AntPathMatcher} javadoc. * @param urlMap map with URLs as keys and beans as values * @see #setMappings */ public void setUrlMap(Map<String, ?> urlMap) { this.urlMap.putAll(urlMap); } /** * Allow {@code Map} access to the URL path mappings, with the option to add or * override specific entries. * <p>Useful for specifying entries directly, for example via "urlMap[myKey]". * This is particularly useful for adding or overriding entries in child * bean definitions. */ public Map<String, ?> getUrlMap() { return this.urlMap; } /** * Calls the {@link #registerHandlers} method in addition to the * superclass's initialization. */ @Override public void initApplicationContext() throws BeansException { super.initApplicationContext(); registerHandlers(this.urlMap); } /** * Register all handlers specified in the URL map for the corresponding paths. * @param urlMap a Map with URL paths as keys and handler beans or bean names as values * @throws BeansException if a handler couldn't be registered * @throws IllegalStateException if there is a conflicting handler registered */ protected void registerHandlers(Map<String, Object> urlMap) throws BeansException { if (urlMap.isEmpty()) { logger.trace("No patterns in " + formatMappingName()); } else { urlMap.forEach((url, handler) -> { // Prepend with slash if not already present. if (!url.startsWith("/")) { url = "/" + url; } // Remove whitespace from handler bean name. if (handler instanceof String handlerName) { handler = handlerName.trim(); } registerHandler(url, handler); }); logMappings(); } } private void logMappings() { if (mappingsLogger.isDebugEnabled()) { Map<String, Object> map = new LinkedHashMap<>(getHandlerMap()); if (getRootHandler() != null) { map.put("/", getRootHandler()); } if (getDefaultHandler() != null) { map.put("/**", getDefaultHandler()); } mappingsLogger.debug(formatMappingName() + " " + map); } else if (logger.isDebugEnabled()) { List<String> patterns = new ArrayList<>(); if (getRootHandler() != null) { patterns.add("/"); } if (getDefaultHandler() != null) { patterns.add("/**"); } patterns.addAll(getHandlerMap().keySet()); logger.debug("Patterns " + patterns + " in " + formatMappingName()); } } }
package Topic32List; class StringBuild { public static void main(String[] args) { StringBuilder sB = new StringBuilder( ); for(int i = 0; i<10; i++){ sB.append( i ); sB.append( "a" ); } sB.replace( sB.length()-12, sB.length()-7, "x"); System.out.println(sB.toString()); } }
/* Program Name: CrapsGame.java * Created on : 04-11-2015 * Author : Jon Bilsbury * Version : 1.0 */ public class CrapsGame { private int sum, point, d1, d2; static DiceFacePanel panel; //constructor for the class public CrapsGame() { point = 0; panel = new DiceFacePanel(); } /** does the first roll @return String containing both of the values */ public String doFirstRoll() { d1 = panel.getValue(panel.die1); //get both of the values d2 = panel.getValue(panel.die2); sum = d1 + d2; //add them for the sum return "d1 = " + d1 + " d2 = " + d2; //return both of the values in a string } /** does a re-roll @return String containing both of the values */ public String rollAgain() { panel.roll(); //roll both of the dies d1 = panel.getValue(panel.die1); //get both of the values d2 = panel.getValue(panel.die2); sum = d1 + d2; //add them for the sum return "d1 = " + d1 + " d2 = " + d2 + " sum = " + sum + " point = " + point; //return both of the values in a string } /** sets the points to the sum */ public void setPointSum(){ if(sum == 4 || sum == 5 || sum == 6 || sum == 8 || sum == 9 || sum == 10) //if there isn't a stopping condition met point = sum; //set the points to the sum } /** checks if the game is won */ public boolean isWon() { if (point == 0){ //if it is the first roll if (sum == 7 || sum == 11){ //if user has won return true;} } else { if (sum == point){ return true;} } return false; } /** checks if the game is over @return bool if the game is over */ public boolean isOver() { if (point == 0){ if (sum == 7 || sum == 11 || sum == 2 || sum == 3 || sum == 12){ //if either player has won return true;} setPointSum(); } else { if (sum == point || sum == 7){ return true;} } return false; } /** resets all of the instance variables */ public void resetGame() { point = 0; //resets all of the instance values to 0 sum = 0; d1 = 0; d2 = 0; } /** returns the panel containing the game @return DiceFacePanel the panel containing both of the dies */ public DiceFacePanel returnObj(){ return panel; //returns the object of the panel } /** returns a string of the values @return String contains the values */ public String printString() { return "d1 = " + d1 + " d2 = " + d2 + " sum = " + sum + " point = " + point; //converts the values and points into a string } }
package com.bnade.wow.repository; import com.bnade.wow.entity.ItemSearchStatistic; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; /** * 物品搜索统计 * Created by liufeng0103@163.com on 2017/7/13. */ public interface ItemSearchStatisticRepository extends JpaRepository<ItemSearchStatistic, Integer> { /** * 查询指定日期之后的物品搜索次数统计 * @param startDate 查询的开始日期 * @param offset 偏移 * @param limit 返回记录数 * @return 每种物品搜索的列表 */ @Query(value = "SELECT item_id,SUM(search_count) FROM item_search_statistic WHERE search_date>=?1 GROUP BY item_id ORDER BY SUM(search_count) DESC LIMIT ?2,?3", nativeQuery = true) List<Object[]> findStartFrom(String startDate, Integer offset, Integer limit); }
public class bagmati extends Nepal//c { public static void kathmandu()// disp c { System.out.println("KTM is in Bagmati"); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.transaction.reactive; import java.util.function.Function; import reactor.core.publisher.Mono; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.PayloadApplicationEvent; /** * A delegate for publishing transactional events in a reactive setup. * Includes the current Reactor-managed {@link TransactionContext} as * a source object for every {@link ApplicationEvent} to be published. * * <p>This delegate is just a convenience. The current {@link TransactionContext} * can be directly included as the event source as well, and then published * through an {@link ApplicationEventPublisher} such as the Spring * {@link org.springframework.context.ApplicationContext}: * * <pre class="code"> * TransactionContextManager.currentContext() * .map(source -> new PayloadApplicationEvent&lt;&gt;(source, "myPayload")) * .doOnSuccess(this.eventPublisher::publishEvent) * </pre> * * @author Juergen Hoeller * @since 6.1 * @see #publishEvent(Function) * @see #publishEvent(Object) * @see ApplicationEventPublisher */ public class TransactionalEventPublisher { private final ApplicationEventPublisher eventPublisher; /** * Create a new delegate for publishing transactional events in a reactive setup. * @param eventPublisher the actual event publisher to use, * typically a Spring {@link org.springframework.context.ApplicationContext} */ public TransactionalEventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } /** * Publish an event created through the given function which maps the transaction * source object (the {@link TransactionContext}) to the event instance. * @param eventCreationFunction a function mapping the source object to the event instance, * e.g. {@code source -> new PayloadApplicationEvent&lt;&gt;(source, "myPayload")} * @return the Reactor {@link Mono} for the transactional event publication */ public Mono<Void> publishEvent(Function<TransactionContext, ApplicationEvent> eventCreationFunction) { return TransactionContextManager.currentContext().map(eventCreationFunction) .doOnSuccess(this.eventPublisher::publishEvent).then(); } /** * Publish an event created for the given payload. * @param payload the payload to publish as an event * @return the Reactor {@link Mono} for the transactional event publication */ public Mono<Void> publishEvent(Object payload) { if (payload instanceof ApplicationEvent) { return Mono.error(new IllegalArgumentException("Cannot publish ApplicationEvent with transactional " + "source - publish payload object or use publishEvent(Function<Object, ApplicationEvent>")); } return publishEvent(source -> new PayloadApplicationEvent<>(source, payload)); } }
package zajecia.OOP.bookstore; /** * Created by RENT on 2017-04-24. */ public class Application { public static void main(String[] args) { Bookstore bookstore = new Bookstore(); insertExampleData(bookstore); // bookstore.showBooks(); // Book[] books = bookstore.getBooks("Henryk Sienkiewicz"); // System.out.println(bookstore.getBook("192")); } public static void insertExampleData(Bookstore bookstore) { Book book=new Book("Ogniem i mieczem","Henryk Sienkiewicz",1900, "192" ); book.setSize(3); String[] ogniemIMieczem =new String[3]; ogniemIMieczem[0] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; ogniemIMieczem[1] = "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."; ogniemIMieczem[2] = "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."; book.setContent(ogniemIMieczem); Book book2=new Book("Qua Vadis","Henryk Sienkiewicz",1910, "193" ); book2.setSize(3); String[] quaVadis =new String[3]; quaVadis[0] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; quaVadis[1] = "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."; quaVadis[2] = "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."; book2.setContent(quaVadis); Book book3=new Book("Dziady IV","Adam Mickiewicz",1960, "194" ); book3.setSize(3); String[] dziady =new String[3]; dziady[0] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; dziady[1] = "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."; dziady[2] = "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."; book3.setContent(dziady); bookstore.add(book); bookstore.add(book2); bookstore.add(book3); } }
package coin.coininventory.entity; import javax.persistence.*; @Entity @Table(name = "locationdependency") public class LocationDependency { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long locationdependencyid; @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinColumn(name = "userfk") private User user; @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinColumn(name = "location") Location location; @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinColumn(name = "sublocation") SubLocation subLocation; public LocationDependency() { } public long getLocationdependencyid() { return locationdependencyid; } public void setLocationdependencyid(long locationdependencyid) { this.locationdependencyid = locationdependencyid; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public SubLocation getSubLocation() { return subLocation; } public void setSubLocation(SubLocation subLocation) { this.subLocation = subLocation; } }
/* * @(#) ISvcInfoDAO.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ebms.svcinfo.dao; import java.util.List; import com.esum.appframework.dao.IBaseDAO; import com.esum.appframework.exception.ApplicationException; /** * * @author heowon@esumtech.com * @version $Revision: 1.2 $ $Date: 2009/01/16 08:25:39 $ */ public interface ISvcInfoDAO extends IBaseDAO { List login(Object object) throws ApplicationException; List ssoLogin(Object object) throws ApplicationException; int updateLangtype(Object object) throws ApplicationException; List selectList(Object object) throws ApplicationException; List nodeInfoDetailRouterMain(Object object) throws ApplicationException; }
package com.juannarvaez.taskworkout.view.Adapter; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import com.juannarvaez.taskworkout.view.Fragment.AgendaFragment; import com.juannarvaez.taskworkout.view.Fragment.ConsejosFragment; import com.juannarvaez.taskworkout.view.Fragment.EjerciciosFragment; import com.juannarvaez.taskworkout.view.Fragment.MasPerfilFragment; import com.juannarvaez.taskworkout.view.Fragment.ObjetivosFragment; public class AdatadorPaginas extends FragmentPagerAdapter { int numeroPaginas; public AdatadorPaginas (@NonNull FragmentManager fm , int numPaginas){ super(fm, numPaginas); this.numeroPaginas=numPaginas; } @NonNull @Override public Fragment getItem(int position){ switch (position){ case 0: return new ConsejosFragment(); case 1: return new AgendaFragment(); case 2: return new ObjetivosFragment(); case 3: return new EjerciciosFragment(); case 4: return new MasPerfilFragment(); default:return null; } } @Override public int getCount(){ return numeroPaginas; } }
package edu.upenn.cis455.Indexer.EMRIndexer; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; /** * Some new pages are crawled after running indexer. So EMR may run several times. * Combine results from different EMR result. * Run on amazon EMR. Put all input files into one folder before running. * */ public class CombineMapReduceResult { public static class TokenizerMapper extends Mapper<Object, Text, Text, Text>{ private Text word = new Text(); private Text info = new Text(); public void map(Object key, Text value, Context context) throws IOException, InterruptedException { String[] kv = value.toString().split("\\s+",2); word.set(kv[0]); info.set(kv[1]); context.write(word, info); } } public static class InvertedIndexReducer extends Reducer<Text,Text,Text,Text> { private Text result = new Text(); public void reduce(Text key, Iterable<Text> values, Context context ) throws IOException, InterruptedException { StringBuilder sb = new StringBuilder(); for (Text val : values) { String text = val.toString(); sb.append(text+ " "); } //System.out.println(sb.toString()); result.set(sb.toString()); context.write(key, result); } } public static void main(String[] args) throws Exception { System.out.println("Combine result"); Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "Combine result"); job.setJarByClass(InvertedIndex.class); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(InvertedIndexReducer.class); job.setReducerClass(InvertedIndexReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
package service.lecture; import java.io.File; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import model.dto.hr.SubjectDTO; import repository.lecture.FileGetRepository; import repository.lecture.LectureDeleteRepository; import repository.lecture.LectureDetailRepository; @Service public class LectureDeletingSerivce { @Autowired private LectureDeleteRepository lectureDeleteRepository; @Autowired private LectureDetailRepository lectureDetailRepository; public void action(HttpServletRequest request, Long num) { SubjectDTO dto = new SubjectDTO(); String path = "\\manager\\lec\\video\\"; String realPath = request.getServletContext().getRealPath(path); System.out.println(realPath); dto.setSubjNo(num); dto = lectureDetailRepository.reposit(dto); String store = dto.getSubjStore(); if(store!=null) { File file = new File(realPath + "\\" + store); file.delete(); System.out.println(store+"삭제하기"); lectureDeleteRepository.reposit(dto.getSubjNo()); } } }
package com.lojaDeComputadorV3.domain; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; @Entity @Table(name = "tbl_compras") @NamedQueries({ @NamedQuery(name = "Compras.listar", query = "SELECT compras FROM Compras compras"), @NamedQuery(name = "Compras.buscarPorCodigo", query = "SELECT compras FROM Compras compras WHERE compras.codigo = :codigo ") }) public class Compras extends EntidadeDominio { // Declara tipo Date @Temporal(value = TemporalType.TIMESTAMP) @NotEmpty(message = "O campo data é obrigatório") @Column(name = "com_data", nullable = false) private Date data; // Validação, campo não pode estar vazio @NotEmpty(message = "O campo status é obrigatório") // coluna no banco de dados @Column(name = "com_status", length = 50, nullable = false) private String status; // Tipo de relacionamento entre tabelas do banco que contem chave estrangeira @ManyToOne(fetch = FetchType.EAGER) // juntando as colunas||nome na tabela filha|||nome na tabela pai @JoinColumn(name = "tbl_computador_id_codigo", referencedColumnName = "id_codigo", nullable = false) private Computador computador; @NotNull(message = "O campo cliente é obrigatório!") // Tipo de relacionamento entre tabelas do banco que contem chave estrangeira @ManyToOne(fetch = FetchType.EAGER) // juntando as colunas||nome na tabela filha - produto|||nome na tabela pai - // produto @JoinColumn(name = "tbl_cliente_id_codigo", referencedColumnName = "id_codigo") private Cliente cliente; public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Computador getComputador() { return computador; } public void setComputador(Computador computador) { this.computador = computador; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((cliente == null) ? 0 : cliente.hashCode()); result = prime * result + ((computador == null) ? 0 : computador.hashCode()); result = prime * result + ((data == null) ? 0 : data.hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; Compras other = (Compras) obj; if (cliente == null) { if (other.cliente != null) return false; } else if (!cliente.equals(other.cliente)) return false; if (computador == null) { if (other.computador != null) return false; } else if (!computador.equals(other.computador)) return false; if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; if (status == null) { if (other.status != null) return false; } else if (!status.equals(other.status)) return false; return true; } @Override public String toString() { return "Compras [data=" + data + ", status=" + status + ", computador=" + computador + ", cliente=" + cliente + ", getCodigo()=" + getCodigo() + "]"; } }
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */ // 1: Recursive class Solution { List<Integer> res = new ArrayList<Integer>(); public List<Integer> postorder(Node root) { if(root == null) return res; for(Node node : root.children){ postorder(node); } res.add(root.val); return res; } } // 2: Iterate class Solution { public List<Integer> postorder(Node root) { List<Integer> res = new ArrayList<Integer>(); if(root == null) return res; Stack<Node> stack = new Stack<Node>(); stack.add(root); while(!stack.isEmpty()){ root = stack.pop(); res.add(root.val); for(Node node : root.children) stack.add(node); } Collections.reverse(res); return res; } }
package com.codingchili.instance.controller; import com.codingchili.core.protocol.Api; import com.codingchili.core.protocol.exception.AuthorizationRequiredException; import com.codingchili.instance.context.GameContext; import com.codingchili.instance.model.admin.AdminEvent; import com.codingchili.instance.model.dialog.AdminEngine; import com.codingchili.instance.transport.InstanceRequest; /** * @author Robin Duda * * Handles admin functions. */ public class AdminHandler implements GameHandler { private AdminEngine engine; private GameContext game; public AdminHandler(GameContext game) { this.game = game; this.engine = new AdminEngine(game); } @Api public void admin(InstanceRequest request) { if (game.instance().realm().isAdmin(request.account())) { engine.handle(request.raw(AdminEvent.class)); } else { request.error(new AuthorizationRequiredException()); } } }
package com.github.gaoyangthu.core.hbase; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; /** * Created with IntelliJ IDEA. * Author: gaoyangthu * Date: 14-3-11 * Time: 下午2:48 */ public class HbasePutSample { public static void main(String[] args) { HbaseTemplate hbaseTemplate = HbaseTemplateFactory.getHbaseTemplate(); HTableInterface hTable = hbaseTemplate.getTable("testtable"); Put put = new Put(Bytes.toBytes("row1")); put.add(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1"), Bytes.toBytes("val1")); put.add(Bytes.toBytes("colfam1"), Bytes.toBytes("qual2"), Bytes.toBytes("val2")); try { hTable.put(put); } catch (IOException e) { e.printStackTrace(); } hbaseTemplate.releaseTable("testtable", hTable); } }
package com.sl.app.doorlock.register.dao; import com.sl.app.doorlock.register.vo.AppDoorlockRegisterVO; import net.sf.json.JSONObject; public interface AppDoorlockRegisterDAO { JSONObject selectOneCheck(AppDoorlockRegisterVO vo); JSONObject selectOneInsert(AppDoorlockRegisterVO vo); }
package cn.fuyoushuo.fqbb.view.flagment; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.Toast; import com.jakewharton.rxbinding.view.RxView; import com.jakewharton.rxbinding.widget.RxTextView; import com.trello.rxlifecycle.FragmentEvent; import com.trello.rxlifecycle.components.support.RxDialogFragment; import com.umeng.analytics.MobclickAgent; import java.util.concurrent.TimeUnit; import butterknife.Bind; import butterknife.ButterKnife; import cn.fuyoushuo.fqbb.MyApplication; import cn.fuyoushuo.fqbb.R; import cn.fuyoushuo.fqbb.commonlib.utils.RxBus; import cn.fuyoushuo.fqbb.presenter.impl.LocalLoginPresent; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; /** * Created by QA on 2016/11/9. */ public class BindEmailDialogFragment extends RxDialogFragment{ @Bind(R.id.bind_email_backArea) RelativeLayout backArea; @Bind(R.id.account_value) EditText emailTextView; @Bind(R.id.verificate_value) EditText verifiTextView; @Bind(R.id.acquire_verification_button) Button verifiAcquireButton; @Bind(R.id.commit_button) Button bindCommitButton; private String emailValue = ""; private String verifiCodeValue = ""; LocalLoginPresent localLoginPresent; private boolean isAccountRight = false; private Long time = 60l; @Override public void show(FragmentManager manager, String tag) { try{ super.show(manager, tag); }catch (Exception e){ // to do nothing } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL, R.style.fullScreenDialog); localLoginPresent = new LocalLoginPresent(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View inflateView = inflater.inflate(R.layout.view_bind_email, container, false); setupUI(inflateView,getActivity()); ButterKnife.bind(this,inflateView); emailTextView.setFocusable(true); return inflateView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); verifiTextView.setInputType(EditorInfo.TYPE_CLASS_PHONE); RxTextView.textChanges(emailTextView).compose(this.<CharSequence>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribe(new Action1<CharSequence>() { @Override public void call(CharSequence charSequence) { emailValue = charSequence.toString(); } }); RxTextView.textChanges(verifiTextView).compose(this.<CharSequence>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribe(new Action1<CharSequence>() { @Override public void call(CharSequence charSequence) { verifiCodeValue = charSequence.toString(); } }); // RxView.focusChanges(emailTextView).compose(this.<Boolean>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) // .subscribe(new Action1<Boolean>() { // @Override // public void call(Boolean aBoolean) { // if(!aBoolean){ // //判断邮箱是否有效 // // } // } // }); RxView.clicks(verifiAcquireButton).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000,TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { localLoginPresent.validateData(emailValue, 2, new LocalLoginPresent.DataValidataCallBack() { @Override public void onValidataSucc(int flag) { if(flag == 1){ isAccountRight = false; Toast.makeText(MyApplication.getContext(),"邮箱已经被注册",Toast.LENGTH_SHORT).show(); }else{ isAccountRight = true; timeForVerifiCode(); localLoginPresent.getVerifiCode(emailValue, "email_bind_email", new LocalLoginPresent.VerifiCodeGetCallBack() { @Override public void onVerifiCodeGetSucc(String account) { Toast.makeText(MyApplication.getContext(),"验证码发送成功,请查收邮件",Toast.LENGTH_SHORT).show(); } @Override public void onVerifiCodeGetError(String msg) { Toast.makeText(MyApplication.getContext(),"验证码发送失败,请重试",Toast.LENGTH_SHORT).show(); } }); } } @Override public void onValidataFail(String msg) { isAccountRight = false; Toast.makeText(MyApplication.getContext(),msg,Toast.LENGTH_SHORT).show(); } }); } }); RxView.clicks(bindCommitButton).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000,TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { if(!isAccountRight || TextUtils.isEmpty(verifiCodeValue)){ Toast.makeText(MyApplication.getContext(),"你输入的邮箱地址或验证码不可用,请重试",Toast.LENGTH_SHORT).show(); return; } localLoginPresent.bindMail(emailValue, verifiCodeValue, new LocalLoginPresent.BindEmailCallBack() { @Override public void onBindEmailSuccess(String account) { Toast.makeText(MyApplication.getContext(),"邮箱绑定成功",Toast.LENGTH_SHORT).show(); RxBus.getInstance().send(new AfterBindEmailSuccessEvent()); dismissAllowingStateLoss(); } @Override public void onBindEmailFail(String msg) { emailValue = ""; verifiCodeValue = ""; emailTextView.setText(""); verifiTextView.setText(""); isAccountRight = false; Toast.makeText(MyApplication.getContext(),"邮箱绑定失败,请重试",Toast.LENGTH_SHORT).show(); } }); } }); RxView.clicks(backArea).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000,TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { dismissAllowingStateLoss(); } }); } @Override public void onDestroy() { super.onDestroy(); localLoginPresent.onDestroy(); ButterKnife.unbind(this); } public static BindEmailDialogFragment newInstance() { BindEmailDialogFragment fragment = new BindEmailDialogFragment(); return fragment; } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart("bindEmail"); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd("bindEmail"); } private void timeForVerifiCode() { verifiAcquireButton.setText("获取验证码(60)"); verifiAcquireButton.setClickable(false); verifiAcquireButton.setBackgroundColor(getResources().getColor(R.color.gray)); Observable.timer(1, TimeUnit.SECONDS).compose(this.<Long>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .repeat(60) .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { if(verifiAcquireButton == null) return; time--; if (time > 0) { if (verifiAcquireButton != null){ verifiAcquireButton.setText("获取验证码(" + time + ")"); } } else { if(verifiAcquireButton != null){ verifiAcquireButton.setClickable(true); verifiAcquireButton.setBackgroundColor(getResources().getColor(R.color.module_6)); verifiAcquireButton.setText("重新获取验证码"); } time = 60l; } } }); } //-------------------------------------------用于处理键盘-------------------------------------------------------- private void setupUI(View view,final Activity context) { //Set up touch listener for non-text box views to hide keyboard. if(!(view instanceof EditText)) { view.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { v.setFocusable(true); v.setFocusableInTouchMode(true); v.requestFocus(); InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(),0); return false; } }); } //If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView,context); } } } //------------------------------------------------总线事件-------------------------------------------------------- public class AfterBindEmailSuccessEvent extends RxBus.BusEvent{} }
package SimpleCalculate; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StackCalculate { int numRange; public StackCalculate(int numRange) { this.numRange = numRange; } public StackCalculate() { } /* * function: //getResult * Description: //调用函数先将一般式转化为后缀表达式,再计算获取结果 * Calls: //toPostfix * Calls By: //getResult */ String getResult(String str) { if (str.contains("/0")) return "-1"; //变成后缀表达式 try { str = toPostfix(str); } catch (Exception e) { e.printStackTrace(); } String[] str0 = str.split(" "); if (!str.contains("/")) //不含除号的基本运算 { Stack<Integer> stack = new Stack<>(); for (String c : str0) { if (c.equals("+") || c.equals("-") || c.equals("×")) { int b = stack.peek(); stack.pop(); int a = stack.peek(); stack.pop(); stack.push(calculate(a, b, c)); //在这里作出调整,对于每一个c和calculate(a,b,c)检查 //在这里作出调整,对于每一个c和calculate(a,b,c)检查 //在范围之外 if (a < 0 || a > numRange || b < 0 || b > numRange) return "-1"; } else stack.push(Integer.parseInt(c)); } if (stack.peek() < 0 || stack.peek() > numRange) return "-1"; return Integer.toString(stack.peek()); } else //带除号转换成分数运算 { Stack<int[]> stack = new Stack<>(); for (String c : str0) { if (c.equals("+") || c.equals("-") || c.equals("×") || c.equals("/")) { int[] b = stack.peek(); stack.pop(); int[] a = stack.peek(); stack.pop(); if (a[0] < 0 || a[0] > numRange || a[1] < 0 || a[1] > numRange || b[0] <= 0 || b[0] > numRange || b[1] <= 0 || b[1] > numRange || a[0] > a[1] && a[1] != 1 || b[0] > b[1] && b[1] != 1) return "-1"; stack.push(calculate(a[0], a[1], b[0], b[1], c)); } else stack.push(new int[]{Integer.parseInt(c), 1}); } //继续对结果答案进行审查 if (stack.peek()[0] < 0 || stack.peek()[0] > numRange || stack.peek()[1] < 0 || stack.peek()[1] > numRange) return "-1"; if (stack.peek()[1] == 1) return Integer.toString(stack.peek()[0]); if ( stack.peek()[0] > stack.peek()[1]) return "-1"; return stack.peek()[0] + "/" + stack.peek()[1]; } } /* * function: //toPostfix * Description: //将普通表达式转化成后缀表达式 * Calls: //无 * Calls By: //getResult() */ String toPostfix(String str) throws Exception { Stack<String> postfix = new Stack<>(); StringBuilder postFix = new StringBuilder(); Pattern p = Pattern.compile("\\d+|[+\\-×/()]");//这个正则为匹配表达式中的数字或运算符 Matcher m = p.matcher(str); while (m.find()) { String c = m.group(); if (c.equals("("))//遇到左括号,直接压栈 { postfix.push(c); continue; } if (c.equals(")"))//遇到右括号,弹栈输出直到弹出左括号(左括号不输出) { while (!postfix.peek().equals("(")) { postFix.append(postfix.peek() + " "); postfix.pop(); } postfix.pop(); continue; } if (c.equals("+") || c.equals("-") || c.equals("×") || c.equals("/")) { if (!postfix.empty() && getPriority(postfix.peek()) >= getPriority(c)) { while (!postfix.empty() && getPriority(postfix.peek()) >= getPriority(c)) { postFix.append(postfix.peek() + " "); postfix.pop(); } } postfix.push(c); } else postFix.append(c + " "); } while (!postfix.empty()) { postFix.append(postfix.peek() + " "); postfix.pop(); } return postFix.toString(); } //获得优先级 int getPriority(String ch) throws Exception { if (ch.equals("+") || ch.equals("-")) return 1; if (ch.equals("×") || ch.equals("/")||ch.equals("÷")) return 2; if (ch.equals("(")) return 0; throw new Exception("illegal operator!"); } //整数运算 int calculate(int a, int b, String ch) { if (ch.equals("+")) return a + b; if (ch.equals("-")) return a - b; if (ch.equals("×")) return a * b; return 0; } //分数运算 int[] calculate(int a1, int a2, int b1, int b2, String ch) { FractionFormat a = new FractionFormat(a1, a2); FractionFormat b = new FractionFormat(b1, b2); if (ch.equals("+")) return a.add(b).getNumber(); if (ch.equals("-")) return a.sub(b).getNumber(); if (ch.equals("×")) return a.multiply(b).getNumber(); if (ch.equals("/")||ch.equals("÷")) return a.divide(b).getNumber(); return new int[]{0, 0}; } }
package com.ferreusveritas.growingtrees.worldgen; import cpw.mods.fml.common.eventhandler.Event.Result; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.event.entity.EntityEvent.EntityConstructing; import net.minecraftforge.event.terraingen.DecorateBiomeEvent; import net.minecraftforge.event.terraingen.InitMapGenEvent; import net.minecraftforge.event.terraingen.DecorateBiomeEvent.Decorate.EventType; /** * <pre><tt> * [ 01 ] [ 02 ] [ 03 ] [ 04 ] * ┌──┬──┬──┐ ┌──┬──┬──┐ ┌──┬──┬──┐ ┌──┬──┬──┐ * │ │ │ │ │ │ │ │ │ │Un│Ex│ │Un│Ex│ │ * ├──┼──┼──┤ ├──┼──┼──┤ ├──┼──┼──┤ ├──┼──┼──┤ * │ │Un│Ex│ │Un│ │ │ │ │ │Ex│ │Ex│Un│ │ * ├──┼──┼──┤ ├──┼──┼──┤ ├──┼──┼──┤ ├──┼──┼──┤ * │ │Ex│Ex│ │Ex│Ex│ │ │ │ │ │ │ │ │ │ * └──┴──┴──┘ └──┴──┴──┘ └──┴──┴──┘ └──┴──┴──┘ * </tt></pre> * * Ex: Chunk that will be tested for existence * Un: Undecorated chunk that will be decorated if the other chunks exist. * * The center chunk was just created it is guaranteed to exist. * */ public class DecorateEventHandler { @SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=true) public void onEvent(DecorateBiomeEvent.Decorate event) { //System.out.println("Decorate Event:" + event.chunkZ + "," + event.chunkZ + " - " + event.type.toString()); if(event.type == EventType.TREE){//Does not affect roofed forests event.setResult(Result.DENY); } /*if(event.type == EventType.BIG_SHROOM){//For mushroom islands.. has no affect on RoofedForests event.setResult(Result.DENY); }*/ //Roofed Forest Seed: 1488218954 //BiomeGenForest(the secret of the Roofed Forest): this.field_150632_aF == 3, new BiomeGenForest(29(BiomeID), 3) } }
package com.example.server.dto; public class TokenRequest { private String client_id="xhxgUDdxeLAHFGp0zml60cT4Pj8SRrIt5fhcusAFOt9NPZrGCs"; private String client_secret= "2Zu2jzMqAey53iOxOGh4Qn2abEIXJF0VJY1F3kuH"; private final String grant_type= "client_credentials"; public TokenRequest() { } public String getClient_id() { return client_id; } public String getClient_secret() { return client_secret; } public String getGrant_type() { return grant_type; } }
package script.groovy.runtime; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import chat.errors.CoreException; import chat.logs.LoggerEx; import groovy.lang.GroovyObject; import org.apache.commons.lang.StringUtils; import script.groovy.annotation.Bean; import script.groovy.object.GroovyObjectEx; import script.groovy.runtime.GroovyRuntime.MyGroovyClassLoader; public class GroovyBeanFactory extends ClassAnnotationHandler { private static final String TAG = GroovyBeanFactory.class.getSimpleName(); private ConcurrentHashMap<String, GroovyObjectEx> beanMap = new ConcurrentHashMap<>(); // private ConcurrentHashMap<String, Class<?>> proxyClassMap = new ConcurrentHashMap<>(); @Override public void handlerShutdown() { beanMap.clear(); // proxyClassMap.clear(); } public GroovyBeanFactory() { // instance = this; } // public Class<?> getProxyClass(String className) { // return proxyClassMap.get(className); // } public <T> GroovyObjectEx<T> getBean(String beanName) { if(beanMap != null) { return beanMap.get(beanName); } return null; } public <T> GroovyObjectEx<T> getBean(Class<?> c) { if(c == null) return null; String groovyPath = GroovyRuntime.path(c); return getBean(groovyPath); } public <T> GroovyObjectEx<T> getBean(Class<?> c, boolean forceCreate) { if(forceCreate) return getObject(c); else return getBean(c); } private <T> GroovyObjectEx<T> getObject(String beanName, Class<?> c, ConcurrentHashMap<String, GroovyObjectEx> beanMap) { if(beanMap == null) { beanMap = this.beanMap; } String groovyPath = GroovyRuntime.path(c); GroovyObjectEx<T> goe = beanMap.get(groovyPath); if(goe == null) { goe = getGroovyRuntime().create(groovyPath); if(beanName == null) { beanName = groovyPath; } if(goe != null) { GroovyObjectEx<T> oldgoe = beanMap.putIfAbsent(beanName, goe); if(oldgoe != null) goe = oldgoe; } } return goe; } private <T> GroovyObjectEx<T> getObject(Class<?> c, ConcurrentHashMap<String, GroovyObjectEx> beanMap) { return getObject(null, c, beanMap); } private <T> GroovyObjectEx<T> getObject(Class<?> c) { return getObject(c, null); } @Override public Class<? extends Annotation> handleAnnotationClass(GroovyRuntime groovyRuntime) { return Bean.class; } @Override public void handleAnnotatedClasses(Map<String, Class<?>> annotatedClassMap, MyGroovyClassLoader classLoader) { ConcurrentHashMap<String, GroovyObjectEx> newBeanMap = new ConcurrentHashMap<>(); // ConcurrentHashMap<String, Class<?>> newProxyClassMap = new ConcurrentHashMap<>(); if (annotatedClassMap != null) { Collection<Class<?>> values = annotatedClassMap.values(); for (Class<?> groovyClass : values) { Bean bean = groovyClass.getAnnotation(Bean.class); String name = bean.name(); if (StringUtils.isBlank(name)) { name = null; } // Class<?> groovyObjectExProxyClass = newProxyClassMap.get(groovyClass.getName()); // if (groovyObjectExProxyClass == null) { // String[] strs = new String[]{ // "package script.groovy.runtime;", // "import script.groovy.object.GroovyObjectEx", // "class GroovyObjectEx" + groovyClass.getSimpleName() + "Proxy extends " + groovyClass.getName() + " implements GroovyInterceptable{", // "private GroovyObjectEx<?> groovyObject;", // "public GroovyObjectEx" + groovyClass.getSimpleName() + "Proxy(GroovyObjectEx<?> groovyObject) {", // "this.groovyObject = groovyObject;", // "}", // "def invokeMethod(String name, args) {", //// "chat.logs.LoggerEx.info(\" PROXY \", \"Invoked \" + name + \" args \" + Arrays.toString(args));", // "Class<?> groovyClass = this.groovyObject.getGroovyClass();", // "def calledMethod = groovyClass.metaClass.getMetaMethod(name, args);", // "def returnObj = calledMethod?.invoke(this.groovyObject.getObject(), args);", // "return returnObj;", // "}", // "Class<?> getGroovyClass() {", // "Class<?> groovyClass = this.groovyObject == null ? null : this.groovyObject.getGroovyClass();", // "return groovyClass;", // "}", // "}" // }; // String proxyClassStr = StringUtils.join(strs, "\r\n"); // groovyObjectExProxyClass = getGroovyRuntime().getClassLoader().parseClass(proxyClassStr, // "/script/groovy/runtime/proxy/GroovyObjectEx" + groovyClass.getSimpleName() + "Proxy.groovy"); // // newProxyClassMap.put(groovyClass.getName(), groovyObjectExProxyClass); // } GroovyObjectEx groovyObjectEx = getObject(name, groovyClass, newBeanMap); try { groovyObjectEx.getObject(false); } catch (CoreException e) { e.printStackTrace(); } } } // ConcurrentHashMap<String, Class<?>> oldProxyClassMap = proxyClassMap; // proxyClassMap = newProxyClassMap; // if (oldProxyClassMap != null) // oldProxyClassMap.clear(); ConcurrentHashMap<String, GroovyObjectEx> oldBeanMap = beanMap; beanMap = newBeanMap; if (oldBeanMap != null) oldBeanMap.clear(); GroovyObjectEx.fillGroovyObjects(beanMap.values(), getGroovyRuntime()); } }
import java.util.Scanner; public class divisiblenumber { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt();int p=0;int arr[]=new int[t]; while(p<t) { int n=sc.nextInt(); if(n%2020==0||n%2020==2021) { int j=n-2020; if(j==0) { arr[p]=0; } else if(j%2021==0) { arr[p]=1; } else if(j%2020==0) { arr[p]=1; } else { arr[p]=0; } } else if(n%2021==0||n%2021==2020) { int j=n-2021; if(j==0) { arr[p]=0; } else if(j%2020==0) { arr[p]=1; } else if(j%2021==0) { arr[p]=1; } else { arr[p]=0; } } else if(n%2020!=0&&n%2021!=0) { arr[p]=0; } p++; } for(int i=0;i<t;i++) { if(arr[i]==1) { System.out.println("YES"); } else if(arr[i]==0) { System.out.println("NO"); } } } }
package com.github.iam20.http; import java.util.Map; public class HttpRequestMessageBuilder { private HttpRequestMessage httpRequestMessage; public HttpRequestMessageBuilder() { httpRequestMessage = new HttpRequestMessage(); } public HttpRequestMessageBuilder method(String method) { httpRequestMessage.setMethod(method.toUpperCase()); return this; } public HttpRequestMessageBuilder header(Map<String, String> header) { httpRequestMessage.setHeader(header); return this; } public HttpRequestMessageBuilder body(String body) { httpRequestMessage.setBody(body); return this; } public HttpRequestMessage build() { return httpRequestMessage; } }
package ws; public interface WebSocketCallback { public void onConnect(); public void onDisconnect(); public void onMessage(ws.Frame frame); public void onError(Throwable t); }
import java.awt.*; import java.util.*; import java.awt.event.*; import java.lang.*; import java.io.*; import java.net.*; import javax.swing.*; import java.math.*; import java.text.*; class RandomGuy { public Socket s; public BufferedReader sin; public PrintWriter sout; Random generator = new Random(); double t1, t2; int me; int boardState; int state[][] = new int[8][8]; // state[0][0] is the bottom left corner of the board (on the GUI) int turn = -1; int round; int validMoves[] = new int[64]; int numValidMoves; // main function that (1) establishes a connection with the server, and then plays whenever it is this player's turn public RandomGuy(int _me, String host) { me = _me; initClient(host); int myMove; while (true) { System.out.println("Read"); readMessage(); if (turn == me) { System.out.println("Move"); getValidMoves(round, state); myMove = move(); //myMove = generator.nextInt(numValidMoves); // select a move randomly String sel = validMoves[myMove] / 8 + "\n" + validMoves[myMove] % 8; System.out.println("Selection: " + validMoves[myMove] / 8 + ", " + validMoves[myMove] % 8); sout.println(sel); } } //while (turn == me) { // System.out.println("My turn"); //readMessage(); //} } // You should modify this function // validMoves is a list of valid locations that you could place your "stone" on this turn // Note that "state" is a global variable 2D list that shows the state of the game private int move() { // just move randomly for now int myMove = generator.nextInt(numValidMoves); return myMove; } // generates the set of valid moves for the player; returns a list of valid moves (validMoves) private void getValidMoves(int round, int state[][]) { int i, j; numValidMoves = 0; if (round < 4) { if (state[3][3] == 0) { validMoves[numValidMoves] = 3*8 + 3; numValidMoves ++; } if (state[3][4] == 0) { validMoves[numValidMoves] = 3*8 + 4; numValidMoves ++; } if (state[4][3] == 0) { validMoves[numValidMoves] = 4*8 + 3; numValidMoves ++; } if (state[4][4] == 0) { validMoves[numValidMoves] = 4*8 + 4; numValidMoves ++; } System.out.println("Valid Moves:"); for (i = 0; i < numValidMoves; i++) { System.out.println(validMoves[i] / 8 + ", " + validMoves[i] % 8); } } else { System.out.println("Valid Moves:"); for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { if (state[i][j] == 0) { if (couldBe(state, i, j)) { validMoves[numValidMoves] = i*8 + j; numValidMoves ++; System.out.println(i + ", " + j); } } } } } //if (round > 3) { // System.out.println("checking out"); // System.exit(1); //} } private boolean checkDirection(int state[][], int row, int col, int incx, int incy) { int sequence[] = new int[7]; int seqLen; int i, r, c; seqLen = 0; for (i = 1; i < 8; i++) { r = row+incy*i; c = col+incx*i; if ((r < 0) || (r > 7) || (c < 0) || (c > 7)) break; sequence[seqLen] = state[r][c]; seqLen++; } int count = 0; for (i = 0; i < seqLen; i++) { if (me == 1) { if (sequence[i] == 2) count ++; else { if ((sequence[i] == 1) && (count > 0)) return true; break; } } else { if (sequence[i] == 1) count ++; else { if ((sequence[i] == 2) && (count > 0)) return true; break; } } } return false; } private boolean couldBe(int state[][], int row, int col) { int incx, incy; for (incx = -1; incx < 2; incx++) { for (incy = -1; incy < 2; incy++) { if ((incx == 0) && (incy == 0)) continue; if (checkDirection(state, row, col, incx, incy)) return true; } } return false; } public void readMessage() { int i, j; String status; try { //System.out.println("Ready to read again"); turn = Integer.parseInt(sin.readLine()); if (turn == -999) { try { Thread.sleep(200); } catch (InterruptedException e) { System.out.println(e); } System.exit(1); } //System.out.println("Turn: " + turn); round = Integer.parseInt(sin.readLine()); t1 = Double.parseDouble(sin.readLine()); System.out.println(t1); t2 = Double.parseDouble(sin.readLine()); System.out.println(t2); for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { state[i][j] = Integer.parseInt(sin.readLine()); } } sin.readLine(); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } System.out.println("Turn: " + turn); System.out.println("Round: " + round); for (i = 7; i >= 0; i--) { for (j = 0; j < 8; j++) { System.out.print(state[i][j]); } System.out.println(); } System.out.println(); } public void initClient(String host) { int portNumber = 3333+me; try { s = new Socket(host, portNumber); sout = new PrintWriter(s.getOutputStream(), true); sin = new BufferedReader(new InputStreamReader(s.getInputStream())); String info = sin.readLine(); System.out.println(info); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } } // compile on your machine: javac *.java // call: java RandomGuy [ipaddress] [player_number] // ipaddress is the ipaddress on the computer the server was launched on. Enter "localhost" if it is on the same computer // player_number is 1 (for the black player) and 2 (for the white player) public static void main(String args[]) { new RandomGuy(Integer.parseInt(args[1]), args[0]); } }
package com.example.demo.controller; import com.example.demo.entity.PaymentSplitParams; import com.example.demo.service.IPaymentDetailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; /** * <p> * 到款详情 前端控制器 * </p> * * @author zjp * @since 2020-11-30 */ @RestController @RequestMapping("/payment") public class PaymentDetailController { private final IPaymentDetailService service; @Autowired public PaymentDetailController(IPaymentDetailService service) { this.service = service; } @PostMapping("export") public void export(HttpServletResponse response, @RequestBody PaymentSplitParams params) { service.export(response, params); } }
package com.goldenasia.lottery.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.Toast; import com.goldenasia.lottery.R; import com.goldenasia.lottery.app.BaseFragment; import com.goldenasia.lottery.base.net.RestCallback; import com.goldenasia.lottery.base.net.RestRequest; import com.goldenasia.lottery.base.net.RestResponse; import com.goldenasia.lottery.data.ChangePasswordCommand; import butterknife.BindView; import butterknife.OnClick; /** * 登录密码设置 * Created by Alashi on 2016/5/2. */ public class LoginPasswordSetting extends BaseFragment { @BindView(R.id.now_password) EditText nowPassword; @BindView(R.id.new_password) EditText newPassword; @BindView(R.id.new_password_verify) EditText newPasswordVerify; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.login_password, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @OnClick(R.id.submit) public void onSubmit() { if (!(check())) { return; } ChangePasswordCommand command = new ChangePasswordCommand(); command.setSa("modifyPassword"); command.setOldpassword(nowPassword.getText().toString()); command.setPassword(newPassword.getText().toString()); command.setPassword2(newPasswordVerify.getText().toString()); executeCommand(command, callback); } private RestCallback callback = new RestCallback() { @Override public boolean onRestComplete(RestRequest request, RestResponse response) { showToast("登录密码修改成功", Toast.LENGTH_SHORT); nowPassword.setText(""); newPassword.setText(""); newPasswordVerify.setText(""); return true; } @Override public boolean onRestError(RestRequest request, int errCode, String errDesc) { showToast("登录密码修改失败:" + errDesc, Toast.LENGTH_SHORT); return true; } @Override public void onRestStateChanged(RestRequest request, @RestRequest.RestState int state) { if (state == RestRequest.RUNNING) { showProgress("正在修改登录密码..."); } else { hideProgress(); } } }; private boolean check() { String now = nowPassword.getText().toString(); String newP = newPassword.getText().toString(); String newPv = newPasswordVerify.getText().toString(); if (now.isEmpty()) { showToast("请输入当前密码", Toast.LENGTH_SHORT); return false; } if (newP.isEmpty()) { showToast("请输入新密码", Toast.LENGTH_SHORT); return false; } if (newPv.isEmpty()) { showToast("请输入新密码", Toast.LENGTH_SHORT); return false; } if (newPv.length() < 6 || newP.length() < 6) { showToast("新密码太短,请重新输入", Toast.LENGTH_SHORT); return false; } if (newPv.length() > 20 || newP.length() > 20) { showToast("新密码太长,请重新输入", Toast.LENGTH_SHORT); return false; } if (!newP.equals(newPv)) { showToast("输入的新密码不一样,请重新输入", Toast.LENGTH_SHORT); return false; } if (now.equals(newP)) { showToast("当前密码和新密码一样,请重新输入", Toast.LENGTH_SHORT); return false; } String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$"; if (!newP.matches(regex)) { showToast("新密码必须包含数字和字母,请重新输入", Toast.LENGTH_SHORT); return false; } return true; } }
package com.aaron.mvpsample.view; public interface IMainView { void showToast(String msg); void showProgress(); void hideProgress(); void load(String data); String getInput(); void clearInput(); }
package util; import business.model.Date; public class HandleUserValidation { public static Boolean verifyLogin(String login) throws UserLoginException { Boolean tamanhoMinMax = false; Boolean dontContainNumber = false; try { tamanhoMinMax = login.matches("[a-zA-Z]{1,20}"); dontContainNumber = !login.matches(".*\\d.*"); if(!(tamanhoMinMax && dontContainNumber)){ throw new UserLoginException(); } } catch (UserLoginException e) { throw e; } return tamanhoMinMax && dontContainNumber; } public static Boolean verifyPassword(String password) throws UserPasswordException { Boolean checkPassword = false; try { checkPassword = password.matches("(?=(.*\\d){2})[a-zA-Z0-9]{8,12}"); if(!checkPassword){ throw new UserPasswordException(); } } catch (UserPasswordException e) { throw e; } return checkPassword; } public static Boolean verifyDate(Date date) throws DateFormatException { Boolean checkDate = false; try { checkDate = validateDate(date.showDate()); if(!checkDate){ throw new DateFormatException(); } } catch (DateFormatException e) { throw e; } return checkDate; } private static Boolean validateDate(String dateformat) { return dateformat.matches("^(?:(?:31(\\/|-|\\.)(?:0?[13578]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)(?:0?2)\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$"); } }
package com.sen.myshop.commons.persistence; import lombok.Data; import java.io.Serializable; /** * @Auther: Sen * @Date: 2019/8/10 02:17 * @Description: */ @Data public abstract class BaseTreeEntity<T extends BaseEntity> extends BaseEntity implements Serializable { private T parent; private Boolean isParent; }
package net.wasdev.ftadmin; public class Config { private String username; private String password; private String truststorePath; private String truststorePass; private String host; private String port; private String contrPackageDir; private Boolean clearCPD; public Config() { super(); this.username = null; this.password = null; this.truststorePath = null; this.truststorePass = null; this.host = null; this.port = null; this.contrPackageDir = null; this.clearCPD = null; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTruststorePath() { return truststorePath; } public void setTruststorePath(String truststorePath) { this.truststorePath = truststorePath; } public String getTruststorePass() { return truststorePass; } public void setTruststorePass(String truststorePass) { this.truststorePass = truststorePass; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getContrPackageDir() { return contrPackageDir; } public void setContrPackageDir(String contrPackageDir) { this.contrPackageDir = contrPackageDir; } public Boolean getClearCPD() { return clearCPD; } public void setClearCPD(Boolean clearCPD) { this.clearCPD = clearCPD; } }
package info.revenberg.loader.service; import info.revenberg.dao.jpa.BundleRepository; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.data.domain.Pageable; @Service public class BatchService { @Autowired private BatchRepository BatchRepository; public BatchService() { } public Long getLastReadCount() { return bundleRepository.getLastReadCount(); } }
package com.thoughtworks.userService.security; import com.thoughtworks.userService.model.User; import com.thoughtworks.userService.repository.UserRepository; import com.thoughtworks.userService.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; @Component public class LoginFilter extends OncePerRequestFilter { @Autowired private UserService userService; @Autowired private UserRepository userRepository; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = request.getHeader(HttpHeaders.AUTHORIZATION); if (token != null){ Long userId = userService.getUserIdByToken(token); if (userId == null){ response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } User user = userRepository.findOne(userId); SecurityContextHolder.getContext().setAuthentication( new UsernamePasswordAuthenticationToken( user,"",new ArrayList<>() ) ); } filterChain.doFilter(request,response); } }
package com.example.attest.model.api; import com.example.attest.model.domain.TransactionStatus; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import java.math.BigDecimal; import lombok.Builder; import lombok.Data; @Data @Builder @JsonInclude(Include.NON_NULL) public class TransactionStatusApiResponse { private String reference; private TransactionStatus status; private BigDecimal amount; private BigDecimal fee; }
package testforMe; import Prog1Tools.IOTools; public class EingabeTest { public static void main(String[] args) { int i = IOTools.readInt("Geben Sie ein int zahl ein"); System.out.println("Eingebene Zahl:"+i); } }
package com.evature.evasdk; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.graphics.Typeface; import android.graphics.drawable.AnimatedVectorDrawable; import android.graphics.drawable.TransitionDrawable; import android.os.Build; import android.os.Handler; import android.os.Message; import android.support.v4.content.ContextCompat; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.util.TypedValue; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.BounceInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.OvershootInterpolator; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; import com.evature.evasdk.appinterface.EvaAppSetup; import com.evature.evasdk.appinterface.EvaResult; import com.evature.evasdk.evaapis.EvaException; import com.evature.evasdk.evaapis.EvaSpeechRecogComponent; import com.evature.evasdk.model.appmodel.AppSearchModel; import com.evature.evasdk.user_interface.SoundLevelView; import com.evature.evasdk.evaapis.SpeechAudioStreamer; import com.evature.evasdk.model.ChatItem; import com.evature.evasdk.user_interface.ChatAdapter; import com.evature.evasdk.user_interface.ProgressWheel; import com.evature.evasdk.util.DLog; import com.evature.evasdk.util.VolumeUtil; /**** * User interface parts of the Evature chat screen */ public class EvatureMainView implements OnItemClickListener, EvaChatApi { private static final String TAG = "EvatureMainView"; private final ImageView mUndoIcon; private final ImageView mResetIcon; private ImageButton mSearchButton; private SoundLevelView mSoundView; private ImageButton mUndoButton; private ImageButton mResetButton; private ImageButton mVolumeButton; private View mSearchButtonCont; private ProgressWheel mProgressBar; private ArrayList<ChatItem> mChatListModel; private ChatAdapter mChatAdapter; private int mEditedChatItemIndex = -1; private EvaChatScreenComponent mEvaChatScreen; private ListView mChatListView; private boolean mSideButtonsVisible; private WeakReference<Handler> mUpdateLevel; public static final long UPDATE_SOUND_VIEW_INTERVAL = 60; // update the soundView every such ms final static float INITIAL_SCALE_SIDE_BUTTON = 0.64f; // should be in sync with XML scaleX/Y of restart_button and undo_button enum SearchButtonIcon{ MICROPHONE, FLAT, NONE }; SearchButtonIcon mSearchButtonIcon = SearchButtonIcon.MICROPHONE; @SuppressLint("NewApi") public EvatureMainView(final EvaChatScreenComponent mainScreen, ArrayList<ChatItem> chatList) { mEvaChatScreen = mainScreen; View view = mEvaChatScreen.getRootView(); mSearchButton = (ImageButton) view.findViewById(R.id.voice_search_button); mSoundView = (SoundLevelView)view.findViewById(R.id.surfaceView_sound_wave); mUndoButton = (ImageButton)view.findViewById(R.id.undo_button); mResetButton = (ImageButton)view.findViewById(R.id.restart_button); mSearchButtonCont = view.findViewById(R.id.voice_search_container); mProgressBar = (ProgressWheel)view.findViewById(R.id.progressBarEvaProcessing); mUndoIcon = (ImageView)view.findViewById(R.id.undo_icon); mResetIcon = (ImageView)view.findViewById(R.id.reset_icon); View.OnClickListener clickHandler = new View.OnClickListener() { @Override public void onClick(View view) { mEvaChatScreen.buttonClickHandler(view); } }; mUndoButton.setOnClickListener(clickHandler); mResetButton.setOnClickListener(clickHandler); mSearchButton.setOnClickListener(clickHandler); //mVolumeButton = (ImageButton) mainActivity.findViewById(R.id.volume_button); mChatListView = (ListView) view.findViewById(R.id.chat_list); // Connect the data of the chat history to the view: if (chatList == null) { mChatListModel = new ArrayList<ChatItem>(); } else { mChatListModel = chatList; } mChatAdapter = new ChatAdapter(mEvaChatScreen.getActivity(), this, R.layout.evature_row_eva_chat, R.id.label, mChatListModel); mChatListView.setAdapter(mChatAdapter); mChatListView.setOnItemClickListener(this); mSoundView.setColor(0xffffffff); mSoundView.setAlign(Gravity.RIGHT); //mProgressBar.getIndeterminateDrawable().setColorFilter(0xffffffff, android.graphics.PorterDuff.Mode.SRC_ATOP); mProgressBar.spin(); mSearchButton.setImageResource(R.drawable.evature_microphone_icon); setupSearchButtonDrag(); scrollToPosition(mChatAdapter.getCount() - 1); } public static void scaleButton(final View button, int duration, float fromScale, float toScale) { button.setVisibility(View.VISIBLE); // no idea why the 1.5 factor is needed, but without it the size is smaller than when using setScale! ScaleAnimation anim = new ScaleAnimation(fromScale, 1.5f*toScale, fromScale, 1.5f*toScale, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f ); anim.setDuration(duration); anim.setFillAfter(true); anim.setFillBefore(true); if (toScale > 0) { anim.setInterpolator(new OvershootInterpolator()); button.setEnabled(true); } else { button.setEnabled(false); anim.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { button.setVisibility(View.INVISIBLE); } }); } button.startAnimation(anim); } @SuppressLint("NewApi") public static void animateButton(final View button, String animProperty, int duration, float from, float to) { // TODO: use http://nineoldandroids.com/ (for compatibility with older devices) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { button.setVisibility(View.VISIBLE); Animator propAnim = ObjectAnimator.ofFloat(button, animProperty, from, to); propAnim.setInterpolator(new OvershootInterpolator()); propAnim.setDuration(duration); propAnim.start(); } } @SuppressLint("NewApi") private void toggleSideButtons(boolean show) { if (mSideButtonsVisible == show) { DLog.d(TAG, "Not toggling side buttons because already "+show); return; } mSideButtonsVisible = show; // use animation to show/hide buttons int animDuration = 400; if (show) { mResetIcon.setVisibility(View.INVISIBLE); mUndoIcon.setVisibility(View.INVISIBLE); // turn search button to shadow showMicButton(SearchButtonIcon.FLAT); animateButton(mSearchButton, "alpha", animDuration/2, 1.0f, 0.7f); // show undo/reset scaleButton(mUndoButton, animDuration, 0f, INITIAL_SCALE_SIDE_BUTTON); scaleButton(mResetButton, animDuration, 0f, INITIAL_SCALE_SIDE_BUTTON); } else { mResetIcon.setVisibility(View.VISIBLE); mUndoIcon.setVisibility(View.VISIBLE); // show search button showMicButton(SearchButtonIcon.MICROPHONE); animateButton(mSearchButton, "alpha", animDuration, 0.7f, 1.0f); animateButton(mSearchButtonCont, "translationX", animDuration, mSearchButtonCont.getTranslationX(), 0f); // hide undo/reset button scaleButton(mUndoButton, animDuration / 2, INITIAL_SCALE_SIDE_BUTTON, 0f); scaleButton(mResetButton, animDuration / 2, INITIAL_SCALE_SIDE_BUTTON, 0f); } } @SuppressLint("NewApi") private static void setTranslationX(View view, float translationX) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { view.setTranslationX(translationX); } else { TranslateAnimation anim = new TranslateAnimation(translationX, translationX, 0, 0); anim.setFillAfter(true); anim.setDuration(0); view.startAnimation(anim); } } Handler touchAnimTimerHandler = new Handler(); MotionEvent targetMotionEvent = null; Runnable touchAnimTimerRunnable = new Runnable() { @Override public void run() { if (targetMotionEvent == null) { return; } int[] searchButtonLocation = {0,0}; mSearchButton.getLocationOnScreen(searchButtonLocation); float origX = targetMotionEvent.getRawX(); float x = origX; float center = searchButtonLocation[0]+mSearchButton.getWidth()/2; int centerScreen = (((View)mResetButton.getParent()).getRight() + ((View)mUndoButton.getParent()).getLeft())/2; if (x > center) { x = center + Math.max(4, (x-center)/9); } else if (x < center) { x = center - Math.max(4, (center-x)/9); } // on initial touch-down move far enogh by touchMargin if (targetMotionEvent.getAction() == MotionEvent.ACTION_DOWN) { if (x > center && x <= centerScreen + mSearchButton.getWidth()/2 + touchMargin) { x = centerScreen + mSearchButton.getWidth()/2 + touchMargin + 1; } else if (x < center && x >= centerScreen - mSearchButton.getWidth()/2 - touchMargin) { x = centerScreen - mSearchButton.getWidth()/2 - touchMargin - 1; } } //DLog.i(TAG, ">>>> Faking event "+targetMotionEvent.getAction() + " from "+targetMotionEvent.getRawX()+" to " + x +" button now at "+center); MotionEvent event1 = MotionEvent.obtain( targetMotionEvent.getDownTime(), targetMotionEvent.getEventTime(), targetMotionEvent.getAction(), x, targetMotionEvent.getRawY(), targetMotionEvent.getMetaState() ); handleSearchButtonMotionEvent(event1, true); if (targetMotionEvent.getAction() == MotionEvent.ACTION_DOWN) { event1 = MotionEvent.obtain( event1.getDownTime(), event1.getEventTime(), MotionEvent.ACTION_MOVE, event1.getRawX(), event1.getRawY(), event1.getMetaState() ); handleSearchButtonMotionEvent(event1, true); MotionEvent event2 = MotionEvent.obtain( targetMotionEvent.getDownTime(), targetMotionEvent.getEventTime(), MotionEvent.ACTION_MOVE, origX, targetMotionEvent.getRawY(), targetMotionEvent.getMetaState() ); targetMotionEvent = event2; //DLog.i(TAG, ">> Faking move to "+targetMotionEvent.getRawX()); } if (targetMotionEvent.getAction() == MotionEvent.ACTION_UP) { targetMotionEvent = null; } else { touchAnimTimerHandler.postDelayed(this, 16); } } }; private View.OnTouchListener getTouchListener(final String txt){ View.OnTouchListener touchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { targetMotionEvent = MotionEvent.obtain(event); touchAnimTimerHandler.removeCallbacks(touchAnimTimerRunnable); touchAnimTimerRunnable.run(); return true; } }; return touchListener; } int touchMargin = -1; private void setupSearchButtonDrag() { Resources r = mEvaChatScreen.getActivity().getResources(); touchMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics()); ((View)mUndoIcon.getParent()).setOnTouchListener(getTouchListener("parent undo")); ((View) mResetIcon.getParent()).setOnTouchListener(getTouchListener("parent reset")); // mUndoButton.setOnTouchListener(getTouchListener("undo button")); // mResetButton.setOnTouchListener(getTouchListener("reset button")); mSearchButton.setOnTouchListener(new View.OnTouchListener() { @SuppressLint("NewApi") @Override public boolean onTouch(View v, MotionEvent event) { return handleSearchButtonMotionEvent(event, false); } }); } boolean hoveringReset = false; boolean hoveringUndo = false; private boolean handleSearchButtonMotionEvent(MotionEvent event, boolean isFake) { switch (event.getAction()) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: toggleSideButtons(false); if (event.getEventTime() - event.getDownTime() <= 500) { float x = event.getRawX() - mSearchButtonCont.getLeft(); float y = event.getRawY() - mSearchButtonCont.getTop(); if (y > mSearchButton.getTop()- touchMargin && x < mSearchButton.getRight() + touchMargin && x > mSearchButton.getLeft() - touchMargin ) { // mSearchButtonCont.performClick(); for some reason this doesn't work when the searchButton is embedded inside FrameLayout if (!isFake) { mEvaChatScreen.buttonClickHandler(mSearchButton); } } } if (hoveringUndo) { mUndoButton.performClick(); mUndoButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP); } if (hoveringReset) { mResetButton.performClick(); mResetButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP); } hoveringUndo = hoveringReset = false; break; case MotionEvent.ACTION_DOWN: hoveringUndo = false; hoveringReset = false; mSideButtonsVisible = false; break; case MotionEvent.ACTION_MOVE: float x = event.getRawX(); float y = event.getRawY(); // moved up, or recording started if (y < mSearchButtonCont.getTop()+ mSearchButton.getTop()- touchMargin || isRecording()) { toggleSideButtons(false); hoveringUndo = false; hoveringReset = false; break; } int searchRight = mSearchButtonCont.getLeft() + mSearchButton.getRight(); int searchLeft = mSearchButtonCont.getLeft() + mSearchButton.getLeft(); if (mSideButtonsVisible == false && isRecording() == false) { // show side buttons if long-press of beginning drag if (event.getEventTime() - event.getDownTime() > 500) { mSearchButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP); } if ((event.getEventTime() - event.getDownTime() > 500) || x > searchRight + touchMargin || x < searchLeft - touchMargin ) { toggleSideButtons(true); // // show drag shadow - if honeycomb+ // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // if (mSearchButtonShadow == null) { // mSearchButtonShadow = new View.DragShadowBuilder(); // } // mSearchButton.startDrag(ClipData.newPlainText("Nada", "Nothing"), (View.DragShadowBuilder)mSearchButtonShadow, null, 0); // } } } if (mSideButtonsVisible) { int searchCenter = (searchRight+searchLeft)/2; float delta = x - searchCenter; if (x > searchCenter+touchMargin) { FrameLayout resetButtonCont = (FrameLayout) mResetButton.getParent(); int resetButtonCenter = (resetButtonCont.getRight()+ resetButtonCont.getLeft())/2; delta = Math.min(delta, resetButtonCenter - searchCenter); // linearly scale button up based on distance float fraction = Math.min(1f, (x - searchCenter - touchMargin) / Math.max(1f, (resetButtonCenter - searchCenter - touchMargin))); // TODO: use com.nineoldandroids.view.ViewHelper for older devices if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { float scale = INITIAL_SCALE_SIDE_BUTTON + (1f-INITIAL_SCALE_SIDE_BUTTON)*fraction; mResetButton.clearAnimation(); mResetButton.setScaleX(scale); mResetButton.setScaleY(scale); if (mUndoButton.getAnimation() == null || mUndoButton.getAnimation().hasEnded()) { mUndoButton.setScaleX(INITIAL_SCALE_SIDE_BUTTON); mUndoButton.setScaleY(INITIAL_SCALE_SIDE_BUTTON); } } hoveringReset = fraction > 0.7; } else if (x < searchCenter-touchMargin) { FrameLayout undoButtonCont = (FrameLayout) mUndoButton.getParent(); int undoCenter = (undoButtonCont.getRight()+undoButtonCont.getLeft())/2; delta = Math.max(delta, undoCenter - searchCenter); // linearly scale button up based on distance float fraction = Math.min(1f, (searchCenter - touchMargin- x ) / Math.max(1f, (searchCenter - undoCenter - touchMargin))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { float scale = INITIAL_SCALE_SIDE_BUTTON + (1f-INITIAL_SCALE_SIDE_BUTTON)*fraction; mUndoButton.clearAnimation(); mUndoButton.setScaleX(scale); mUndoButton.setScaleY(scale); if (mResetButton.getAnimation() == null || mResetButton.getAnimation().hasEnded()) { mResetButton.setScaleX(INITIAL_SCALE_SIDE_BUTTON); mResetButton.setScaleY(INITIAL_SCALE_SIDE_BUTTON); } } hoveringUndo = fraction > 0.7; } setTranslationX(mSearchButtonCont, delta); } break; } return true; } public boolean isRecording() { if (mUpdateLevel != null && mUpdateLevel.get() != null) { SearchHandler handler = (SearchHandler)mUpdateLevel.get(); if (handler != null && handler.isRecording()) { return true; } } return false; } /********** UI of Recording button state **************/ @SuppressLint("NewApi") private void showMicButton(SearchButtonIcon what) { if (mSearchButtonIcon == what) { return; } if (what == SearchButtonIcon.FLAT) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mSearchButton.clearAnimation(); AnimatedVectorDrawable animatedDrawable = (AnimatedVectorDrawable) ContextCompat.getDrawable(mEvaChatScreen.getActivity(), R.drawable.evature_animated_microphone); mSearchButton.setImageDrawable(animatedDrawable); animatedDrawable.start(); // hide the flat microphone when the animation completes mSearchButton.postDelayed(new Runnable() { @Override public void run() { if (mSearchButtonIcon == SearchButtonIcon.FLAT) { mSearchButton.setImageDrawable(null); } } }, 450); // should be in sync with the animation duration defined in the xml } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mSearchButton.clearAnimation(); ValueAnimator animator = ValueAnimator.ofInt(mSearchButton.getPaddingTop(), mSearchButton.getHeight()/2); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator){ int val = ((Integer) valueAnimator.getAnimatedValue()).intValue(); mSearchButton.setPadding(mSearchButton.getPaddingLeft(), val, mSearchButton.getPaddingRight(), val); } }); animator.setDuration(450); animator.start(); } else { mSearchButton.setImageDrawable(null); } } else if (what == SearchButtonIcon.MICROPHONE) { if (isRecording()) { DLog.d(TAG, "Not setting to microphone icon because in recording"); return; // don't change back to icon if recording } // if (mProgressBar.getVisibility() == View.VISIBLE) { // // wait with icon switch until progressbar is hidden // pendingIconSwitch = true; // return; // } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mSearchButton.clearAnimation(); AnimatedVectorDrawable animatedDrawable = (AnimatedVectorDrawable) ContextCompat.getDrawable(mEvaChatScreen.getActivity(), R.drawable.evature_animated_microphone_reverse); mSearchButton.setImageDrawable(animatedDrawable); animatedDrawable.start(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mSearchButton.clearAnimation(); mSearchButton.setImageResource(R.drawable.evature_microphone_icon); ValueAnimator animator = ValueAnimator.ofInt(mSearchButton.getHeight()/2, 0); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator){ int val = ((Integer) valueAnimator.getAnimatedValue()).intValue(); mSearchButton.setPadding(mSearchButton.getPaddingLeft(), val, mSearchButton.getPaddingRight(), val); } }); animator.setDuration(450); animator.start(); } else { mSearchButton.setImageResource(R.drawable.evature_microphone_icon); } } else { mSearchButton.setImageDrawable(null); } mSearchButtonIcon = what; } public void activateSearchButton() { DLog.d(TAG, "activate search button"); mSearchButton.post(new Runnable() { @Override public void run() { //to show the recording is active mSearchButton.setEnabled(true); mProgressBar.setVisibility(View.GONE); mSearchButton.setBackgroundResource(R.drawable.evature_transition_button_activate); TransitionDrawable drawable = (TransitionDrawable) mSearchButton.getBackground(); drawable.startTransition(100); showMicButton(SearchButtonIcon.FLAT); } }); } @SuppressLint("NewApi") public void flashSearchButton(final int times) { // flash is used to draw user attention to button if (isRecording() || mSideButtonsVisible) { return; // do not flash button while recording, or while user is choosing side button } if (times == 0) { return; } if (times == -1) { DLog.d(TAG, "flash search button"); } mSearchButton.post(new Runnable() { @Override public void run() { if (times > 0) { mProgressBar.setVisibility(View.GONE); showMicButton(SearchButtonIcon.MICROPHONE); mSearchButton.setEnabled(true); bounceView(times, mSearchButtonCont); } mSearchButton.setBackgroundResource(R.drawable.evature_transition_button_activate); TransitionDrawable drawable = (TransitionDrawable) mSearchButton.getBackground(); final int duration = 150; drawable.startTransition(duration); mSearchButton.postDelayed(new Runnable() { @Override public void run() { // reverse the transition after it completes mSearchButton.setBackgroundResource(R.drawable.evature_transition_button_activate); TransitionDrawable drawable = (TransitionDrawable) mSearchButton.getBackground(); drawable.reverseTransition(duration); mSearchButton.postDelayed(new Runnable() { @Override public void run() { flashSearchButton(-(Math.abs(times)-1)); } }, duration); } }, duration); } }); } public static void bounceView(final int height, View view) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { bounceView(height, view, "translationY", -30); } // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // bounceView(height, view, "translationZ", 5); // } } @SuppressLint("NewApi") private static void bounceView(final int height, View view, String property, int heightFactor) { ObjectAnimator anim1 = ObjectAnimator.ofFloat(view, property, 0, heightFactor*height); final ObjectAnimator anim2 = ObjectAnimator.ofFloat(view, property, heightFactor*height, 0); anim1.setDuration(70*height); anim2.setDuration(300*height); anim1.setInterpolator(new DecelerateInterpolator()); anim2.setInterpolator(new BounceInterpolator()); anim1.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); anim2.start(); } }); anim1.start(); } public void disableSearchButton() { DLog.d(TAG, "disable search button"); mSearchButton.post(new Runnable() { @Override public void run() { mProgressBar.setVisibility(View.VISIBLE); mSearchButton.setEnabled(false); showMicButton(SearchButtonIcon.NONE); mSearchButton.setBackgroundResource(R.drawable.evature_transition_button_activate); TransitionDrawable drawable = (TransitionDrawable) mSearchButton.getBackground(); drawable.reverseTransition(50); mSearchButton.postDelayed(new Runnable() { @Override public void run() { mSearchButton.setBackgroundResource(R.drawable.evature_transition_button_dectivate); TransitionDrawable drawable = (TransitionDrawable) mSearchButton.getBackground(); drawable.startTransition(50); } }, 60); } }); } // return to normal button view public void deactivateSearchButton() { DLog.d(TAG, "deactivate search button"); mSearchButton.post(new Runnable() { @Override public void run() { mProgressBar.setVisibility(View.GONE); mSearchButton.setEnabled(true); showMicButton(SearchButtonIcon.MICROPHONE); mSearchButton.setBackgroundResource(R.drawable.evature_transition_button_activate); TransitionDrawable drawable = (TransitionDrawable) mSearchButton.getBackground(); drawable.reverseTransition(100); mSearchButton.postDelayed(new Runnable() { @Override public void run() { mSearchButton.setBackgroundResource(R.drawable.evature_transition_button_activate); TransitionDrawable drawable = (TransitionDrawable) mSearchButton.getBackground(); drawable.resetTransition(); } }, 110); } }); } @SuppressLint("NewApi") public void flashBadSearchButton(final int times) { if (isRecording() || mSideButtonsVisible) { return; } if (times == 0) { return; } if (times == -1) { DLog.d(TAG, "flash bad search button"); } mSearchButton.post(new Runnable() { @Override public void run() { if (times > 0) { mProgressBar.setVisibility(View.GONE); showMicButton(SearchButtonIcon.MICROPHONE); mSearchButton.setEnabled(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ObjectAnimator anim = ObjectAnimator.ofFloat(mSearchButtonCont, "translationX", 50, -50f); anim.setDuration(110); anim.setRepeatCount(times); anim.setRepeatMode(ValueAnimator.REVERSE); anim.setInterpolator(new AccelerateDecelerateInterpolator()); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); mSearchButtonCont.setTranslationX(0); } }); anim.start(); } else { TranslateAnimation anim = new TranslateAnimation(50f, -50f, 0, 0); anim.setDuration(110); anim.setRepeatCount(times); anim.setInterpolator(new AccelerateDecelerateInterpolator()); anim.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { setTranslationX(mSearchButtonCont, 0); } }); mSearchButtonCont.startAnimation(anim); } } mSearchButton.setBackgroundResource(R.drawable.evature_transition_button_bad); TransitionDrawable drawable = (TransitionDrawable) mSearchButton.getBackground(); drawable.startTransition(100); mSearchButton.postDelayed(new Runnable() { @Override public void run() { mSearchButton.setBackgroundResource(R.drawable.evature_transition_button_bad); TransitionDrawable drawable = (TransitionDrawable) mSearchButton.getBackground(); drawable.reverseTransition(150); // repeat mSearchButton.postDelayed(new Runnable() { public void run() { flashBadSearchButton(-(Math.abs(times)-1)); } }, 110); } }, 110); } }); } private boolean mainButtonsShown = true; public boolean areMainButtonsShown() { return mainButtonsShown && !mSideButtonsVisible; } // used to hide microphone when editing existing chatItem public void toggleMainButtons(boolean showMainButtons) { mainButtonsShown = showMainButtons; DLog.d(TAG, "Setting main button to " + showMainButtons); FrameLayout undoButtonCont = (FrameLayout) mUndoButton.getParent(); FrameLayout resetButtonCont = (FrameLayout) mResetButton.getParent(); mSearchButtonCont.setVisibility(showMainButtons ? View.VISIBLE : View.GONE); undoButtonCont.setVisibility(showMainButtons ? View.VISIBLE : View.GONE); resetButtonCont.setVisibility(showMainButtons ? View.VISIBLE : View.GONE); } public void hideSpeechWave() { if (mUpdateLevel != null) { Handler handler = mUpdateLevel.get(); if (handler != null) handler.removeMessages(0); mUpdateLevel = null; } mSoundView.setVisibility(View.GONE); } /*********** Update View based on Recording Volume **************/ static class SearchHandler extends Handler { private boolean processing = false; private EvaSpeechRecogComponent speechSearch; private EvatureMainView view; private int lastInd = -1; public SearchHandler(EvaSpeechRecogComponent speechSearch, EvatureMainView view) { this.speechSearch = speechSearch; this.view = view; } public boolean isRecording() { return speechSearch.getSpeechAudioStreamer().getIsRecording(); } @Override public void handleMessage(Message msg) { SpeechAudioStreamer speechAudioStreamer = speechSearch.getSpeechAudioStreamer(); if (speechAudioStreamer.getIsRecording()) { if (speechAudioStreamer.getBufferIndex() != lastInd) { lastInd = speechAudioStreamer.getBufferIndex(); view.mSoundView.setSoundData( speechAudioStreamer.getSoundLevelBuffer(), speechAudioStreamer.getBufferIndex() ); //view.mSoundView.stopSpringAnimation(); if (view.mSoundView.getVisibility() != View.VISIBLE) view.mSoundView.setVisibility(View.VISIBLE); } } else { // continue sending data to soundView - but fake it as a zero volume sound speechAudioStreamer.addVolumeSampleForVisulazation(speechAudioStreamer.getMinSoundLevel()); view.mSoundView.setSoundData( speechAudioStreamer.getSoundLevelBuffer(), speechAudioStreamer.getBufferIndex() ); if (speechAudioStreamer.wasNoise && !processing) { processing = true; view.disableSearchButton(); //view.showStatus("Processing..."); } } sendEmptyMessageDelayed(0, UPDATE_SOUND_VIEW_INTERVAL); super.handleMessage(msg); } } public void startSpeechRecognition(final EvaSpeechRecogComponent speechSearch, Object cookie) { //showStatus("Listening..."); mUpdateLevel = new WeakReference<Handler>(new SearchHandler(speechSearch, this)); try { Handler handler = mUpdateLevel.get(); if (handler != null) { speechSearch.startRecognizer(cookie); handler.sendEmptyMessage(0); } else { throw new EvaException("updateVolume Level is null"); } activateSearchButton(); } catch (EvaException e) { DLog.e(TAG, "Exception starting recorder", e); } } /************ Chat item interaction **************/ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ChatItem item = (ChatItem) view.getTag(); if (item == null) { if (mEditedChatItemIndex != -1) { closeEditChatItem(false); } return; } switch (item.getType()) { // case DialogAnswer: // clickedDialogAnswer(item); // break; case MultiChoiceQuestion: case Eva: if (item.getSearchModel() != null) { AppSearchModel model = item.getSearchModel(); if (EvaAppSetup.tapChatToActivate) { model.setIsComplete(true); } if (model.getIsComplete()) { EvaResult result = model.triggerSearch(mEvaChatScreen.getActivity()); mEvaChatScreen.handleCallbackResult(result, null, item); return; } } editEvaChat(item, position); break; case EvaWelcome: if (mEditedChatItemIndex != -1) { closeEditChatItem(false); } else { showExamples(); } break; case User: editMeChat(item, position); break; } } /* private void clickedDialogAnswer(ChatItem item) { DialogAnswerChatItem dialogItem = (DialogAnswerChatItem) item; DialogQuestionChatItem question = dialogItem.getQuestion(); if (question.isAnswered()) { return; // already answered } dialogItem.setChosen(); // remove un-chosen answers ArrayList<Integer> indexesToRemove = new ArrayList<Integer>(); for (DialogAnswerChatItem answer : question.getAnswers()) { if (answer.isChosen() == false) { indexesToRemove.add(mChatListModel.indexOf(answer)); //mChatAdapter.remove(answer); } } mAnimAdapter.animateDismiss(indexesToRemove); addChatItem(new ChatItem(dialogItem.getChat())); // move this to mainActivity //eva.replyToDialog(dialogItem.getIndex()); }*/ public void addChatItem(final ChatItem chatItem) { mEvaChatScreen.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (mEditedChatItemIndex != -1 && chatItem.getType() == ChatItem.ChatType.User) { // adding a "me" chat - close the editted me-chat closeEditChatItem(false); } if (mChatAdapter != null) { mChatAdapter.add(chatItem); scrollToPosition(mChatAdapter.getCount() - 1); } else if (mChatListModel != null) { mChatListModel.add(chatItem); scrollToPosition(mChatListModel.size() - 1); } } }); } private void addUtterance() { if (mEditedChatItemIndex != -1) { closeEditChatItem(false); } ChatItem editChat = new ChatItem(""); editChat.setStatus(ChatItem.Status.EDITING); toggleMainButtons(false); addChatItem(editChat); mEditedChatItemIndex = mChatListModel.size()-1; mEvaChatScreen.addEmptyFragment(); } private void editEvaChat(ChatItem item, int position) { if (EvaAppSetup.tapToEditChat == false) { return; } if (mEditedChatItemIndex != -1) { closeEditChatItem(false); } else { if (item.getType() == ChatItem.ChatType.MultiChoiceQuestion) { // search for "Me" chat after for (int i=position+1; i<mChatListModel.size(); i++) { ChatItem itemAfter = mChatListModel.get(i); if (itemAfter.getType() == ChatItem.ChatType.User) { editMeChat(itemAfter, i); return; } } // no me chat after question - add one addUtterance(); } else { // search for last "Me" chat before for (int i=mChatListModel.size()-1; i>0; i--) { ChatItem itemBefore = mChatListModel.get(i); if (itemBefore.getType() == ChatItem.ChatType.User) { editMeChat(itemBefore, i); return; } } // no me-chat - add one addUtterance(); } } } private void editMeChat(ChatItem current, int position) { if (EvaAppSetup.tapToEditChat == false) { return; } if (mEditedChatItemIndex != -1) { closeEditChatItem(false); } else { // you can only edit the last utterance - make sure there isn't another one of type User later on for (int i=position+1; i< mChatListModel.size(); i++ ) { ChatItem itemAfter = mChatListModel.get(i); if (itemAfter.getType() == ChatItem.ChatType.User) { Toast.makeText(mEvaChatScreen.getActivity(), "You can only modify your last utterance", Toast.LENGTH_SHORT).show(); return; } } if (current.getStatus() != ChatItem.Status.EDITING) { current.setStatus(ChatItem.Status.EDITING); toggleMainButtons(false); mEditedChatItemIndex = position; mChatAdapter.notifyDataSetChanged(); } mEvaChatScreen.addEmptyFragment(); } } private ChatItem exampleChatItem; private void showExamples() { if (exampleChatItem != null && mChatListModel.contains(exampleChatItem)) { mChatListModel.remove(exampleChatItem); exampleChatItem = null; } Resources resources = mEvaChatScreen.getActivity().getResources(); List<String> examples = mEvaChatScreen.getExamplesStrings(); // select random subset int MAX_NUM_OF_EXAMPLES = 5; int numOfExamples = Math.min(MAX_NUM_OF_EXAMPLES, examples.size()); Random rand = new Random(System.currentTimeMillis()); for (int i=0; i< numOfExamples; i++) { Collections.swap(examples, i, rand.nextInt(examples.size())); } String greeting = resources.getString(R.string.evature_examples_greetings); String examplesString = ""; for (int i=0; i< numOfExamples; i++) { examplesString += "\n "+examples.get(i).trim(); } SpannableString chatFormatted = new SpannableString(greeting+examplesString); int col = resources.getColor(R.color.evature_chat_secondary_text); chatFormatted.setSpan(new ForegroundColorSpan(col), greeting.length(), chatFormatted.length(), 0); chatFormatted.setSpan(new StyleSpan(Typeface.ITALIC), greeting.length(), chatFormatted.length(), 0); exampleChatItem = new ChatItem(chatFormatted, null, ChatItem.ChatType.Eva); exampleChatItem.clearAlreadyAnimated(); addChatItem(exampleChatItem); flashSearchButton(5); } public View getViewForChatItem(ChatItem chatItem) { return mChatListView.findViewWithTag(chatItem); } /*** * Close the chat-utterance that is being edited right now * * @param isSubmitted - true if submit modification, false if revert to pre-modified text (or remove new utterance) */ private void closeEditChatItem(boolean isSubmitted) { mEvaChatScreen.removeEmptyFragment(); if (mEditedChatItemIndex == -1) { DLog.e(TAG, "Unexpected closed edit chat item"); return; } if (mEditedChatItemIndex >= mChatListModel.size()) { DLog.e(TAG, "Edited item "+mEditedChatItemIndex+" but chatList size is "+mChatListModel.size()); return; } InputMethodManager imm = (InputMethodManager) mEvaChatScreen.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); if (imm == null) { DLog.e(TAG, "no input method manager"); } else { imm.hideSoftInputFromWindow(mChatListView.getWindowToken(), 0); } ChatItem editedChatItem = mChatListModel.get(mEditedChatItemIndex); editedChatItem.setStatus(ChatItem.Status.NONE); toggleMainButtons(true); String preModifiedString = editedChatItem.getChat().toString(); if (isSubmitted) { View rowView = getViewForChatItem(editedChatItem); if (rowView == null) { DLog.e(TAG, "Unexpected edited row not found"); return; } EditText editText = (EditText)rowView.findViewById(R.id.editText); if (editText == null) { DLog.e(TAG, "Unexpected editText not found"); return; } // if the pre-edit text is empty - this is a new chat to be added - not existing chat to edit boolean editLastUtterance = !preModifiedString.equals(""); Spannable preEditChat = editedChatItem.getChat(); String newText = editText.getText().toString(); editedChatItem.setChat(newText); mEvaChatScreen.onEventChatItemModified(editedChatItem, preEditChat, false, editLastUtterance); } else { // not submitting - just canceling edit // if this chat was empty text (new chat) - cancel adding it if (preModifiedString.equals("")) { mChatAdapter.dismissItem(mChatListView, mEditedChatItemIndex, ChatAdapter.DismissStep.ANIMATE_DISMISS); mChatAdapter.dismissItem(mChatListView, mEditedChatItemIndex, ChatAdapter.DismissStep.DO_DELETE); } } mEditedChatItemIndex = -1; mChatAdapter.notifyDataSetChanged(); } public void dismissItems(int start, int end, ChatAdapter.DismissStep step) { if (start < 0) { return; } mChatAdapter.dismissItems(mChatListView, start, end, step); if (step == ChatAdapter.DismissStep.ANIMATE_RESTORE) { scrollToPosition(end-1); } else if (step == ChatAdapter.DismissStep.ANIMATE_DISMISS) { scrollToPosition(start-1); } } @SuppressLint("NewApi") public void scrollToPosition(final int scrollTo) { mChatListView.post(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mChatListView.smoothScrollToPositionFromTop(scrollTo, 110); } else { mChatListView.smoothScrollToPosition(scrollTo); } } }); } public final OnEditorActionListener editorActionHandler = new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { DLog.d(TAG, "editor Action "+actionId); if (mEditedChatItemIndex == -1) { DLog.e(TAG, "Unexpected execute no edit chat item"); return false; } closeEditChatItem(true); return false; } }; /** * If a chat item is edited - back will close the edit * @return true if back button was useful */ public boolean handleBackPressed() { if (mEditedChatItemIndex == -1) { return false; } closeEditChatItem(false); return true; } public void clearChatHistory() { if (mEditedChatItemIndex != -1) { closeEditChatItem(false); } mChatAdapter.clear(); } public ArrayList<ChatItem> getChatListModel() { return mChatListModel; } public void notifyDataChanged() { mEvaChatScreen.getActivity().runOnUiThread(new Runnable() { @Override public void run() { mChatAdapter.notifyDataSetChanged(); } }); } public void voiceResponseToChatItem(ChatItem storeResultInItem, SpannableString chat) { if (mEditedChatItemIndex != -1) { closeEditChatItem(false); } storeResultInItem.setChat(chat); dismissItems(mChatListModel.indexOf(storeResultInItem) + 1, mChatListModel.size(), ChatAdapter.DismissStep.DO_DELETE); } public void setVolumeIcon() { if (mVolumeButton == null) { return; } VolumeUtil.checkVolume(this.mEvaChatScreen.getActivity()); if (VolumeUtil.isLowVolume()) { mVolumeButton.setVisibility(View.VISIBLE); mVolumeButton.setImageResource(VolumeUtil.getVolumeIcon()); } else { mVolumeButton.setVisibility(View.GONE); } } }
package cn.ctw.spider.controller; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.ctw.spider.SpiderApplication; import cn.ctw.spider.service.QueryMovieService; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=SpiderApplication.class) public class QueryMovieServiceTest { @Autowired private QueryMovieService queryMovieService; @Test public void queryMovieDetailsByMidTest(){ queryMovieService.queryMovieDetailsByMid("641515"); } @Test public void everyDayBoxOfficeList(){ queryMovieService.everyDayBoxOfficeList("641515"); } @Test public void realtimeRank(){ queryMovieService.realtimeRank(); } }
package com.tyland.musicbox.ui; import android.content.pm.PackageManager; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.TextView; import com.tyland.musicbox.R; import com.tyland.musicbox.data.MusicDataAccess; import com.tyland.musicbox.model.Music; import com.tyland.musicbox.util.Log; import com.tyland.musicbox.util.PermissionUtils; import com.tyland.musicbox.util.Utils; import com.tyland.swipemenulistview.SwipeMenu; import com.tyland.swipemenulistview.SwipeMenuCreator; import com.tyland.swipemenulistview.SwipeMenuItem; import com.tyland.swipemenulistview.SwipeMenuListView; import java.util.List; /** * Created by tyland on 2018/4/28. */ public class MusicFragment extends BaseFragment implements AdapterView.OnItemClickListener { private SwipeMenuListView mListView; private List<Music> mMusicList; private MusicAdapter mAdapter; private static final int ADD_MENU = 0; @Override public View getView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_music_list, container, false); mListView = (SwipeMenuListView) view.findViewById(R.id.lv_music_list); checkPermission(PermissionUtils.CODE_READ_EXTERNAL_STORAGE); setEmptyListView(view, mListView); mListView.setOnItemClickListener(this); // mListView.setMenuCreator(creator); mListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(int position, SwipeMenu menu, int index) { switch (index) { case ADD_MENU: // open Log.d("添加" + mMusicList.get(position).getTitle()); break; } // false : close the menu; true : not close the menu return false; } }); mListView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT); return view; } @Override public void onPermissionGranted(int requestCode) { updateMusicData(); setAdapter(); } @Override public void onPermissionDenied(int requestCode) { setAdapter(); } private void updateMusicData() { Log.d("update music data........"); Bundle arg = getArguments(); MusicDataAccess access = new MusicDataAccess(getContext()); if (arg == null) { mMusicList = access.getAllMusic(); } else { long albumId = arg.getLong(AlbumDetailActivity.KEY_ALBUM_ID); mMusicList = access.getMusicByAlbumId(albumId); } } private void setAdapter() { if (mAdapter == null) { mAdapter = new MusicAdapter(); } else { mAdapter.notifyDataSetChanged(); } mListView.setAdapter(mAdapter); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Music music = mMusicList.get(position); Log.d("点击了" + music.getTitle()); getCurrentActivity().addToPlayQueue(music); getService().play(music); Log.d(music.toString()); } SwipeMenuCreator creator = new SwipeMenuCreator() { @Override public void create(SwipeMenu menu) { SwipeMenuItem addItem = new SwipeMenuItem(getActivity()); addItem.setBackground(getResources().getDrawable(R.drawable.btn_add_queue)); addItem.setWidth(getResources().getDimensionPixelOffset(R.dimen.list_swipe_item_width)); addItem.setTitle(getString(R.string.add_to_queue)); addItem.setTitleSize(Utils.px2dp(getContext(), getResources().getDimensionPixelSize(R.dimen.text_add_swipe_menu_size))); addItem.setTitleColor(Color.WHITE); menu.addMenuItem(ADD_MENU, addItem); } }; private class MusicAdapter extends BaseAdapter { @Override public int getCount() { return mMusicList == null ? 0 : mMusicList.size(); } @Override public Object getItem(int position) { return mMusicList.get(position); } @Override public long getItemId(int position) { return mMusicList.get(position).getId(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate( R.layout.view_music_items, parent, false); holder = new ViewHolder(); holder.tvMusicTitle = (TextView) convertView.findViewById(R.id.tv_music_title); holder.tvMusicArtist = (TextView) convertView.findViewById(R.id.tv_music_album); holder.tvMusicDuration = (TextView) convertView.findViewById(R.id.tv_music_duration); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Music music = mMusicList.get(position); holder.tvMusicTitle.setText(music.getTitle()); holder.tvMusicArtist.setText(music.getArtist()); holder.tvMusicDuration.setText(Utils.timeFormatTommss(music.getDuration())); return convertView; } private class ViewHolder { TextView tvMusicTitle; TextView tvMusicArtist; TextView tvMusicDuration; } } }
package cn.sau.one.po; import java.util.Date; public class Picture { private Integer pictureId; private String pictureUrl; private String pictureType; private Date pictureTime; private Integer userId; public Integer getPictureId() { return pictureId; } public void setPictureId(Integer pictureId) { this.pictureId = pictureId; } public String getPictureUrl() { return pictureUrl; } public void setPictureUrl(String pictureUrl) { this.pictureUrl = pictureUrl == null ? null : pictureUrl.trim(); } public String getPictureType() { return pictureType; } public void setPictureType(String pictureType) { this.pictureType = pictureType == null ? null : pictureType.trim(); } public Date getPictureTime() { return pictureTime; } public void setPictureTime(Date pictureTime) { this.pictureTime = pictureTime; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } }