text
stringlengths
10
2.72M
package com.anonymous9495.mashit; import java.io.Serializable; /** * Created by staffonechristian on 2017-09-09. */ public class UserData implements Serializable{ private String name; private String emailId; private String fbId; private String userId; private int hotScore; private String gender; private String profilePicUri; public UserData(){ this.hotScore=0; } public String getProfilePicUri() { return profilePicUri; } public void setProfilePicUri(String profilePicUri) { this.profilePicUri = profilePicUri; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getFbId() { return fbId; } public void setFbId(String fbId) { this.fbId = fbId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public int getHotScore() { return hotScore; } public void setHotScore(int hotScore) { this.hotScore = hotScore; } }
// 插入与归并(25) import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main { private static int[] strSplit(String string) { String[] split = string.split(" "); int[] splited = new int[split.length]; for (int i=0;i<split.length;i++) { splited[i] = Integer.parseInt(split[i]); } return splited; } // private static void merge(int[] a,int low,int high,int mid) // { // int[] temp = new int[high-low+1]; // // int i = low; // int j = mid+1; // int k = 0; // while (i<=mid && j<=high) // { // // 较小的移入数组 // if (a[i]<a[j]) // { // temp[k++] = a[i++]; // }else { // temp[k++] = a[j++]; // } // } // // while (i<=mid) // { // temp[k++] = a[i++]; // } // // while (j<=high) // { // temp[k++] = a[j++]; // } // // for (int k1=0;k1<temp.length;k1++) // { // a[k1+low] = temp[k1]; // } // // System.out.println(Arrays.toString(a)); // // } // private static void mergerSort(int[] a,int low,int high) // { // int mid = (high + low) / 2; // if (low<high) // { // // 左归并 // mergerSort(a,low,mid); // // 右归并 // mergerSort(a,mid+1,high); // // 归并 // merge(a,low,high,mid); // } // } private static void isMergeEqual(int[] com,int[] origin,int step) { int inital = 0; int end = inital + step; while (end<com.length+1) { Arrays.sort(origin,inital,end); inital = end; end = inital + step; } if (end<com.length) { Arrays.sort(origin,end,origin.length); } // for (int inital=0;;inital) } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = Integer.parseInt(scanner.nextLine()); int[] origin = strSplit(scanner.nextLine()); int[] comp = strSplit(scanner.nextLine()); ArrayList<Integer> integers = new ArrayList<>(); // 如果前面的数都有序,后面是原始序列,那么就是插入 // 即找出与原始序列不一样的,然后看后面是否完全一样 int flag = 0; // 之前的可能都无序 for (int i=1;i<origin.length;i++) { if (origin[i] == comp[i]) { flag = i; break; } } boolean isSort = true; for (int i=flag;i<origin.length;i++) { if (origin[i] != comp[i]) { // 不完全一样 isSort = false; break; } } if (isSort) { System.out.println("Insertion Sort"); Arrays.sort(origin,0,flag+1); // System.out.println(Arrays.toString(origin)); // 这个输出格式改下 }else { System.out.println("Merge Sort"); for (int step=1;step<comp.length;step *= 2) { isMergeEqual(comp,origin,step); // System.out.println("step:"+step+";"+Arrays.toString(origin)); if (Arrays.equals(comp,origin)) { // System.out.println("相等:"+Arrays.toString(origin)); // 再执行一次 isMergeEqual(comp,origin,step<<1); break; } } } StringBuilder stringBuilder = new StringBuilder(3 * comp.length); for (Integer integer:origin) { stringBuilder.append(integer); stringBuilder.append(" "); } stringBuilder.deleteCharAt(stringBuilder.length()-1); System.out.println(stringBuilder.toString()); // System.out.println(isSort); System.out.println(flag); // 它的下一次输出是后面一个非有序的数 } }
package com.zhongyp.spring.demo.annotation; import com.sun.istack.internal.NotNull; import com.sun.istack.internal.Nullable; import lombok.NonNull; /** * @author zhongyp. * @date 2019/7/4 */ public class NullAnnotation { // @Nullable public static String nullable(@Nullable String b){ System.out.println(b); return b; } // @NotNull public static String notNull(@NotNull String b){ System.out.println(b); return b; } // @com.sun.istack.internal.Nullable public static String internalNullable(@com.sun.istack.internal.Nullable String b){ System.out.println(b); return b; } @NonNull public static String nonNull(@NonNull String b){ System.out.println(b); return b; } public static void main(String[] args) { NullAnnotation.notNull(null); NullAnnotation.nonNull(null); NullAnnotation.nullable(null); } }
package controller; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import entity.StaffEntity; import service.LoginService; import service.StaffService; import service.impl.LoginServiceImpl; @Controller @RequestMapping public class StaffController { @Resource(name="staffService") private StaffService staffService; @RequestMapping("/login") public String login(HttpRequest request,HttpSession session){ LoginService loginService=new LoginServiceImpl(); boolean isLogin=loginService.isLogin((Integer)session.getAttribute("id"), session.getAttribute("password").toString()); if (isLogin) { return "staff/main"; } return "staff/login"; } @RequestMapping(name="/test") public String test(){ StaffEntity staffEntity=new StaffEntity(); staffEntity.setStaffId(321); staffEntity.setStaffName("test"); staffEntity.setPassword("321"); staffService.addStaff(staffEntity); return "test"; } }
import java.io.BufferedInputStream; import java.util.*; /** * @author EasonZz */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); int n = sc.nextInt(); if (n < 3) { System.out.println(0); return; } int left = sc.nextInt(), mid = sc.nextInt(), right; int count = 0; for (int i = 0; i < n - 2; i++) { right = sc.nextInt(); if ((mid > left && mid > right) || (mid < left && mid < right)) { count++; } left = mid; mid = right; } System.out.println(count); } }
package com.example.bouncingball; import android.graphics.Paint; public class Bloque { private Paint pincel; private int anchoBloque; private int altoBloque; private int posX; private int posY; private int dureza; private int id; private int nroFila; private int nroColumna; private int puntaje; public Bloque (int posX, int posY, int ancho, int alto){ this.posX=posX; this.posY=posY; this.anchoBloque=ancho; this.altoBloque=alto; this.pincel=pincel; this.id=id; this.puntaje=100; } public Bloque (int posX, int posY, int ancho, int alto, Paint pincel, int est){ this.posX=posX; this.posY=posY; this.anchoBloque=ancho; this.altoBloque=alto; this.pincel=pincel; this.dureza=est; this.id=id; this.puntaje=100; } public int getNroColumna() { return nroColumna; } public void setNroColumna(int nroColumna) { this.nroColumna = nroColumna; } public int getNroFila() { return nroFila; } public int getDureza() { return dureza; } public void setDureza(int dureza) { this.dureza = dureza; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Paint getPincel() { return pincel; } public void setPincel(Paint pincel) { this.pincel = pincel; } public int getAnchoBloque() { return anchoBloque; } public int getAltoBloque() { return altoBloque; } public int getPosX() { return posX; } public void setPosX(int posX) { this.posX = posX; } public int getPosY() { return posY; } public void setPosY(int posY) { this.posY = posY; } public int getPuntaje() { return puntaje; } }
/** * Sencha GXT 3.0.1 - Sencha for GWT * Copyright(c) 2007-2012, Sencha, Inc. * licensing@sencha.com * * http://www.sencha.com/products/gxt/license/ */ package com.sencha.gxt.desktopapp.client.spreadsheet; import com.sencha.gxt.desktopapp.client.FileBasedMiniAppView; public interface SpreadsheetView extends FileBasedMiniAppView { int getSelectedColumn(); int getSelectedRow(); void refresh(); void setValue(Worksheet worksheet); void updateDetails(String cellName, String cellValue); void updateGrid(); void updateSelectedCells(String value); }
package DesignPattern.Decorator; public class FilmStar extends Modeling { public FilmStar(){ super(); System.out.println(" FilmStart cost 5000"); setPrice(5000f); } @Override public void show() { } @Override public float cost() { // TODO Auto-generated method stub return super.getPrice(); } }
package ua.siemens.dbtool.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ua.siemens.dbtool.dao.JobTypeDAO; import ua.siemens.dbtool.dao.WorkPackageTypeDAO; import ua.siemens.dbtool.model.auxilary.JobType; import ua.siemens.dbtool.model.auxilary.WorkPackageType; import ua.siemens.dbtool.service.JobTypeService; import ua.siemens.dbtool.service.JsonService; import java.util.Collection; import java.util.Comparator; import java.util.stream.Collectors; /** * Implementation of {@link JobType} * * @author Perevoznyk Pavlo * creation date 29 August 2017 * @version 1.0 */ @Service public class JobTypeServiceImpl implements JobTypeService { private static final Logger LOG = LoggerFactory.getLogger(JobTypeServiceImpl.class); private JobTypeDAO jobTypeDAO; private WorkPackageTypeDAO workPackageTypeDAO; private JsonService jsonService; @Autowired public JobTypeServiceImpl(JobTypeDAO jobTypeDAO, WorkPackageTypeDAO workPackageTypeDAO, JsonService jsonService) { this.jobTypeDAO = jobTypeDAO; this.workPackageTypeDAO = workPackageTypeDAO; this.jsonService = jsonService; } @Override @Transactional public void save(JobType jobType) { jobTypeDAO.save(jobType); } @Override @Transactional public void save(String jobType) { JobType newJobType = jsonService.convertJsonToJobType(jobType); WorkPackageType wpType = workPackageTypeDAO.findById(newJobType.getWpTypeId()); if (wpType.getJobTypes().contains(newJobType)) { throw new DataIntegrityViolationException("Job type exists already!"); } wpType.getJobTypes().add(newJobType); workPackageTypeDAO.update(wpType); } @Override @Transactional public void update(JobType jobType) { jobTypeDAO.update(jobType); } @Override @Transactional public void delete(Long id) { jobTypeDAO.delete(id); } @Override @Transactional public JobType findById(Long id) { return jobTypeDAO.findById(id); } @Override @Transactional public Collection<JobType> findAll() { return jobTypeDAO.findAll().stream() .sorted(Comparator.comparing(JobType::getName)) .collect(Collectors.toList()); } }
package uchet.service.permissions; import uchet.models.Permission; import uchet.models.Position; import java.util.List; import java.util.Map; public interface PermissionService { List<Permission> getAll(); }
package com.jwebsite.daoimpl; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.jwebsite.dao.PhotoClassDao; import com.jwebsite.db.DBManager; import com.jwebsite.db.DbConn; import com.jwebsite.db.ConnectionPool.PooledConnection; import com.jwebsite.pub.HashMapOperate; import com.jwebsite.vo.SiteClass; public class PhotoClassDaoImpl implements PhotoClassDao { HashMapOperate ho=new HashMapOperate<SiteClass>(); public int AddPhotoClass(SiteClass photoclass) { // TODO Auto-generated method stub PooledConnection conn = null; String sqlStr=""; sqlStr="delete from Site_Class where ClassID ="; int ID=0; try { conn = DBManager.getConnection(); ID=conn.executeUpdate(sqlStr); conn.close(); } catch (SQLException e) { e.printStackTrace(); System.out.println("添加图片栏目出错"+e); } finally { conn.close(); } return ID; } public void DelPhotoClass(int ID) { // TODO Auto-generated method stub PooledConnection conn = null; String sqlStr="delete from Site_Class where ClassID ="+ID; try { conn = DBManager.getConnection(); conn.executeUpdate(sqlStr); conn.close(); } catch (SQLException e) { e.printStackTrace(); System.out.println(this.toString()+"删除图片栏目出错"+e); } finally { conn.close(); } } public List<SiteClass> GetAllChildNode(int ClassID,List<SiteClass> childlist) { // TODO Auto-generated method stub return null; } public String GetAllClass() { // TODO Auto-generated method stub StringBuffer sb=new StringBuffer(); List<SiteClass> classlist=GetParentNode("select * from Site_Class o where o.depth=0 and o.parentId=0"); for(SiteClass photoclass:classlist){ sb.append("<option value='"+photoclass.getClassID()+"'>"+photoclass.getClassName()+"</option>"); List<SiteClass> childlist=new ArrayList<SiteClass>(); childlist=GetAllChildNode(photoclass.getClassID(), childlist); for(SiteClass childclass:childlist){ sb.append("<option value='"+childclass.getClassID()+"'>"); for(int i=0;i<childclass.getDepth();i++){ sb.append("&nbsp;&nbsp;&nbsp;&nbsp;"); } sb.append("└─"+childclass.getClassName()+"</option>"); } } return sb.toString(); } public String GetAllClass(int ClassID) { // TODO Auto-generated method stub StringBuffer sb=new StringBuffer(); List<SiteClass> classlist=GetParentNode("select * from Site_Class o where o.depth=0 and o.parentId=0"); String selected=""; for(SiteClass photoclass:classlist){ if(photoclass.getClassID()==ClassID){selected="selected='selected'";}else{selected="";} sb.append("<option value='"+photoclass.getClassID()+"' "+selected+" >"+photoclass.getClassName()+"</option>"); List<SiteClass> childlist=new ArrayList<SiteClass>(); childlist=GetAllChildNode(photoclass.getClassID(), childlist); for(SiteClass childclass:childlist){ if(childclass.getClassID()==ClassID){selected="selected='selected'";}else{selected="";} sb.append("<option value='"+childclass.getClassID()+"' "+selected+" >"); for(int i=0;i<childclass.getDepth();i++){ sb.append("&nbsp;&nbsp;&nbsp;&nbsp;"); } sb.append("└─"+childclass.getClassName()+"</option>"); } } return sb.toString(); } public String GetClass(String ClassID) { // TODO Auto-generated method stub ArrayList<HashMap<String, String>> cml=DbConn.executeQuery("select * from site_class where ChannelID =3 "); List<SiteClass> classlist=ho.HashMapToObjectList(cml,SiteClass.class); SiteClass photoclass=classlist.get(0); return "<option selected='selected' value='"+photoclass.getClassID()+"'>"+photoclass.getClassName()+"</option>"; } public List<SiteClass> GetParentNode(String sql) { // TODO Auto-generated method stub ArrayList<HashMap<String, String>> cml=DbConn.executeQuery(sql); List<SiteClass> classlist=ho.HashMapToObjectList(cml,SiteClass.class); return classlist; } public SiteClass GetPhotoClass(String ClassID) { // TODO Auto-generated method stub return null; } public SiteClass GetPhotoClassByID(int ID) { // TODO Auto-generated method stub return null; } public List<SiteClass> GetPhotoClassList(String sql) { // TODO Auto-generated method stub List<SiteClass> pclist=null; ArrayList<HashMap<String, String>> list= DbConn.executeQuery(sql); if(list!=null&&list.size()>0){ for(HashMap<String, String> m:list){ HashMapOperate<SiteClass> ho=new HashMapOperate<SiteClass>(); SiteClass pc= (SiteClass)ho.HashMapToPojo(m,SiteClass.class); pclist.add(pc); } } return pclist; } //根据子节点获取所有上级节点 public List<SiteClass> GetPhotoParent(int ClassID, List<SiteClass> list) { // TODO Auto-generated method stub HashMap<String, String> cml=DbConn.executeQueryOne("select * from site_class where ClassID ="+ClassID); SiteClass photocla=(SiteClass)ho.HashMapToPojo(cml,SiteClass.class); if(photocla==null){}else if(photocla.getParentID()==0){ list.add(photocla); }else{ list.add(photocla); GetPhotoParent(photocla.getParentID(), list); } return list; } public List<SiteClass> GetphotoByClass(int ClassID) { // TODO Auto-generated method stub String sql="select * from Site_Class o where o.parentId = "+ClassID+" order by o.classId asc "; ArrayList<HashMap<String, String>> cml=DbConn.executeQuery(sql); List<SiteClass> li=ho.HashMapToObjectList(cml,SiteClass.class); return li; } public void UpdatePhotoClass(SiteClass sc) { // TODO Auto-generated method stub DbConn.executeUpdate(sc, "classID"); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.processors.hazelcast.processors; import org.apache.nifi.annotation.behavior.*; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.flowfile.FlowFile; import org.apache.nifi.annotation.lifecycle.OnScheduled; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.SeeAlso; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.processor.exception.ProcessException; import org.apache.nifi.processor.AbstractProcessor; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; import org.apache.nifi.processor.ProcessorInitializationContext; import org.apache.nifi.processor.Relationship; import org.apache.nifi.processor.util.StandardValidators; import org.apache.nifi.processors.hazelcast.zookeeper.service.HazlecastService; import org.codehaus.jackson.map.ObjectMapper; import java.io.BufferedInputStream; import java.io.InputStream; import java.util.*; import java.util.concurrent.atomic.AtomicReference; @Tags({"example"}) @CapabilityDescription("Provide a description") @SeeAlso({}) @ReadsAttributes({@ReadsAttribute(attribute="", description="")}) @WritesAttributes({@WritesAttribute(attribute="", description="")}) @EventDriven @SupportsBatching public class PutHazlecastMap extends AbstractProcessor { public static final PropertyDescriptor HAZLECASTZOOKEEPERCLIENTSERVICE = new PropertyDescriptor .Builder().name("HazlecastZookeeperClientService") .displayName("HazlecastZookeeperClientService") .description("Hazlecast ZookeeperClientService") .required(true) .identifiesControllerService(HazlecastService.class) .build(); public static final PropertyDescriptor MAP_NAME = new PropertyDescriptor .Builder().name("MAP_NAME") .displayName("Map Name") .description("Hazlecast Map name") .required(true) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .build(); public static final Relationship REL_SUCCESS = new Relationship.Builder() .name("SUCCESS") .description("Success relationship") .build(); public static final Relationship REL_FAILURE = new Relationship.Builder() .name("FAILURE") .description("Failure relationship") .build(); protected static final PropertyDescriptor BATCH_SIZE = new PropertyDescriptor.Builder() .name("Batch Size") .description("The maximum number of FlowFiles to process in a single execution.") .required(true) .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR) .defaultValue("25") .build(); private List<PropertyDescriptor> descriptors; private Set<Relationship> relationships; protected HazlecastService clientService; @OnScheduled public void onScheduled(final ProcessContext context) { clientService = context.getProperty(HAZLECASTZOOKEEPERCLIENTSERVICE).asControllerService(HazlecastService.class); } @Override protected void init(final ProcessorInitializationContext context) { final List<PropertyDescriptor> descriptors = new ArrayList<PropertyDescriptor>(); descriptors.add(HAZLECASTZOOKEEPERCLIENTSERVICE); descriptors.add(MAP_NAME); descriptors.add(BATCH_SIZE); this.descriptors = Collections.unmodifiableList(descriptors); final Set<Relationship> relationships = new HashSet<Relationship>(); relationships.add(REL_SUCCESS); relationships.add(REL_FAILURE); this.relationships = Collections.unmodifiableSet(relationships); } @Override public Set<Relationship> getRelationships() { return this.relationships; } @Override public final List<PropertyDescriptor> getSupportedPropertyDescriptors() { return descriptors; } @Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { final int batchSize = context.getProperty(BATCH_SIZE).asInteger(); List<FlowFile> flowFiles = session.get(batchSize); if (flowFiles == null || flowFiles.size() == 0) { return; } for (final FlowFile flowFile : flowFiles) { final PutFlowFile putFlowFile = processFlowFile(session,context,flowFile); if (putFlowFile.getSuccess()) { // sub-classes should log appropriate error messages before returning null session.transfer(putFlowFile.getFlowFile(), REL_SUCCESS); } else { session.transfer(putFlowFile.getFlowFile(), REL_FAILURE); } } } private PutFlowFile processFlowFile(final ProcessSession session, final ProcessContext context, final FlowFile flowFile){ PutFlowFile putFlowFile = new PutFlowFile(); putFlowFile.setFlowFile(flowFile); final ObjectMapper mapper = new ObjectMapper(); final AtomicReference<Map> jsonDataIn = new AtomicReference<>(null); try { session.read(flowFile, in -> { try (final InputStream bufferedIn = new BufferedInputStream(in)) { jsonDataIn.set(mapper.readValue(bufferedIn,HashMap.class)); } }); clientService.put(MAP_NAME.getName(), jsonDataIn.get().get("key"), jsonDataIn.get().get("value")); putFlowFile.setSuccess(Boolean.TRUE); return putFlowFile; } catch (final Exception pe) { getLogger().error("Failed to parse {} as JSON due to {}; routing to failure", new Object[]{flowFile, pe.toString()}, pe); putFlowFile.setSuccess(Boolean.FALSE); return putFlowFile; } // if (rootNode.isArray()) { // getLogger().error("Root node of JSON must be a single document, found array for {}; routing to failure", new Object[]{flowFile}); // return null; // } } }
package com.candlelit.slimeweed; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import org.junit.jupiter.api.*; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; public class FilerClientTest { private static SeaweedFilerClient client; private static byte[] byteTest; private static final String path = "/com/candlelit/slimeweed/test"; private static final String fileName = "articuno.png"; @BeforeAll public static void before() { client = new SeaweedFilerClient("localhost"); BufferedImage image = null; try { URL url = new URL("https://heavy.com/wp-content/uploads/2016/07/red_articuno_po-e1470145578952.jpg?quality=65&strip=all&w=1350"); image = ImageIO.read(url); ByteArrayOutputStream output = new ByteArrayOutputStream(); System.out.println("Successfully downloaded some picture, now converting to byte array..."); ImageIO.write(image, "jpg", output); byteTest = output.toByteArray(); } catch (IOException e) { e.printStackTrace(); } } @Test public void post() { System.out.println("Testing posting.."); try { String response = client.postFile(path, fileName, byteTest); Assertions.assertEquals(response, "{\"name\":\"" + fileName + "\",\"size\":" + byteTest.length + "}"); } catch (IOException e) { e.printStackTrace(); } } @Test public void get() { System.out.println("Testing getting.."); try { client.postFile(path, fileName, byteTest); byte[] bytes = client.getFile(path, fileName); Assertions.assertEquals(byteTest.length, bytes.length); } catch (IOException e) { e.printStackTrace(); } } @Test public void delete() { System.out.println("Testing deleting.."); try { client.postFile(path, fileName + 2, byteTest); boolean response = client.deleteFile(path, fileName + 2); Assertions.assertTrue(response); } catch (IOException e) { e.printStackTrace(); } } @Test public void list() { System.out.println("Testing listing.."); try { int size = 10; for (int i = 0; i < size; i++) client.postFile(path, fileName + i, byteTest); List<String> list = client.listFiles(path); Assertions.assertTrue(list.size() >= size); }catch (IOException e) { e.printStackTrace(); } } @AfterAll public static void cleanup() { try { List<String> list = client.listFiles(path); for (String li : list) client.deleteFile(path, li); } catch (IOException e) { e.printStackTrace(); } } }
/* * 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 controller; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Named; import model.ContDB; import service.ContService; @Named @RequestScoped public class ContController { private int id; private String iban; private String descriere; private Double amount; private String data; private List<ContDB> conturi; @EJB private ContService contService; @PostConstruct public void init() { List<ContDB> c = this.contService.getConturi(); if (c != null) { this.conturi = c; } } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getIban() { return iban; } public void setIban(String iban) { this.iban = iban; } public String getDescriere() { return descriere; } public void setDescriere(String descriere) { this.descriere = descriere; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public String getData() { return data; } public void setData(String data) { this.data = data; } public List<ContDB> getConturi() { return conturi; } public void setConturi(List<ContDB> conturi) { this.conturi = conturi; } public ContService getContService() { return contService; } public void setContService(ContService contService) { this.contService = contService; } }
package denoflionsx.DenPipes.AddOns.Forestry.logger; import denoflionsx.denLib.Mod.Logger.DenFormat; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Logger; public class ForestryPipeLogger { private static final Logger LOG = Logger.getLogger(ForestryPipeLogger.class.getName()); static { try { DenFormat f = new DenFormat(); Handler handler = new FileHandler("DenPipes-Forestry.log"); handler.setFormatter(f); LOG.addHandler(handler); } catch (Throwable t) { t.printStackTrace(); } } public ForestryPipeLogger() { } public void info(String msg) { LOG.info(msg); } }
package fr.mawathilde.minecraftsuggestions.client.renderer; import fr.mawathilde.minecraftsuggestions.MinecraftSuggestions; import net.minecraft.client.renderer.entity.AbstractZombieRenderer; import net.minecraft.client.renderer.entity.EntityRendererManager; import net.minecraft.client.renderer.entity.model.ZombieModel; import net.minecraft.entity.monster.ZombieEntity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public class AngryZombieRenderer extends AbstractZombieRenderer<ZombieEntity, ZombieModel<ZombieEntity>> { protected static final ResourceLocation ANGRY_ZOMBIE_TEXTURE = new ResourceLocation(MinecraftSuggestions.MOD_ID, "textures/entity/zombie/angry_zombie.png"); public AngryZombieRenderer(EntityRendererManager renderManagerIn) { super(renderManagerIn, new ZombieModel<>(0.0F, false), new ZombieModel<>(0.5F, true), new ZombieModel<>(1.0F, true)); } @Override public ResourceLocation getEntityTexture(ZombieEntity entity) { return ANGRY_ZOMBIE_TEXTURE; } }
package ru.parse.dump.objects; /** * Dump header. */ public class DumpHeader { private final long version; private final DumpPlatform platform; private final boolean hashed; private final boolean j9VM; private final String jvmVersion; public DumpHeader(long version, DumpPlatform platform, boolean hashed, boolean j9VM, String jvmVersion) { this.version = version; this.platform = platform; this.hashed = hashed; this.j9VM = j9VM; this.jvmVersion = jvmVersion; } public long getVersion() { return version; } public DumpPlatform getPlatform() { return platform; } public boolean isHashed() { return hashed; } public boolean isJ9VM() { return j9VM; } public String getJvmVersion() { return jvmVersion; } @Override public String toString() { return "DumpHeader{" + "version=" + version + ", platform=" + platform + ", hashed=" + hashed + ", j9VM=" + j9VM + ", jvmVersion='" + jvmVersion + '\'' + '}'; } }
package UI.editor; import experiments.RewardStation; import javax.swing.*; import java.awt.*; /** * Created by Netai Benaim * for G-Lab, Hebrew University of Jerusalem * contact at: netai.benaim@mail.huji.ac.il * version: * <p> * this is RewardIcon in UI.editor * created on 9/15/2016 */ // // TODO: 9/29/2016 fix id issues i particular upon creation with pre existing stations public class RewardIcon extends JLabel { // the icon for the reward private ImageIcon img; // id of reward station private int id; // x location private int x; // y location private int y; // clicker precision distance to be a regarded as a choice private static final int clickBounds = 20; // the reward station associated with this icon private RewardStation rew; // selected indicator for icon change private boolean selected = false; // factor //int[] origin = {150,150}; /** * @return the associated station with this icon */ public RewardStation getRew() { return rew; } /** * @param rew set station to this reward */ public void setRew(RewardStation rew) { this.rew = rew; //this.rew.setX((float)); } /** * constructor * @param id id number * @param x location * @param y location */ public RewardIcon(int id, int x, int y) { this.id = id; this.x = x; this.y = y; // addRewImage("C:\\Users\\owner\\Documents\\LAB_STRUCTURE\\src\\UI\\editor\\rew.png"); addRewImage(".\\src\\UI\\editor\\rew.png"); } /** * @return the icon */ public ImageIcon getImg() { return img; } @Override public int getX() { return x; } /** * @param x location */ public void setX(int x) { this.x = x; } @Override public int getY() { return y; } /** * @param y location */ public void setY(int y) { this.y = y; } /** * @return station id */ public int getId() { return id; } // set the image to this icon private void addRewImage(String path) { img = new ImageIcon(path); Image image = img.getImage(); // transform it Image newimg = image.getScaledInstance(10, 15, java.awt.Image.SCALE_SMOOTH); img = new ImageIcon(newimg); } /** * mark this station as selected */ public void select() { if (selected) { // addRewImage("C:\\Users\\owner\\Documents\\LAB_STRUCTURE\\src\\UI\\editor\\rew.jpeg"); addRewImage(".\\src\\UI\\editor\\rew.jpeg"); } else { // addRewImage("C:\\Users\\owner\\Documents\\LAB_STRUCTURE\\src\\UI\\editor\\rew.png"); addRewImage(".\\src\\UI\\editor\\rew.png"); } } /** * * @return true if station has been selected false otherwise */ public boolean isSelected() { return selected; } /** * * @param selected indicate that this has been selected */ public void setSelected(boolean selected) { this.selected = selected; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(img.getImage(), 0,0, null); } /** * return true if this icon is in the vicinity of the point * @param x location * @param y location * @return true if this is within clickBounds of x,y */ public boolean nearPoint(int x, int y){ return (Math.abs(this.x - x) < clickBounds && Math.abs(this.y - y) < clickBounds); } }
package Learn; public class L8 { public static void main(String args[]){ int [] nums = {1,2,3,4,5}; for(int x : nums){ System.out.print(x); System.out.print(","); } System.out.print("\n"); String [] names = {"Tom","Jame","Lacy"}; for(String x : names){ System.out.print(x); System.out.print(","); } } }
/* * 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 pbo3.pkg10117089.latihan49.biayaemaskawin; /** * * @author a */ public class Emas { private double totalBerat; private double harga; public double getTotalBerat() { return totalBerat; } public void setTotalBerat(double totalBerat) { this.totalBerat = totalBerat; } public double getHarga() { return harga; } public void setHarga(double harga) { this.harga = harga; } public double totalHarga(double totalBerat, double harga){ return totalBerat*harga; } }
package com.igs.qhrzlc.view.activity; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.igs.qhrzlc.presenter.PresenterCaoPanList; import com.igs.qhrzlc.utils.IntentUtils; import com.igs.qhrzlc.view.fragment.HomeFragment; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import qhrzzx.igs.com.igs_mvp.R; /** * 操盘手 */ public class CaoPanListActivity extends Activity { @InjectView(R.id.tv_title) TextView tvTitle; @InjectView(R.id.tv_back) TextView tvBack; @InjectView(R.id.test_item) LinearLayout testItem; private PresenterCaoPanList presenterCaoPanList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cao_pan_list); ButterKnife.inject(this); presenterCaoPanList = new PresenterCaoPanList(this); String type = getIntent().getStringExtra(HomeFragment.KEY_CAO_PAN_TYPE); if(type != null){ if (type.equals(HomeFragment.CAO_PAN_TYPE_RQ)) { presenterCaoPanList.initTitleBar(CaoPanListActivity.this, tvTitle, R.string.titlebar_rq); } else if (type.equals(HomeFragment.CAO_PAN_TYPE_CS)) { presenterCaoPanList.initTitleBar(CaoPanListActivity.this, tvTitle, R.string.titlebar_cs); } else { presenterCaoPanList.initTitleBar(CaoPanListActivity.this, tvTitle, R.string.titlebar_wj); } }else{ presenterCaoPanList.initTitleBar(CaoPanListActivity.this, tvTitle, R.string.titlebar_myCaoPan); } } @OnClick({R.id.tv_back,R.id.test_item}) public void onclick(View view) { switch (view.getId()) { case R.id.tv_back: IntentUtils.back(this); break; case R.id.test_item: IntentUtils.goIntent(this,CaoPanDetailActivity.class); break; } } }
package Ch14; public class bubbleSort { public static void main(String args[]) { int a[] = { 69, 10, 30, 2, 16, 8, 21, 22 }; bubbleSort bs = new bubbleSort(); System.out.printf("\n정렬할 원소 : "); for (int i = 0; i < a.length; i++) { System.out.printf(" %d", a[i]); } bs.bubblesort(a); } public void bubblesort(int a[]) { int i, j, temp, size; size = a.length; for (i = size - 1; i > 0; i--) { System.out.printf("\n버블 정렬 %d 단계 : ", size - 1); for (j = 0; j < i; j++) { if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } System.out.printf("\n\t"); for (int k = 0; k < size; k++) { System.out.printf("3%d ", a[k]); } } } } }
/* Session.java Purpose: Description: History: Mon May 30 21:29:17 2005, Created by tomyeh Copyright (C) 2005 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zk.ui; import java.util.Map; import org.zkoss.zk.ui.ext.Scope; /** * A user session. * * <p>To get the current session, use {@link Sessions#getCurrent}, * or {@link Desktop#getSession}. * * <p>A session, {@link Session}, might have multiple pages, * {@link Page}, while a page belongs to exactly one session. * A page, {@link Page}, might have many components, {@link Component}, while * a component belongs to exactly one page. * * @author tomyeh */ public interface Session extends Scope { /** Returns the device type that this session belongs to. * * <p>A device type identifies the type of a client. For example, "ajax" * represents the Web browsers with Ajax support, * while "mil" represents clients that supports * <i>Mobile Interactive markup Language</i> (on Limited Connected Device, * such as mobile phones). * * <p>All desktops of the same session must belong to the same * device type. * * <p>The session's device type is determined by the first desktop's * device type. * * @since 2.4.1 */ public String getDeviceType(); /** Returns the value of the specified custom attribute. */ public Object getAttribute(String name); /** Sets the value of the specified custom attribute. * @return the previous value if any (since ZK 5) */ public Object setAttribute(String name, Object value); /** Removes the specified custom attribute. * @return the previous value if any (since ZK 5) */ public Object removeAttribute(String name); /** Returns a map of custom attributes associated with this session. */ public Map getAttributes(); /** Returns the Web application that this session belongs to. */ public WebApp getWebApp(); /** Returns the fully qualified name of the client or the last proxy * that sent the first request creating this session. * If the engine cannot or chooses not to resolve the hostname * (to improve performance), this method returns the dotted-string form of * the IP address. * @since 3.0.1 */ public String getRemoteHost(); /** Returns the Internet Protocol (IP) address of the client or last * proxy that sent the first request creating this session. * @since 3.0.1 */ public String getRemoteAddr(); /** Returns the host name of the server to which the first request was sent * (and created this session). * It is the value of the part before ":" in the Host header value, if any, * or the resolved server name, or the server IP address. * * @see #getLocalName * @since 3.0.1 */ public String getServerName(); /** Returns the host name of the Internet Protocol (IP) interface * on which the first request was received (and creates this session). * * <p>Note: it is the host name defined in the server. To retrieve the name * in URL, use {@link #getServerName}. * * @see #getServerName * @since 3.0.1 */ public String getLocalName(); /** Returns the Internet Protocol (IP) address of the interface on which * the first request was received (and creates this session). * @since 3.0.1 */ public String getLocalAddr(); /** Invalidates this session then unbinds any objects bound to it. * * <p>Note: you usually have to ask the client to redirect to another page * (or reload the same page) by use of {@link Executions#sendRedirect}. * * <p>The session is not invalidated immediately. Rather, it is * invalidated after processing the current request. */ public void invalidate(); /** Specifies the time, in seconds, between client requests before * the servlet container will invalidate this session. * A negative time indicates the session should never timeout. * * @see org.zkoss.zk.ui.util.Configuration#setTimerKeepAlive * @see org.zkoss.zk.ui.util.Configuration#setSessionMaxInactiveInterval */ public void setMaxInactiveInterval(int interval); /** Return the time, in seconds, between client requests before * the servlet container will invalidate this session. * A negative time indicates the session should never timeout. * * @see org.zkoss.zk.ui.util.Configuration#isTimerKeepAlive * @see org.zkoss.zk.ui.util.Configuration#getSessionMaxInactiveInterval * @since 3.0.0 */ public int getMaxInactiveInterval(); /** Returns the native session, or null if not available. * The returned object depends on the type of clients. * If HTTP, the object is an instance of javax.servlet.http.HttpSession. * If portlet, the object is an instance of javax.portlet.PortletSession. */ public Object getNativeSession(); }
/* * 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 ee_t04_listas; /** * * @author Victor Hugo Bolaños */ public class Nodo <T>{ private T dato; private Nodo < T > siguiente; public Nodo ( T dato ) { this . dato = dato; siguiente = null ; } public void setDato ( T dato ) { this . dato = dato; } public T getDato () { return dato; } public void setSiguiente ( Nodo < T > siguiente ) { this . siguiente = siguiente; } public Nodo < T > getSiguiente () { return siguiente; } }
package com.sam.ui.controller; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.sam.sec.model.TxDataModel; import com.sam.ui.service.UIService; @RestController @RequestMapping(value = "/transactions") public class UIController { private Logger logger = LogManager.getLogger(UIController.class); @Autowired private UIService uiService; @RequestMapping(method = RequestMethod.GET, produces = { "application/json" }) @ResponseBody public String getTransactions() { try { JSONObject responseDetailsJson = new JSONObject(); JSONArray jsonArray = new JSONArray(); List<TxDataModel> sagaTransactions = uiService.getTransactions(); for (TxDataModel sagaTxData : sagaTransactions) { JSONObject jsonObject = new JSONObject(); jsonObject.put("tx", sagaTxData.getTx() == null ? "-" : sagaTxData.getTx()); jsonObject.put("txStatus", sagaTxData.getTxStatus() == null ? "-" : sagaTxData.getTxStatus()); jsonObject.put("step", sagaTxData.getStep() == null ? "-" : sagaTxData.getStep()); jsonObject.put("apiPayload", sagaTxData.getApiPayload() == null ? "-" : sagaTxData.getApiPayload()); jsonObject.put("apiResponse", sagaTxData.getApiResponse() == null ? "-" : sagaTxData.getApiResponse()); jsonObject.put("apiResponseStatus", sagaTxData.getApiResponseStatus() == null ? "-" : sagaTxData.getApiResponseStatus().value()); jsonObject.put("capiPayload", sagaTxData.getCapiPayload() == null ? "-" : sagaTxData.getCapiPayload()); jsonObject.put("capiResponse", sagaTxData.getCapiResponse() == null ? "-" : sagaTxData.getCapiResponse()); jsonObject.put("capiResponseStatus", sagaTxData.getCapiResponseStatus() == null ? "-" : sagaTxData.getCapiResponseStatus().value()); jsonObject.put("status", sagaTxData.getStatus() == null ? "-" : sagaTxData.getStatus()); jsonArray.put(jsonObject); } responseDetailsJson.put("data", jsonArray); return responseDetailsJson.toString(); } catch (Exception ex) { logger.error("Exception in fetching tx data", ex); return "{\"data\":[]}"; } } }
package graph; import java.util.LinkedList; import java.util.Queue; public class SimplestBFS implements PathSearcher{ class Node{ int number; int x; int y; Node parent; Node (int x, int y, int number){ this.number = number; this.x = x; this.y = y; } @Override public String toString(){ return "["+x+","+y+"]="+graph[x][y]; } } public final int[][] graph; public final int barrier = 0; public boolean[][] visited; public final int[][] neighbors = {{1,0},{-1,0},{0,1},{0,-1}}; public SimplestBFS(int[][] graph){ this.graph = graph; this.visited = new boolean[graph.length][graph[0].length]; } public Node getStart(int start){ for (int i = 0; i < graph.length; i++){ for (int j = 0; j < graph[0].length; j++){ if (graph[i][j] == start) { return new Node(i, j, start); } } } return null; } @Override public void search(int start, int end){ Queue<Node> queue = new LinkedList<>(); Node startNode = getStart(start); if (startNode == null) { System.out.println("start point does not exist!"); System.exit(1); } //没问题 queue.offer(startNode); visited[startNode.x][startNode.y] = true; while (!queue.isEmpty()){ Node pNode = queue.poll(); if (pNode.number == end){ printPaths(pNode); break; } for (int i = 0; i < 4; i++){ int nextX = pNode.x + neighbors[i][0]; int nextY = pNode.y + neighbors[i][1]; if (isOutOfBounds(nextX, nextY) || visited[nextX][nextY] || isBarrier(nextX,nextY)){ continue; } visited[nextX][nextY] = true; Node nextNode = new Node(nextX, nextY, graph[nextX][nextY]); nextNode.parent = pNode; queue.offer(nextNode); } } } public void printPaths(Node pNode){ while (pNode != null){ System.out.println(pNode); pNode = pNode.parent; } } public boolean isOutOfBounds(int x, int y){ if (x < 0 || x >= graph.length || y < 0 || y >= graph[0].length){ return true; } return false; } public boolean isBarrier(int x, int y){ if (graph[x][y] == barrier){ return true; } return false; } public static void main(String[] args) { int[][] graph = { {2,0,2,2}, {2,1,2,0}, {2,0,2,2}, {2,2,2,3} }; SimplestBFS bfs = new SimplestBFS(graph); bfs.search(1,3); } }
package com.prive.exercices.euroMillion; @SuppressWarnings("serial") class NameJeuxException extends Exception { //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // CONSTRUCTEUR //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% public NameJeuxException(String message) { super(message); } }
package basic; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Koala { public static void main(String[] args) { try { FileInputStream inkoala = new FileInputStream("d:/d_other/koala.jpg"); FileOutputStream oukoala = new FileOutputStream("d:/d_Other/연습용/koala.jpg"); int c; while((c=inkoala.read()) != -1){ System.out.println((char)c); } inkoala.close(); oukoala.close(); } catch (IOException e) { System.out.println(" 파일에 쓰기 오류입니다."); } } }
package ng.mobilea.airvoucher.utilities.loaders; import android.content.Context; import android.content.Intent; import android.util.Log; import ng.mobilea.airvoucher.client.AgentService; import ng.mobilea.airvoucher.client.ServiceGenerator; import ng.mobilea.airvoucher.entities.MyVoucher; import ng.mobilea.airvoucher.fragments.SmsFrag; import ng.mobilea.airvoucher.utilities.DataFactory; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by ISHIMWE Aubain Consolateur. email: iaubain@yahoo.fr / aubain.c.ishimwe@oltranz.com Tel: +250 785 534 672 / +250 736 864 662 on 12/13/2017. */ public class VoucherLoader { private OnVoucherLoader mListener; private Context context; private String message; private MyVoucher vResponse = null; private MyVoucher vRequest; public VoucherLoader(OnVoucherLoader mListener, Context context, MyVoucher vRequest) { this.mListener = mListener; this.context = context; this.vRequest = vRequest; } public void startLoading(){ BackLoading backLoading = new BackLoading(); backLoading.execute(); } public interface OnVoucherLoader { void onVoucherLoader(boolean isLoaded, Object object); } private class BackLoading{ void execute(String... parms) { try { Log.d("Request", DataFactory.objectToString(vRequest)); AgentService agentService = ServiceGenerator.createService(AgentService.class, AgentService.BASE_URL); Call<MyVoucher> callService = agentService.uploadVoucher(AgentService.CREATE_VOUCHER, vRequest); callService.enqueue(new Callback<MyVoucher>() { @Override public void onResponse(Call<MyVoucher> call, Response<MyVoucher> response) { int statusCode = response.code(); if(statusCode == 500){ message = "internal server error"; onPostExecute(vResponse); return; }else if(statusCode != 200 && statusCode != 201){ message = response.message(); onPostExecute(vResponse); return; } if(response.body() == null){ message = "Empty server response"; onPostExecute(vResponse); return; } onPostExecute(response.body()); } @Override public void onFailure(Call<MyVoucher> call, Throwable t) { message = "Network failure. "+t.getMessage(); onPostExecute(vResponse); } }); } catch (Exception e) { e.printStackTrace(); onPostExecute(vResponse); } } private void sendBroadcast(){ Intent broadcastIntent = new Intent(SmsFrag.SMS_BROADCAST_FILTER).setAction(SmsFrag.SMS_BROADCAST_FILTER); context.sendBroadcast(broadcastIntent); } protected void onPostExecute(MyVoucher myVoucher) { try{ if(myVoucher == null) mListener.onVoucherLoader(false, message); else{ mListener.onVoucherLoader(true, myVoucher); } }catch (Exception e){ e.printStackTrace(); mListener.onVoucherLoader(false, "Error: "+e.getMessage()); } if(context != null){ sendBroadcast(); } } } }
package com.hillel.javaElementary.classes.Lesson_7; import java.util.Date; public class MulticastingLifecycleObserver implements IHumanLifecycleObserver { private final IHumanLifecycleObserver[] observers; public MulticastingLifecycleObserver(IHumanLifecycleObserver[] observers) { this.observers = observers; } @Override public void onHumanWasBorn(boolean gender, String name, Date birthday) { for (IHumanLifecycleObserver observer:observers){ observer.onHumanWasBorn(gender, name, birthday); } } @Override public void onWentToKindergarten(String kindergartenName, int age) { for (IHumanLifecycleObserver observer:observers){ observer.onWentToKindergarten(kindergartenName, age); } } @Override public void onWentToSchool(String schoolName, int age) { for (IHumanLifecycleObserver observer:observers){ observer.onWentToSchool(schoolName, age); } } @Override public void onWentToUniversity(String universityName, int age) { for (IHumanLifecycleObserver observer:observers){ observer.onWentToUniversity(universityName, age); } } @Override public void onGotWork(String position, int salary) { for (IHumanLifecycleObserver observer:observers){ observer.onGotWork(position, salary); } } @Override public void onBoughtCar(String brand, int cost, int age) { for (IHumanLifecycleObserver observer:observers){ observer.onBoughtCar(brand, cost, age); } } @Override public void onCreatingFamily(String wifeName, int age) { for (IHumanLifecycleObserver observer:observers){ observer.onCreatingFamily(wifeName, age); } } @Override public void onGaveBirth(String childName, boolean gender, Date birthday) { for (IHumanLifecycleObserver observer:observers){ observer.onGaveBirth(childName, gender, birthday); } } @Override public void onDeath(Date date) { for (IHumanLifecycleObserver observer:observers){ observer.onDeath(date); } } }
package android.support.constraint.solver.widgets; import android.support.constraint.solver.LinearSystem; import android.support.constraint.solver.SolverVariable; import android.support.constraint.solver.widgets.ConstraintWidget.DimensionBehaviour; public class Optimizer { static void applyDirectResolutionHorizontalChain(ConstraintWidgetContainer constraintWidgetContainer, LinearSystem linearSystem, int i, ConstraintWidget constraintWidget) { int i2; int i3; int x; float f; float f2; ConstraintWidget constraintWidget2 = constraintWidgetContainer; LinearSystem linearSystem2 = linearSystem; int i4 = i; float f3 = 0.0f; int i5 = 0; ConstraintWidget constraintWidget3 = constraintWidget; float f4 = f3; int i6 = i5; int i7 = i6; ConstraintWidget constraintWidget4 = null; while (true) { i2 = 8; i3 = 1; if (constraintWidget3 == null) { break; } if (constraintWidget3.getVisibility() != i2) { i3 = i5; } if (i3 == 0) { i6++; if (constraintWidget3.mHorizontalDimensionBehaviour != DimensionBehaviour.MATCH_CONSTRAINT) { i7 = ((i7 + constraintWidget3.getWidth()) + (constraintWidget3.mLeft.mTarget != null ? constraintWidget3.mLeft.getMargin() : i5)) + (constraintWidget3.mRight.mTarget != null ? constraintWidget3.mRight.getMargin() : i5); } else { f4 += constraintWidget3.mHorizontalWeight; } } constraintWidget4 = constraintWidget3.mRight.mTarget != null ? constraintWidget3.mRight.mTarget.mOwner : null; if (constraintWidget4 != null && (constraintWidget4.mLeft.mTarget == null || !(constraintWidget4.mLeft.mTarget == null || constraintWidget4.mLeft.mTarget.mOwner == constraintWidget3))) { constraintWidget4 = null; } ConstraintWidget constraintWidget5 = constraintWidget4; constraintWidget4 = constraintWidget3; constraintWidget3 = constraintWidget5; } if (constraintWidget4 != null) { x = constraintWidget4.mRight.mTarget != null ? constraintWidget4.mRight.mTarget.mOwner.getX() : i5; if (constraintWidget4.mRight.mTarget != null && constraintWidget4.mRight.mTarget.mOwner == constraintWidget2) { x = constraintWidgetContainer.getRight(); } } else { x = i5; } float f5 = ((float) (x - i5)) - ((float) i7); float f6 = f5 / ((float) (i6 + i3)); if (i4 == 0) { f = f6; f2 = f; } else { f = f3; f2 = f5 / ((float) i4); } constraintWidget4 = constraintWidget; while (constraintWidget4 != null) { i3 = constraintWidget4.mLeft.mTarget != null ? constraintWidget4.mLeft.getMargin() : i5; int margin = constraintWidget4.mRight.mTarget != null ? constraintWidget4.mRight.getMargin() : i5; float f7 = 0.5f; if (constraintWidget4.getVisibility() != i2) { float f8 = (float) i3; f += f8; linearSystem2.addEquality(constraintWidget4.mLeft.mSolverVariable, (int) (f + f7)); if (constraintWidget4.mHorizontalDimensionBehaviour != DimensionBehaviour.MATCH_CONSTRAINT) { f += (float) constraintWidget4.getWidth(); } else if (f4 == f3) { f += (f2 - f8) - ((float) margin); } else { f += (((constraintWidget4.mHorizontalWeight * f5) / f4) - f8) - ((float) margin); } linearSystem2.addEquality(constraintWidget4.mRight.mSolverVariable, (int) (f7 + f)); if (i4 == 0) { f += f2; } f += (float) margin; } else { int i8 = (int) ((f - (f2 / 2.0f)) + f7); linearSystem2.addEquality(constraintWidget4.mLeft.mSolverVariable, i8); linearSystem2.addEquality(constraintWidget4.mRight.mSolverVariable, i8); } ConstraintWidget constraintWidget6 = constraintWidget4.mRight.mTarget != null ? constraintWidget4.mRight.mTarget.mOwner : null; if (!(constraintWidget6 == null || constraintWidget6.mLeft.mTarget == null || constraintWidget6.mLeft.mTarget.mOwner == constraintWidget4)) { constraintWidget6 = null; } constraintWidget4 = constraintWidget6 == constraintWidget2 ? null : constraintWidget6; } } static void applyDirectResolutionVerticalChain(ConstraintWidgetContainer constraintWidgetContainer, LinearSystem linearSystem, int i, ConstraintWidget constraintWidget) { int i2; int i3; int x; float f; float f2; ConstraintWidget constraintWidget2 = constraintWidgetContainer; LinearSystem linearSystem2 = linearSystem; int i4 = i; float f3 = 0.0f; int i5 = 0; ConstraintWidget constraintWidget3 = constraintWidget; float f4 = f3; int i6 = i5; int i7 = i6; ConstraintWidget constraintWidget4 = null; while (true) { i2 = 8; i3 = 1; if (constraintWidget3 == null) { break; } if (constraintWidget3.getVisibility() != i2) { i3 = i5; } if (i3 == 0) { i6++; if (constraintWidget3.mVerticalDimensionBehaviour != DimensionBehaviour.MATCH_CONSTRAINT) { i7 = ((i7 + constraintWidget3.getHeight()) + (constraintWidget3.mTop.mTarget != null ? constraintWidget3.mTop.getMargin() : i5)) + (constraintWidget3.mBottom.mTarget != null ? constraintWidget3.mBottom.getMargin() : i5); } else { f4 += constraintWidget3.mVerticalWeight; } } constraintWidget4 = constraintWidget3.mBottom.mTarget != null ? constraintWidget3.mBottom.mTarget.mOwner : null; if (constraintWidget4 != null && (constraintWidget4.mTop.mTarget == null || !(constraintWidget4.mTop.mTarget == null || constraintWidget4.mTop.mTarget.mOwner == constraintWidget3))) { constraintWidget4 = null; } ConstraintWidget constraintWidget5 = constraintWidget4; constraintWidget4 = constraintWidget3; constraintWidget3 = constraintWidget5; } if (constraintWidget4 != null) { x = constraintWidget4.mBottom.mTarget != null ? constraintWidget4.mBottom.mTarget.mOwner.getX() : i5; if (constraintWidget4.mBottom.mTarget != null && constraintWidget4.mBottom.mTarget.mOwner == constraintWidget2) { x = constraintWidgetContainer.getBottom(); } } else { x = i5; } float f5 = ((float) (x - i5)) - ((float) i7); float f6 = f5 / ((float) (i6 + i3)); if (i4 == 0) { f = f6; f2 = f; } else { f = f3; f2 = f5 / ((float) i4); } constraintWidget4 = constraintWidget; while (constraintWidget4 != null) { i3 = constraintWidget4.mTop.mTarget != null ? constraintWidget4.mTop.getMargin() : i5; int margin = constraintWidget4.mBottom.mTarget != null ? constraintWidget4.mBottom.getMargin() : i5; float f7 = 0.5f; if (constraintWidget4.getVisibility() != i2) { float f8 = (float) i3; f += f8; linearSystem2.addEquality(constraintWidget4.mTop.mSolverVariable, (int) (f + f7)); if (constraintWidget4.mVerticalDimensionBehaviour != DimensionBehaviour.MATCH_CONSTRAINT) { f += (float) constraintWidget4.getHeight(); } else if (f4 == f3) { f += (f2 - f8) - ((float) margin); } else { f += (((constraintWidget4.mVerticalWeight * f5) / f4) - f8) - ((float) margin); } linearSystem2.addEquality(constraintWidget4.mBottom.mSolverVariable, (int) (f7 + f)); if (i4 == 0) { f += f2; } f += (float) margin; } else { int i8 = (int) ((f - (f2 / 2.0f)) + f7); linearSystem2.addEquality(constraintWidget4.mTop.mSolverVariable, i8); linearSystem2.addEquality(constraintWidget4.mBottom.mSolverVariable, i8); } ConstraintWidget constraintWidget6 = constraintWidget4.mBottom.mTarget != null ? constraintWidget4.mBottom.mTarget.mOwner : null; if (!(constraintWidget6 == null || constraintWidget6.mTop.mTarget == null || constraintWidget6.mTop.mTarget.mOwner == constraintWidget4)) { constraintWidget6 = null; } constraintWidget4 = constraintWidget6 == constraintWidget2 ? null : constraintWidget6; } } static void checkMatchParent(ConstraintWidgetContainer constraintWidgetContainer, LinearSystem linearSystem, ConstraintWidget constraintWidget) { int i; int i2 = 2; if (constraintWidgetContainer.mHorizontalDimensionBehaviour != DimensionBehaviour.WRAP_CONTENT && constraintWidget.mHorizontalDimensionBehaviour == DimensionBehaviour.MATCH_PARENT) { constraintWidget.mLeft.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mLeft); constraintWidget.mRight.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mRight); i = constraintWidget.mLeft.mMargin; int width = constraintWidgetContainer.getWidth() - constraintWidget.mRight.mMargin; linearSystem.addEquality(constraintWidget.mLeft.mSolverVariable, i); linearSystem.addEquality(constraintWidget.mRight.mSolverVariable, width); constraintWidget.setHorizontalDimension(i, width); constraintWidget.mHorizontalResolution = i2; } if (constraintWidgetContainer.mVerticalDimensionBehaviour != DimensionBehaviour.WRAP_CONTENT && constraintWidget.mVerticalDimensionBehaviour == DimensionBehaviour.MATCH_PARENT) { constraintWidget.mTop.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mTop); constraintWidget.mBottom.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBottom); i = constraintWidget.mTop.mMargin; int height = constraintWidgetContainer.getHeight() - constraintWidget.mBottom.mMargin; linearSystem.addEquality(constraintWidget.mTop.mSolverVariable, i); linearSystem.addEquality(constraintWidget.mBottom.mSolverVariable, height); if (constraintWidget.mBaselineDistance > 0 || constraintWidget.getVisibility() == 8) { constraintWidget.mBaseline.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBaseline); linearSystem.addEquality(constraintWidget.mBaseline.mSolverVariable, constraintWidget.mBaselineDistance + i); } constraintWidget.setVerticalDimension(i, height); constraintWidget.mVerticalResolution = i2; } } static void checkHorizontalSimpleDependency(ConstraintWidgetContainer constraintWidgetContainer, LinearSystem linearSystem, ConstraintWidget constraintWidget) { int i = 1; if (constraintWidget.mHorizontalDimensionBehaviour == DimensionBehaviour.MATCH_CONSTRAINT) { constraintWidget.mHorizontalResolution = i; return; } int i2 = 2; int margin; int width; if (constraintWidgetContainer.mHorizontalDimensionBehaviour == DimensionBehaviour.WRAP_CONTENT || constraintWidget.mHorizontalDimensionBehaviour != DimensionBehaviour.MATCH_PARENT) { float f = 0.5f; if (constraintWidget.mLeft.mTarget == null || constraintWidget.mRight.mTarget == null) { SolverVariable solverVariable; if (constraintWidget.mLeft.mTarget != null && constraintWidget.mLeft.mTarget.mOwner == constraintWidgetContainer) { margin = constraintWidget.mLeft.getMargin(); width = constraintWidget.getWidth() + margin; constraintWidget.mLeft.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mLeft); constraintWidget.mRight.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mRight); linearSystem.addEquality(constraintWidget.mLeft.mSolverVariable, margin); linearSystem.addEquality(constraintWidget.mRight.mSolverVariable, width); constraintWidget.mHorizontalResolution = i2; constraintWidget.setHorizontalDimension(margin, width); } else if (constraintWidget.mRight.mTarget != null && constraintWidget.mRight.mTarget.mOwner == constraintWidgetContainer) { constraintWidget.mLeft.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mLeft); constraintWidget.mRight.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mRight); margin = constraintWidgetContainer.getWidth() - constraintWidget.mRight.getMargin(); width = margin - constraintWidget.getWidth(); linearSystem.addEquality(constraintWidget.mLeft.mSolverVariable, width); linearSystem.addEquality(constraintWidget.mRight.mSolverVariable, margin); constraintWidget.mHorizontalResolution = i2; constraintWidget.setHorizontalDimension(width, margin); } else if (constraintWidget.mLeft.mTarget != null && constraintWidget.mLeft.mTarget.mOwner.mHorizontalResolution == i2) { solverVariable = constraintWidget.mLeft.mTarget.mSolverVariable; constraintWidget.mLeft.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mLeft); constraintWidget.mRight.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mRight); margin = (int) ((solverVariable.computedValue + ((float) constraintWidget.mLeft.getMargin())) + f); width = constraintWidget.getWidth() + margin; linearSystem.addEquality(constraintWidget.mLeft.mSolverVariable, margin); linearSystem.addEquality(constraintWidget.mRight.mSolverVariable, width); constraintWidget.mHorizontalResolution = i2; constraintWidget.setHorizontalDimension(margin, width); } else if (constraintWidget.mRight.mTarget == null || constraintWidget.mRight.mTarget.mOwner.mHorizontalResolution != i2) { int i3 = 0; width = constraintWidget.mLeft.mTarget != null ? i : i3; int i4 = constraintWidget.mRight.mTarget != null ? i : i3; if (width == 0 && i4 == 0) { if (constraintWidget instanceof Guideline) { Guideline guideline = (Guideline) constraintWidget; if (guideline.getOrientation() == i) { float relativeBegin; constraintWidget.mLeft.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mLeft); constraintWidget.mRight.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mRight); i4 = -1; if (guideline.getRelativeBegin() != i4) { relativeBegin = (float) guideline.getRelativeBegin(); } else if (guideline.getRelativeEnd() != i4) { relativeBegin = (float) (constraintWidgetContainer.getWidth() - guideline.getRelativeEnd()); } else { relativeBegin = guideline.getRelativePercent() * ((float) constraintWidgetContainer.getWidth()); } width = (int) (relativeBegin + f); linearSystem.addEquality(constraintWidget.mLeft.mSolverVariable, width); linearSystem.addEquality(constraintWidget.mRight.mSolverVariable, width); constraintWidget.mHorizontalResolution = i2; constraintWidget.mVerticalResolution = i2; constraintWidget.setHorizontalDimension(width, width); constraintWidget.setVerticalDimension(i3, constraintWidgetContainer.getHeight()); } } else { constraintWidget.mLeft.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mLeft); constraintWidget.mRight.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mRight); margin = constraintWidget.getX(); width = constraintWidget.getWidth() + margin; linearSystem.addEquality(constraintWidget.mLeft.mSolverVariable, margin); linearSystem.addEquality(constraintWidget.mRight.mSolverVariable, width); constraintWidget.mHorizontalResolution = i2; } } } else { solverVariable = constraintWidget.mRight.mTarget.mSolverVariable; constraintWidget.mLeft.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mLeft); constraintWidget.mRight.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mRight); margin = (int) ((solverVariable.computedValue - ((float) constraintWidget.mRight.getMargin())) + f); width = margin - constraintWidget.getWidth(); linearSystem.addEquality(constraintWidget.mLeft.mSolverVariable, width); linearSystem.addEquality(constraintWidget.mRight.mSolverVariable, margin); constraintWidget.mHorizontalResolution = i2; constraintWidget.setHorizontalDimension(width, margin); } return; } else if (constraintWidget.mLeft.mTarget.mOwner == constraintWidgetContainer && constraintWidget.mRight.mTarget.mOwner == constraintWidgetContainer) { width = constraintWidget.mLeft.getMargin(); i = constraintWidget.mRight.getMargin(); if (constraintWidgetContainer.mHorizontalDimensionBehaviour == DimensionBehaviour.MATCH_CONSTRAINT) { margin = constraintWidgetContainer.getWidth() - i; } else { width += (int) ((((float) (((constraintWidgetContainer.getWidth() - width) - i) - constraintWidget.getWidth())) * constraintWidget.mHorizontalBiasPercent) + f); margin = constraintWidget.getWidth() + width; } constraintWidget.mLeft.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mLeft); constraintWidget.mRight.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mRight); linearSystem.addEquality(constraintWidget.mLeft.mSolverVariable, width); linearSystem.addEquality(constraintWidget.mRight.mSolverVariable, margin); constraintWidget.mHorizontalResolution = i2; constraintWidget.setHorizontalDimension(width, margin); return; } else { constraintWidget.mHorizontalResolution = i; return; } } constraintWidget.mLeft.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mLeft); constraintWidget.mRight.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mRight); width = constraintWidget.mLeft.mMargin; margin = constraintWidgetContainer.getWidth() - constraintWidget.mRight.mMargin; linearSystem.addEquality(constraintWidget.mLeft.mSolverVariable, width); linearSystem.addEquality(constraintWidget.mRight.mSolverVariable, margin); constraintWidget.setHorizontalDimension(width, margin); constraintWidget.mHorizontalResolution = i2; } static void checkVerticalSimpleDependency(ConstraintWidgetContainer constraintWidgetContainer, LinearSystem linearSystem, ConstraintWidget constraintWidget) { int i = 1; if (constraintWidget.mVerticalDimensionBehaviour == DimensionBehaviour.MATCH_CONSTRAINT) { constraintWidget.mVerticalResolution = i; return; } int i2 = 8; int i3 = 2; int margin; int height; if (constraintWidgetContainer.mVerticalDimensionBehaviour == DimensionBehaviour.WRAP_CONTENT || constraintWidget.mVerticalDimensionBehaviour != DimensionBehaviour.MATCH_PARENT) { float f = 0.5f; if (constraintWidget.mTop.mTarget == null || constraintWidget.mBottom.mTarget == null) { SolverVariable solverVariable; if (constraintWidget.mTop.mTarget != null && constraintWidget.mTop.mTarget.mOwner == constraintWidgetContainer) { margin = constraintWidget.mTop.getMargin(); height = constraintWidget.getHeight() + margin; constraintWidget.mTop.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mTop); constraintWidget.mBottom.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBottom); linearSystem.addEquality(constraintWidget.mTop.mSolverVariable, margin); linearSystem.addEquality(constraintWidget.mBottom.mSolverVariable, height); if (constraintWidget.mBaselineDistance > 0 || constraintWidget.getVisibility() == i2) { constraintWidget.mBaseline.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBaseline); linearSystem.addEquality(constraintWidget.mBaseline.mSolverVariable, constraintWidget.mBaselineDistance + margin); } constraintWidget.mVerticalResolution = i3; constraintWidget.setVerticalDimension(margin, height); } else if (constraintWidget.mBottom.mTarget != null && constraintWidget.mBottom.mTarget.mOwner == constraintWidgetContainer) { constraintWidget.mTop.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mTop); constraintWidget.mBottom.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBottom); margin = constraintWidgetContainer.getHeight() - constraintWidget.mBottom.getMargin(); height = margin - constraintWidget.getHeight(); linearSystem.addEquality(constraintWidget.mTop.mSolverVariable, height); linearSystem.addEquality(constraintWidget.mBottom.mSolverVariable, margin); if (constraintWidget.mBaselineDistance > 0 || constraintWidget.getVisibility() == i2) { constraintWidget.mBaseline.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBaseline); linearSystem.addEquality(constraintWidget.mBaseline.mSolverVariable, constraintWidget.mBaselineDistance + height); } constraintWidget.mVerticalResolution = i3; constraintWidget.setVerticalDimension(height, margin); } else if (constraintWidget.mTop.mTarget != null && constraintWidget.mTop.mTarget.mOwner.mVerticalResolution == i3) { solverVariable = constraintWidget.mTop.mTarget.mSolverVariable; constraintWidget.mTop.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mTop); constraintWidget.mBottom.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBottom); margin = (int) ((solverVariable.computedValue + ((float) constraintWidget.mTop.getMargin())) + f); height = constraintWidget.getHeight() + margin; linearSystem.addEquality(constraintWidget.mTop.mSolverVariable, margin); linearSystem.addEquality(constraintWidget.mBottom.mSolverVariable, height); if (constraintWidget.mBaselineDistance > 0 || constraintWidget.getVisibility() == i2) { constraintWidget.mBaseline.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBaseline); linearSystem.addEquality(constraintWidget.mBaseline.mSolverVariable, constraintWidget.mBaselineDistance + margin); } constraintWidget.mVerticalResolution = i3; constraintWidget.setVerticalDimension(margin, height); } else if (constraintWidget.mBottom.mTarget != null && constraintWidget.mBottom.mTarget.mOwner.mVerticalResolution == i3) { solverVariable = constraintWidget.mBottom.mTarget.mSolverVariable; constraintWidget.mTop.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mTop); constraintWidget.mBottom.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBottom); margin = (int) ((solverVariable.computedValue - ((float) constraintWidget.mBottom.getMargin())) + f); height = margin - constraintWidget.getHeight(); linearSystem.addEquality(constraintWidget.mTop.mSolverVariable, height); linearSystem.addEquality(constraintWidget.mBottom.mSolverVariable, margin); if (constraintWidget.mBaselineDistance > 0 || constraintWidget.getVisibility() == i2) { constraintWidget.mBaseline.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBaseline); linearSystem.addEquality(constraintWidget.mBaseline.mSolverVariable, constraintWidget.mBaselineDistance + height); } constraintWidget.mVerticalResolution = i3; constraintWidget.setVerticalDimension(height, margin); } else if (constraintWidget.mBaseline.mTarget == null || constraintWidget.mBaseline.mTarget.mOwner.mVerticalResolution != i3) { int i4 = 0; height = constraintWidget.mBaseline.mTarget != null ? i : i4; int i5 = constraintWidget.mTop.mTarget != null ? i : i4; if (constraintWidget.mBottom.mTarget == null) { i = i4; } if (height == 0 && i5 == 0 && i == 0) { if (constraintWidget instanceof Guideline) { Guideline guideline = (Guideline) constraintWidget; if (guideline.getOrientation() == 0) { float relativeBegin; constraintWidget.mTop.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mTop); constraintWidget.mBottom.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBottom); i2 = -1; if (guideline.getRelativeBegin() != i2) { relativeBegin = (float) guideline.getRelativeBegin(); } else if (guideline.getRelativeEnd() != i2) { relativeBegin = (float) (constraintWidgetContainer.getHeight() - guideline.getRelativeEnd()); } else { relativeBegin = guideline.getRelativePercent() * ((float) constraintWidgetContainer.getHeight()); } height = (int) (relativeBegin + f); linearSystem.addEquality(constraintWidget.mTop.mSolverVariable, height); linearSystem.addEquality(constraintWidget.mBottom.mSolverVariable, height); constraintWidget.mVerticalResolution = i3; constraintWidget.mHorizontalResolution = i3; constraintWidget.setVerticalDimension(height, height); constraintWidget.setHorizontalDimension(i4, constraintWidgetContainer.getWidth()); } } else { constraintWidget.mTop.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mTop); constraintWidget.mBottom.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBottom); margin = constraintWidget.getY(); height = constraintWidget.getHeight() + margin; linearSystem.addEquality(constraintWidget.mTop.mSolverVariable, margin); linearSystem.addEquality(constraintWidget.mBottom.mSolverVariable, height); if (constraintWidget.mBaselineDistance > 0 || constraintWidget.getVisibility() == i2) { constraintWidget.mBaseline.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBaseline); linearSystem.addEquality(constraintWidget.mBaseline.mSolverVariable, margin + constraintWidget.mBaselineDistance); } constraintWidget.mVerticalResolution = i3; } } } else { solverVariable = constraintWidget.mBaseline.mTarget.mSolverVariable; constraintWidget.mTop.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mTop); constraintWidget.mBottom.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBottom); margin = (int) ((solverVariable.computedValue - ((float) constraintWidget.mBaselineDistance)) + f); height = constraintWidget.getHeight() + margin; linearSystem.addEquality(constraintWidget.mTop.mSolverVariable, margin); linearSystem.addEquality(constraintWidget.mBottom.mSolverVariable, height); constraintWidget.mBaseline.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBaseline); linearSystem.addEquality(constraintWidget.mBaseline.mSolverVariable, constraintWidget.mBaselineDistance + margin); constraintWidget.mVerticalResolution = i3; constraintWidget.setVerticalDimension(margin, height); } return; } else if (constraintWidget.mTop.mTarget.mOwner == constraintWidgetContainer && constraintWidget.mBottom.mTarget.mOwner == constraintWidgetContainer) { height = constraintWidget.mTop.getMargin(); i = constraintWidget.mBottom.getMargin(); if (constraintWidgetContainer.mVerticalDimensionBehaviour == DimensionBehaviour.MATCH_CONSTRAINT) { margin = constraintWidget.getHeight() + height; } else { height = (int) ((((float) height) + (((float) (((constraintWidgetContainer.getHeight() - height) - i) - constraintWidget.getHeight())) * constraintWidget.mVerticalBiasPercent)) + f); margin = constraintWidget.getHeight() + height; } constraintWidget.mTop.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mTop); constraintWidget.mBottom.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBottom); linearSystem.addEquality(constraintWidget.mTop.mSolverVariable, height); linearSystem.addEquality(constraintWidget.mBottom.mSolverVariable, margin); if (constraintWidget.mBaselineDistance > 0 || constraintWidget.getVisibility() == i2) { constraintWidget.mBaseline.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBaseline); linearSystem.addEquality(constraintWidget.mBaseline.mSolverVariable, constraintWidget.mBaselineDistance + height); } constraintWidget.mVerticalResolution = i3; constraintWidget.setVerticalDimension(height, margin); return; } else { constraintWidget.mVerticalResolution = i; return; } } constraintWidget.mTop.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mTop); constraintWidget.mBottom.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBottom); height = constraintWidget.mTop.mMargin; margin = constraintWidgetContainer.getHeight() - constraintWidget.mBottom.mMargin; linearSystem.addEquality(constraintWidget.mTop.mSolverVariable, height); linearSystem.addEquality(constraintWidget.mBottom.mSolverVariable, margin); if (constraintWidget.mBaselineDistance > 0 || constraintWidget.getVisibility() == i2) { constraintWidget.mBaseline.mSolverVariable = linearSystem.createObjectVariable(constraintWidget.mBaseline); linearSystem.addEquality(constraintWidget.mBaseline.mSolverVariable, constraintWidget.mBaselineDistance + height); } constraintWidget.setVerticalDimension(height, margin); constraintWidget.mVerticalResolution = i3; } }
package com.ryg.utils; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.Log; import com.ryg.dynamicload.DLBasePluginActivity; import com.ryg.dynamicload.DLBasePluginFragmentActivity; public class DLUtils { private static final String TAG = "DLUtils"; public static PackageInfo getPackageInfo(Context context, String apkFilepath) { PackageManager pm = context.getPackageManager(); PackageInfo pkgInfo = null; try { pkgInfo = pm.getPackageArchiveInfo(apkFilepath, PackageManager.GET_ACTIVITIES); } catch (Exception e) { // should be something wrong with parse e.printStackTrace(); } return pkgInfo; } public static Drawable getAppIcon(Context context, String apkFilepath) { PackageManager pm = context.getPackageManager(); PackageInfo pkgInfo = getPackageInfo(context, apkFilepath); if (pkgInfo == null) { return null; } // Workaround for http://code.google.com/p/android/issues/detail?id=9151 ApplicationInfo appInfo = pkgInfo.applicationInfo; if (Build.VERSION.SDK_INT >= 8) { appInfo.sourceDir = apkFilepath; appInfo.publicSourceDir = apkFilepath; } return pm.getApplicationIcon(appInfo); } public static CharSequence getAppLabel(Context context, String apkFilepath) { PackageManager pm = context.getPackageManager(); PackageInfo pkgInfo = getPackageInfo(context, apkFilepath); if (pkgInfo == null) { return null; } // Workaround for http://code.google.com/p/android/issues/detail?id=9151 ApplicationInfo appInfo = pkgInfo.applicationInfo; if (Build.VERSION.SDK_INT >= 8) { appInfo.sourceDir = apkFilepath; appInfo.publicSourceDir = apkFilepath; } return pm.getApplicationLabel(appInfo); } public static String getProxyViewAction(String className, ClassLoader classLoader) { int activityType = getActivityType(className, classLoader); return getProxyViewActionByActivityType(activityType); } public static String getProxyViewAction(Class<?> cls) { int activityType = getActivityType(cls); return getProxyViewActionByActivityType(activityType); } private static String getProxyViewActionByActivityType(int activityType) { String proxyViewAction = null; switch (activityType) { case DLConstants.ACTIVITY_TYPE_NORMAL: { proxyViewAction = DLConstants.PROXY_ACTIVITY_VIEW_ACTION; break; } case DLConstants.ACTIVITY_TYPE_FRAGMENT: { proxyViewAction = DLConstants.PROXY_FRAGMENT_ACTIVITY_VIEW_ACTION; break; } case DLConstants.ACTIVITY_TYPE_ACTIONBAR: case DLConstants.ACTIVITY_TYPE_UNKNOWN: default: break; } if (proxyViewAction == null) { Log.e(TAG, "unsupported activityType:" + activityType); } return proxyViewAction; } private static int getActivityType(String className, ClassLoader classLoader) { int activityType = DLConstants.ACTIVITY_TYPE_UNKNOWN; try { Class<?> cls = Class.forName(className, false, classLoader); activityType = getActivityType(cls); } catch (ClassNotFoundException e) { e.printStackTrace(); } return activityType; } private static int getActivityType(Class<?> cls) { int activityType = DLConstants.ACTIVITY_TYPE_UNKNOWN; try { if (cls.asSubclass(DLBasePluginActivity.class) != null) { activityType = DLConstants.ACTIVITY_TYPE_NORMAL; return activityType; } } catch (ClassCastException e) { // ignored } try { if (cls.asSubclass(DLBasePluginFragmentActivity.class) != null) { activityType = DLConstants.ACTIVITY_TYPE_FRAGMENT; return activityType; } } catch (ClassCastException e) { // ignored } //TODO: handle other activity types, ActionbarActivity,eg. return activityType; } public static void showDialog(Activity activity, String title, String message) { new AlertDialog.Builder(activity).setTitle(title).setMessage(message) .setPositiveButton("确定", null).show(); } }
package xyz.softwaredeveloveper.CustomCache; import org.junit.After; import org.junit.Before; import org.junit.Test; import xyz.softwaredeveloveper.impl.TimeStampLog; import java.util.Optional; import static org.junit.Assert.*; public class TimeStampLogTest { private TimeStampLog<Integer> log = new TimeStampLog<>(); @Before public void before() { } @After public void after() { log.clear(); } @Test public void shouldAddNewEntryAndReturnItAsTheOldest() { Integer key = 1; Long timeStamp = log.add(key); assertNotNull(timeStamp); assertEquals(1, log.size()); assertEquals(key, log.getTheOldestEntry()); } @Test public void shouldTimeStampBeDifferentOnEveryInsertion() { Long t1 = log.add(1); Long t2 = log.add(2); Long t3 = log.add(3); Long t4 = log.add(4); assertNotEquals(t1, t2); assertNotEquals(t3, t4); assertNotEquals(t2, t3); assertNotEquals(t2, t4); assertEquals(4, log.size()); } @Test public void shouldGetTheOldestEntrySimpleCase() { Integer expectedOldest = 1; log.add(1); log.add(2); log.add(3); log.add(4); assertEquals(expectedOldest, log.getTheOldestEntry()); } @Test public void shouldGetTheOldestEntry() { Integer expectedOldest = 3; Long timeStamp = log.add(1); Long timeStamp2 = log.add(2); log.add(3); log.add(4); log.remove(timeStamp); log.remove(timeStamp2); assertEquals(expectedOldest, log.getTheOldestEntry()); } @Test public void shouldGetTheOldestEntryByAlteringTimeStamp() { Integer expectedOldest = 3; Long timeStamp = log.add(1); Long timeStamp2 = log.add(2); log.add(3); log.add(4); log.remove(timeStamp); log.remove(timeStamp2); assertEquals(expectedOldest, log.getTheOldestEntry()); } @Test public void shouldNotFindTimeStampById() { log.add(1); log.add(2); Long timeStamp = log.add(3); log.add(4); log.remove(timeStamp); Optional<Long> timeStampResult = log.findTimeStamp(3); assertFalse(timeStampResult.isPresent()); } @Test public void shouldFindTimeStampById() { log.add(1); log.add(2); Long timeStamp = log.add(3); log.add(4); Optional<Long> timeStampResult = log.findTimeStamp(3); assertTrue(timeStampResult.isPresent()); assertEquals(timeStamp, timeStampResult.get()); } @Test public void shouldRegenerateTimeStampByTimeStamp() { log.add(1); log.add(2); Long timeStamp = log.add(3); log.add(4); Long newTimeStamp = log.regenerateTimeStamp(timeStamp); assertNotEquals(timeStamp, newTimeStamp); assertTrue(newTimeStamp > timeStamp); assertEquals(newTimeStamp, log.findTimeStamp(3).get()); assertEquals(4, log.size()); } @Test public void shouldRegenerateTimeStampById() { log.add(1); log.add(2); Long timeStamp = log.add(3); log.add(4); Optional<Long> newTimeStamp = log.regenerateTimeStamp(3); assertTrue(newTimeStamp.isPresent()); assertNotEquals(timeStamp, newTimeStamp.get()); assertTrue(newTimeStamp.get() > timeStamp); assertEquals(newTimeStamp.get(), log.findTimeStamp(3).get()); assertEquals(4, log.size()); } @Test public void shouldNotRegenerateTimeStamp() { log.add(1); log.add(2); Long timeStamp = log.add(3); log.add(4); Optional<Long> newTimeStamp = log.regenerateTimeStamp(50); assertFalse(newTimeStamp.isPresent()); } @Test public void shouldUpdateValueByTimeStamp() { log.add(1); log.add(2); Long timeStamp = log.add(3); log.add(4); boolean isUpdated = log.updateValueByTimeStamp(timeStamp, 10); assertTrue(isUpdated); assertEquals(4, log.size()); Integer actualValue = log.getId(timeStamp); assertEquals(new Integer(10), actualValue); } @Test public void testEvictTheOldestRegistry() { log.add(23434); log.add(12111); Long timeStamp = log.add(555523); log.add(44444); assertEquals(new Integer(23434), log.evictTheOldestRegistry()); } @Test public void testEvictTheOldestRegistryByRemovingEntry() { Long timeStamp = log.add(23434); log.add(12111); Long timeStamp2 = log.add(555523); log.add(44444); log.remove(timeStamp); Integer evicted = log.evictTheOldestRegistry(); assertEquals(2, log.size()); assertEquals(new Integer(12111), evicted); assertNull(log.getId(timeStamp)); assertNotNull(log.getId(timeStamp2)); } }
package View; import javafx.scene.effect.DropShadow; import javafx.scene.effect.Effect; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; public class ViewEffects { public static Effect getShadowEffect(int xOffset,int yOffset) { DropShadow dropShadow = new DropShadow(); dropShadow.setOffsetX(xOffset); dropShadow.setOffsetY(yOffset); return dropShadow; } public static Font getHeadersFont() { return Font.font("Arial", FontWeight.BOLD, 24); } }
/** Name: Rafiul Huq Date: 10/07/2018 Course Section: IT 206-006 Assignment: Programming Assignment 8 Description: This program will keep track of all a companyís servers. There is a maximum of 206 servers and a server must be either a web server or a file server, cannot just be a server. The program will track a serverís name (names must be unique), operating system (between Window, Linux, and OS X), hard drive capacity (terabytes), and level of usage (from 0 to 100). A file server also requires tracking the number of users with accounts on the server, up to 5000. A web server also requires tracking a list of programming languages that supported by the server (minimum of 2, maximum of 5). To calculate usage level for a file server, you multiply the number of users by 0.05, it the values exceeds 100, it will be set to 100. To calculate for a web server, multiply the number of programming languages supported by 20 to get the usage level. The final server report must be well-formatted with a report header, listing the server type, server name, operating system installed, hard drive capacity, and level of usage. A file server must also include the number of users with accounts and a web server must include the number of supported programming languages. Lastly, the report should include the total number of servers and the total hard drive capacity (in terabytes) across all servers. */ import javax.swing.JOptionPane; public class ServerSystem { /* This method creates any constants and the array of servers needed. It also called the other methods it input is String[] args it returns nothing */ public static void main(String[] args) { final int MAX_NUM_SERVERS = 206; Server[] servers = new Server[MAX_NUM_SERVERS]; do { try { servers[Server.getNumServers()] = addServer(); } catch(IllegalArgumentException e) { JOptionPane.showMessageDialog(null, "Server could not be created\n" + e.getMessage()); } } while (JOptionPane.showConfirmDialog(null, "Add another server? ") == JOptionPane.YES_OPTION); double total = totalCapacity(servers); summaryReport(servers, total); } /* This method creates a server and asks for user input for all its attributes and the kind of server it is It has no input it returns a server object */ public static Server addServer() { Server aServer = null; Object[] options = {"Web Server", "File Server"}; switch (JOptionPane.showOptionDialog(null, "What type of server is being added?","A New Server", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,options,options[0])) { case JOptionPane.YES_OPTION: aServer = new WebServer(JOptionPane.showInputDialog("Enter the servers name: "), JOptionPane.showInputDialog("Enter the OS type(Window, Linux, OS X): "), Double.parseDouble(JOptionPane.showInputDialog("Enter the server's capacity: "))); do { try { ((WebServer)aServer).setLanguage(JOptionPane.showInputDialog("Enter a supported language: ")); } catch (IllegalArgumentException e) { JOptionPane.showMessageDialog(null, "Language could not be added.\n" + e.getMessage()); } } while (JOptionPane.showConfirmDialog(null, "Enter another language? ") == JOptionPane.YES_OPTION); break; case JOptionPane.NO_OPTION: aServer = new FileServer(JOptionPane.showInputDialog("Enter the servers name: "), JOptionPane.showInputDialog("Enter the OS type: "), Double.parseDouble(JOptionPane.showInputDialog("Enter the server's capacity: ")), Integer.parseInt(JOptionPane.showInputDialog("Enter the number of users for the server: "))); break; default: throw new RuntimeException("Error in server selection"); } return aServer; } /* This method calculates the total capacity across all servers it inputs the array of servers from main it returns the total capacity */ public static double totalCapacity(Server[] servers) { double total = 0; for (int x=0;x<Server.getNumServers();x++) { total += servers[x].getCapacity(); } return total; } /* This method prints out the final report that details every server added and the total number of servers added and the total capacity overall it inputs the array of servers from main it returns nothing */ public static void summaryReport(Server[] servers, double total) { String output = "***Server Report***\n\n"; for (int x=0;x<Server.getNumServers();x++) { output += servers[x].toString() + "\n"; } output += "\nNumber of Servers: " + Server.getNumServers() + "\nTotal capacity across all servers: " + total + " Terabytes"; JOptionPane.showMessageDialog(null, output); } }
package architecture.exception; public class BoardPostingDuplicationException extends RuntimeException{ // private static final long serialVersionUID = -6038657093205153751L; public BoardPostingDuplicationException(String message){ // super(message); } }
package com.shadow.repository; import com.shadow.domain.ImageFile; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by qq65827 on 2015/1/26. */ @Repository public interface ImageFileRepository extends MyCustomRepository<ImageFile,Long> { public List<ImageFile> findByUserId(long userId); public List<ImageFile> findAll(); }
package com.example.navigationdrawerandfragments; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.Settings; import android.speech.RecognitionListener; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.Locale; import pl.droidsonroids.gif.GifImageView; import static android.media.MediaPlayer.*; public class MessageFragment extends Fragment { private Button playButton,forwardButton,rewindButton; private SeekBar positionBar; private TextView elapsedTime,remainTime,songname; private MediaPlayer mediaPlayer; private int totaltime; private int positon; private ImageView gifImageView; private ArrayList<File> mySongs; private String msongName; private RelativeLayout parentRelativeLayout; private SpeechRecognizer speechRecognizer; private Intent speechRecognizerIntent; private String keeper=""; private static MessageFragment instance=null; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View RootView=inflater.inflate(R.layout.fragment_message,container,false); instance=this; //---------------------------------------------------------------------------------- setRetainInstance(true); gifImageView=RootView.findViewById(R.id.mic); checkVoiceCommandPermission(); speechRecognizer=SpeechRecognizer.createSpeechRecognizer(getActivity()); speechRecognizerIntent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); parentRelativeLayout=(RelativeLayout)RootView.findViewById(R.id.parentRelativeLayout); speechRecognizer.setRecognitionListener(new RecognitionListener() { @Override public void onReadyForSpeech(Bundle params) { } @Override public void onBeginningOfSpeech() { } @Override public void onRmsChanged(float rmsdB) { } @Override public void onBufferReceived(byte[] buffer) { } @Override public void onEndOfSpeech() { } @Override public void onError(int error) { } @Override public void onResults(Bundle results) { ArrayList<String> matchesFound=results.getStringArrayList(speechRecognizer.RESULTS_RECOGNITION); gifImageView.setImageResource(R.drawable.micoff); if(matchesFound!=null) { keeper=matchesFound.get(0); if(keeper.equalsIgnoreCase("Play the song") || keeper.equalsIgnoreCase("Please Play the song") ||keeper.equalsIgnoreCase("Play song")|| keeper.equalsIgnoreCase("Play")) { playSong(); } if(keeper.equalsIgnoreCase("Pause the song") || keeper.equalsIgnoreCase("Please Pause the song") ||keeper.equalsIgnoreCase("Pause song")|| keeper.equalsIgnoreCase("Pause")) { pauseSong(); } if(keeper.equalsIgnoreCase("Play the next song") || keeper.equalsIgnoreCase("Please Play the next song") ||keeper.equalsIgnoreCase("Play next song")|| keeper.equalsIgnoreCase("next")) { playnextSong(); } if(keeper.equalsIgnoreCase("Play the previous song") || keeper.equalsIgnoreCase("Please Play the previous song") ||keeper.equalsIgnoreCase("Play previous song")|| keeper.equalsIgnoreCase("previous")) { playpreviousSong(); } if(keeper.equalsIgnoreCase("stop")) { onstop(); } Toast.makeText(getActivity(),"Result ="+keeper,Toast.LENGTH_SHORT).show(); } } @Override public void onPartialResults(Bundle partialResults) { } @Override public void onEvent(int eventType, Bundle params) { } }); parentRelativeLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: gifImageView.setImageResource(R.drawable.mico); speechRecognizer.startListening(speechRecognizerIntent); keeper=""; break; case MotionEvent.ACTION_UP: speechRecognizer.stopListening(); break; } return false; } }); //------------------------------------------------------------------------ playButton=(Button)RootView.findViewById(R.id.playBtn); elapsedTime=(TextView)RootView.findViewById(R.id.elapsedTimeLabel); remainTime=(TextView)RootView.findViewById(R.id.remainTimeLabel); songname=(TextView)RootView.findViewById(R.id.tv); positionBar=(SeekBar)RootView.findViewById(R.id.positionBar); songname.setSelected(true); if(getArguments()!=null) { mySongs = (ArrayList) getArguments().getSerializable("songs"); msongName = mySongs.get(positon).getName(); String namesong = getArguments().getString("name"); songname.setText(namesong); songname.setSelected(true); positon = getArguments().getInt("position", 0); Uri uri = Uri.parse(mySongs.get(positon).toString()); if (mediaPlayer != null) { mediaPlayer.pause(); mediaPlayer.stop(); mediaPlayer.release(); } mediaPlayer = MediaPlayer.create(getActivity(), uri); mediaPlayer.setLooping(true); mediaPlayer.seekTo(0); mediaPlayer.setVolume(0.5f, 0.5f); mediaPlayer.start(); playButton.setBackgroundResource(R.drawable.stop); totaltime=mediaPlayer.getDuration(); positionBar.setMax(totaltime); } playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mediaPlayer!=null) { if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); playButton.setBackgroundResource(R.drawable.stop); } else { mediaPlayer.pause(); playButton.setBackgroundResource(R.drawable.play); } } } }); forwardButton = (Button) RootView.findViewById(R.id.forwardBtn); rewindButton=(Button)RootView.findViewById(R.id.rewindbtn); forwardButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mediaPlayer!=null) { if(mediaPlayer.getCurrentPosition()>0) playnextSong(); } } }); rewindButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mediaPlayer!=null) { playpreviousSong(); } } }); positionBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(fromUser) { if(mediaPlayer!=null) { mediaPlayer.seekTo(progress); }positionBar.setProgress(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); SeekBar volumeBar = (SeekBar) RootView.findViewById(R.id.volumeBar); volumeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { float volumeNumber=progress/100f; if(mediaPlayer!=null)mediaPlayer.setVolume(volumeNumber,volumeNumber); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); new Thread(new Runnable() { @Override public void run(){ while(mediaPlayer!=null) { try { Message message=new Message(); message.what=mediaPlayer.getCurrentPosition(); handler.sendMessage(message); Thread.sleep(1000); } catch (Exception ignored) { } } } }).start(); return RootView; } private Handler handler=new Handler() { @Override public void handleMessage(Message msg) { int currentPosition=msg.what; positionBar.setProgress(currentPosition); String elapsed=createTimeLabel(currentPosition); elapsedTime.setText(elapsed); String remaining=createTimeLabel(totaltime-currentPosition); remainTime.setText("-"+remaining); } }; public String createTimeLabel(int time) { String timeLabel=""; int min=time/1000/60; int sec=time/1000%60; timeLabel=min+":"; if(sec<10) { timeLabel+="0"; } timeLabel+=sec; return timeLabel; } private void playnextSong() { mediaPlayer.pause(); mediaPlayer.stop(); mediaPlayer.release(); positon=((positon+1)%mySongs.size()); Uri uri=Uri.parse(mySongs.get(positon).toString()); mediaPlayer=MediaPlayer.create(getActivity(),uri); msongName=mySongs.get(positon).toString(); songname.setText(msongName.substring(msongName.lastIndexOf('/')+1)); totaltime=mediaPlayer.getDuration(); mediaPlayer.setLooping(true); positionBar.setMax(totaltime); mediaPlayer.start(); if (!mediaPlayer.isPlaying()) { playButton.setBackgroundResource(R.drawable.play); } else { playButton.setBackgroundResource(R.drawable.stop); } } private void playpreviousSong() { mediaPlayer.pause(); mediaPlayer.stop(); mediaPlayer.release(); positon=((positon-1)<0?(mySongs.size()-1):(positon-1)); Uri uri=Uri.parse(mySongs.get(positon).toString()); mediaPlayer=MediaPlayer.create(getActivity(),uri); msongName=mySongs.get(positon).toString(); songname.setText(msongName.substring(msongName.lastIndexOf('/')+1)); totaltime=mediaPlayer.getDuration(); mediaPlayer.setLooping(true); positionBar.setMax(totaltime); mediaPlayer.start(); if (!mediaPlayer.isPlaying()) { playButton.setBackgroundResource(R.drawable.play); } else { playButton.setBackgroundResource(R.drawable.stop); } } private void checkVoiceCommandPermission() { if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) { if(!(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO)== PackageManager.PERMISSION_GRANTED)) { Intent intent=new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getActivity().getPackageName())); startActivity(intent); getActivity().finish(); } } } private void playSong() { if (mediaPlayer!=null && !mediaPlayer.isPlaying()) { mediaPlayer.start(); playButton.setBackgroundResource(R.drawable.stop); } } private void pauseSong() { if (mediaPlayer!=null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); playButton.setBackgroundResource(R.drawable.play); } } public void onstop() { if(mediaPlayer!=null) mediaPlayer.release(); mediaPlayer=null; } public static MessageFragment getInstance(){ return instance; } }
package com.ifeng.recom.mixrecall.common.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.Type; public class GsonUtil { private static final Logger logger = LoggerFactory.getLogger(GsonUtil.class); private final static Gson gson = new Gson(); private final static Gson gsonWithoutExpose = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); /** * 把对象转换为jsonString,并捕获异常 * * @param object * @return */ public static String object2json(Object object) { try { return gson.toJson(object); } catch (Exception e) { logger.error("jsonstr Exception:{}", e); return null; } } /** * * @param object * @param typeOfT * @return */ public static String object2json(Object object, Type typeOfT){ try { return gson.toJson(object, typeOfT); } catch (Exception e) { logger.error("jsonstr Exception:{}", e); return null; } } public static String object2jsonWithoutExpose(Object object){ try { return gsonWithoutExpose.toJson(object); } catch (Exception e) { logger.error("jsonstr Exception:{}", e); return null; } } public static String object2jsonWithoutExpose(Object object, Type typeOfT){ try { return gsonWithoutExpose.toJson(object, typeOfT); } catch (Exception e) { logger.error("jsonstr Exception:{}", e); return null; } } /** * 将jackson json转化为list、map等复杂对象 * 例如: List<Bean> beanList = mapper.readValue(jsonString, new TypeReference<List<Bean>>() {}); * * @param text * @param typeReference * @param <T> * @return * @throws IOException */ public static final <T> T json2Object(String text, Type typeReference) { try { return gson.fromJson(text, typeReference); } catch (Exception e) { e.printStackTrace(); logger.error("jsonstr:{},Exception:{}", text, e); } return null; } public static final <T> T json2Object(String text, Class<T> classOfT) { try { return gson.fromJson(text, classOfT); } catch (Exception e) { e.printStackTrace(); logger.error("jsonstr:{},Exception:{}", text, e); } return null; } public static final <T> T json2ObjectWithoutExpose(String text, Type typeReference) { try { return gsonWithoutExpose.fromJson(text, typeReference); } catch (Exception e) { e.printStackTrace(); logger.error("jsonstr:{},Exception:{}", text, e); } return null; } public static final <T> T json2ObjectWithoutExpose(String text, Class<T> classOfT) { try { return gsonWithoutExpose.fromJson(text, classOfT); } catch (Exception e) { e.printStackTrace(); logger.error("jsonstr:{},Exception:{}", text, e); } return null; } public static final String o2jWithoutExpose(Object o) { try { return gsonWithoutExpose.toJson(o); } catch (Exception e) { logger.error("toJsonError", e); } return null; } }
package com.damianogiusti.cleanandroid.ui; /** * Created by Damiano Giusti on 03/05/17. */ public class others_ui_packages_here { }
package xhu.wncg.firesystem.modules.mapper; import xhu.wncg.firesystem.modules.controller.vo.TransferTableVO; import xhu.wncg.firesystem.modules.controller.qo.TransferTableQO; import xhu.wncg.common.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 移交书 * * @author zhaobo * @email 15528330581@163.com * @version 2017-11-02 15:58:15 */ @Mapper public interface TransferTableMapper extends BaseMapper<TransferTableQO, TransferTableVO> { }
package com._520it.wms.util; import java.util.Calendar; import java.util.Date; /** * Created by 123 on 2017/8/5. */ public class DateUtil { // 当前天的最后一秒 public static Date getEndDate(Date current){ Calendar c = Calendar.getInstance(); c.setTime(current); c.set(Calendar.HOUR_OF_DAY,23); c.set(Calendar.MINUTE,59); c.set(Calendar.SECOND,59); return c.getTime(); } }
package ua.epam.provider.dao; import org.junit.Assert; import org.junit.jupiter.api.Test; import ua.epam.provider.entity.User; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; import java.util.Random; class UserDaoTest { private UserDao userDao = new UserDao(); @Test void createUser() { int number = userDao.getAllUsers().size(); String email = "email1@email.com"; String phone = "1"; if (!userDao.isExistUser(email) && !userDao.isExistUserPhone(phone)) { User user = new User("name1", "1", email, phone,0); userDao.createUser(user); user = userDao.getUser(email); Assert.assertEquals(userDao.getAllUsers().size(), number + 1); userDao.deleteUser(user); } else Assert.assertTrue(userDao.getAllUsers().size() == number); } @Test void updateUser() { String email = "Email@email.com"; String phone = "111111"; if (!userDao.isExistUser(email) && !userDao.isExistUserPhone(phone)) { User user = new User("Name","1111", email, phone,0); userDao.createUser(user); user = userDao.getUser(email); String updateEmail = "EmailUpdate@email.com"; String updatePhone = "222222"; if (!userDao.isExistUser(updateEmail) && !userDao.isExistUserPhone(updatePhone)) { User newUser = new User("NewName", "2222", updateEmail, updatePhone,0); userDao.updateUser(user, newUser); Assert.assertTrue(userDao.isExistUser(updateEmail)); newUser = userDao.getUser(updateEmail); userDao.deleteUser(newUser); } else { System.out.println("User for update with email " + updateEmail + " or phone " + updatePhone + " is exists."); user = userDao.getUser(email); userDao.deleteUser(user); } } else System.out.println("User for update with email " + email + " or phone " + phone + " is exists."); } @Test void updateUserPassword() { String email = "email2@email.com"; String phone = "2"; if (!userDao.isExistUser(email) && !userDao.isExistUserPhone(phone)) { User user = new User("name2","2", email, phone,0); userDao.createUser(user); String newPassword = "1"; String password = user.getPassword(); userDao.updateUserPassword(user.getEmail(), newPassword); User newUser = userDao.getUser(email); if (newPassword.equals(password)) Assert.assertTrue(newUser.getPassword().equals(user.getPassword())); else Assert.assertFalse(newUser.getPassword().equals(user.getPassword())); userDao.deleteUser(newUser); } else System.out.println("User for update with email " + email + " or phone " + phone + " is exists."); } @Test void deleteUser() { String email = "email3@email.com"; String phone = "3"; if (!userDao.isExistUser(email) && !userDao.isExistUserPhone(phone)) { User user = new User("name3", "3", email, phone,0); userDao.createUser(user); int number = userDao.getAllUsers().size(); user = userDao.getUser(email); userDao.deleteUser(user); Assert.assertEquals(userDao.getAllUsers().size(), number - 1); } else System.out.println("User for update with email " + email + " or phone " + phone + " is exists."); } @Test void isExistUser() { String email = "email4@email.com"; String phone = "4"; if (!userDao.isExistUser(email) && !userDao.isExistUserPhone(phone)) { User user = new User("name4", "4", email, phone,0); userDao.createUser(user); Assert.assertTrue(userDao.isExistUser(email)); user = userDao.getUser(email); userDao.deleteUser(user); } else System.out.println("User for update with email " + email + " or phone " + phone + " is exists."); } @Test void getAllUsers() { List<User> userList = userDao.getAllUsers(); for (User user : userList ) { Assert.assertTrue(userDao.isExistUser(user.getEmail())); Assert.assertTrue(userDao.isExistUserPhone(user.getPhone())); } } @Test void getUser() { String email = "email5@email.com"; String phone = "5"; if (!userDao.isExistUser(email) && !userDao.isExistUserPhone(phone)) { User user = new User("name5", "5", email, phone,0); userDao.createUser(user); Assert.assertTrue(userDao.isExistUser(userDao.getUser(email).getEmail())); Assert.assertTrue(userDao.isExistUserPhone(userDao.getUser(email).getPhone())); user = userDao.getUser(email); userDao.deleteUser(user); } else System.out.println("User for update with email " + email + " or phone " + phone + " is exists."); } @Test void changeActiveStatus() { String email = "email6@email.com"; String phone = "6"; if (!userDao.isExistUser(email) && !userDao.isExistUserPhone(phone)) { User user = new User("name6", "6", email, phone,0); userDao.createUser(user); Random random = new Random(); Integer status = random.nextInt(1); userDao.changeActiveStatus(user.getEmail(), status); User newUser = userDao.getUser(user.getEmail()); Assert.assertTrue(newUser.getStatusActive().equals(status)); userDao.deleteUser(newUser); } else System.out.println("User for update with email " + email + " or phone " + phone + " is exists."); } @Test void addMoney() { String email = "email7@email.com"; String phone = "7"; if (!userDao.isExistUser(email) && !userDao.isExistUserPhone(phone)) { User user = new User("name7", "7", email, phone,0); userDao.createUser(user); user = userDao.getUser(email); Double account = user.getAccount(); Random random = new Random(); Double newAccount = random.nextDouble(); BigDecimal result = new BigDecimal(newAccount); result = result.setScale(2, RoundingMode.DOWN); newAccount = result.doubleValue(); if (newAccount > 0) { userDao.addMoney(user.getEmail(), newAccount + account); User newUser = userDao.getUser(user.getEmail()); Assert.assertTrue(newUser.getAccount().equals(newAccount + account)); } else Assert.assertTrue(user.getAccount().equals(account)); userDao.deleteUser(user); } else System.out.println("User for update with email " + email + " or phone " + phone + " is exists."); } @Test void findUserById() { String email = "email8@email.com"; String phone = "8"; if (!userDao.isExistUser(email) && !userDao.isExistUserPhone(phone)) { User user = new User("name8", "8", email, phone,0); userDao.createUser(user); user = userDao.getUser(email); User newUser = userDao.findUserById(user.getId()); Assert.assertTrue(newUser.getEmail().equals(user.getEmail())); Assert.assertTrue(newUser.getPhone().equals(user.getPhone())); userDao.deleteUser(user); } else System.out.println("User for update with email " + email + " or phone " + phone + " is exists."); } @Test void isExistUserPhone() { String email = "email9@email.com"; String phone = "9"; if (!userDao.isExistUser(email) && !userDao.isExistUserPhone(phone)) { User user = new User("name9", "9", email, phone,0); userDao.createUser(user); Assert.assertTrue(userDao.isExistUserPhone(phone)); user = userDao.getUser(email); userDao.deleteUser(user); } else System.out.println("User for update with email " + email + " or phone " + phone + " is exists."); } }
package strings; // 1.wap to enter a word and character and delete the inputted character from word import java.util.*; class S4_character_delete { Scanner sc=new Scanner(System.in); void d(char ch) { System.out.println("ENTER A WORD"); String str=sc.next(); StringBuffer stb=new StringBuffer(str); for(int i=0;i<stb.length();i++) { char ich=stb.charAt(i); ich=Character.toUpperCase(ich); ch=Character.toUpperCase(ch); if(ich==ch) { stb.deleteCharAt(i); i--; } } System.out.println(stb); } }
package pl.pmisko.mypetclinic.services; import pl.pmisko.mypetclinic.model.Specialty; public interface SpecialtyService extends CrudService<Specialty, Long> { }
package com.lfj.service.impl; import com.lfj.entity.Permission; import com.lfj.mapper.PermissionMapper; import com.lfj.service.IPermissionService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author lfj * @since 2020-03-04 */ @Service public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService { }
package com.rhino.mailParser; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Date; import java.util.LinkedList; import java.util.Map; import org.apache.log4j.Logger; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.rhino.mailParser.betterParser.AddressWordParser; import com.rhino.mailParser.betterParser.AmountWordParser; import com.rhino.mailParser.betterParser.AmountWordParserMustHaveSkipWord; import com.rhino.mailParser.betterParser.DateWordParser; import com.rhino.mailParser.betterParser.WordParserInterface; import com.rhino.mailParser.data.DataTypeDAO; import com.rhino.mailParser.data.UserData; import com.rhino.mailParser.data.UserDataDAO; public class BetterMailParser implements MailParserInterface{ private static Logger logger = Logger.getLogger(BetterMailParser.class); private SessionFactory sessionFactory; private static Map<String,String> dataType = null; private Object SYNC_OBJ = new Object(); //The user is the email address public void readAccount(String host, String user, String password, String path, Date date,String sysUser) throws Exception { readMap(); path = path + "/" + sysUser +"/"+ user + "/" + "Inbox"; File file = new File(path); // need to be recursive if (!file.exists()) { logger.error("The path " + path + " do not exist"); return; } if (!file.isDirectory()) { logger.error("The path " + path + " is not a folder"); return; } File[] files = file.listFiles(); if (files.length == 0) { logger.error("The path " + path + " contain 0 files"); return; } Session session = sessionFactory.openSession(); UserDataDAO userDataDAO = new UserDataDAO(); userDataDAO.setSession(session); Transaction tx = session.beginTransaction(); tx.begin(); for (File f : files) { if(!f.getName().endsWith("txt")){ logger.info("cannot parse file "+f.getName()); continue; } logger.info("File: " + f.getAbsolutePath()); LinkedList<WordParserInterface> parsers = new LinkedList<WordParserInterface>(); parsers.add(new AmountWordParser(new String[]{"of","is","for","us"},new String[]{"amount","balance","total","payment"})); parsers.add(new AmountWordParserMustHaveSkipWord(new String[]{"is"},new String[]{"account"})); parsers.add(new AddressWordParser(null,new String[]{"http","https"})); parsers.add(new DateWordParser(null,new String[]{"date"},"EEEEEEEEEEE MMMMMMMMMMMM dd yyyy",4)); parsers.add(new DateWordParser(null,new String[]{"date"},"MMMMMMMMMMMM dd yyyy",3)); UserData data = new UserData(); data.setUserID(sysUser); try { BufferedReader br = new BufferedReader(new FileReader(f)); String subject = br.readLine(); String from = br.readLine(); String messageId = br.readLine(); data.setMessageFrom(from); data.setMessageTitle(subject); data.setMessageIndex(Integer.parseInt(messageId)); String line; while ((line = br.readLine()) != null) { line = line.replaceAll("<", " "); String[] words = line.split(" "); for(String word:words){ word = word.trim(); if(word.length()<2){ continue; } LinkedList<String> splitWords = split(word); for(String splitWord:splitWords){ for(WordParserInterface parser:parsers){ parser.parse(splitWord, data); } } } } br.close(); } catch (Exception e) { logger.error(e, e); } if(data.getAmount()>-1){ try{ String type = dataType.get(data.getFrom()); data.setType(type); if(data.getFrom().equals("NULL")){ data.setFrom(data.getMessageFrom()); } userDataDAO.save(data); }catch(Exception e){ logger.error(e,e); } } } tx.commit(); session.close(); } public LinkedList<String> split(String word){ char c[] = word.toCharArray(); int x=0; LinkedList<String> tmp = new LinkedList<String>(); for(int i=0;i<c.length-1;i++){ if(c[i]=='.' || c[i+1] =='.'){ continue; } if((c[i]>='!' && c[i]<'A' && c[i+1]>='A' && c[i+1]<='z') || (c[i]>='A' && c[i]<='z' && c[i+1]>='!' && c[i+1]<'A')){ String s = word.substring(x, i+1); if(s.length()>1){ tmp.add(s); } x=i+1; } } if(x>0){ String s = word.substring(x, word.length()); if(s.length()>1){ tmp.add(s); } }else{ tmp.add(word); } return tmp; } private void readMap(){ if (dataType !=null){ return; } synchronized (SYNC_OBJ) { if (dataType !=null){ return; } Session session = sessionFactory.openSession(); DataTypeDAO userDataDAO = new DataTypeDAO(); userDataDAO.setSession(session); Transaction tx = session.beginTransaction(); tx.begin(); dataType = userDataDAO.getTypeMap(); tx.commit(); session.close(); } } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
package com.ifeng.recom.mixrecall.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by liligeng on 2019/8/19. */ @RestController @RequestMapping("/mixrecom/debug") public class DebugController { }
/* * Copyright (C) 2014 Changchao project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sherchen.likewechatphotoviewer.views; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.ImageView; import com.sherchen.likewechatphotoviewer.R; /** * The ratio is width to height */ public class RatioImageView extends ImageView { public static final float DEF_RATIO = 1.0f; public RatioImageView(Context context) { super(context); } public RatioImageView(Context context, AttributeSet attrs) { super(context, attrs); initStyleable(context, attrs); } public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initStyleable(context, attrs); } // public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super(context, attrs, defStyleAttr, defStyleRes); // initStyleable(context, attrs); // } private float weight; private void initStyleable(Context context, AttributeSet attrs){ TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RatioImageView); weight = array.getFloat(R.styleable.RatioImageView_riv_ratio, DEF_RATIO); array.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = (int) (width / weight); super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); } }
/** * This class is generated by jOOQ */ package schema.tables; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Identity; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import schema.BitnamiEdx; import schema.Keys; import schema.tables.records.CourseStructuresCoursestructureRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class CourseStructuresCoursestructure extends TableImpl<CourseStructuresCoursestructureRecord> { private static final long serialVersionUID = -943359014; /** * The reference instance of <code>bitnami_edx.course_structures_coursestructure</code> */ public static final CourseStructuresCoursestructure COURSE_STRUCTURES_COURSESTRUCTURE = new CourseStructuresCoursestructure(); /** * The class holding records for this type */ @Override public Class<CourseStructuresCoursestructureRecord> getRecordType() { return CourseStructuresCoursestructureRecord.class; } /** * The column <code>bitnami_edx.course_structures_coursestructure.id</code>. */ public final TableField<CourseStructuresCoursestructureRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bitnami_edx.course_structures_coursestructure.created</code>. */ public final TableField<CourseStructuresCoursestructureRecord, Timestamp> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>bitnami_edx.course_structures_coursestructure.modified</code>. */ public final TableField<CourseStructuresCoursestructureRecord, Timestamp> MODIFIED = createField("modified", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>bitnami_edx.course_structures_coursestructure.course_id</code>. */ public final TableField<CourseStructuresCoursestructureRecord, String> COURSE_ID = createField("course_id", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.course_structures_coursestructure.structure_json</code>. */ public final TableField<CourseStructuresCoursestructureRecord, String> STRUCTURE_JSON = createField("structure_json", org.jooq.impl.SQLDataType.CLOB, this, ""); /** * The column <code>bitnami_edx.course_structures_coursestructure.discussion_id_map_json</code>. */ public final TableField<CourseStructuresCoursestructureRecord, String> DISCUSSION_ID_MAP_JSON = createField("discussion_id_map_json", org.jooq.impl.SQLDataType.CLOB, this, ""); /** * Create a <code>bitnami_edx.course_structures_coursestructure</code> table reference */ public CourseStructuresCoursestructure() { this("course_structures_coursestructure", null); } /** * Create an aliased <code>bitnami_edx.course_structures_coursestructure</code> table reference */ public CourseStructuresCoursestructure(String alias) { this(alias, COURSE_STRUCTURES_COURSESTRUCTURE); } private CourseStructuresCoursestructure(String alias, Table<CourseStructuresCoursestructureRecord> aliased) { this(alias, aliased, null); } private CourseStructuresCoursestructure(String alias, Table<CourseStructuresCoursestructureRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return BitnamiEdx.BITNAMI_EDX; } /** * {@inheritDoc} */ @Override public Identity<CourseStructuresCoursestructureRecord, Integer> getIdentity() { return Keys.IDENTITY_COURSE_STRUCTURES_COURSESTRUCTURE; } /** * {@inheritDoc} */ @Override public UniqueKey<CourseStructuresCoursestructureRecord> getPrimaryKey() { return Keys.KEY_COURSE_STRUCTURES_COURSESTRUCTURE_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<CourseStructuresCoursestructureRecord>> getKeys() { return Arrays.<UniqueKey<CourseStructuresCoursestructureRecord>>asList(Keys.KEY_COURSE_STRUCTURES_COURSESTRUCTURE_PRIMARY, Keys.KEY_COURSE_STRUCTURES_COURSESTRUCTURE_COURSE_ID); } /** * {@inheritDoc} */ @Override public CourseStructuresCoursestructure as(String alias) { return new CourseStructuresCoursestructure(alias, this); } /** * Rename this table */ public CourseStructuresCoursestructure rename(String name) { return new CourseStructuresCoursestructure(name, null); } }
package br.com.fitNet.util; public class Mensagens { private String mensagemSucesso; private String mensagemErro; public Mensagens(){ this.mensagemSucesso = ""; this.mensagemErro = ""; } public String getMensagemSucesso() { return mensagemSucesso; } public void setMensagemSucesso(String mensagem) { this.mensagemSucesso = mensagem; } public String getMensagemErro() { return mensagemErro; } public void setMensagemErro(String mensagem) { this.mensagemErro = mensagem; } }
package com.apon.taalmaatjes.backend.api.returns; import java.sql.Date; import java.util.List; public class ReportReturn { private Date dateStart; private Date dateEnd; private List<RangeReportReturn> volunteers; private List<RangeReportReturn> students; public ReportReturn(Date dateStart, Date dateEnd) { this.dateStart = dateStart; this.dateEnd = dateEnd; } public Date getDateStart() { return dateStart; } public void setDateStart(Date dateStart) { this.dateStart = dateStart; } public Date getDateEnd() { return dateEnd; } public void setDateEnd(Date dateEnd) { this.dateEnd = dateEnd; } public List<RangeReportReturn> getVolunteers() { return volunteers; } public void setVolunteers(List<RangeReportReturn> volunteers) { this.volunteers = volunteers; } public List<RangeReportReturn> getStudents() { return students; } public void setStudents(List<RangeReportReturn> students) { this.students = students; } }
// // Decompiled by Procyon v0.5.36 // package com.davivienda.multifuncional.cuadrecifrasmulti.session; import java.util.Collection; import java.util.Date; import com.davivienda.sara.entitys.Tipomovimientocuadremulti; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import com.davivienda.sara.entitys.Movimientocuadremulti; import javax.annotation.PostConstruct; import com.davivienda.multifuncional.tablas.tipomovimientocuadremulti.servicio.TipoMovimientoCuadreMultiServicio; import com.davivienda.multifuncional.cuadrecifrasmulti.servicio.CuadreCifrasMultiSessionServicio; import javax.persistence.PersistenceContext; import javax.persistence.EntityManager; import javax.ejb.TransactionManagementType; import javax.ejb.TransactionManagement; import javax.ejb.Local; import javax.ejb.Stateless; @Stateless @Local({ CuadreCifrasMultiSessionLocal.class }) @TransactionManagement(TransactionManagementType.CONTAINER) public class CuadreCifrasMultiSessionBean implements CuadreCifrasMultiSessionLocal { @PersistenceContext private EntityManager em; private CuadreCifrasMultiSessionServicio servicio; private TipoMovimientoCuadreMultiServicio servicioTipoMov; @PostConstruct public void postConstructor() { this.servicio = new CuadreCifrasMultiSessionServicio(this.em); this.servicioTipoMov = new TipoMovimientoCuadreMultiServicio(this.em); } @Override public Movimientocuadremulti grabarMovimientoCuadre(final Movimientocuadremulti mc, final boolean actualizar) throws EntityServicioExcepcion { final Movimientocuadremulti mCuadremulti = this.servicio.grabarMovimientoCuadre(mc, actualizar); return mCuadremulti; } @Override public Tipomovimientocuadremulti buscarTipoMovimientoCuadre(final Integer codigoTipoMovimientoCuadre) throws EntityServicioExcepcion { return this.servicioTipoMov.buscar(codigoTipoMovimientoCuadre); } @Override public Collection<Movimientocuadremulti> getUsuarioFecha(final String usuario, final Date fechaInicial) throws EntityServicioExcepcion { return this.servicio.getUsuarioFecha(usuario, fechaInicial); } }
package com.weiziplus.springboot.common.utils.token; import com.weiziplus.springboot.common.utils.redis.RedisUtil; import lombok.extern.slf4j.Slf4j; /** * 用户token配置 * * @author wanglongwei * @data 2019/5/8 9:06 */ @Slf4j public class TokenUtil { /** * 根据用户id获取用户Redis的key值 * * @param audience---用户角色 * @param userId---用户ID * @return */ public static String getAudienceRedisKey(String audience, Long userId) { return audience + userId; } /** * 根据用户id创建token * * @param audience---用户角色 * @param userId---用户ID * @param expireTime---过期时间 * @return */ protected static String createToken(String audience, Long userId, Long expireTime) { String token = null; try { token = JwtTokenUtil.createToken(userId, audience); } catch (Exception e) { log.error(audience.concat("用户token创建失败,userId:") + userId + e); return null; } RedisUtil.set(getAudienceRedisKey(audience, userId), token, expireTime); return token; } }
package cn.Lamda; /** * 实现方法的引用接口 * @param <P> 引用方法的参数类型 * @param <R> 引用方法的返回类型 */ interface IMessage5<P,R>{ public R zhuanhuan(P p); } public class TextDemo5 { public static void main(String[] args) { //即:将String.valueOf()方法变为了IMessage接口里的zhuanhuan()方法 IMessage5<Integer, Integer> msg = String :: valueof; String str = msg.zhuanhuan(1000); System.out.println(str.replaceAll("0", "9"));//将0换成9 //输出结果1999 } }
package uk.nhs.hee.web.component; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.hippoecm.hst.core.component.HstRequest; import org.hippoecm.hst.core.component.HstResponse; import org.onehippo.cms7.crisp.api.resource.ResourceException; import org.onehippo.cms7.essentials.components.CommonComponent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.oauth2.client.http.AccessTokenRequiredException; import uk.nhs.hee.web.beans.opengraph.list.FileItem; import uk.nhs.hee.web.ms.graph.service.GraphServiceFactory; public class HEEWebSharepointFilesComponent extends CommonComponent { private static final Logger LOGGER = LoggerFactory.getLogger(HEEWebSharepointFilesComponent.class.getName()); @Override public void doBeforeRender(HstRequest request, HstResponse response) { super.doBeforeRender(request, response); setComponentId(request, response); try { GraphServiceFactory graphServiceFactory = new GraphServiceFactory(request); // Member Of Map<String, String> groups = graphServiceFactory.getGroupService().getAllGroups(); // Removes main/domain group 'manifestouk' (for brevity) groups = groups .entrySet() .stream() .filter(group -> !"manifestouk".equals(group.getValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); LOGGER.info("groups = " + groups); // Get root/group sites Map<String, String> sites = graphServiceFactory.getSiteService() .getSitesByGroupIncludingRootSite(groups.keySet().stream().collect(Collectors.toList())); // Get sites with files Map<String, List<FileItem>> sharepointSiteFiles = graphServiceFactory.getListItemService().getSharedFileItemsBySites(sites); LOGGER.debug("Sharepoint Site Files for the user '{}' => {}", request.getUserPrincipal().getName(), sites); request.setModel("sharepointSiteFiles", sharepointSiteFiles); } catch (AccessTokenRequiredException e) { LOGGER.error("Looks like 'accessToken' is not availabe in the session. " + "Probably user didn't login yet. " + "Wondering how the user has reached this point past spring security guard", e); } catch (ResourceException e) { LOGGER.error(e.getMessage(), e); } } }
//Nicole Leon 3/20/19 package textExcel; public class ValueCell extends RealCell { public ValueCell(String input) { super(input); } //same fullCellText and abbreviatedCelltext //plus same DoubleValue and getText public String getText() { return valueText.substring(0,valueText.length()-10); } /* public double getDoubleValue() {//same as RealCell return Double.parseDouble(valueText); } */ /*public double getValue() { return value; }*/ public String abbreviatedCellText() { // text for spreadsheet cell display, must be exactly length 10 String newString = toString(getDoubleValue()) + " "; //so that takes in the double and gives us dat nice .0 return newString.substring(0,10); } public String fullCellText() { // text for individual cell inspection, not truncated or padded return valueText; } }
package JavaBasics; /** * Created by RXC8414 on 5/3/2017. */ public class WhileLoop { public static void main(String[] args) { //Declare and initialize my counter int i = 0; // We are looping from 0-10 and printing out the value of counter while(i <= 10){ System.out.println("Counter = "+i); i++; //Increasing counter } } }
package com.perfect.web.service; import com.perfect.entity.User; import com.perfect.web.form.UserForm; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.IService; /** * <p> * 用户表 服务类 * </p> * * @author Ben. * @since 2017-03-15 */ public interface UserService extends IService<User> { Page<User> pageList(Page<User> page, UserForm form); }
package com.trinary.security.token; import java.util.HashMap; import java.util.Map; import com.trinary.security.entities.User; import org.springframework.stereotype.Component; @Component public class MemoryResidentTokenManager extends TokenManager { protected static Map<String, Token> tokenMap = new HashMap<String, Token>(); protected static Map<String, Token> userMap = new HashMap<String, Token>(); public MemoryResidentTokenManager(TokenFactory tokenFactory) { super(tokenFactory); } @Override protected Token getTokenByString(String tokenString) { synchronized(tokenMap) { return tokenMap.get(tokenString); } } @Override protected Token getTokenByPrincipal(User principal) { synchronized(userMap) { return userMap.get(principal.getUsername()); } } @Override protected void storeToken(Token token) { synchronized(tokenMap) { tokenMap.put(token.getToken(), token); } synchronized(userMap) { userMap.put(token.getPrincipal().getUsername(), token); } } @Override protected Token releaseToken(Token token) { synchronized(tokenMap) { tokenMap.remove(token.getToken()); } synchronized(userMap) { userMap.remove(token.getPrincipal().getUsername()); } return token; } }
package Daos; import java.io.*; import beans.User; public class UserSerializer implements UserDao{ public static final UserSerializer us = new UserSerializer(); @Override public void logNewUser(User u) { if (u ==null) { System.out.println("Something went wrong, no user was passed"); return; } File f = new File("src/main/resources/users/" + u.getUsername() +".txt"); if (f.exists() && !f.canWrite()) { System.out.println("This username is already taken"); return; } try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } try (ObjectOutputStream saver = new ObjectOutputStream( new FileOutputStream("src/main/resources/users/" + u.getUsername()+".txt"))) { System.out.println(u.getClass()); saver.writeObject(u); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } { } } @Override public void deleteUser(User u) { File f = new File("src/main/resources/users/" + u.getUsername() +".txt"); if (f.exists()) { f.delete(); } else { System.out.println("couldn't delete."); } } @Override public void updateUser(User u) { File f = new File("src/main/resources/users/" + u.getUsername() +".txt"); if (f.exists()) { f.setExecutable(true); f.setWritable(true); this.logNewUser(u); f.setWritable(false); } else { System.out.println("couldn't delete"); } } @Override public User findUser(String username, String password) { if (username == null && password == null) { System.out.println("Username or Password is incorrect."); return null; } try (ObjectInputStream reader = new ObjectInputStream( new FileInputStream("src/main/resources/users/" + username + ".txt"))) { User u = (User) reader.readObject(); if (u.getPassword().equals(password)) { return u; } System.out.println("Password is incorrect"); return null; } catch (FileNotFoundException e) { System.out.println("This username doesn't match the files."); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); } return null; } @Override public User findUser(String username, User AccessingAccount) { if (username == null) { System.out.println("Username is incorrect"); return null; } else if (!AccessingAccount.isAdmin()){ System.out.println("You are not an Administrator, access denied."); return null; } try (ObjectInputStream reader = new ObjectInputStream( new FileInputStream("src/main/resources/users/" + username + ".txt"))) { User u = (User) reader.readObject(); return u; } catch (FileNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); } return null; } String getUserList() { StringBuilder = new File directory = new File("src/main/respurces/users"); File[] dirContents = directory.listFiles(); for (File f: dirContents) { } } }
package jsonparser.tests; import java.util.Arrays; public class Person { public String name; public int age; public String hobbies[]; public int negage; public Person spouce; public Person() { } @Override public String toString() { return "Name : " + name + ", age : " + age + ", hobbies : " + Arrays.toString(hobbies) + ", negage: " + negage + ((spouce == null) ? "": ", spouce: " + spouce); } }
package me.chillgu.jwt; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Jwt02Application { public static void main(String[] args) { SpringApplication.run(Jwt02Application.class, args); } }
package com.woniu.controller; import com.woniu.pojo.ResultVO; import com.woniu.pojo.Patient; import com.woniu.service.IPatientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.util.List; /** * @author llf * @date 2020/3/24 17:10 */ @Controller public class TestController { @Autowired private IPatientService patientService; // @RequestMapping("/index") // public String springbootTest(){ // return "index" ; // } // // @RequestMapping("/login") // public String show(){ return "login"; } @ResponseBody @RequestMapping("/loginIn") public ResultVO login(@RequestBody Patient patient, HttpSession session){ ResultVO resultVO =null; Patient loginUser = patientService.loginTest(patient); if (loginUser != null) { session.setAttribute("loginUser", loginUser); resultVO = new ResultVO(200,"登陆成功"); }else { resultVO = new ResultVO(500,"登陆失败"); } return resultVO; } @ResponseBody @PostMapping("/register") public ResultVO register(@RequestBody Patient patient){ ResultVO resultVO = null; try { patient.setPatientStatus(1); patientService.register(patient); resultVO = new ResultVO(200, "注册成功"); } catch (Exception e) { resultVO = new ResultVO(500, "注册失败"); }finally { return resultVO; } } @GetMapping("/patientList") @ResponseBody public ResultVO findAll() { List<Patient> list = patientService.findAll(); ResultVO resultVO = null; if(list != null && list.size() > 0) { resultVO = new ResultVO(200,"查询成功", list); } else { resultVO = new ResultVO(500, "查询失败"); } return resultVO; } }
package fr.nirahtech.garage.repositories; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import fr.nirahtech.garage.entities.Vehicule; public interface VehiculesRepository extends JpaRepository<Vehicule, Integer> { Optional<Vehicule> findById(Long id); }
package com.javatutorial.teennumberchecker; public class Main { public static void main(String[] args) { System.out.println(TeenNumberChecker.hasTeen(9,99,19)); System.out.println(TeenNumberChecker.hasTeen(23,15,42)); System.out.println(TeenNumberChecker.hasTeen(22,99,24)); System.out.println(TeenNumberChecker.isTeen(19)); System.out.println(TeenNumberChecker.isTeen(15)); System.out.println(TeenNumberChecker.isTeen(22)); //,99,24)); } }
package com.sezioo.permission.param; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @Getter @Setter public class TestVo { @NotNull private Integer id; @NotBlank private String msg; }
package com.leetcode.oj.hash; import java.util.ArrayList; import java.util.List; public class SudokuSolver { public void solveSudoku(char[][] board) { List<Integer> empty = new ArrayList<>(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == '.') empty.add(i * 9 + j); // save empty cell coordinates } } dfs(empty, board, 0); } private boolean dfs(List<Integer> empty, char[][] board, int current) { // all empty cells are filled. if (current == empty.size()) return true; int row = empty.get(current) / 9; int col = empty.get(current) % 9; for (char i = '1'; i <= '9'; i++) { // set [row, col] to i and validate current board, then do it recursively. board[row][col] = i; if (isValid(board, row, col) && dfs(empty, board, current + 1)) return true; else board[row][col] = '.'; // no good, set it back to empty and try another value. } return false; } // valid board after adding value in [i, j] private boolean isValid(char[][] board, int i, int j) { char v = board[i][j]; for (int t = 0; t < 9; t++) { int row = i / 3 * 3 + t / 3; int col = j / 3 * 3 + t % 3; if ((t != i && board[t][j] == v) || (t != j && board[i][t] == v) || (row != i && col != j && board[row][col] == v)) return false; } return true; } }
package com.example.studyEnum; /** * @PackageName: com.example.studyEnum * @ClassName: EnumTest * @Description: TODO * @author: qiuweijie * @date: 2019/12/26 10:53 */ public class EnumTest { public void judge(SeasonEnum s){ switch (s){ case SPRING: System.out.println("春"); break; case SUMMER: System.out.println("夏"); break; case FALL: System.out.println("秋"); break; case WINTER: System.out.println("冬"); break; } } public static void main(String[] args) { for(SeasonEnum seasonEnum : SeasonEnum.values()){ System.out.println(seasonEnum); } new EnumTest().judge(SeasonEnum.FALL); System.out.println(SeasonEnum.FALL.getName()); } }
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}.business.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.persistence.Temporal; import javax.persistence.TemporalType; @MappedSuperclass public class BaseModel { @Temporal(TemporalType.TIMESTAMP) @Column(name = "last_update", updatable = false, columnDefinition = "TIMESTAMP") private Date lastUpdate; }
package edu.ncsu.csc563.velocity.actors.components; public class ForcedMovement extends Component { private Transform mTransform; public static float mSpeed = 0.2f; public ForcedMovement(Transform transform) { this.mTransform = transform; } @Override public void update() { this.mTransform.translate(0, 0, -ForcedMovement.mSpeed); } }
package ru.job4j.max; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class MaxTest { @Test public void whenFirstLessSecond() { Max max = new Max(); int result = max.max(1, 4); assertThat(result, is(4)); } @Test public void whenSecondLessFirst() { Max max = new Max(); int result = max.max(3, 2); assertThat(result, is(3)); } @Test public void whenSecondAndThirdLessFirst() { Max max = new Max(); int temp = max.max(max.max(4, 3), 2); assertThat(temp, is(4)); } @Test public void whenFirstAndThirdLessSecond() { Max max = new Max(); int temp = max.max(max.max(2, 6), 4); assertThat(temp, is(6)); } @Test public void whenFirstAndSecondLessThird() { Max max = new Max(); int temp = max.max(max.max(1, 4), 6); assertThat(temp, is(6)); } }
package mobile.komputer.unsyiah.ac.id.mahasiswa; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import mobile.komputer.unsyiah.ac.id.mahasiswa.model.AturMahasiswaDB; public class TambahActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tambah); } /** * Tangani jika tombol btnTambah di-click */ public void clickBtnTambah(View view) { // Ambil data yang diisi TextView txtNIM = (TextView) findViewById(R.id.txtNIM); String nim = txtNIM.getText().toString(); TextView txtNama = (TextView) findViewById(R.id.txtNama); String nama = txtNama.getText().toString(); // Tambah data ke database SQLiteOpenHelper aturMahasiswaDB = new AturMahasiswaDB(this); SQLiteDatabase db = aturMahasiswaDB.getWritableDatabase(); // Sebutkan nilai baru yang akan ditambahkan ContentValues mahasiswaBaru = new ContentValues(); mahasiswaBaru.put(AturMahasiswaDB.MAHASISWA_NIM, nim); mahasiswaBaru.put(AturMahasiswaDB.MAHASISWA_NAMA, nama); // Tambahkan ke database db.insert(AturMahasiswaDB.TABEL_MAHASISWA, null, mahasiswaBaru); // Tutup koneksi ke database db.close(); // Kirim kembali ke Activity MainActivity Intent pesan = new Intent(getApplicationContext(), MainActivity.class); startActivity(pesan); finish(); } }
package org.sinhro.ForeignLanguageCourses.repository; import org.sinhro.ForeignLanguageCourses.domain.Language; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface LanguageRepository extends JpaRepository<Language, Integer> { }
package com.esum.framework.core.queue.listener; import javax.jms.JMSException; import com.esum.framework.core.queue.JmsMessageHandler; public class TopicChannelListener extends AbstractJmsChannelListener { private String messageSelector = null; public TopicChannelListener(JmsMessageHandler handler) { super(handler); } public String getMessageSelector() { return messageSelector; } public void setMessageSelector(String messageSelector) { this.messageSelector = messageSelector; } @Override protected void initProperties() throws JMSException { this.connection = handler.createTopicConnection(false); this.session = handler.createTopicSession(connection, isTransacted(), getAcknowledgeMode()); this.consumer = handler.createConsumer(session, getMessageSelector()); } }
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { // We run this test for AOT to verify that there is a HDeoptimize with dex pc 0. /// CHECK-START: int Main.$noinline$getInt(byte[], int) BCE (after) /// CHECK: Deoptimize dex_pc:0 public static int $noinline$getInt(byte[] array, int offset) { // The aget for `array[offset]` is at dex pc 0, so the Deoptimize // from dynamic BCE shall also be at dex pc 0. return ((array[offset ] & 0xFF) << 0) + ((array[offset + 1] & 0xFF) << 8) + ((array[offset + 2] & 0xFF) << 16) + ((array[offset + 3] & 0xFF) << 24); } public static void main(String[] args) { System.loadLibrary(args[0]); if (hasJit()) { byte[] array = { 0, 1, 2, 3 }; ensureJitCompiled(Main.class, "$noinline$getInt"); if (!hasJitCompiledEntrypoint(Main.class, "$noinline$getInt")) { throw new Error("Unexpected entrypoint!"); } if ($noinline$getInt(array, 0) != 0x03020100) { throw new Error(); } try { // The HDeoptimize at dex pc 0 was previously handled poorly as the dex pc 0 // was used to detect whether we entered the method. This meant that the // instrumentation would have reported MethodEnteredEvent and we would have // told JIT that the method was entered. With JIT-on-first-use we would also // immediatelly recompile the method and run the compiled code leading to // a an infinite deoptimization recursion, yielding StackOverflowError. $noinline$getInt(array, 1); } catch (ArrayIndexOutOfBoundsException ignored) {} } System.out.println("passed"); } public static native boolean hasJit(); public native static boolean hasJitCompiledEntrypoint(Class<?> cls, String methodName); public native static void ensureJitCompiled(Class<?> cls, String methodName); }
package com.javasampleapproach.mysql.exam.repo; import org.springframework.data.repository.CrudRepository; import com.javasampleapproach.mysql.exam.model.Teacherwise; import com.javasampleapproach.mysql.model.Admission; import com.javasampleapproach.mysql.model.Unit; public interface Teacherwiserepository extends CrudRepository<Teacherwise, Long > { //List<Admission> findbyAdmission(); // List<Admission> findbyAdmission(String Admission); // Object findbyAdm(); }
package com.gustavoballeste.authlogin.data.dao; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; import com.gustavoballeste.authlogin.data.model.Token; @Dao public interface TokenDao { @Query("SELECT * FROM token") Token get(); @Insert void insert(Token token); @Query("DELETE FROM token") void delete(); @Update void update(Token token); }
package com.proyectogrado.alternativahorario.entidades; import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; /** * * @author Steven */ @Entity @Table(name = "usuarios") @SequenceGenerator(name="SecuenciaUsuarios", sequenceName = "SEC_IDUSUARIOS") @NamedQueries({ @NamedQuery(name = "Usuario.findByNombre", query = "SELECT u FROM Usuario u WHERE u.usuario = :usuario")}) public class Usuario implements Serializable { private static final long serialVersionUID = 1L; @Getter @Setter @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SecuenciaUsuarios") @Basic(optional = false) @Column(name = "id") private BigDecimal id; @Getter @Setter @Column(name = "usuario") private String usuario; @Getter @Setter @Column(name = "clave") private String clave; @Getter @Setter @Column(name = "tipo") private String tipo; @Getter @Setter @Column(name = "estado") private String estado; public Usuario() { } public Usuario(BigDecimal id) { this.id = id; } }
package com.example.springboot.urlshortener.service; import java.util.Optional; import java.util.Random; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.springboot.urlshortener.dao.URLRepository; import com.example.springboot.urlshortener.entity.URLPair; @Service public class URLShortenerServiceImpl implements URLShortenerService { private static final char[] charTable = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; private static final int BASE = charTable.length; private static final int SHORTENERSIZE = 6; private Logger logger = Logger.getLogger(getClass().getName()); private URLRepository customerRepository; @Autowired public URLShortenerServiceImpl(URLRepository theCustomerRepository) { customerRepository = theCustomerRepository; } @Override public URLPair findUrlByShortUrl(String shortUrl) { Optional<URLPair> result = customerRepository.findByShortUrl(shortUrl); URLPair theUrl = null; if (result.isPresent()) { theUrl = result.get(); } else { //The short Url was not found. theUrl = null; } return theUrl; } @Override public String searchOrGenerateShortUrl(String longUrl) { Optional<URLPair> result = customerRepository.findByLongUrl(longUrl); URLPair theUrl = null; String shortUrl = null; if (result.isPresent()) { //The long Url was found in the database. theUrl = result.get(); shortUrl = theUrl.getShortUrl(); logger.info("[Log info] the original long URL already exists in the database: " + longUrl); } else { //The long Url was not found in the database. shortUrl = generateShortUrl(longUrl); theUrl = new URLPair(longUrl, shortUrl); customerRepository.save(theUrl); logger.info("[Log info] the original long URL does not exist in the database. Generate the new short URL: " + shortUrl); } return shortUrl; } @Override public String generateShortUrl(String longUrl) { Optional<URLPair> result = Optional.empty(); String shortUrl = null; Random rand = new Random(); StringBuilder temp = new StringBuilder(); do { temp.setLength(0); for (int i = 0; i < SHORTENERSIZE; i++) { int index = rand.nextInt(BASE); temp.append(charTable[index]); } shortUrl = new String(temp); result = customerRepository.findByShortUrl(shortUrl); } while (result.isPresent()); return shortUrl; } }
package com.needii.dashboard.controller; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.needii.dashboard.components.CompomentList; import com.needii.dashboard.components.Messages; import com.needii.dashboard.helper.ResponseStatusEnum; import com.needii.dashboard.model.BaseResponse; import com.needii.dashboard.model.Category; import com.needii.dashboard.model.CategoryParse; import com.needii.dashboard.model.City; import com.needii.dashboard.model.FileBucket; import com.needii.dashboard.model.Product; import com.needii.dashboard.model.ProductCityMap; import com.needii.dashboard.model.ProductData; import com.needii.dashboard.model.ProductStatus; import com.needii.dashboard.model.ProductTagMap; import com.needii.dashboard.model.SkuData; import com.needii.dashboard.model.Skus; import com.needii.dashboard.model.Supplier; import com.needii.dashboard.model.Tag; import com.needii.dashboard.model.form.ProductDataForm; import com.needii.dashboard.model.form.ProductForm; import com.needii.dashboard.model.form.SearchForm; import com.needii.dashboard.model.form.SkuForm; import com.needii.dashboard.service.CategoryService; import com.needii.dashboard.service.CityService; import com.needii.dashboard.service.LanguageService; import com.needii.dashboard.service.ProductDataService; import com.needii.dashboard.service.ProductService; import com.needii.dashboard.service.ProductStatusService; import com.needii.dashboard.service.SkuDataService; import com.needii.dashboard.service.SkuService; import com.needii.dashboard.service.SupplierService; import com.needii.dashboard.service.TagService; import com.needii.dashboard.service.cache.ConfigurationCache; import com.needii.dashboard.utils.ChartData; import com.needii.dashboard.utils.ConfigurationKey; import com.needii.dashboard.utils.Constants; import com.needii.dashboard.utils.KeyValue; import com.needii.dashboard.utils.Option; import com.needii.dashboard.utils.Pagination; import com.needii.dashboard.utils.Utils; import com.needii.dashboard.utils.UtilsMedia; import com.needii.dashboard.utils.UtilsSku; import com.needii.dashboard.validator.FileValidator; import com.needii.dashboard.validator.ProductFormValidator; import com.needii.dashboard.validator.SkuFormValidator; import com.needii.dashboard.view.ProductExportExcel; @Controller @RequestMapping(value = "/products" ) @PostAuthorize("hasAuthority('SUPERADMIN') or hasAuthority('ADMIN')") public class ProductController extends BaseController { @Autowired ServletContext context; @Autowired private ProductService productService; @Autowired private ProductDataService productDataService; @Autowired private CategoryService categoryService; @Autowired private SkuService skuService; @Autowired private CityService cityService; @Autowired private TagService tagService; @Autowired private SupplierService supplierService; @Autowired private SkuDataService skuDataService; @Autowired private LanguageService languageService; @Autowired CompomentList compomentList; @Autowired private FileValidator fileValidator; @Autowired private ProductFormValidator productFormValidator; @Autowired private SkuFormValidator skuFormValidator; @Autowired ConfigurationCache configurationCache; @Autowired Messages messages; @Autowired ProductStatusService productStatusService; @PostConstruct public void initialize() { super.initialize(); } @ModelAttribute("statusList") public Map<Integer, String> status() { return compomentList.status(); } @ModelAttribute("productList") public Map<Integer, String> productList() { Map<Integer, String> pStatuses = new HashMap<>(); List<ProductStatus> plStatuses = productStatusService.findAll(); for(ProductStatus pStatus : plStatuses) { if(pStatus != null) { pStatuses.put(pStatus.getId(), pStatus.getName()); } } return pStatuses; } @ModelAttribute("categoriesList") public Map<Long, String> categoriesList() { List<Category> categories = categoryService.findAll(0); Map<Long, String> categoriesList = new LinkedHashMap<>(); categoriesList.put(null, "Chọn danh mục"); for (Category category : categories) { categoriesList.put(category.getId(), category.getData().getName()); } return categoriesList; } @ModelAttribute("supplierList") public Map<Long, String> supplierList() { List<Supplier> suppliers = supplierService.findAll(); Map<Long, String> supplierList = new LinkedHashMap<>(); supplierList.put((long) 0, "Chọn nhà cung cấp"); for (Supplier supplier : suppliers) { supplierList.put(supplier.getId(), supplier.getFullName()); } return supplierList; } @RequestMapping(value = {""}, method = RequestMethod.GET) public String index(Model model, @ModelAttribute("searchForm") SearchForm searchForm, @RequestParam(name = "page", required = false) Integer page) { if (page == null) page = 1; Pagination pagination = new Pagination(page, this.numberPage); Option option = new Option(); option.setPagination(pagination); List<Category> categories = categoryService.findAll(); Map<String, Object> queryString = new HashMap<>(); queryString.put("id", searchForm.getId()); queryString.put("name", searchForm.getName()); queryString.put("status", searchForm.getStatus()); queryString.put("supplierId", searchForm.getSupplierId()); if(searchForm.getCategoryId() != null) { List<Long> categoryIds = categories .stream() .filter(x -> x.getCategoryParentListId().contains(String.valueOf(searchForm.getCategoryId()))) .map(Category::getId) .collect(Collectors.toList()); categoryIds.add(searchForm.getCategoryId()); queryString.put("categoryId", StringUtils.join(categoryIds, ",")); } option.setQueryString(queryString); long totalRecord = productService.count(option).intValue(); List<Product> items = productService.findAll(option); model.addAttribute("totalRecord", totalRecord); model.addAttribute("limit", this.numberPage); model.addAttribute("currentPage", page); model.addAttribute("searchForm", searchForm); model.addAttribute("items", items); model.addAttribute("languages", languageService.findAll()); List<KeyValue> chartData = prepareDataForWeek(); model.addAttribute("chartData", chartData); return "products"; } @ResponseStatus(value=HttpStatus.OK) @RequestMapping(value = { "/get-all-product-autocomplete/" }, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<BaseResponse> getProductsForAutocompleted(@RequestParam(name="name", required=false) String name){ BaseResponse response = new BaseResponse(); response.setStatus(ResponseStatusEnum.SUCCESS); response.setMessage(ResponseStatusEnum.SUCCESS); response.setData(null); try { Option option = new Option(); List<Object> objects = new ArrayList<>(); Map<String, Object> queryString = new HashMap<>(); queryString.put("name", name); option.setQueryString(queryString); List<Product> products = productService.findAll(option); for(Product product : products) { Object data = new Object() { @SuppressWarnings("unused") public final long id = product.getId(); @SuppressWarnings("unused") public final String text = product.getProductData().stream().findFirst().get().getName(); }; objects.add(data); }; response.setResults(objects); } catch(Exception ex) { response.setStatus(ResponseStatusEnum.FAIL); response.setMessageError(ex.getMessage()); ex.printStackTrace(); } return new ResponseEntity<>(response, HttpStatus.OK); } @ModelAttribute("categoriesListAll") public Map<Long, String> getAllCate(){ List<Category> categories = categoryService.findAll(); Map<Long, String> categoriesList = new LinkedHashMap<>(); List<CategoryParse> categoryParses = Utils.parseCategoriesArray(categories, 0); categoriesList.put(null, "Chọn danh mục"); for (CategoryParse categoryParse : categoryParses) { categoriesList.put(categoryParse.getId(), StringUtils.repeat("===||", categoryParse.getLevel()) + categoryParse.getName()); } return categoriesList; } @RequestMapping(value = {"/{id}/create"}, method = RequestMethod.GET) public String create(Model model) { model.addAttribute("productForm", new ProductForm()); return "productCreate"; } @RequestMapping(value = {"/{id}/create"}, method = RequestMethod.POST) public String store(FileBucket thumbnail, @RequestParam(name = "images", required = false) MultipartFile[] images, @ModelAttribute("productForm") ProductForm productForm, BindingResult result, Model model, final RedirectAttributes redirectAttributes) { thumbnail.setFiled("image"); fileValidator.validate(thumbnail, result); productFormValidator.validate(productForm, result); if (result.hasErrors()) { if(productForm.getSupplierId() != null && !productForm.getSupplierId().isEmpty()){ Supplier supplier = supplierService.findOne(Integer.valueOf(productForm.getSupplierId())); model.addAttribute("supplier", supplier); } if (productForm.getCategoryId() != null && !productForm.getCategoryId().isEmpty()) { Category category = categoryService.findOne(Integer.valueOf(productForm.getCategoryId())); model.addAttribute("category", category); if(category != null) { List<String> categories = category.getCategoryParentListId(); if(categories != null && categories.size() > 0) { productForm.setCategoryId(categories.get(0)); } model.addAttribute("categories", categories); } } if (productForm.getCityId() != null && !productForm.getCityId().isEmpty()) { List<City> productCities = cityService.findByIdIn(Utils.stringToIntegerList(productForm.getCityId())); model.addAttribute("productCities", productCities); } if (productForm.getTag() != null && !productForm.getTag().isEmpty()) { List<Tag> tags = tagService.findByIdIn(Utils.stringToIntegerList(productForm.getTag())); model.addAttribute("tags", tags); } model.addAttribute("productForm", productForm); return "productCreate"; } Category category = categoryService.findOne(Integer.valueOf(productForm.getCategoryId())); Supplier supplier = supplierService.findOne(Integer.valueOf(productForm.getSupplierId())); if (category == null || supplier == null) { return "404"; } try { boolean productAutoApprove = configurationCache.get(ConfigurationKey.PRODUCT_AUTO_APPROVED).equals("1") ? true :productForm.getApprove(); Product product = new Product(); product.setCategory(category); product.setQuantity(Integer.valueOf(productForm.getQuantity())); product.setIsNew(productForm.getIsNew()); product.setIsTodayDeal(productForm.getIsTodayDeal()); product.setIsCommingDeal(productForm.getIsCommingDeal()); product.setIsBestSeller(productForm.getIsBestSeller()); product.setIsHot(productForm.getIsHot()); product.setApprove(productAutoApprove); product.setStatus(productAutoApprove?1:productForm.getStatus()); product.setIsShowHome(product.getIsShowHome()); product.setIsPromotion(productForm.getIsPromotion()); product.setAvailableForSale(productForm.getAvailableForSale()); product.setPrice(Float.valueOf(productForm.getPrice())); product.setLastPrice(Float.valueOf(productForm.getPrice())); if(productForm.getLastPrice() != null && !productForm.getLastPrice().isEmpty()) { product.setLastPrice(Float.valueOf(productForm.getLastPrice())); } product.setSupplier(supplier); if(!productForm.getCashbackAmount().isEmpty()) { product.setCashbackAmount(Float.valueOf(productForm.getCashbackAmount())); } product.setDiscountPercent(0); if(!productForm.getProductDataForm().getIsDeliveryGlobalFree()) { product.setHeight(Float.valueOf(productForm.getHeight())); product.setWeight(Float.valueOf(productForm.getWeight())); product.setDepth(Float.valueOf(productForm.getDepth())); product.setWidth(Float.valueOf(productForm.getWidth())); } if (!thumbnail.isEmpty()) { String webappRoot = context.getRealPath(Constants.SAVE_PRODUCT_THUMBNAIL_PATH); Map<String, String> resultUpload = UtilsMedia.uploadImage(thumbnail.getFile(), webappRoot); product.setImage(Constants.SAVE_PRODUCT_THUMBNAIL_PATH + resultUpload.get("fileName")); } List<ProductCityMap> productCities = new ArrayList<>(); if(productForm.getCityId() != null) { List<Integer> cityIds = Utils.stringToIntegerList(productForm.getCityId()); for(int cityId : cityIds) { ProductCityMap cityMap = new ProductCityMap(); cityMap.setCity(cityService.findOne(cityId)); cityMap.setProduct(product); productCities.add(cityMap); } } product.setProductCities(productCities); List<ProductTagMap> productTags= new ArrayList<>(); if(productForm.getTag() != null) { List<Integer> tagIds = Utils.stringToIntegerList(productForm.getTag()); for(int tagId : tagIds) { ProductTagMap tagMap = new ProductTagMap(); tagMap.setTag(tagService.findOne(tagId)); tagMap.setProduct(product); productTags.add(tagMap); } } product.setProductTags(productTags); productService.create(product); ProductData productData = new ProductData(); ProductDataForm productDataForm = productForm.getProductDataForm(); productData.setName(productDataForm.getName()); productData.setProduct(product); productData.setLanguageId(Constants.DEFAULT_VIETNAMESE_LANGUAGE_ID); String slug = Utils.stringToSlug(productData.getName()); productData.setSlug(slug); productData.setShortDescription(productDataForm.getShortDescription()); productData.setDescription(productDataForm.getDescription()); productData.setProductStatus(productForm.getProductDataForm().getProductStatus()); if(!productForm.getProductDataForm().getIsDeliveryGlobalFree()) { if(!productForm.getProductDataForm().getIsDeliveryInCityFree()) { productData.setDeliveryFeeMaxInCity(productForm.getProductDataForm().getDeliveryFeeMaxInCity()); productData.setDeliveryFeeMinInCity(productForm.getProductDataForm().getDeliveryFeeMinInCity()); } if(!productForm.getProductDataForm().getIsDeliveryOutCityFree()) { productData.setDeliveryFeeMaxOutCity(productForm.getProductDataForm().getDeliveryFeeMaxOutCity()); productData.setDeliveryFeeMinOutCity(productForm.getProductDataForm().getDeliveryFeeMinOutCity()); } } if (!productDataForm.getFromStringDate().isEmpty()){ SimpleDateFormat formatter = new SimpleDateFormat(Constants.dateFormat); Date startTime = null; Date endTime = null; try { startTime = formatter.parse(productDataForm.getFromStringDate()); endTime = formatter.parse(productDataForm.getToStringDate()); } catch (ParseException e) { e.printStackTrace(); } productData.setStartTime(startTime); productData.setEndTime(endTime); } productData.setWarrantyPeriod(productDataForm.getWarrantyPeriod()); productData.setWarrantyType(productDataForm.getWarrantyType()); productData.setIsDeliveryGlobalFree(productDataForm.getIsDeliveryGlobalFree()); productData.setIsDeliveryInCityFree(productDataForm.getIsDeliveryInCityFree()); productData.setIsDeliveryOutCityFree(productDataForm.getIsDeliveryOutCityFree()); productData.setUnit(productDataForm.getUnit()); if(!productDataForm.getIsDeliveryGlobalFree()) { if(productDataForm.getIsDeliveryInCityFree()) { productData.setDeliveryFeeMinInCity(productDataForm.getDeliveryFeeMinInCity()); productData.setDeliveryFeeMaxInCity(productDataForm.getDeliveryFeeMaxInCity()); } if(productDataForm.getIsDeliveryOutCityFree()) { productData.setDeliveryFeeMinOutCity(productDataForm.getDeliveryFeeMinOutCity()); productData.setDeliveryFeeMaxOutCity(productDataForm.getDeliveryFeeMaxOutCity()); } } if(productDataForm.getFreeForOrderAmountReachToInCity()!= null && !productDataForm.getFreeForOrderAmountReachToInCity().isEmpty()){ productData.setFreeForOrderAmountReachToInCity(Float.valueOf(productDataForm.getFreeForOrderAmountReachToInCity())); } if(productDataForm.getFreeForOrderAmountReachToInGlobal() != null && !productDataForm.getFreeForOrderAmountReachToInGlobal().isEmpty()){ productData.setFreeForOrderAmountReachToInCity(Float.valueOf(productDataForm.getFreeForOrderAmountReachToInGlobal())); } productDataService.create(productData); Skus sku = new Skus(); SkuData skuData = new SkuData(); SkuForm skuForm = productForm.getSkuForm(); List<String> imageSlide = sku.getImageSlideAsListString(true); imageSlide.add(product.getImage()); if (images != null && images.length > 0) { for (MultipartFile image : images) { if (!image.isEmpty()) { String webappRoot = context.getRealPath(Constants.SAVE_PRODUCT_PATH); Map<String, String> resultUpload = UtilsMedia.uploadImage(image, webappRoot); imageSlide.add(Constants.SAVE_PRODUCT_PATH + resultUpload.get("fileName")); } } } sku.setProduct(product); sku.setImageSlide(String.join(";", imageSlide)); sku.setCashbackAmount(Float.valueOf((productForm.getCashbackAmount() == null || productForm.getCashbackAmount().isEmpty())? "0" : productForm.getCashbackAmount())); sku.setDiscountPercent(Float.valueOf((productForm.getDiscountPercent() == null || productForm.getDiscountPercent().isEmpty())? "0" : productForm.getDiscountPercent())); sku.setIsDefault(true); sku.setPrice(Float.valueOf(productForm.getPrice())); if(productForm.getLastPrice() != null && !productForm.getLastPrice().isEmpty()) { sku.setLastPrice(Float.valueOf(productForm.getLastPrice())); } sku.setQuantity(Integer.valueOf(productForm.getQuantity())); sku.setStatus(product.getStatus()); sku.setSkuCode(UtilsSku.createSkuCode(skuForm.getName(), product.getId())); skuService.create(sku); skuData.setName(skuForm.getName()); skuData.setLanguage(Constants.DEFAULT_VIETNAMESE_LANGUAGE_ID); skuData.setSkus(sku); skuDataService.create(skuData); redirectAttributes.addFlashAttribute( "success_message", messages.get("General.message.create_success", new Object[]{"sản phẩm"})); }catch (Exception ex){ this.setLog(ex, redirectAttributes); } return "redirect:/products"; } @RequestMapping(value = {"/{id}/edit"}, method = RequestMethod.GET) public String edit(@PathVariable long id, Model model) { Product product = productService.findOne(id); if (product == null) { return "404"; } Category category = product.getCategory(); List<String> categories = category.getCategoryParentListId(); Supplier supplier = product.getSupplier(); ProductForm productForm = new ProductForm(product); float cashbackPercentForNeedi = Float.valueOf(configurationCache.get(ConfigurationKey.CASH_BACK_PERCENT_FOR_NEEDII)); productForm.setCashbackDefault(Utils.getCashBackForCustomer(productForm.getCashbackDefault(), cashbackPercentForNeedi)); if(productForm.getLastPrice() != null && !productForm.getLastPrice().isEmpty()) { productForm.setCashbackDefaultLabel(String.valueOf(Float.valueOf(productForm.getLastPrice())*productForm.getCashbackDefault())); }else{ productForm.setCashbackDefaultLabel(String.valueOf(Float.valueOf(productForm.getPrice())*productForm.getCashbackDefault())); } if (productForm.getCityId() != null && !productForm.getCityId().isEmpty()) { List<City> productCities = cityService.findByIdIn(Utils.stringToIntegerList(productForm.getCityId())); model.addAttribute("productCities", productCities); } if (productForm.getTag() != null && !productForm.getTag().isEmpty()) { List<Tag> productTags = tagService.findByIdIn(Utils.stringToIntegerList(productForm.getTag())); model.addAttribute("productTags", productTags); } model.addAttribute("productForm", productForm); model.addAttribute("category", category); model.addAttribute("categories", categories); model.addAttribute("supplier", supplier); return "productEdit"; } @RequestMapping(value = {"/{id}/edit"}, method = RequestMethod.POST) public String update(@PathVariable long id, FileBucket thumbnail, @ModelAttribute("productForm") ProductForm productForm, BindingResult result, Model model, final RedirectAttributes redirectAttributes) { productFormValidator.validate(productForm, result); if (result.hasErrors()) { Product product = productService.findOne(id); Supplier supplier = supplierService.findOne(Integer.valueOf(productForm.getSupplierId())); if (!productForm.getCategoryId().isEmpty()) { Category category = categoryService.findOne(Integer.valueOf(productForm.getCategoryId())); if(category != null) { List<String> categories = category.getCategoryParentListId(); productForm.setCategoryId(categories.get(0)); model.addAttribute("category", category); model.addAttribute("categories", categories); } } if (productForm.getCityId() != null && !productForm.getCityId().isEmpty()) { List<City> productCities = cityService.findByIdIn(Utils.stringToIntegerList(productForm.getCityId())); model.addAttribute("productCities", productCities); } if (productForm.getTag() != null && !productForm.getTag().isEmpty()) { List<Tag> productTags = tagService.findByIdIn(Utils.stringToIntegerList(productForm.getTag())); model.addAttribute("productTags", productTags); } model.addAttribute("productForm", productForm); model.addAttribute("supplier", supplier); return "productEdit"; } Category category = categoryService.findOne(Integer.valueOf(productForm.getCategoryId())); Supplier supplier = supplierService.findOne(Integer.valueOf(productForm.getSupplierId())); Product product = productService.findOne(id); if (product == null || category == null || supplier == null) { return "404"; } try { product.setCategory(category); product.setQuantity(Integer.valueOf(productForm.getQuantity())); product.setIsNew(productForm.getIsNew()); product.setIsTodayDeal(productForm.getIsTodayDeal()); product.setIsCommingDeal(productForm.getIsCommingDeal()); product.setIsBestSeller(productForm.getIsBestSeller()); product.setIsHot(productForm.getIsHot()); product.setApprove(productForm.getApprove()); product.setIsShowHome(product.getIsShowHome()); product.setIsPromotion(productForm.getIsPromotion()); product.setAvailableForSale(productForm.getAvailableForSale()); product.setStatus(productForm.getStatus()); product.setPrice(Float.valueOf(productForm.getPrice())); if(productForm.getLastPrice() != null && !productForm.getLastPrice().isEmpty()) { product.setLastPrice(Float.valueOf(productForm.getLastPrice())); } product.setCashbackAmount(Float.valueOf(productForm.getCashbackAmount())); product.setDiscountPercent(0); product.setSupplier(supplier); product.setIsReject(false); product.setRejectReason(""); if(!productForm.getProductDataForm().getIsDeliveryGlobalFree()) { product.setHeight(Float.valueOf(productForm.getHeight())); product.setWeight(Float.valueOf(productForm.getWeight())); product.setDepth(Float.valueOf(productForm.getDepth())); product.setWidth(Float.valueOf(productForm.getWidth())); } if (!thumbnail.isEmpty()) { String webappRoot = context.getRealPath(Constants.SAVE_PRODUCT_THUMBNAIL_PATH); Map<String, String> resultUpload = UtilsMedia.uploadImage(thumbnail.getFile(), webappRoot); product.setImage(Constants.SAVE_PRODUCT_THUMBNAIL_PATH + resultUpload.get("fileName")); } List<ProductCityMap> productCities = product.getProductCities(); if (productForm.getCityId() != null) { List<Integer> cityIds = Utils.stringToIntegerList(productForm.getCityId()); for (int cityId : cityIds) { if (productCities.stream().noneMatch(x -> x.getCity().getId() == cityId && x.getProduct().getId() == product.getId())) { ProductCityMap cityMap = new ProductCityMap(); cityMap.setCity(cityService.findOne(cityId)); cityMap.setProduct(product); productCities.add(cityMap); } } product.setProductCities(productCities); } List<ProductTagMap> productTags= product.getProductTags(); if (productForm.getTag() != null) { List<Integer> tagIds = Utils.stringToIntegerList(productForm.getTag()); for (int tagId : tagIds) { if (productTags.stream().noneMatch(x -> x.getTag().getId() == tagId && x.getProduct().getId() == product.getId())) { ProductTagMap tagMap = new ProductTagMap(); tagMap.setTag(tagService.findOne(tagId)); tagMap.setProduct(product); productTags.add(tagMap); } } product.setProductTags(productTags); } ProductDataForm productDataForm = productForm.getProductDataForm(); ProductData productData = product.getData(); productData.setName(productDataForm.getName()); productData.setProduct(product); productData.setLanguageId(1); String slug = Utils.stringToSlug(productData.getName()); productData.setSlug(slug); productData.setShortDescription(productDataForm.getShortDescription()); productData.setDescription(productDataForm.getDescription()); productData.setProductStatus(productDataForm.getProductStatus()); productData.setUnit(productDataForm.getUnit()); if(!productForm.getProductDataForm().getIsDeliveryGlobalFree()) { if(!productForm.getProductDataForm().getIsDeliveryInCityFree()) { productData.setDeliveryFeeMaxInCity(productForm.getProductDataForm().getDeliveryFeeMaxInCity()); productData.setDeliveryFeeMinInCity(productForm.getProductDataForm().getDeliveryFeeMinInCity()); } if(!productForm.getProductDataForm().getIsDeliveryOutCityFree()) { productData.setDeliveryFeeMaxOutCity(productForm.getProductDataForm().getDeliveryFeeMaxOutCity()); productData.setDeliveryFeeMinOutCity(productForm.getProductDataForm().getDeliveryFeeMinOutCity()); } } if (!productDataForm.getFromStringDate().isEmpty() && !productDataForm.getToStringDate().isEmpty()){ SimpleDateFormat formatter = new SimpleDateFormat(Constants.dateFormat); Date startTime = null; Date endTime = null; try { startTime = formatter.parse(productDataForm.getFromStringDate()); endTime = formatter.parse(productDataForm.getToStringDate()); } catch (ParseException e) { e.printStackTrace(); } productData.setStartTime(startTime); productData.setEndTime(endTime); } productData.setWarrantyPeriod(productDataForm.getWarrantyPeriod()); productData.setWarrantyType(productDataForm.getWarrantyType()); productData.setIsDeliveryGlobalFree(productDataForm.getIsDeliveryGlobalFree()); productData.setIsDeliveryInCityFree(productDataForm.getIsDeliveryInCityFree()); productData.setIsDeliveryOutCityFree(productDataForm.getIsDeliveryOutCityFree()); if(!productDataForm.getIsDeliveryGlobalFree()) { if(productDataForm.getIsDeliveryInCityFree()) { productData.setDeliveryFeeMinInCity(productDataForm.getDeliveryFeeMinInCity()); productData.setDeliveryFeeMaxInCity(productDataForm.getDeliveryFeeMaxInCity()); } if(productDataForm.getIsDeliveryOutCityFree()) { productData.setDeliveryFeeMinOutCity(productDataForm.getDeliveryFeeMinOutCity()); productData.setDeliveryFeeMaxOutCity(productDataForm.getDeliveryFeeMaxOutCity()); } } if(productDataForm.getFreeForOrderAmountReachToInGlobal() != null && !productDataForm.getFreeForOrderAmountReachToInGlobal().isEmpty()) productData.setFreeForOrderAmountReachToInCity(Float.valueOf(productDataForm.getFreeForOrderAmountReachToInGlobal())); if(productDataForm.getFreeForOrderAmountReachToInCity() != null && !productDataForm.getFreeForOrderAmountReachToInCity().isEmpty()){ productData.setFreeForOrderAmountReachToInCity(Float.valueOf(productDataForm.getFreeForOrderAmountReachToInCity())); } productData.setProduct(product); Set<ProductData> productDatas = new HashSet<>(); productDatas.add(productData); product.setProductData(productDatas); productService.update(product); //update default sku List<Skus> skus = skuService.findByProductId(product.getId()); if(skus != null && skus.size() > 0) { Skus defaultSku = skus.get(0); defaultSku.setQuantity(product.getQuantity()); skuService.update(defaultSku); } redirectAttributes.addFlashAttribute( "success_message", messages.get("General.message.edit_success", new Object[]{"sản phẩm"})); } catch (Exception ex){ this.setLog(ex, redirectAttributes); } return "redirect:/products"; } @RequestMapping(value = {"/{id}/product-sku"}, method = RequestMethod.GET) public String listSku(@PathVariable long id, Model model) { Product product = productService.findOne(id); if (product == null) { return "404"; } model.addAttribute("product", product); return "productSku"; } @RequestMapping(value = {"/{id}/create/0/sku"}, method = RequestMethod.GET) public String createSku(@PathVariable long id, Model model) { Product product = productService.findOne(id); if (product == null) { return "404"; } model.addAttribute("skuForm", new SkuForm()); return "productSkuCreate"; } @RequestMapping(value = {"{id}/create/0/sku"}, method = RequestMethod.POST) public String storeSku(@PathVariable long id, @RequestParam(name = "file", required = false) MultipartFile[] files, @ModelAttribute("skuForm") SkuForm skuForm, BindingResult result, Model model, final RedirectAttributes redirectAttributes) { skuFormValidator.validate(skuForm, result); if (result.hasErrors()) { model.addAttribute("skuForm", skuForm); return "productSkuCreate"; } Product product = productService.findOne(id); if (product == null) { return "404"; } try { Skus sku = new Skus(); List<String> images = sku.getImageSlideAsListString(true); images.addAll(skuForm.getImages()); if (files != null && files.length > 0) { for (MultipartFile file : files) { if (!file.isEmpty()) { String webappRoot = context.getRealPath(Constants.SAVE_PRODUCT_PATH); Map<String, String> resultUpload = UtilsMedia.uploadImage(file, webappRoot); images.add(Constants.SAVE_PRODUCT_PATH + resultUpload.get("fileName")); } } } sku.setProduct(product); sku.setImageSlide(String.join(";", images)); sku.setCashbackAmount((skuForm.getCashbackAmount() != null && !skuForm.getCashbackAmount().isEmpty()) ? Float.valueOf(skuForm.getCashbackAmount()): 0); sku.setDiscountPercent(0); sku.setIsDefault(skuForm.getIsDefault()); if(skuForm.getIsDefault()){ List<Skus> skus = product.getSkuses(); for (Skus s : skus){ s.setIsDefault(false); skuService.update(s); } } sku.setPrice(Float.valueOf(skuForm.getPrice())); sku.setLastPrice(Float.valueOf(skuForm.getPrice())); if(skuForm.getLastPrice() != null && !skuForm.getLastPrice().isEmpty()) { sku.setLastPrice(Float.valueOf(skuForm.getLastPrice())); } sku.setQuantity(Integer.valueOf(skuForm.getQuantity())); sku.setSkuCode(UtilsSku.createSkuCode(skuForm.getName(), product.getId())); sku.setStatus(skuForm.getStatus()); skuService.create(sku); SkuData skuData = new SkuData(); skuData.setName(skuForm.getName()); skuData.setLanguage(1); skuData.setSkus(sku); skuDataService.create(skuData); redirectAttributes.addFlashAttribute( "success_message", messages.get("General.message.create_success", new Object[]{"sản phẩm"})); }catch (Exception ex){ this.setLog(ex, redirectAttributes); } return "redirect:/products"; } @RequestMapping(value = {"/{id}/edit/{skuId}/sku"}, method = RequestMethod.GET) public String editSku(@PathVariable long id, @PathVariable long skuId, Model model) { Skus sku = skuService.findOne(skuId); Product product = productService.findOne(id); if (sku == null || product == null) { return "404"; } model.addAttribute("skuForm", new SkuForm(sku, 1)); return "productSkuEdit"; } @RequestMapping(value = {"/{id}/edit/{skuId}/sku"}, method = RequestMethod.POST) public String updateSku(@PathVariable long id, @PathVariable long skuId, @RequestParam(name = "file", required = false) MultipartFile[] files, @ModelAttribute("skuForm") @Validated SkuForm skuForm, BindingResult result, Model model, final RedirectAttributes redirectAttributes) { skuFormValidator.validate(skuForm, result); Skus sku = skuService.findOne(skuId); Product product = productService.findOne(id); if (sku == null || product == null) { return "404"; } try { List<String> images = sku.getImageSlideAsListString(false); if (result.hasErrors()) { skuForm.setImages(images); model.addAttribute("skuForm", skuForm); return "productSkuEdit"; } int size = images.size(); if(size < 4) { for(int x = 4; x > size; x--) { images.add(new String()); } } images.addAll(skuForm.getImages()); int index = 0; if (files != null && files.length > 0) { for (MultipartFile file : files) { if (!file.isEmpty()) { String webappRoot = context.getRealPath(Constants.SAVE_PRODUCT_PATH); Map<String, String> resultUpload = UtilsMedia.uploadImage(file, webappRoot); if(index == images.size()) { images.add(Constants.SAVE_PRODUCT_PATH + resultUpload.get("fileName")); } else { images.set(index, Constants.SAVE_PRODUCT_PATH + resultUpload.get("fileName")); } } index+=1; } } List<String> finalImages = new ArrayList<>(); for(String image : images) { if(!image.isEmpty()) { finalImages.add(image); } } sku.setProduct(product); sku.setImageSlide(String.join(";", finalImages)); sku.setCashbackAmount((skuForm.getCashbackAmount() != null && !skuForm.getCashbackAmount().isEmpty()) ? Float.valueOf(skuForm.getCashbackAmount()): 0); sku.setDiscountPercent(0); sku.setIsDefault(skuForm.getIsDefault()); if(skuForm.getIsDefault()){ List<Skus> skus = product.getSkuses(); for (Skus s : skus){ s.setIsDefault(false); skuService.update(s); } } sku.setPrice(Float.valueOf(skuForm.getPrice())); sku.setLastPrice(Float.valueOf(skuForm.getPrice())); if(skuForm.getLastPrice() != null && !skuForm.getLastPrice().isEmpty() && Float.valueOf(skuForm.getLastPrice()) > 0) { sku.setLastPrice(Float.valueOf(skuForm.getLastPrice())); } sku.setQuantity(Integer.valueOf(skuForm.getQuantity())); sku.setSkuCode(UtilsSku.createSkuCode(skuForm.getName(), product.getId())); sku.setStatus(skuForm.getStatus()); skuService.update(sku); SkuData skuData = sku.getData(); skuData.setName(skuForm.getName()); skuData.setSkus(sku); skuDataService.update(skuData); redirectAttributes.addFlashAttribute( "success_message", messages.get("General.message.edit_success", new Object[]{"sản phẩm"})); }catch (Exception ex){ this.setLog(ex, redirectAttributes); } return "redirect:/products"; } @RequestMapping(value = { "{id}/delete" }, method = RequestMethod.POST) public String delete(@PathVariable long id, final RedirectAttributes redirectAttributes) { Product product = productService.findOne(id); if(product == null) { return "404"; } try { product.setIsDeleted(true); productService.update(product); redirectAttributes.addFlashAttribute( "success_message", messages.get("General.message.delete_success", new Object[]{"sản phẩm"})); }catch (Exception ex){ this.setLog(ex, redirectAttributes); } return "redirect:/products"; } @RequestMapping(value = { "/export-excel" }, method = RequestMethod.GET) public ModelAndView exportExcel(Model model, @RequestParam(name = "name", required = false) String name, @RequestParam(name = "status", required = false) Integer status, @RequestParam(name = "supplierId", required = false) Long supplierId, @RequestParam(name = "categoryId", required = false) Long categoryId) { Option option = new Option(); List<Category> categories = categoryService.findAll(); Map<String, Object> queryString = new HashMap<>(); queryString.put("name", name); queryString.put("status", status); queryString.put("supplierId", supplierId); queryString.put("categoryId", categoryId); if(categoryId!= null) { List<Long> categoryIds = categories .stream() .filter(x -> x.getCategoryParentListId().contains(String.valueOf(categoryId))) .map(Category::getId) .collect(Collectors.toList()); categoryIds.add(categoryId); queryString.put("categoryId", StringUtils.join(categoryIds, ",")); } option.setQueryString(queryString); // Temporary fix int limit = productService.count(option).intValue(); if (limit == 0) { limit ++; } Pagination pagination = new Pagination(1, limit); option.setPagination(pagination); List<Product> products = productService.findAll(option); return new ModelAndView(new ProductExportExcel(), "products", products); } @RequestMapping(value = { "/change-status/{id}" }, method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<BaseResponse> changeStatus(@PathVariable("id") Long id, Model model) { Product entity = productService.findOne(id); BaseResponse response = new BaseResponse(); response.setStatus(ResponseStatusEnum.SUCCESS); response.setMessage(ResponseStatusEnum.SUCCESS); response.setData(null); try { if (entity == null) { response.setStatus(ResponseStatusEnum.NOT_FOUND); response.setMessage(ResponseStatusEnum.NOT_FOUND); } else { entity.setStatus(entity.getStatus() == 1 ? 0 : 1); productService.update(entity); response.setStatus(ResponseStatusEnum.SUCCESS); response.setMessage(ResponseStatusEnum.SUCCESS); } } catch (Exception ex) { response.setStatus(ResponseStatusEnum.FAIL); response.setMessageError(ex.getMessage()); ex.printStackTrace(); } return new ResponseEntity<>(response, HttpStatus.OK); } public List<KeyValue> prepareDataForWeek() { List<KeyValue> chartData = new ArrayList<KeyValue>(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); String firstDay = ""; String lastDay = ""; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); for (int i = 0; i < 7; i++) { if (i == 0) { firstDay = df.format(cal.getTime()); } if (i == 6) { lastDay = df.format(cal.getTime()); } chartData.add(new KeyValue(df.format(cal.getTime()), "0")); cal.add(Calendar.DATE, 1); } List<ChartData> list = productService.findInWeek(firstDay, lastDay); for (ChartData item : list) { for (KeyValue chart : chartData) { if (item.getChartKey().equals(chart.getKey())) { chart.setValue(item.getChartValue()); break; } } } return chartData; } public List<KeyValue> prepareDataForMonth() { List<KeyValue> chartData = new ArrayList<KeyValue>(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, 1); String firstDay = ""; String lastDay = ""; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); firstDay = df.format(cal.getTime()); cal.add(Calendar.MONTH, 1); cal.set(Calendar.DAY_OF_MONTH, 1); cal.add(Calendar.DATE, -1); lastDay = df.format(cal.getTime()); List<ChartData> list = productService.findInMonth(firstDay, lastDay); for (int i = 0; i < list.size(); i++) { chartData.add(new KeyValue(list.get(i).getChartKey(), list.get(i).getChartValue())); } return chartData; } public List<KeyValue> prepareDataForYear() { List<KeyValue> chartData = new ArrayList<KeyValue>(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_YEAR, 1); String firstDay = ""; String lastDay = ""; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); firstDay = df.format(cal.getTime()); cal.add(Calendar.YEAR, 1); cal.set(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DATE, -1); lastDay = df.format(cal.getTime()); List<ChartData> list = productService.findInYear(firstDay, lastDay); for (int i = 0; i < list.size(); i++) { chartData.add(new KeyValue(list.get(i).getChartKey(), list.get(i).getChartValue())); } return chartData; } @RequestMapping(value = { "/report/" }, method = RequestMethod.GET) @ResponseBody public Object report(Model model, @RequestParam(name="type", required=false, defaultValue="week") String type) { List<KeyValue> chartData = new ArrayList<KeyValue>(); if (type.equals("week")) { chartData = prepareDataForWeek(); } if (type.equals("month")) { chartData = prepareDataForMonth(); } if (type.equals("year")) { chartData = prepareDataForYear(); } model.addAttribute("chartData", chartData); return chartData; } }
package ru.mcfr.oxygen.updater.web; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import ru.mcfr.oxygen.updater.Version; import ru.mcfr.oxygen.updater.utils.Streamer; import ru.mcfr.oxygen.updater.utils.Zipper; import sun.net.www.protocol.http.HttpURLConnection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Vector; /** * Created by IntelliJ IDEA. * User: ws * Date: 28.04.11 * Time: 15:28 * To change this template use File | Settings | File Templates. */ public class XMLBasedUpdater extends AbstractConnector{ private Vector<Map<String, String>> packages; public XMLBasedUpdater(Properties p) { super(p); } @Override public InputStream get(String url) { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean checkUpdates(HttpURLConnection urlConn) { DataInputStream input; this.packages = new Vector<Map<String, String>>(); try { if (urlConn == null) return false; input = new DataInputStream (urlConn.getInputStream ()); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(input); input.close (); urlConn.disconnect(); parseXmlResponse(doc,props.getProperty("trunk", "stable")); int not_used = 0; for (Map<String,String> info : packages){ String base_path = ""; if (info.get("type").equalsIgnoreCase("frameworks")) base_path = props.getProperty("path-to-framework"); else base_path = props.getProperty("path-to-plugin"); String path = base_path + File.separator + info.get("package"); if (new File(path).exists()){ Version existVersion = Version.fromDir(path); if (existVersion == null | existVersion.compareTo(info.get("version")) > -1){ info.put("not-use","true"); not_used++; } } } if (not_used == packages.size()) return false; return true; }catch (IOException e) { logger.error(e.getLocalizedMessage()); } catch (ParserConfigurationException e) { logger.error(e.getLocalizedMessage()); } catch (SAXException e) { logger.error(e.getLocalizedMessage()); } return false; } private void parseXmlResponse(Document resp, String filter){ NodeList entrys = resp.getElementsByTagName("entry"); for (int i = 0; i < entrys.getLength(); i ++){ Element entry = (Element) entrys.item(i); Map<String, String> info = new HashMap<String, String>(); info.put("version", entry.getAttribute("version")); info.put("path", entry.getAttribute("path")); Element branch = (Element) entry.getParentNode(); info.put("branch", branch.getAttribute("name")); Element package_ = (Element) branch.getParentNode(); info.put("package", package_.getAttribute("name")); info.put("type", package_.getAttribute("type")); if (filter.contains(branch.getAttribute("name"))) packages.add(info); } } //only download to storage actual versions public Map<String,String> downloadUpdatesTo(String destMainRelative){ Map <String, String> res = new HashMap<String, String>(); //if dest places in main subfolders destMainRelative = destMainRelative.replace("\\",File.separator).replace("/", File.separator); for (Map<String,String> packageInfo : packages) { if (packageInfo.keySet().contains("not-use")) continue; // updates/[type]/[name]/[version]/ File destFolder = new File(props.getProperty("path-to-main") + File.separator + destMainRelative + File.separator + packageInfo.get("type") + File.separator + packageInfo.get("package") + File.separator + packageInfo.get("version")); destFolder.mkdirs(); try { HttpURLConnection urlConn = connectToURL(props.getProperty("server-url") + packageInfo.get("path")); String fileName = urlConn.getURL().getFile(); //get file name from url String[] tmp = fileName.split("\\?")[0].split("\\/"); fileName = tmp[tmp.length-1]; if (urlConn != null) { File destFile = new File(destFolder.getAbsolutePath() + File.separator + fileName); Streamer.downloadFromStream(urlConn.getInputStream(), destFile); urlConn.disconnect(); Zipper.unzip(destFile, destFolder.getAbsolutePath()); // install to[key] from[value] res.put(packageInfo.get("type"), destFolder.getAbsolutePath()); } } catch (IOException e) { logger.error(e.getLocalizedMessage()); } } return res; } }
package com.rafael.personalitytest.ui.answer; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import android.widget.Toast; import com.rafael.personalitytest.App; import com.rafael.personalitytest.R; import com.rafael.personalitytest.model.Question; import com.whygraphics.multilineradiogroup.MultiLineRadioGroup; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class AnswerActivity extends AppCompatActivity { private ProgressDialog progressDialog; private Question question; @Inject AnswerViewModel viewModel; @BindView(R.id.txt_description) TextView textView; @BindView(R.id.rg_options) MultiLineRadioGroup radioGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_answer); ButterKnife.bind(this); ((App) getApplication()).getComponent().inject(this); Bundle bundle = getIntent().getExtras(); if (bundle == null) finish(); question = (Question) bundle.get("question"); if (question == null) finish(); progressDialog = new ProgressDialog(this); progressDialog.setTitle("Enviando"); progressDialog.setMessage("aguarde enviando sua resposta"); progressDialog.setCancelable(false); textView.setText(question.getDescription()); radioGroup.addButtons(question.getOptions().toArray(new String[0])); radioGroup.checkAt(0); viewModel.getAnswerProgress().observe(this, showProgressBar -> { if (showProgressBar) progressDialog.show(); else progressDialog.dismiss(); }); viewModel.getAnswerStatus().observe(this, status -> { if (status) { Toast.makeText(getApplicationContext(), "Parabéns continue respondendo as perguntas!!!", Toast.LENGTH_LONG).show(); finish(); } }); viewModel.getAnswerError().observe(this, message -> Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show()); } @OnClick(R.id.button_confirm) void confirm() { viewModel.sendAnswer(question.getId(), question.getDescription(), radioGroup.getCheckedRadioButtonText().toString()); } }
package com.blog.Iservice; import java.util.List; import com.blog.bean.Adminuser; import com.blog.bean.DongTai; public interface IAdminuserService { /** *先查询账户是否存在,否则返回false */ public boolean isLogin(String a_name); /** *先查询账户是否存在,返回Adminuser */ public Adminuser isAdminUserByname(String a_name); /** *先查询账户是否存在,如果不存在则插入数据,否则返回false */ public boolean isRegAdminUser(Adminuser adminuser); /** *修改密码 */ public boolean Change_a_pass(Adminuser adminuser,int a_id); public List<Adminuser> adminuserlist(); public int getTotalCountadminuser(); public List<Adminuser> adminuserlistBypage(int currentPage, int pageSize); }
package com.esum.comp.nckims; import java.io.IOException; import com.esum.framework.core.component.ComponentException; import com.esum.framework.core.component.config.ComponentConfig; import com.esum.framework.core.config.Configurator; import com.esum.framework.core.exception.SystemException; public class NcKimsConfig extends ComponentConfig { public static String NCKIMS_INFO_TABLE_ID = "nckims_info_id"; public static String MODULE_NAME = "NCKIMS"; public static String RECV_DATA_TYPE = "recvDataType"; public static String SENDER_ID = "senderId"; public static String RECVER_ID = "recverId"; public static String LOCK_TABLE_NAME; public static int FORCED_UNLOCK_INTERVAL_SEC; protected NcKimsConfig(String componentId) { super(componentId); } public void init() throws SystemException { super.setInterfaceInfoTableId(NcKimsConfig.NCKIMS_INFO_TABLE_ID); try { Configurator.init(getConfigId(), getInstallPath() + "/conf/nckims/config.properties"); } catch (IOException e) { throw new ComponentException("init()", e.getMessage(), e); } MODULE_NAME = this.getComponentId(); LOCK_TABLE_NAME = Configurator.getInstance(getConfigId()).getString("lock.table.name", null); FORCED_UNLOCK_INTERVAL_SEC = Configurator.getInstance(getConfigId()).getInt("forced.unlock.interval", 600); } protected void destroyOtherConfigs() throws SystemException { } }
package com.project.maps; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MainActivity extends FragmentActivity { private GoogleMap map; private LatLng latLngBiru = new LatLng(-6.984043, 110.410701); private LatLng latLngKuning = new LatLng(-6.985289, 110.410724); private LatLng latLngsatu = new LatLng(-6.984298, 110.409382); private LatLng latLngMerah = new LatLng(35.6839537, 139.7308615); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); map = mapFrag.getMap(); map.setMyLocationEnabled(true); map.addMarker(new MarkerOptions() .position(latLngBiru) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)) .title("Lawang Sewu").snippet("Lokasi Pariwisata")); map.addMarker(new MarkerOptions() .position(latLngKuning) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)) .title("Pusat Oleh-Oleh Pandanaran").snippet("Kuliner Semarang")); map.addMarker(new MarkerOptions() .position(latLngsatu) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)) .title("Monumen Tugu Muda").snippet("Lokasi Pariwisata")); map.addMarker(new MarkerOptions() .position(latLngMerah) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_RED)) .title("kantin kampus").snippet("makan makan")); map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLngBiru, 17)); CameraPosition cameraPosition = new CameraPosition.Builder() .target(latLngBiru) .zoom(17) .bearing(0) .tilt(45) .build(); map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } }
package com.dream.searchit; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.dream.searchit.models.Contact_info; public class AddPerson extends AppCompatActivity { private EditText tv_first; private EditText tv_second; private EditText tv_third; private Button btn_person; private DatabaseHandler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); handler = new DatabaseHandler(this); tv_first= (EditText) findViewById(R.id.edit_first_person); tv_second= (EditText) findViewById(R.id.edit_second_person); tv_third= (EditText) findViewById(R.id.edit_third_person); btn_person= (Button) findViewById(R.id.person_button); btn_person.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = tv_first.getText().toString(); long phone = Long.parseLong(tv_second.getText().toString()); String address = tv_third.getText().toString(); Contact_info contact1 = new Contact_info(name, phone, address); DatabaseHandler handler = new DatabaseHandler(AddPerson.this); long a = handler.AddContact(contact1); if(a!=-1){ Toast.makeText(AddPerson.this,"Contact successfully saved!",Toast.LENGTH_SHORT).show(); finish(); } else{ Toast.makeText(AddPerson.this,"Error!",Toast.LENGTH_SHORT).show(); } } }); } @Override protected void onResume() { super.onResume(); } }
package kr.co.flyingturtle.edu.batch; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import kr.co.flyingturtle.repository.mapper.AttendMapper; @Component public class SpringBatchAttend extends HandlerInterceptorAdapter { @Autowired private AttendMapper mapper; // public static void main(String[] args) { /* Connection con = null; String user = "flyingturtle"; String password = "helloturtle^"; String url = "jdbc:mysql://203.236.209.131:3306/flyingturtle"; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, user, password); String qu = "select * from tb_member"; Statement st = con.createStatement(); ResultSet rs = st.executeQuery(qu); while(rs.next()) { int memberNo = rs.getInt("memberNo"); System.out.println(memberNo); } }catch(Exception e) { System.out.println(e); } } */ //결석 자동화 // @Scheduled(cron = "0 00 00 * * *") // public void attendData() { // // String comm = "python C://bit2019//flying_turtle//python//crawling.py"; // Runtime rt = Runtime.getRuntime(); // // Process p; // try { // p = rt.exec(comm); // p.getErrorStream().close(); // p.getInputStream().close(); // p.getOutputStream().close(); // p.waitFor(); // } catch(Exception e) { // e.printStackTrace(); // } // } }
package com.trump.auction.trade.service.impl.bid.initiali; import com.trump.auction.trade.service.AuctionInfoService; import com.trump.auction.trade.service.BidManagerService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Slf4j @Component public class SaveBidINitiali implements CommandLineRunner { private static final Long isBid=1L; @Autowired private AuctionInfoService auctionInfoService; @Autowired private BidManagerService managerService; @Override public void run(String... strings) throws Exception { log.info("SaveBidINitiali BID task "); } }
package com.wang; public class Guess1To10 { public static void main(String[] args) { } }
package com.algaworks.algamoney.api.data.repository; import com.algaworks.algamoney.api.data.entity.EntryEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * @author jsilva on 31/10/2019 */ public interface EntryRepository extends JpaRepository<EntryEntity, Long>, JpaSpecificationExecutor<EntryEntity> { }
package com.cninfo.proxy.http.impl; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.hadoop.io.IOUtils; import org.apache.log4j.Logger; import com.cninfo.proxy.http.ProxyCache; public class StandardCache implements ProxyCache { static Logger logger = Logger.getLogger(StandardCache.class.getName()); private static ProxyCache singleton; private File cache; private StandardCache(){ } /** * @param path */ private StandardCache(String path){ this.cache = new File(path); if(cache.exists()){ if(!cache.isDirectory() || !cache.canWrite()){ throw new IllegalStateException("缓存不可写或其它原因"); } }else if(!cache.mkdirs()){ throw new IllegalStateException("创建缓存目录失败"); } } /** * @return */ public static ProxyCache getSingleton(){ if(singleton == null){ throw new IllegalStateException("缓存尚未初始化,请先调用initial方法"); } return singleton; } /** * @param root */ public static void initial(String root){ if(singleton == null){ synchronized(StandardCache.class){ singleton = new StandardCache(root); } } } /* (non-Javadoc) * @see com.cninfo.proxy.http.ProxyCache#getInputStream(java.lang.String) */ public InputStream getInputStream(String path) throws IOException{ File file = new File(cache.getPath()+path); InputStream in = new FileInputStream(file); return in; } /* (non-Javadoc) * @see com.cninfo.proxy.http.ProxyCache#exists(java.lang.String) */ public boolean exists(String path){ File file = new File(cache.getPath()+path); return file.exists() && file.canRead(); } /* (non-Javadoc) * @see com.cninfo.proxy.http.ProxyCache#writeable(java.lang.String) */ public boolean writeable(String path){ File file = new File(cache.getPath()+path); return file.canWrite(); } /* (non-Javadoc) * @see com.cninfo.proxy.http.ProxyCache#write(java.io.InputStream, java.lang.String) */ public void write(InputStream in, String path) throws IOException{ File file = new File(cache.getPath()+path); File parent = file.getParentFile(); if(!parent.exists()&& !parent.mkdirs()){ throw new IllegalStateException(parent.getPath()+"缓存文件目录创建失败"); } BufferedOutputStream out = null; BufferedInputStream bin = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); bin = new BufferedInputStream(in); byte[] buf = new byte[1024]; int len = 0; while((len = bin.read(buf))>0){ out.write(buf, 0, len); }; out.flush(); } catch (IOException e) { e.printStackTrace(); throw new IOException(path+"文件写入失败"); }finally{ if(out != null){ IOUtils.closeStream(out); logger.debug("FileOutputStream has closed"); } } } }
/* Copyright (C) 2013-2016, Securifera, Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Securifera, Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ The copyright on this package is held by Securifera, Inc */ /* * SettingsJDialog.java * */ package pwnbrew.shell; import java.awt.Cursor; import java.awt.event.WindowEvent; import javax.swing.JDialog; /** * * */ public class ShellSettingsJDialog extends JDialog { private final ShellJPanelListener theListener; private static final String NAME_Class = ShellSettingsJDialog.class.getSimpleName(); //======================================================================= /** Creates new form SettingsJDialog * @param parent * @param modal */ public ShellSettingsJDialog( ShellJPanelListener parent, boolean modal ) { super( parent.getParentJFrame() , modal); theListener = parent; initComponents(); initializeComponents(); setLocationRelativeTo(null); }//End Constructor //======================================================================= /** * Initializes all the components */ private void initializeComponents(){ ShellSettings theSettings = theListener.getShellSettings(); String curDir = theSettings.getCurrentDir(); if( curDir != null ){ curDirField.setText(curDir); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { encodingButtonGroup = new javax.swing.ButtonGroup(); cancelJButton = new javax.swing.JButton(); saveOrOkJButton = new javax.swing.JButton(); curDirLabel = new javax.swing.JLabel(); curDirField = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Settings"); setModal(true); setName("Options"); // NOI18N cancelJButton.setText("Cancel"); cancelJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelJButtonActionPerformed(evt); } }); saveOrOkJButton.setText("OK"); saveOrOkJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveOrOkJButtonActionPerformed(evt); } }); curDirLabel.setText("Current Directory:"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(saveOrOkJButton, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2) .addComponent(cancelJButton)) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(curDirLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(curDirField, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE) .addGap(28, 28, 28))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(curDirLabel) .addComponent(curDirField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 145, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(saveOrOkJButton) .addComponent(cancelJButton)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void cancelJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelJButtonActionPerformed closeDialog(); }//GEN-LAST:event_cancelJButtonActionPerformed private void saveOrOkJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveOrOkJButtonActionPerformed ShellSettings theSettings = theListener.getShellSettings(); String curDir = curDirField.getText(); theSettings.setCurrentDir(curDir); closeDialog(); }//GEN-LAST:event_saveOrOkJButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelJButton; private javax.swing.JTextField curDirField; private javax.swing.JLabel curDirLabel; private javax.swing.ButtonGroup encodingButtonGroup; private javax.swing.JButton saveOrOkJButton; // End of variables declaration//GEN-END:variables // ========================================================================== /** * Processes {@link WindowEvent}s occurring on this component. * <p> * This method is overridden to handle unsaved changes when the window is closed * using the X(exit) button and give the user the option of cancelling the close. * * @param event the {@code WindowEvent} */ @Override //Overrides JFrame.processWindowEvent( WindowEvent ) protected void processWindowEvent( WindowEvent event ) { if( WindowEvent.WINDOW_CLOSING == event.getID() ) closeDialog(); else super.processWindowEvent( event ); } // ========================================================================== /** * Handles the logic necessary before the dialog is closed */ private void closeDialog() { dispose(); } }
package fr.aresrpg.tofumanchou.infra.data; import fr.aresrpg.commons.domain.condition.Option; import fr.aresrpg.commons.domain.log.Logger; import fr.aresrpg.commons.domain.log.LoggerBuilder; import fr.aresrpg.dofus.protocol.DofusConnection; import fr.aresrpg.tofumanchou.domain.data.Account; import fr.aresrpg.tofumanchou.domain.data.entity.player.Perso; import fr.aresrpg.tofumanchou.infra.io.ManchouProxy; import java.net.SocketAddress; /** * * @since */ public class ManchouAccount implements Account { private int id; private SocketAddress adress; private String accountName; private String pass; private Perso perso; private Logger logger = new LoggerBuilder(String.valueOf(id)).setUseConsoleHandler(false, true, Option.none(), Option.none()).build(); private DofusConnection connection; private ManchouBank bank = new ManchouBank(); private ManchouProxy proxy; public ManchouAccount(int id, SocketAddress adress, String accountName, String pass, Perso perso) { this.id = id; this.adress = adress; this.accountName = accountName; this.pass = pass; this.perso = perso; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; return obj instanceof ManchouAccount && ((ManchouAccount) obj).id == id; } @Override public int hashCode() { return id; } /** * @param pass * the pass to set */ public void setPass(String pass) { this.pass = pass; } /** * @return the connection */ public DofusConnection getConnection() { return connection; } /** * @param connection * the connection to set */ public void setConnection(DofusConnection connection) { this.connection = connection; } /** * @param id * the id to set */ public void setId(int id) { this.id = id; } /** * @param adress * the adress to set */ public void setAdress(SocketAddress adress) { this.adress = adress; } /** * @param accountName * the accountName to set */ public void setAccountName(String accountName) { this.accountName = accountName; } /** * @param perso * the perso to set */ public void setPerso(Perso perso) { this.perso = perso; } /** * @param logger * the logger to set */ public void setLogger(Logger logger) { this.logger = logger; } @Override public int getId() { return id; } @Override public SocketAddress getAdress() { return adress; } @Override public String getAccountName() { return accountName; } @Override public String getPassword() { return pass; } @Override public Perso getPerso() { return perso; } @Override public String toString() { return "ManchouAccount [id=" + id + ", adress=" + adress + ", accountName=" + accountName + ", pass=" + pass + ", perso=" + perso + "]"; } @Override public Logger getLogger() { return logger; } @Override public ManchouBank getBank() { return this.bank; } @Override public ManchouProxy getProxy() { return proxy; } /** * @param proxy * the proxy to set */ public void setProxy(ManchouProxy proxy) { this.proxy = proxy; } /** * @param bank * the bank to set */ public void setBank(ManchouBank bank) { this.bank = bank; } }
package cn.jaychang.scstudy.account.entity; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * @author zhangjie * @package cn.jaychang.scstudy.account.entity * @description 账户 * @create 2018-10-07 09:47 */ @TableName("t_account") @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Account implements Serializable{ private static final long serialVersionUID = -6537408005535999301L; /** * 账户id */ private Long id; /** * 账号 */ private String userId; /** * 用户余额 */ private BigDecimal balance; /** * 冻结金额,扣款暂存余额 */ private BigDecimal freezeAmount; /** * 创建时间 */ private Date createTime; /** * 最后更新时间 */ private Date updateTime; }
package com.git.cloud.resmgt.compute.handler; import java.util.ArrayList; import java.util.HashMap; 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 com.git.cloud.common.enums.EnumResouseHeader; import com.git.cloud.common.exception.RollbackableBizException; import com.git.cloud.foundation.util.PwdUtil; import com.git.cloud.handler.service.AutomationService; import com.git.cloud.policy.service.IIpAllocToDeviceNewService; import com.git.cloud.resmgt.common.dao.ICmDeviceDAO; import com.git.cloud.resmgt.common.dao.ICmHostDAO; import com.git.cloud.resmgt.common.dao.ICmPasswordDAO; import com.git.cloud.resmgt.common.dao.ICmVmDAO; import com.git.cloud.resmgt.common.dao.IRmDatacenterDAO; import com.git.cloud.resmgt.common.dao.IRmVmManageServerDAO; import com.git.cloud.resmgt.common.model.bo.CmDeviceHostShowBo; import com.git.cloud.resmgt.common.model.po.CmDevicePo; import com.git.cloud.resmgt.common.model.po.CmVmPo; import com.git.cloud.resmgt.common.model.po.ScanResult; import com.git.cloud.resmgt.common.service.ICmDeviceService; import com.git.cloud.resmgt.compute.model.vo.VmMonitorVo; import com.git.support.common.MesgFlds; import com.git.support.common.MesgRetCode; import com.git.support.common.VmGlobalConstants; import com.git.support.general.field.GeneralKeyField; import com.git.support.invoker.common.impl.ResAdptInvokerFactory; import com.git.support.invoker.common.inf.IResAdptInvoker; import com.git.support.sdo.impl.BodyDO; import com.git.support.sdo.impl.DataObject; import com.git.support.sdo.impl.HeaderDO; import com.git.support.sdo.inf.IDataObject; public class VmControllerServicePOWERVMImpl implements VmControllerService{ private static Logger log = LoggerFactory.getLogger(VmControllerServicePOWERVMImpl.class); private Logger logger = LoggerFactory.getLogger(this.getClass()); private ICmDeviceService iCmDeviceService; @Autowired private AutomationService automationService; @Autowired private ResAdptInvokerFactory resInvokerFactory; @Autowired private ICmHostDAO cmHostDAO; @Autowired private IRmVmManageServerDAO rmVmMgServerDAO; @Autowired private ICmPasswordDAO cmPasswordDAO; @Autowired private IRmDatacenterDAO rmDatacenterDAO; @Autowired private ICmVmDAO cmVMDao; private IIpAllocToDeviceNewService iIpAllocToDeviceService; private ICmDeviceDAO icmDeviceDAO; public IIpAllocToDeviceNewService getiIpAllocToDeviceService() { return iIpAllocToDeviceService; } public void setiIpAllocToDeviceService( IIpAllocToDeviceNewService iIpAllocToDeviceService) { this.iIpAllocToDeviceService = iIpAllocToDeviceService; } public ICmDeviceDAO getIcmDeviceDAO() { return icmDeviceDAO; } public void setIcmDeviceDAO(ICmDeviceDAO icmDeviceDAO) { this.icmDeviceDAO = icmDeviceDAO; } public ICmDeviceService getiCmDeviceService() { return iCmDeviceService; } public void setiCmDeviceService(ICmDeviceService iCmDeviceService) { this.iCmDeviceService = iCmDeviceService; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public String vmRunningState(String vmId) throws Exception { CmVmPo vmInfo = iCmDeviceService.findPowerInfoByVmId(vmId); if(vmInfo == null){ return null; } //遍历扫描所需信息,并进行查询 String hostId = vmInfo.getHostId(); String url = vmInfo.getManageIp(); String username = vmInfo.getUserName(); String password = vmInfo.getPassword(); if (StringUtils.isBlank(password)) throw new RollbackableBizException("获取HOST [" + username + "] password is null"); password = PwdUtil.decryption(password); String hostName = vmInfo.getHostName(); List<String> vmNameList = new ArrayList<String>(); String vmName = vmInfo.getLparName(); String loginfo = "虚拟机名称:" + vmName; log.debug(loginfo); vmNameList.add(vmName); String result = ""; try { //header HeaderDO header = HeaderDO.CreateHeaderDO(); header.setOperationBean("scanVMState"); header.setResourceClass(EnumResouseHeader.PV_RES_CLASS.getValue()); header.setResourceType(EnumResouseHeader.PV_RES_TYPE.getValue()); header.set("DATACENTER_QUEUE_IDEN", rmDatacenterDAO.getDataCenterByHostId(hostId).getQueueIden()); System.out.println("rmDatacenterDAO.getDataCenterByHostId(hostId).getQueueIden(): "+rmDatacenterDAO.getDataCenterByHostId(hostId).getQueueIden()); //body BodyDO body = BodyDO.CreateBodyDO(); body.set(GeneralKeyField.Power.URL, url); body.set(GeneralKeyField.Power.USERNAME, username); body.set(GeneralKeyField.Power.PASSWORD, password); body.set(GeneralKeyField.Power.HOST_NAME, hostName); body.set(GeneralKeyField.VM.VAPP_NAME, vmNameList); //reqData IDataObject reqData = DataObject.CreateDataObject(); reqData.setDataObject(MesgFlds.HEADER, header); reqData.setDataObject(MesgFlds.BODY, body); IDataObject rspData = null; IResAdptInvoker invoker = resInvokerFactory.findInvoker("AMQ"); rspData = invoker.invoke(reqData, 1200000); if (rspData == null) { result = "请求响应失败!"; } else { HeaderDO rspHeader = rspData.getDataObject(MesgFlds.HEADER, HeaderDO.class); BodyDO rspBody = rspData.getDataObject(MesgFlds.BODY,BodyDO.class); if (MesgRetCode.SUCCESS.equals(rspHeader.getRetCode())) { DataObject powerState = (DataObject) rspBody.get("POWER_STATE"); List<Map> vmStateList = (List<Map>) powerState.get(hostName); result = (String) vmStateList.get(0).get(vmName); }else{ result = "fail"; } } } catch (Exception e) { result = e.getMessage(); logger.error("异常exception",e); } return result; } //执行开机、关机、挂起、重启 private String vmPowerOperation(String vmId,String operation) throws RollbackableBizException{ //CmDeviceVMShowBo cmDeviceVMShowBo = iCmDeviceService.getCmDeviceVMInfo(vmId); CmVmPo vmInfo = iCmDeviceService.findPowerInfoByVmId(vmId); //String vmName = cmDeviceVMShowBo.getVm_name(); String hostId = vmInfo.getHostId(); String vmName =vmInfo.getLparName(); String hostName=vmInfo.getHostName(); String userName = vmInfo.getUserName(); String powerPwd = vmInfo.getPassword(); powerPwd = PwdUtil.decryption(powerPwd); String ip = vmInfo.getManageIp(); // String vcHostIP = ""; String result = ""; try { String loginfo = "虚拟机名称:" + vmName; log.debug(loginfo); //header HeaderDO header = HeaderDO.CreateHeaderDO(); header.setResourceClass(EnumResouseHeader.PV_RES_CLASS.getValue()); header.setResourceType(EnumResouseHeader.PV_RES_TYPE.getValue()); header.set("DATACENTER_QUEUE_IDEN", rmDatacenterDAO.getDataCenterByHostId(hostId).getQueueIden()); header.setOperationBean("vmPowerManagerImpl"); //body BodyDO body = BodyDO.CreateBodyDO(); body.set(GeneralKeyField.Power.URL, ip); body.set(GeneralKeyField.Power.USERNAME, userName); body.set(GeneralKeyField.Power.PASSWORD, powerPwd); body.set(GeneralKeyField.Power.HOST_NAME,hostName); body.set(GeneralKeyField.VM.VAPP_NAME, vmName); body.set(GeneralKeyField.VM.POWER_OPER_TYPE, operation); //reqData IDataObject reqData = DataObject.CreateDataObject(); reqData.setDataObject(MesgFlds.HEADER, header); reqData.setDataObject(MesgFlds.BODY, body); IDataObject rspData = null; IResAdptInvoker invoker = resInvokerFactory.findInvoker("AMQ"); rspData = invoker.invoke(reqData, 1200000); if (rspData == null) { result = "请求响应失败!"; } else { HeaderDO rspHeader = rspData.getDataObject(MesgFlds.HEADER, HeaderDO.class); if (MesgRetCode.SUCCESS.equals(rspHeader.getRetCode())) { String runningState = "unknown"; if("poweron".equals(operation)){ runningState = "poweron"; }else if("shutdown".equals(operation)){ runningState = "poweroff"; } CmDevicePo vmVo = new CmDevicePo(); vmVo.setId(vmId); vmVo.setRunningState(runningState); iCmDeviceService.updateCmdeviceRunningState(vmVo); result = "success"; }else{ result = "fail"; } } } catch (Exception e) { result = e.getMessage(); logger.error("异常exception",e); } return result; } private String moveVM(String sourceCIp, String targetCIp, String vmId, String dataStoreName,String info) throws Exception { CmVmPo vmInfo = iCmDeviceService.findPowerInfoByVmId(vmId); if(vmInfo == null){ return null; } //遍历扫描所需信息,并进行查询 String hostId = vmInfo.getHostId(); String url = vmInfo.getManageIp(); String username = vmInfo.getUserName(); String password = vmInfo.getPassword(); if (StringUtils.isBlank(password)) throw new RollbackableBizException("获取HOST [" + username + "] password is null"); password = PwdUtil.decryption(password); String hostName = vmInfo.getHostName(); String vmName = vmInfo.getLparName(); String loginfo = "虚拟机名称:" + vmName; log.debug(loginfo); String result = ""; String[] infoList = info.split(";"); String tarHostId = infoList[0]; //目标lpar_id String dest_lpar_id = infoList[1]; //npiv光纤卡对应关系 String virtual_fc_mappings = infoList[2]; //vscsi光纤卡对应关系 String virtual_scsi_mappings = infoList[3]; //源vois lparID String source_msp_id = infoList[4]; //目标vois lparID String dest_msp_id = infoList[5]; CmDeviceHostShowBo cmDeviceHostShowBo = iCmDeviceService.getCmDeviceHostInfo(tarHostId); String destHostName = cmDeviceHostShowBo.getDevice_name(); try { //header HeaderDO header = HeaderDO.CreateHeaderDO(); header.setOperationBean("migratePowerLparImpl"); header.setResourceClass(EnumResouseHeader.PV_RES_CLASS.getValue()); header.setResourceType(EnumResouseHeader.PV_RES_TYPE.getValue()); header.set("DATACENTER_QUEUE_IDEN", rmDatacenterDAO.getDataCenterByHostId(hostId).getQueueIden()); System.out.println("rmDatacenterDAO.getDataCenterByHostId(hostId).getQueueIden(): "+rmDatacenterDAO.getDataCenterByHostId(hostId).getQueueIden()); //body BodyDO body = BodyDO.CreateBodyDO(); body.set(GeneralKeyField.Power.URL, url); body.set(GeneralKeyField.Power.USERNAME, username); body.set(GeneralKeyField.Power.PASSWORD, password); //源物理主机名称 源lpar所在物理机 body.set(GeneralKeyField.Power.HOST_NAME, hostName); //虚拟机名称 源lpar名字 body.set(GeneralKeyField.VM.VAPP_NAME, vmName); body.set(GeneralKeyField.Power.DEST_LPAR_ID,dest_lpar_id); body.set(GeneralKeyField.Power.VIRTUAL_FC_MAPPINGS, virtual_fc_mappings); body.set(GeneralKeyField.Power.VIRTUAL_SCSI_MAPPINGS, virtual_scsi_mappings); body.set("source_msp_id", source_msp_id); body.set("dest_msp_id", dest_msp_id); body.set(GeneralKeyField.Power.DEST_HOST_NAME, destHostName); //reqData IDataObject reqData = DataObject.CreateDataObject(); reqData.setDataObject(MesgFlds.HEADER, header); reqData.setDataObject(MesgFlds.BODY, body); IDataObject rspData = null; IResAdptInvoker invoker = resInvokerFactory.findInvoker("AMQ"); rspData = invoker.invoke(reqData, 1200000); if (rspData == null) { result = "请求响应失败!"; } else { HeaderDO rspHeader = rspData.getDataObject(MesgFlds.HEADER, HeaderDO.class); BodyDO rspBody = rspData.getDataObject(MesgFlds.BODY,BodyDO.class); if (MesgRetCode.SUCCESS.equals(rspHeader.getRetCode())) { result = "success"; }else{ result = "fail"; } } } catch (Exception e) { result = e.getMessage(); logger.error("异常exception",e); } return result; } @SuppressWarnings("unchecked") @Override public List<ScanResult> scanAndUpdateVmIndicator(List<CmDevicePo> vmPoList, String virtualTypeCode) throws Exception { String vmName = null; String hostId = null; String url = null; String username = null; String password = null; String hostName = null; List<String> vmNameList = new ArrayList<String>(); String vmId = null; List<ScanResult> resultList = new ArrayList<ScanResult>(); for (CmDevicePo devicePo : vmPoList) { vmName = devicePo.getDeviceName(); vmId = iCmDeviceService.findVmIdByName(vmName); CmVmPo vmInfo = iCmDeviceService.findPowerInfoByVmId(vmId); if(vmInfo == null){ return null; } //遍历扫描所需信息,并进行查询 hostId = vmInfo.getHostId(); url = vmInfo.getManageIp(); username = vmInfo.getUserName(); password = vmInfo.getPassword(); if (StringUtils.isBlank(password)) throw new RollbackableBizException("获取HOST [" + username + "] password is null"); password = PwdUtil.decryption(password); hostName = vmInfo.getHostName(); vmName = vmInfo.getLparName(); // 都使用lpar名称 String loginfo = "虚拟机名称:" + vmName; log.debug(loginfo); vmNameList.add(vmName); } try { //header HeaderDO header = HeaderDO.CreateHeaderDO(); header.setOperationBean("scanVMState"); header.setResourceClass(EnumResouseHeader.PV_RES_CLASS.getValue()); header.setResourceType(EnumResouseHeader.PV_RES_TYPE.getValue()); header.set("DATACENTER_QUEUE_IDEN", rmDatacenterDAO.getDataCenterByHostId(hostId).getQueueIden()); //body BodyDO body = BodyDO.CreateBodyDO(); body.set(GeneralKeyField.Power.URL, url); body.set(GeneralKeyField.Power.USERNAME, username); body.set(GeneralKeyField.Power.PASSWORD, password); body.set(GeneralKeyField.Power.HOST_NAME, hostName); body.set(GeneralKeyField.VM.VAPP_NAME, vmNameList); //reqData IDataObject reqData = DataObject.CreateDataObject(); reqData.setDataObject(MesgFlds.HEADER, header); reqData.setDataObject(MesgFlds.BODY, body); IDataObject rspData = null; IResAdptInvoker invoker = resInvokerFactory.findInvoker("AMQ"); rspData = invoker.invoke(reqData, 1200000); if (rspData == null) { return null; } else { HeaderDO rspHeader = rspData.getDataObject(MesgFlds.HEADER, HeaderDO.class); BodyDO rspBody = rspData.getDataObject(MesgFlds.BODY,BodyDO.class); if (MesgRetCode.SUCCESS.equals(rspHeader.getRetCode())) { DataObject hostData = (DataObject) rspBody.get("POWER_STATE"); DataObject vmData = (DataObject) hostData.get(hostName); for(String vmNme : vmNameList){ String state = (String) vmData.get(vmNme); //更新数据 CmDevicePo cmDevicePo = new CmDevicePo(); cmDevicePo.setId(iCmDeviceService.findVmIdByName(vmNme)); cmDevicePo.setRunningState(state); iCmDeviceService.updateCmdeviceRunningState(cmDevicePo); //返回数据 ScanResult sr = new ScanResult(); sr.setDeviceStatus(state); sr.setDeviceId(hostId); sr.setDeviceName(hostName); resultList.add(sr); } }else{ resultList = null; } } } catch (Exception e) { logger.error("异常exception",e); } return resultList; } }
package com.yuan.library.imagedialog; /** * yuan * 2020/2/14 **/ public interface OnImageClickListener { void onImageClickListener(); }
package com.renker.ws.service; public interface IExampleService { public String Hellow(String msg); }
package ir.ac.aut; import java.util.ArrayList; public class PcPlayer extends Player{ //the Color array which contains the index of every color private static COLOR[] nextPlayersColor={ COLOR.RED, COLOR.BLUE, COLOR.YELLOW, COLOR.GREEN }; /* Type of cards: -1)NumericCards 0)SkipCards 1)ReverseCards 2)Draw2Cards 3)WildDrawCards 4)WildCards */ //if a house of this array is 1 means that the right player of this PCPlayer doesn't have the specified Type of card private int[] rightPlayerTypeCards; //if a house of this array is 1 means that the right player of this PCPlayer doesn't have the specified Color of card private int[] rightPlayerColorCards; //if a house of this array is 1 means that the right player of this PCPlayer doesn't have the specified number of card (between numeric cards private int[] rightPlayerNumericCards; //if a house of this array is 1 means that the left player of this PCPlayer doesn't have the specified Type of card private int[] leftPlayerTypeCards; //if a house of this array is 1 means that the left player of this PCPlayer doesn't have the specified Color of card private int[] leftPlayerColorCards; //if a house of this array is 1 means that the left player of this PCPlayer doesn't have the specified number of card (between numeric cards private int[] leftPlayerNumericCards; /** * the consturctor of this class * @param name the name of the player * @param pcPlayersCards the array list containing the cards of this PCPlayer */ public PcPlayer(String name, ArrayList<Cart> pcPlayersCards){ super(name, pcPlayersCards); rightPlayerTypeCards = new int[5]; rightPlayerColorCards = new int[4]; rightPlayerNumericCards = new int[10]; leftPlayerTypeCards = new int[5]; leftPlayerColorCards = new int[4]; leftPlayerNumericCards = new int[10]; for(int i=0 ; i<4 ; i++){ rightPlayerColorCards[i]=0; leftPlayerColorCards[i]=0; } for(int i=0; i<5; i++){ leftPlayerTypeCards[i]=0; rightPlayerTypeCards[i]=0; } for(int i=0; i<10; i++){ leftPlayerNumericCards[i]=0; rightPlayerNumericCards[i]=0; } //since at the start of the game we dont know anything about the players at first its holds only zero numbers } /** * a function that returns the number of wild Cards * @return */ private int numWildCards(){ int wildCarts = 0; for(int i=0; i<playersCarts.size(); i++){ if( playersCarts.get(i) instanceof WildCart){ wildCarts++; } } return wildCarts; } /** * a method to get the number of Wild Draw crads * @return number of wild draw cards */ private int numWildDrawCards(){ int wildCarts = 0; for(int i=0; i<playersCarts.size(); i++){ if(playersCarts.get(i) instanceof WildDrawCart ){ wildCarts++; } } return wildCarts; } /** * this method should choose a card between its card and return it after removing it * @param lastCartPlayed the last played cart in the game * @param clockWise the type of rotation in the game * @return the Cart choosen */ public Cart aiPlayCart(Cart lastCartPlayed, boolean clockWise, int numNextPlayersCards){ System.out.println("the "+namePlayer+" carts:"); printCarts(lastCartPlayed); System.out.println("info ai:"); int chosenCart=aiChose(lastCartPlayed, clockWise, numNextPlayersCards); if(chosenCart==-1){ //no carts available to play return null; }else{ Cart playedCart = playersCarts.get(chosenCart); playersCarts.remove(chosenCart); return playedCart; } } /** * this is the ai method which using the information plays a draw+2 card * @return */ @Override public Cart playDraw2Cart(){ //this method is a defense method for the player to defend itself against a draw+2 cart //and its called only if we are sure that there actually exists a draw+2 cart in his hand, but anyway if(numDraw2Carts() == 0){ return null; } for(int i=0; i<playersCarts.size(); i++){ if(playersCarts.get(i) instanceof Draw2Cart){ Cart thisCard = playersCarts.get(i); playersCarts.remove(i); return thisCard; } } return null; } /** * this method is for this player to play with specifically WildDraw cards * @return */ @Override public Cart playWildDrawCart(){ //this method is a defense method for the player to defend itself against a draw+2 cart //and its called only if we are sure that there actually exists a WildDraw+4 cart in his hand, but anyway if(numWildDrawCarts()==0){ return null; } Cart temp; for(int i=0; i<playersCarts.size(); i++){ if(playersCarts.get(i) instanceof WildDrawCart){ temp = playersCarts.get(i); playersCarts.remove(i); return temp; } } return null; } /** * this is the main ai method for choosing the next card * @param lastPlayedCart * @param clockWise * @return */ private int aiChose(Cart lastPlayedCart, boolean clockWise, int numNextPlayersCards) { int canPlayNum = numPlayableNormalCarts(lastPlayedCart); if (canPlayNum == 0) { canPlayNum = numWildCards() + numWildDrawCards(); if (canPlayNum == 0) { System.out.println("this (bot) player can't play"); return -1; } else { //has to play a wild kinded cart return choseWildKindCard( numNextPlayersCards); } } System.out.println(); int[] container = new int[playersCarts.size()]; int exp = 0; for (int i = 0; i < playersCarts.size(); i++) { if ((playersCarts.get(i) instanceof WildDrawCart || playersCarts.get(i) instanceof WildCart)) { continue; } else if (playersCarts.get(i).canPlayCart(lastPlayedCart)) { container[exp] = i; //holds the index of the available cards exp++; } } //now we have an array of the cards(index) we are able to play with the size of exp int[] points= new int[exp]; for(int i=0; i<exp; i++){ points[i]=playersCarts.get(container[i]).getPoint(); if(playersCarts.get(container[i]) instanceof Draw2Cart){ if(numNextPlayersCards<4){ points[i]+=10; } points[i]+=probabilityNextPlayer(clockWise, 2, playersCarts.get(container[i]).getColor().ordinal(), -1); }else if(playersCarts.get(container[i]) instanceof NumericCart){ points[i]+=probabilityNextPlayer(clockWise, -1, playersCarts.get(container[i]).getColor().ordinal(), ((NumericCart) playersCarts.get(container[i])).getNumber()); }else if(playersCarts.get(container[i]) instanceof ReverseCart){ if(numNextPlayersCards<3){ points[i]+=10; } points[i]+=probabilityNextPlayer(clockWise, 1, playersCarts.get(container[i]).getColor().ordinal(),-1); }else if(playersCarts.get(container[i]) instanceof SkipCart){ if(numNextPlayersCards<3){ points[i]+=10; } points[i]+=probabilityNextPlayer(clockWise, 0, playersCarts.get(container[i]).getColor().ordinal(),-1); } } int maxPoint=-1; int indexMaxPoint=-1; for(int i=0; i<exp; i++){ if(maxPoint<points[i]){ maxPoint=points[i]; indexMaxPoint=i; } } return container[indexMaxPoint]; } /** * a method to choose a wild kind card if available in case you cannot play any other card of your hand * @param numNextPlayersCards the number of the next players cards * @return */ private int choseWildKindCard(int numNextPlayersCards){ //this method should choose the index of the wild kinded card choosen card if(numWildDrawCards()==0){ //wild cards for(int i=0; i<playersCarts.size(); i++){ if(playersCarts.get(i) instanceof WildCart){ return i; } } }else if(numWildCards()==0){ // Wild Draw cards for(int i=0; i<playersCarts.size(); i++){ if(playersCarts.get(i) instanceof WildDrawCart){ return i; } } }else { //can play both if (numNextPlayersCards < 7 ){ for (int i = 0; i < playersCarts.size(); i++) { if (playersCarts.get(i) instanceof WildDrawCart) { return i; } } } for (int i = 0; i < playersCarts.size(); i++) { if (playersCarts.get(i) instanceof WildCart) { return i; } } } //will never come this far because we are sure we have Wild-kinded carts in our hand return -1; } /** * the probability of the next player to not have a card(Type, color, number-if numeric) * @param clockWise kind of rotation in the game * @param typeCard the type of card * @param colorCard the color of the card played * @param indexNumber the number -in case its a numeric card- * @return this method will return a number(0, 5, 10) : the probability of not having a card */ private int probabilityNextPlayer(boolean clockWise, int typeCard, int colorCard, int indexNumber){ int answer =0; //the type if(indexNumber==-1) { //not a numeric card if (clockWise) { //left player is the next player if (leftPlayerTypeCards[typeCard] > 0) { //the left player doesnt have this type of card answer+=5; } } else { //the right player is the next player if (rightPlayerTypeCards[typeCard] > 0) { //the right player doesnt have this type of card answer+=5; } } }else{ //its a numeric card if(clockWise){ //left player is the next player if(leftPlayerNumericCards[indexNumber]>0){ //the left player doesnt have this type of card answer+=5; } }else{ //right player is the next player if(rightPlayerNumericCards[indexNumber]>0){ //the left player doesnt have this type of card answer+=5; } } } if(colorCard==-1){ //was a wild kinded card if(answer==5){ return 10; } return 0; }else { //the color if (clockWise) { //the left player is the next player if (leftPlayerColorCards[colorCard] > 0) { answer += 5; } } else { //the right player is the next player if (rightPlayerColorCards[colorCard] > 0) { answer += 5; } } return answer; } } /** * a method for updating the information about the right player * @param lastCard the last played card * @param lastPlayed a boolean to specify if the last player played a card * @param hasWild a boolean to specify if the player has wild kind card */ public void updateInfoRight(Cart lastCard, boolean lastPlayed, boolean hasWild){ //when a player doesn't have anything to play after a cart means that player doesn't have that Type of card and that color and doesn't have Wild kind cards either if(lastCard instanceof Draw2Cart){ //doesnt have that type of card rightPlayerTypeCards[2]=1; if(!hasWild) { //doesnt have any wild kind card rightPlayerTypeCards[3] = 1; rightPlayerTypeCards[4] = 1; } rightPlayerColorCards[lastCard.getColor().ordinal()]=1; }else if(lastCard instanceof NumericCart){ rightPlayerNumericCards[((NumericCart) lastCard).getNumber()]=1; if(!hasWild) { //doesnt have any wild kind card rightPlayerTypeCards[3] = 1; rightPlayerTypeCards[4] = 1; } rightPlayerColorCards[lastCard.getColor().ordinal()]=1; }else if(lastCard instanceof ReverseCart){ rightPlayerTypeCards[1]=1; if(!hasWild) { //doesnt have any wild kind card rightPlayerTypeCards[3] = 1; rightPlayerTypeCards[4] = 1; } rightPlayerColorCards[lastCard.getColor().ordinal()]=1; }else if(lastCard instanceof SkipCart){ //the second player after the one who played the skip card rightPlayerTypeCards[0]=1; if(!hasWild) { //doesnt have any wild kind card rightPlayerTypeCards[3] = 1; rightPlayerTypeCards[4] = 1; } rightPlayerColorCards[lastCard.getColor().ordinal()]=1; }else if(lastCard instanceof WildCart){ if(!hasWild) { //doesnt have any wild kind card rightPlayerTypeCards[3] = 1; rightPlayerTypeCards[4] = 1; } rightPlayerColorCards[Game.getBaseColor().ordinal()]=1; }else if(lastCard instanceof WildDrawCart) { if(!hasWild) { //doesnt have any wild kind card rightPlayerTypeCards[3] = 1; rightPlayerTypeCards[4] = 1; } //the next statement is only for the second player after the one who played if (!lastPlayed){ rightPlayerColorCards[Game.getBaseColor().ordinal()] = 1; } } return; } /** * a method for updating the information about the left player * @param lastCard the last played card * @param lastPlayed a boolean to specify if the last player played a card * @param hasWild a boolean to specify if the player has wild kind card */ public void updateInfoLeft(Cart lastCard, boolean lastPlayed, boolean hasWild){ //when a player doesn't have anything to play after a cart means that player doesn't have that Type of card and that color and doesn't have Wild kind cards either if(lastCard instanceof Draw2Cart){ //doesnt have that type of card leftPlayerTypeCards[2]=1; if(hasWild==false) { //doesnt have any wild kind card leftPlayerTypeCards[3] = 1; leftPlayerTypeCards[4] = 1; } leftPlayerColorCards[lastCard.getColor().ordinal()]=1; }else if(lastCard instanceof NumericCart){ leftPlayerNumericCards[((NumericCart) lastCard).getNumber()]=1; if(hasWild==false) { //doesnt have any wild kind card leftPlayerTypeCards[3] = 1; leftPlayerTypeCards[4] = 1; } leftPlayerColorCards[lastCard.getColor().ordinal()]=1; }else if(lastCard instanceof ReverseCart){ leftPlayerTypeCards[1]=1; if(hasWild==false) { //doesnt have any wild kind card leftPlayerTypeCards[3] = 1; leftPlayerTypeCards[4] = 1; } leftPlayerColorCards[lastCard.getColor().ordinal()]=1; }else if(lastCard instanceof SkipCart){ //the second player after the one who played the skip card leftPlayerTypeCards[0]=1; if(hasWild==false) { //doesnt have any wild kind card leftPlayerTypeCards[3] = 1; leftPlayerTypeCards[4] = 1; } leftPlayerColorCards[lastCard.getColor().ordinal()]=1; }else if(lastCard instanceof WildCart){ if(hasWild==false) { //doesnt have any wild kind card leftPlayerTypeCards[3] = 1; leftPlayerTypeCards[4] = 1; } leftPlayerColorCards[Game.getBaseColor().ordinal()]=1; }else if(lastCard instanceof WildDrawCart) { if(hasWild==false) { //doesnt have any wild kind card leftPlayerTypeCards[3] = 1; leftPlayerTypeCards[4] = 1; } //the next statement is only for the second player after the one who played if (!lastPlayed){ leftPlayerColorCards[Game.getBaseColor().ordinal()] = 1; } } return; } /** * a method for deleting all the info about a player because the specified player has new cards in his hands * for the right player */ public void addedCardToRightPlayer(){ for(int i=0; i<4; i++){ rightPlayerColorCards[i]=0; } for(int i=0; i<10; i++){ rightPlayerNumericCards[i]=0; } for(int i=0; i<5; i++){ rightPlayerTypeCards[i]=0; } } /** * a method for deleting all the info about a player because the specified player has new cards in his hands * for the left player */ public void addedCardToLeftPlayer(){ for(int i=0; i<4; i++){ leftPlayerColorCards[i]=0; } for(int i=0; i<10; i++){ leftPlayerNumericCards[i]=0; } for(int i=0; i<5; i++){ leftPlayerTypeCards[i]=0; } } /** * a method to choose the color of the board after playing a wild card * @param clockWise the kind of rotation in the game * @return the color chosen */ public COLOR getColorAi(boolean clockWise){ double[] choice =new double[4]; for(int i=0; i<4; i++){ //if the player has that color better is for that player to chose the base color of the board that color choice[i]=getAiColorRepetition(COLOR.getColorByIndex(i)); if(clockWise) { choice[i] +=leftPlayerColorCards[i]; }else{ choice[i] +=rightPlayerColorCards[i]; } } double max=-1; COLOR color= null; for(int i=0; i<4; i++){ if(max<choice[i]){ color=nextPlayersColor[i]; max=choice[i]; } } return color; } /** * get the number of repetition of each color in probability * @param color the color * @return the probability in double */ private double getAiColorRepetition(COLOR color){ double num = 0; double total = (double) playersCarts.size(); for(int i=0; i<playersCarts.size(); i++){ if(playersCarts.get(i) instanceof WildDrawCart || playersCarts.get(i) instanceof WildCart){ continue; } if(playersCarts.get(i).getColor().equals(color)){ num++; } } return (num/total); } }
package io.github.ihongs.action.serv; import io.github.ihongs.Core; import io.github.ihongs.CoreSerial; import io.github.ihongs.HongsException; import io.github.ihongs.HongsExemption; import io.github.ihongs.action.ActionHelper; import io.github.ihongs.action.ActionDriver; import io.github.ihongs.action.NaviMap; import io.github.ihongs.util.Dawn; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 权限信息输出动作 * * <h3>web.xml配置:</h3> * <pre> * &lt;servlet&gt; * &lt;servlet-name&gt;JsAuth&lt;/servlet-name&gt; * &lt;servlet-class&gt;io.github.ihongs.action.JSAuthAction&lt;/servlet-class&gt; * &lt;/servlet&gt; * &lt;servlet-mapping&gt; * &lt;servlet-name&gt;JsAuth&lt;/servlet-name&gt; * &lt;url-pattern&gt;/common/auth/*&lt;/url-pattern&gt; * &lt;/servlet-mapping&gt; * </pre> * * @author Hongs */ public class AuthAction extends ActionDriver { /** * 服务方法 * 判断配置和消息有没有生成, 如果没有则生成; 消息按客户语言存放 * @param req * @param rsp * @throws java.io.IOException * @throws javax.servlet.ServletException */ @Override public void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { /* // 2020/05/14 通过配置和用户的修改时间来判断是否能有变化 // 受是否登录、不同用户等影响, 权限经常变化, 必须禁止缓存 rsp.setHeader("Expires", "0"); rsp.addHeader("Pragma" , "no-cache"); rsp.setHeader("Cache-Control", "no-cache"); */ Core core = ActionDriver.getActualCore(req ); ActionHelper helper = core.get(ActionHelper.class); String name = req.getPathInfo(); if (name == null || name.length() == 0) { helper.error400("Path info required"); return; } int p = name.lastIndexOf( '.' ); if (p < 0) { helper.error400("File type required"); return; } String type = name.substring(1 + p); name = name.substring(1 , p); if (!"js".equals(type) && !"json".equals(type)) { helper.error400( "Wrong file type: " + type); return; } String s; try { NaviMap sitemap = NaviMap.getInstance(name); Set<String> roleset = sitemap.getRoleSet( ); Set<String> authset ; // 没有设置 rsname 的不公开 if (null == sitemap.session) { helper.error404("Auth data for '"+name+"' is not open to the public"); return; } // HTTP 304 缓存策略 if (roleset instanceof CoreSerial.Mtimes) { CoreSerial.Mtimes rolemod = (CoreSerial.Mtimes) roleset; long l = Math.max( sitemap.dataModified(), rolemod.dataModified() ); long m = helper.getRequest( ).getDateHeader( "If-Modified-Since" ); if ( l != 0 ) { // HTTP 时间精确到秒 l = l / 1000; m = m / 1000; if ( m >= l ) { helper.getResponse().setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } else { helper.getResponse().setHeader( "Cache-Control", "no-cache" ); helper.getResponse().setDateHeader("Last-Modified", l * 1000); }} } Map<String, Boolean> datamap = new HashMap(); if (null == roleset) authset = new HashSet(); else authset = sitemap.getRoleAuths(roleset.toArray(new String[]{})); for(String act : sitemap.actions) { datamap.put( act , authset.contains(act) ); } s = Dawn.toString(datamap); } catch (HongsException | HongsExemption ex) { if (ex.getErrno() == 920) { // 配置缺失 helper.error404(ex.getMessage()); } else { helper.error500(ex.getMessage()); } return; } catch (IllegalArgumentException ex ) { helper.error500(ex.getMessage( )); return; } // 输出权限信息 if ("json".equals(type)) { helper.print(s, "application/json"); } else { String c = req.getParameter("callback"); if (c != null && c.length( ) != 0 ) { if (!c.matches("^[a-zA-Z_\\$][a-zA-Z0-9_]*$")) { helper.error400("Illegal callback function name!"); return; } helper.print(c+"("+s+");", "text/javascript" ); } else { helper.print("if(!self.HsAUTH)self.HsAUTH={};Object.assign(self.HsAUTH,"+s+");", "text/javascript"); } } } }