text
stringlengths
10
2.72M
package com.taimoor.mapstruct.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * @author Taimoor Choudhary */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Education { private String degreeName; private String institute; private Integer yearOfPassing; }
package model; public interface CModel { }
package sysinfo.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import sysinfo.model.Kelas; @RepositoryRestResource(collectionResourceRel = "kelas", path = "kelas") public interface KelasRepository extends JpaRepository<Kelas, Integer> { }
package com.smart.droidies.tamil.natkati.library.util; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.List; public class AuspiciousDays { private int year; private int month; private List<Festive> auspiciousDays; private List<Festive> monthAuspiciousDays; public List<Festive> getAuspiciousDays() { return auspiciousDays; } public void setAuspiciousDays(List<Festive> auspiciousDays) { this.auspiciousDays = auspiciousDays; } public AuspiciousDays(int pYear) { this.year = pYear; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public List<Festive> getMonthAuspiciousDays() { return monthAuspiciousDays; } public void setMonthAuspiciousDays(List<Festive> monthAuspiciousDays) { this.monthAuspiciousDays = monthAuspiciousDays; } public void processMonthAuspicious(int iDispMonth) { this.month = iDispMonth; if (auspiciousDays.size() > 0) { monthAuspiciousDays = new ArrayList<Festive>(); Iterator<Festive> itFestive = auspiciousDays.iterator(); while (itFestive.hasNext()) { Festive festive = (Festive) itFestive.next(); if (festive.getFestiveDate().getMonth() == iDispMonth - 1) { monthAuspiciousDays.add(festive); } } } } public List<Festive> getAuspiciousList(Calendar calActiveDay) { List<Festive> listAuspicious = null; String strXMLDate = TamizUtil.getFestiveXMLDate(calActiveDay); if (calActiveDay == null) { return null; } if (month == calActiveDay.get(Calendar.MONTH)) { // TODO - Implement this check later if required } if (monthAuspiciousDays != null && monthAuspiciousDays.size() > 0) { Iterator<Festive> itAuspicious = monthAuspiciousDays.iterator(); while (itAuspicious.hasNext()) { Festive festive = (Festive) itAuspicious.next(); if (strXMLDate.equals(festive.getXmlDate())) { if (listAuspicious == null) { listAuspicious = new ArrayList<Festive>(); } listAuspicious.add(festive); } } } return listAuspicious; } }
package edu.neu.ccs.cs5010; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class RecommendationSystem { private static GetUserInfo getUserInfo; private static FollowerGraph followerGraph; private static Recommend recommend; private static UserVertex[] userVertexList; private static Users[] userList; private static List<int[]> edges; private static HashSet<Integer> newUserRecommend; private static HashSet<Integer> friendOfFriend; private static HashSet<Integer> influenceUser; public static void setRecommend1(String nodeFile, String edgeFile) throws IOException { newUserRecommend = new HashSet<>(); getUserInfo = new GetUserInfo(); userList = getUserInfo.getInfo(nodeFile); edges = getUserInfo.getEdge(edgeFile); followerGraph = new FollowerGraph(); userVertexList = followerGraph.createFollowerGraph(userList,edges); recommend = new Recommend(); for(int i = 0; i< userVertexList.length; i++) { newUserRecommend = recommend.findTheMostOne(userVertexList,userVertexList[i]); Users[] recomendArray = hashSetToUserArray(userList,newUserRecommend); //System.out.println(newUserRecommend); GenerateFile generateFile = new GenerateFile(); generateFile.writeFile(recomendArray,"recommend1" + " " + userVertexList[i].getUserID()); } } public static void setRecommend2(String nodeFile, String edgeFile) throws IOException { friendOfFriend = new HashSet<>(); getUserInfo = new GetUserInfo(); userList = getUserInfo.getInfo(nodeFile); edges = getUserInfo.getEdge(edgeFile); followerGraph = new FollowerGraph(); userVertexList = followerGraph.createFollowerGraph(userList,edges); recommend = new Recommend(); for(int i = 0; i < userVertexList.length; i++){ friendOfFriend = recommend.friendOfFriend(userVertexList,userVertexList[i]); Users[] friendOfFriendArray = hashSetToUserArray(userList,friendOfFriend); GenerateFile generateFile = new GenerateFile(); generateFile.writeFile(friendOfFriendArray,"recommend2" + " " + userVertexList[i].getUserID()); } } public static void setRecommend3(String nodeFile, String edgeFile) throws IOException { influenceUser = new HashSet<>(); getUserInfo = new GetUserInfo(); userList = getUserInfo.getInfo(nodeFile); edges = getUserInfo.getEdge(edgeFile); followerGraph = new FollowerGraph(); userVertexList = followerGraph.createFollowerGraph(userList,edges); recommend = new Recommend(); for(int i = 0; i < userVertexList.length; i++){ influenceUser = recommend.followInfluencer(userVertexList); Users[] influenceArray = hashSetToUserArray(userList,influenceUser); GenerateFile generateFile = new GenerateFile(); //generateFile.createFileDir("testFile"); //FileWriter fileWriter = new FileWriter("testFile"); generateFile.writeFile(influenceArray,"testFile"); } } public static Users[] hashSetToUserArray(Users[] userList, HashSet<Integer> set){ Users[] userArray = new Users[set.size()]; int j = 0; List<Integer> userIDList = new ArrayList(new HashSet(set)); for(int i = 0; i < userList.length; i++) { for (Integer IDnum : userIDList) { if (IDnum == userList[i].getUsersID()){ userArray[j] = userList[i]; j ++; } } } System.out.println(userArray); return userArray; } public static void main(String[] args) throws IOException { //setRecommend1("nodes_small.csv","edges_small copy.csv"); //setRecommend2("nodes_small.csv","edges_small copy.csv"); setRecommend3("nodes_small.csv","edges_small copy.csv"); } }
/* * 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 FileIO; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author YNZ */ public class OutputStreams { public static void main(String[] args) { try (FileOutputStream fileOutputStream = new FileOutputStream(new File("OutputStream.txt"), true)) { char c = 'a'; for (int i = 0; i < 10; i++) { fileOutputStream.write(c++); } } catch (IOException ex) { Logger.getLogger(OutputStreams.class.getName()).log(Level.SEVERE, null, ex); } } }
package com.zantong.mobilecttx.api; /** * Created by Administrator on 2016/5/5. */ public interface OnLoadServiceBackUI { void onSuccess(Object clazz, int index); void onFailed(); }
package com.containers.repository; import com.containers.model.Damage; import org.springframework.data.jpa.repository.JpaRepository; public interface DamageRepository extends JpaRepository<Damage, Long> { }
package org.antran.saletax.internal; import static org.junit.Assert.assertEquals; import org.antran.saletax.api.Categories; import org.antran.saletax.api.IAmount; import org.antran.saletax.api.ICart; import org.antran.saletax.api.ICartCalculator; import org.junit.Test; public class SaleTaxCalculatorTest { @Test public void shouldCalculateSaleTax() { // given ICart cart = new Cart(); cart.add(new Product("12.49", Categories.BOOK), 1); cart.add(new Product("14.99"), 1); cart.add(new Product("0.85", Categories.FOOD), 1); // when ICartCalculator calculator = new CalculatorFactory().saleTaxCaculator(); IAmount saleTax = calculator.calculate(cart); // then assertEquals(new Amount("1.50"), saleTax); } @Test public void shouldCalculateSaleTaxWithImportedProduct() { // given ICart cart = new Cart(); cart.add(new Product("10.00", Categories.FOOD, true), 1); cart.add(new Product("47.50", Categories.OTHER, true), 1); // when ICartCalculator calculator = new CalculatorFactory().saleTaxCaculator(); IAmount saleTax = calculator.calculate(cart); // then assertEquals(new Amount("7.65"), saleTax); } @Test public void shouldCalculateSaleTaxWithImportedProduct_2() { // given ICart cart = new Cart(); cart.add(new Product("27.99", Categories.OTHER, true), 1); cart.add(new Product("18.99", Categories.OTHER), 1); cart.add(new Product("9.75", Categories.MEDICAL), 1); cart.add(new Product("11.25", Categories.FOOD, true), 1); // when ICartCalculator calculator = new CalculatorFactory().saleTaxCaculator(); IAmount saleTax = calculator.calculate(cart); // then assertEquals(new Amount("6.70"), saleTax); } }
import java.rmi.Remote; public interface MiInterfazRemota extends Remote { public void miMetodo1() throws java.rmi.RemoteException; public int miMetodo2() throws java.rmi.RemoteException; }
package com.accenture.test.assesment.entites; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "AWS_CLOUD") public class AwsCloud { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") private int id; @Column(name = "AWSFEATURE") private String awsFeature; @Column(name = "AWSFEATUREDESCRIPTION") private String awsFeatureDescription; @Column(name = "FEATURETYPE") private String featureType; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAwsFeature() { return awsFeature; } public void setAwsFeature(String awsFeature) { this.awsFeature = awsFeature; } public String getAwsFeatureDescription() { return awsFeatureDescription; } public void setAwsFeatureDescription(String awsFeatureDescription) { this.awsFeatureDescription = awsFeatureDescription; } public String getFeatureType() { return featureType; } public void setFeatureType(String featureType) { this.featureType = featureType; } @Override public String toString() { return "AwsCloud [id=" + id + ", awsFeature=" + awsFeature + ", awsFeatureDescription=" + awsFeatureDescription + ", featureType=" + featureType + "]"; } }
// ----------------------------------------------------- // Assignment #4 // // Written by: Alexandre Kang, 40027204 // ----------------------------------------------------- package package1; public class Students extends Employees{ public static enum status {undergraduate, graduate, alumni}; private status classification; private double rate; private final double UD_TA_rate = 18.25; private final double GD_TA_rate = 1.2*UD_TA_rate; private int numberOfClasses; private int totalNumberOfWorkingHours; public Students() { super(); classification = status.undergraduate; rate = UD_TA_rate; numberOfClasses = 0; totalNumberOfWorkingHours = 0; } public Students(long i, String fiName, String faName, String c, int y, status ta, int cl, int w) { super(i,fiName,faName,c,y); if (ta==status.undergraduate) { this.classification = status.undergraduate; rate = UD_TA_rate; } if (ta==status.graduate) { this.classification = status.graduate; rate = GD_TA_rate; } if (ta!=(status.undergraduate) || (ta!=status.graduate)) { System.out.print("Error"); } numberOfClasses = cl; totalNumberOfWorkingHours = w; } public Students(Students s) { setId(s.getId()); setFirstName(s.getFirstName()); setFamilyName(s.getFamilyName()); setCity(s.getCity()); setHireYear(s.getHireYear()); if (s.getClassification()==status.undergraduate) { s.classification = status.undergraduate; rate = UD_TA_rate; } if (s.getClassification()==status.graduate) { s.classification = status.graduate; rate = GD_TA_rate; } if (s.getClassification()!=(status.undergraduate) || (s.getClassification()!=status.graduate)) { System.out.print("Error"); } numberOfClasses = s.numberOfClasses; totalNumberOfWorkingHours = s.totalNumberOfWorkingHours; } public status getClassification() { return classification; } public void setSt(status ta) { if (ta==status.undergraduate) { this.classification = status.undergraduate; rate = UD_TA_rate; } if (ta==status.graduate) { this.classification = status.graduate; rate = GD_TA_rate; } if (ta!=(status.undergraduate) || (ta!=status.graduate)) { System.out.print("Error"); } } public int getNumberOfClasses() { return numberOfClasses; } public void setNumberOfClasses(int c) { this.numberOfClasses = c; } public int getTotalNumberOfWorkingHours() { return totalNumberOfWorkingHours; } public void setTotalNumberOfWorkingHours(int w) { this.totalNumberOfWorkingHours = w; } public String toString() { return super.toString() + "\nClassification: " + getClassification() + "\nNumber Of Classes: " + getNumberOfClasses() + "\nNumber Of Working Hours: " + getTotalNumberOfWorkingHours(); } }
package com.birivarmi.birivarmiapp.model; public enum MetaFieldType { TEXT("TEXT"), TEXTAREA("TEXTAREA"), DROPDOWN("DROPDOWN"), RADIO("RADIO"), CHECKBOX("CHECKBOX"), URL("URL"), DATE("DATE"), DATEINTERVAL("DATEINTERVAL"); private final String type; private MetaFieldType(String type){ this.type = type; } public String getType(){ return this.type; } }
package com.alex.eat; public class BasketEggsArray implements Weigh { private Eggs[] eggses; private int index; private int size; public BasketEggsArray(int size) { this.eggses = new Eggs[size]; this.size = size; this.index = -1; } public void addEggs(Eggs eggs) { if (index < size - 1) { index = index + 1; this.eggses[index] = eggs; } else { System.out.println("Sorry basket is full!"); } } public Eggs getEggs() { if (index >= 0) { Eggs eggs = eggses[index]; index = index - 1; return eggs; } else { throw new IllegalStateException("Sorry, no eggses in basket!"); } } @Override public int getWeight() { int sum = 0; //1variant // for (int i = 0; i < eggses.length; i++) { // Eggs currentEggs = eggses[i]; // if (currentEggs != null) { // sum = sum + eggses[i].getWeight(); // } // } //2 variant // for (int i = 0; i < getCurrentSize(); i++) { // sum = sum + eggses[i].getWeight(); // } //3 variant for (Eggs eggs : eggses) { if (eggs != null) { sum = sum + eggs.getWeight(); } } return sum; } public Eggs[] getEggses() { return eggses; } public int getCurrentSize() { return index + 1; } }
package com.mpls.v2.service.impl; import com.mpls.v2.dto.GroupFullDTO; import com.mpls.v2.dto.GroupShortDTO; import com.mpls.v2.model.Group; import com.mpls.v2.model.User; import com.mpls.v2.repository.GroupRepository; import com.mpls.v2.service.GroupService; import com.mpls.v2.service.UserService; import com.mpls.v2.service.exceptions.FindException; import com.mpls.v2.service.exceptions.IdException; import com.mpls.v2.service.exceptions.SaveException; import com.mpls.v2.service.exceptions.UpdateException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import static com.mpls.v2.dto.utils.builder.Builder.map; @Service public class GroupServiceImpl implements GroupService{ @Autowired GroupRepository groupRepository; @Autowired UserService userService; @Override public Group save(Group group) { if (group != null) { return groupRepository.save(group); }else{ throw new SaveException("Group must be not null"); } } @Override public Group update(Group group) { if (group.getId() == null || group.getId() < 1) throw new UpdateException(" invalid id GroupService"); else if (groupRepository.findOne(group.getId()) == null) throw new UpdateException(" there are no group with such id GroupService"); try { return groupRepository.save(group); } catch (Exception e) { throw new UpdateException("GroupService"); } } @Override public Group update(GroupShortDTO groupShortDTO) { Group group; if (groupShortDTO.getId() == null || groupShortDTO.getId() < 1) throw new UpdateException(" invalid id GroupService"); else if ((group= groupRepository.findOne(groupShortDTO.getId())) == null) throw new UpdateException(" there are no group with such id "); try { return groupRepository.save(map(groupShortDTO,Group.class).setUsers(group.getUsers())); } catch (Exception e) { throw new UpdateException("GroupService"); } } @Override public Group update(GroupFullDTO groupFullDTO) { return update(map(groupFullDTO,Group.class)); } @Override public List<Group> findAll() { return groupRepository.findAll(); } @Override public Group findOne(Long id) { if (id != null || id >= 0) { return groupRepository.findOne(id); } else { throw new IdException("id must be not null"); } } @Override public Boolean delete(Long id) { if (id != null || id >= 0) { try { groupRepository.delete(groupRepository.findOne(id)); return true; } catch (Exception e) { return false; } } else { throw new IdException("id must be not null"); } } @Override public Group findByName(String name) { if (name != null) { return groupRepository.findByName(name); } else { throw new FindException("name must be not null"); } } }
package com.delrima.webgene.server.servlet; import javax.servlet.ServletException; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.delrima.webgene.client.common.Action; import com.delrima.webgene.client.common.ActionException; import com.delrima.webgene.client.common.Result; import com.delrima.webgene.client.rpc.ActionHandlerService; import com.delrima.webgene.server.services.ActionHandlerServiceImpl; import com.google.gwt.user.server.rpc.RemoteServiceServlet; @SuppressWarnings("serial") public class ActionHandlerServiceServlet extends RemoteServiceServlet implements ActionHandlerService<Result> { private ActionHandlerService<Result> dispatchService; @SuppressWarnings("unchecked") @Override public void init() throws ServletException { // initialize super class super.init(); // retrieve dispatch service dependency WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); this.dispatchService = context.getBean(ActionHandlerServiceImpl.class); } @Override public Result execute(Action<Result> action) throws ActionException { return dispatchService.execute(action); } }
package com.sinodynamic.hkgta.dao.memberapp; import org.springframework.stereotype.Repository; import com.sinodynamic.hkgta.dao.GenericDao; import com.sinodynamic.hkgta.entity.rpos.CandidateCustomer; @Repository public class CandidateCustomerDaoImpl extends GenericDao<CandidateCustomer> implements CandidateCustomerDao { }
/* * 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.jclouds.rackspace.cloudbigdata.v1; import java.io.Closeable; import java.util.Set; import org.jclouds.location.Region; import org.jclouds.location.functions.RegionToEndpoint; import org.jclouds.rackspace.cloudbigdata.v1.features.ClusterApi; import org.jclouds.rackspace.cloudbigdata.v1.features.ProfileApi; import org.jclouds.rest.annotations.Delegate; import org.jclouds.rest.annotations.EndpointParam; import com.google.inject.Provides; /** * Provides access to the Rackspace Cloud Big Data v1 API. * * Rackspace Cloud Big Data is an on-demand Apache Hadoop service on the Rackspace open cloud. The service * supports a RESTful API and alleviates the pain associated with deploying, managing, and scaling Hadoop clusters. */ public interface CloudBigDataApi extends Closeable { /** * Provides a set of all regions available. * * @return the Region codes configured */ @Provides @Region Set<String> getConfiguredRegions(); /** * Provides access to all Profile features. * @param region The region for the profile API. * @return A profile API context. */ @Delegate ProfileApi getProfileApi(@EndpointParam(parser = RegionToEndpoint.class) String region); /** * Provides access to all Cluster features. * @param region The region for the profile API. * @return A cluster API context. */ @Delegate ClusterApi getClusterApi(@EndpointParam(parser = RegionToEndpoint.class) String region); /** * @return the Zone codes configured * @deprecated Please use {@link #getConfiguredRegions()} instead. To be removed in jclouds 2.0. */ @Deprecated @Provides @Region Set<String> getConfiguredZones(); /** * Provides access to all Profile features. * @param zone The zone (region) for the profile API. * @return A profile API context. * @deprecated Please use {@link #getProfileApi(String)} instead. To be removed in jclouds 2.0. */ @Deprecated @Delegate ProfileApi getProfileApiForZone(@EndpointParam(parser = RegionToEndpoint.class) String zone); /** * Provides access to all Cluster features. * @param zone The zone (region) for the profile API. * @return A cluster API context. * @deprecated Please use {@link #getClusterApi(String)} instead. To be removed in jclouds 2.0. */ @Deprecated @Delegate ClusterApi getClusterApiForZone(@EndpointParam(parser = RegionToEndpoint.class) String zone); }
package com.oa.bbs.service; import java.util.List; import org.directwebremoting.annotations.RemoteMethod; import org.directwebremoting.annotations.RemoteProxy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.oa.bbs.dao.ForumDao; import com.oa.bbs.form.Forum; import com.oa.page.form.Page; @Service public class ForumServiceImpl implements ForumService { @Autowired private ForumDao forumDao; @Override public void addForum(Forum forum) { forumDao.addForum(forum); } @Override public void updateForum(Forum forum) { forumDao.updateForum(forum); } @Override public void deleteForum(Integer forumId) { forumDao.deleteForum(forumId); } @Override public List<Forum> findAllForumByUserId(Integer userId) { return forumDao.findAllForumByUserId(userId); } @Override public Forum findForumById(Integer forumId) { return forumDao.findForumById(forumId); } @Override public List<Forum> findAllForumByPage(Page page) { return forumDao.findForumByPage(page); } @Override public List<Forum> findAllForums() { return forumDao.findForums(); } }
import java.util.ArrayList; /** * Diese Klasse verwaltet eine unbegrenzte Anzahl von Namen. * * @author Alexander Palmer * @version 22.06.2015 */ public class Freunde { private ArrayList<String> meineFreunde; /** * Erzeugt eine Instanz von ArrayList und stellt * die Sammlung der Klasse zur Verfügung. */ public Freunde() { meineFreunde = new ArrayList<String>(); } /** * Fügt eine neue String-Referenz der Sammlung hinzu * @param name Name eines Freundes */ public boolean hinzufuegen(String name) { if(name!=null) { return meineFreunde.add(name); } return false; } /** * Liefert den Namen eines Freundes an einer bestimmten * Position innerhalb der Sammlung * @param position Index der Sammlung, beginnend bei 0 * @return liefert den gefundenen Namen an der Position oder null */ public String gibName(int position) { if(position >= 0 && position < meineFreunde.size()) { return meineFreunde.get(position); } return null; } /** * Liefert die Anzahl der gespeicherten Referenzen der Sammlung * @return Anzahl gespeicherter Refernzen in Sammlung */ public int gibAnzahlFreunde() { return meineFreunde.size(); } /** * Entfernt eine Objektreferenz innerhalb der Sammlung, wenn * Position gültig ist * @param position Index eines Elements beginnend bei 0 * @return true wenn das Entfernen geklappt hat, ansonsten false */ public boolean loescheFreund(int position) { int aktAnzahl=meineFreunde.size(); if(position >= 0 && position < meineFreunde.size()) { meineFreunde.remove(position); } if (aktAnzahl > meineFreunde.size()) { return true; } else { return false; } } /** * Gibt alle Namen der Sammlung in der Konsole aus */ public void alleNamenAusgeben() { for(String name : meineFreunde) { System.out.println(name); } } /** * Sucht einen Namen in der Sammlung und liefert true, * wenn Name in der Sammlung vorhanden * @param name Der gesuchte Name * @return true wenn Name gefunden, ansonsten false */ public boolean sucheFreund(String name) { if(name!=null) { return meineFreunde.contains(name); } return false; } /** * Liefert die Position (Index) eines Namens innerhalb der Sammlung * @param name Gesuchter Name der Person * @return der Index der gesuchten Person */ public int gibPosition(String name) { if(name!=null) { return meineFreunde.indexOf(name); } return -1; } }
/* * Created By Liang Shan Guang at 2019/3/10 17:50 * Description : 原则1-开闭原则 */ package 第3章_软件设计七大原则.S01_开闭原则OpenClose;
/* * 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 org.una.clienteaeropuerto.utils; import javafx.scene.image.ImageView; /** * * @author Andres */ public class Imagen { private ImageView imageView; public Imagen(ImageView imageView) { this.imageView = imageView; } public ImageView getImageView() { return imageView; } public void setImageView(ImageView imageView) { this.imageView = imageView; } }
package com.androidbook.simplelayout; import android.os.Bundle; public class frame_layout extends layout_menu_class { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.frame_layout); } }
package engineTester; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import org.lwjgl.util.vector.Vector2f; import org.lwjgl.util.vector.Vector3f; import entities.Camera; import entities.ColisionLife; import entities.Enemy; import entities.Entity; import entities.Light; import gui.GuiRenderer; import gui.GuiTexture; import models.RawModel; import models.TexturedModel; import objConverter.ModelData; import objConverter.OBJFileLoader; import renderEngine.DisplayManager; import renderEngine.Loader; import renderEngine.MasterRenderer; import terrains.Terrain; import textures.ModelTexture; public class MainGameLoop { public static List<GuiTexture> guis = new ArrayList<GuiTexture>(); public static Loader loader = new Loader(); public static void main(String[] args) { // Criacao de um display DisplayManager.createDisplay(); ModelData data = OBJFileLoader.loadOBJ("teste"); // Inicializacoa dos modelos RawModel model = loader.loadToVAO(data.getVertices(), data.getTextureCoords(), data.getNormals(), data.getIndices()); // Inicializacao das texturas TexturedModel treeModel = new TexturedModel(model,new ModelTexture(loader.loadTexture("tree"))); TexturedModel fernModel = new TexturedModel(model,new ModelTexture(loader.loadTexture("fern"))); TexturedModel enemyModel = new TexturedModel(model,new ModelTexture(loader.loadTexture("inimigo"))); TexturedModel bg0 = new TexturedModel(model,new ModelTexture(loader.loadTexture("fundo1"))); TexturedModel bg1 = new TexturedModel(model,new ModelTexture(loader.loadTexture("fundo2"))); TexturedModel bg2 = new TexturedModel(model,new ModelTexture(loader.loadTexture("fundoD"))); TexturedModel bg3 = new TexturedModel(model,new ModelTexture(loader.loadTexture("fundoD"))); TexturedModel lifeModel = new TexturedModel(model,new ModelTexture(loader.loadTexture("vida"))); // Inicializacao de atributos especiais para as texturas treeModel.getTexture().setUseFakeLighting(true); fernModel.getTexture().setHasTransparacy(true); bg0.getTexture().setHasTransparacy(true); bg1.getTexture().setHasTransparacy(true); bg2.getTexture().setHasTransparacy(true); bg3.getTexture().setHasTransparacy(true); lifeModel.getTexture().setUseFakeLighting(true); // Inicalizando GUI GuiTexture gui = new GuiTexture(loader.loadTexture("health"), new Vector2f(-0.65f,0.9f),new Vector2f(0.3f,0.3f)); GuiTexture gui2 = new GuiTexture(loader.loadTexture("green"), new Vector2f(-0.45f,0.9f),new Vector2f(0.35f,0.021f)); guis.add(gui); guis.add(gui2); GuiRenderer guiRenderer = new GuiRenderer (loader); List<Enemy> enemies = new ArrayList<Enemy>(); List<Entity> entities = new ArrayList<Entity>(); List<Entity> lifes = new ArrayList<Entity>(); List<Entity> bg = new ArrayList<Entity>(); // Determinando posicoes randomicas para cada objeto inserido Random random = new Random(); for(int i=0;i<50;i++){ entities.add(new Entity(treeModel, new Vector3f(random.nextFloat() * -200,0, random.nextFloat() * -200),0,0,0,3)); entities.add(new Entity(fernModel, new Vector3f(random.nextFloat() * -200, 0, random.nextFloat() * -200) ,0 ,0 ,0, 1)); entities.add(new Entity(fernModel, new Vector3f(random.nextFloat() * -200, 0, random.nextFloat() * -200) ,0 ,0 ,0, 1)); } for(int i=0;i<10;i++){ enemies.add(new Enemy(enemyModel, new Vector3f(random.nextFloat() * -200,0,random.nextFloat() * -200), 0, 0, 0, 2)); lifes.add(new Entity(lifeModel, new Vector3f(random.nextFloat()*-200,1, random.nextFloat()*-200),0,0,0,1)); } bg.add(new Entity(bg0, new Vector3f(-100,-30,-210),0,0,0,120)); bg.add(new Entity(bg1, new Vector3f(-100,-30,10),0,180,0,120)); bg.add(new Entity(bg2, new Vector3f(-210,-30,-100),0,270,0,120)); bg.add(new Entity(bg3, new Vector3f(10,-30,-100),0,90,0,120)); // Inicializao do modelo de Luz Light light = new Light(new Vector3f(20000,20000,2000),new Vector3f(1,1,1)); // Inicializacao do terreno Terrain terrain = new Terrain(0,0,loader,new ModelTexture(loader.loadTexture("floor"))); // Inicializacao da Camera do usuario (FPS) Camera camera = new Camera(); // Iniciando o render do jogo MasterRenderer renderer = new MasterRenderer(); //Pra barra de vida int HP = Camera.getHP(); // Loop do Jogo while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) { camera.move(); // Renderizacoes renderer.processTerrain(terrain); if(Camera.getHP() < 100){ ColisionLife.checkColision(lifes, guis); } for(Entity bck:bg){ renderer.processEntity(bck); } for(Entity entity:entities){ entity.Update(); renderer.processEntity(entity); } for(Enemy enemy:enemies){ if(enemy.Update() > 0){ renderer.processEntity(enemy); } } for(Entity lifeaux:lifes){ lifeaux.Update(); renderer.processEntity(lifeaux); } renderer.render(light, camera); guiRenderer.render(guis); GuiTexture guiaux = guis.get(1); Vector2f positionaux = guiaux.getPosition(); Vector2f scaleaux = guiaux.getScale(); if (Camera.getHP() != HP) { int dif = HP - Camera.getHP(); HP = Camera.getHP(); positionaux.setX(positionaux.x - dif*0.004f); scaleaux.setX(scaleaux.x - dif*0.004f); } guiaux.setPosition(positionaux); guiaux.setScale(scaleaux); guis.add(1, guiaux); if(enemies.size() == Camera.getKilled()) win(); else if(Camera.getHP() == 0) lose(); // update a tela DisplayManager.updateDisplay(); } // Libera memoria corretamente renderer.cleanUp(); loader.cleanUp(); DisplayManager.closeDisplay(); } public static void win(){ GuiTexture gui3 = new GuiTexture(loader.loadTexture("youwon"), new Vector2f(0f,0f),new Vector2f(1f,1f)); guis.add(gui3); } public static void lose(){ GuiTexture gui3 = new GuiTexture(loader.loadTexture("youdied"), new Vector2f(0f,0f),new Vector2f(1f,1f)); guis.add(gui3); } } // This line make it work /* package engineTester; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import org.lwjgl.util.vector.Vector2f; import org.lwjgl.util.vector.Vector3f; import entities.Camera; import entities.ColisionLife; import entities.Entity; import entities.Light; import gui.GuiRenderer; import gui.GuiTexture; import models.RawModel; import models.TexturedModel; import objConverter.ModelData; import objConverter.OBJFileLoader; import renderEngine.DisplayManager; import renderEngine.Loader; import renderEngine.MasterRenderer; import terrains.Terrain; import textures.ModelTexture; public class MainGameLoop { public static void main(String[] args) throws InterruptedException { boolean flagEnded = false; // Criacao de um display DisplayManager.createDisplay(); // Inicializacao do Loader Loader loader = new Loader(); // Inicializa modelos de dados ModelData data = OBJFileLoader.loadOBJ("capsula"); ModelData data2 = OBJFileLoader.loadOBJ("cubo"); ModelData data3 = OBJFileLoader.loadOBJ("vida"); // Inicializacoa dos modelos // Pega os // vertices, coordenada uv da textura, normais e indices para VBO RawModel capsuleModel = loader.loadToVAO(data.getVertices(), data.getTextureCoords(), data.getNormals(), data.getIndices()); RawModel cubeModel = loader.loadToVAO(data2.getVertices(), data2.getTextureCoords(), data2.getNormals(), data2.getIndices()); RawModel lifeModel = loader.loadToVAO(data3.getVertices(), data3.getTextureCoords(), data3.getNormals(), data3.getIndices()); // Inicializacao das texturas // .png em potencia de 2 TexturedModel capsule = new TexturedModel(capsuleModel,new ModelTexture(loader.loadTexture("capsula"))); TexturedModel cube = new TexturedModel(cubeModel,new ModelTexture(loader.loadTexture("cubo"))); TexturedModel life = new TexturedModel(lifeModel,new ModelTexture(loader.loadTexture("vida"))); // Inicializacao de atributos especiais para as texturas capsule.getTexture().setUseFakeLighting(true); capsule.getTexture().setHasTransparacy(true); List<Entity> lifes = new ArrayList<Entity>(); // Determinando posicoes randomicas para cada objeto inserido Random random = new Random(); for(int i=0;i<200;i++){ lifes.add(new Entity(life, new Vector3f(random.nextFloat()*400 - 200,0, random.nextFloat() * -150),random.nextFloat()*180,random.nextFloat()*180,random.nextFloat()*90,3)); // entities.add(new Entity(cube, new Vector3f(random.nextFloat()*800 - 400,10, // random.nextFloat() * -600),random.nextFloat()*180,random.nextFloat()*180,random.nextFloat()*180,3)); } // Inicializao do modelo de Luz Light light = new Light(new Vector3f(20000,20000,2000),new Vector3f(1,1,1)); // Inicializacao do terreno Terrain terrain = new Terrain(0,0,loader,new ModelTexture(loader.loadTexture("floor"))); // Terrain terrain2 = new Terrain(1,0,loader,new ModelTexture(loader.loadTexture("floor"))); // Inicializacao da Camera do usuario (FPS) Camera camera = new Camera(); // Inicalizando GUI List<GuiTexture> guis = new ArrayList<GuiTexture> (); GuiTexture gui = new GuiTexture(loader.loadTexture("health"), new Vector2f(-0.65f,0.9f),new Vector2f(0.3f,0.3f)); // GuiTexture gui2 = new GuiTexture(loader.loadTexture("green"), new Vector2f(-0.45f,0.9f),new Vector2f(0.1f,0.021f)); GuiTexture gui2 = new GuiTexture(loader.loadTexture("green"), new Vector2f(-0.45f,0.9f),new Vector2f(0.35f,0.021f)); GuiTexture gui3 = new GuiTexture(loader.loadTexture("youdied"), new Vector2f(0f,0f),new Vector2f(1f,1f)); guis.add(gui); guis.add(gui2); // guis.add(gui4); GuiRenderer guiRenderer = new GuiRenderer (loader); // Iniciando o render do jogo MasterRenderer renderer = new MasterRenderer(); // Loop do Jogo while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) { // Game logic camera.move(); // Renderizacoes renderer.processTerrain(terrain); // renderer.processTerrain(terrain2); for(Entity entity:lifes){ renderer.processEntity(entity); } renderer.render(light, camera); if (!flagEnded) { ColisionLife.checkColision(camera, lifes, guis); GuiTexture guiaux = guis.get(1); Vector2f positionaux = guiaux.getPosition(); Vector2f scaleaux = guiaux.getScale(); if (scaleaux.x > 0) { positionaux.setX(positionaux.x - 0.001f); scaleaux.setX(scaleaux.x - 0.001f); } guiaux.setPosition(positionaux); guiaux.setScale(scaleaux); guis.add(1, guiaux); // Ve se jogador morreu // adiciona tela de morte if (guiaux.getScale().getX() < 0) { flagEnded =!flagEnded; guis.removeAll(guis); guis.add(gui3); } } // render do GUI guiRenderer.render(guis); // update a tela DisplayManager.updateDisplay(); } // Libera memoria corretamente guiRenderer.cleanUp(); renderer.cleanUp(); loader.cleanUp(); DisplayManager.closeDisplay(); } } // This line make it work */
package com.matheusmarques.passaroavoado; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.viewport.StretchViewport; import com.badlogic.gdx.utils.viewport.Viewport; import java.util.Random; import javax.swing.ViewportLayout; public class PassaroAvoado extends ApplicationAdapter { private SpriteBatch batch; private Texture passaro; // feito dessa forma porque celulares merda não rodam texture como array. private Texture passaro1; private Texture passaro2; private Texture passaro3; private Texture fundo; private Random numeroRandom; private BitmapFont fonte; private Texture canoCima; private Texture canoBaixo; private Circle passaroCirculo; private Rectangle CanoCimaRet; private Rectangle CanoBaixoRet; private ShapeRenderer shape; private Texture GameOver; private String frase; private float larguraDispostivo; private float alturaDispostivo; private int pontuacao = 0; private int estadoJogo = 0; // jogo não iniciado; private boolean marcouPonto = false; private float variacao = 0; private float velocidadeQueda = 0; private float posicaoInicial; private float posicaoMovimentoCano; private float espacoEntreCanos; private float espacoEntreCanosRandom; private float deltaTime; private OrthographicCamera camera; private Viewport viewport; private final float VIRTUAL_WIDTH = 768; private final float VIRTUAL_HEIGHT = 1024; @Override public void create () { batch = new SpriteBatch(); fonte = new BitmapFont(); fonte.setColor(Color.WHITE); fonte.getData().setScale(4); passaroCirculo = new Circle(); CanoCimaRet = new Rectangle(); CanoBaixoRet = new Rectangle(); shape = new ShapeRenderer(); passaro1 = new Texture("passaro1.png"); passaro2 = new Texture("passaro2.png"); passaro3 = new Texture("passaro3.png"); fundo = new Texture("fundo.png"); canoCima = new Texture("cano_topo.png"); canoBaixo = new Texture("cano_baixo.png"); GameOver = new Texture("game_over.png"); camera = new OrthographicCamera(); camera.position.set(VIRTUAL_WIDTH/2,VIRTUAL_HEIGHT/2,0); viewport = new StretchViewport(VIRTUAL_WIDTH,VIRTUAL_HEIGHT,camera); frase= new String(); frase = "Toque para Iniciar"; numeroRandom = new Random(); larguraDispostivo = VIRTUAL_WIDTH; alturaDispostivo = VIRTUAL_HEIGHT; posicaoInicial = alturaDispostivo/2; posicaoMovimentoCano =larguraDispostivo; espacoEntreCanos = 300; } @Override public void render () { camera.update(); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); deltaTime =Gdx.graphics.getDeltaTime(); variacao += deltaTime * 10; if((int) variacao==0) passaro = passaro1; if((int) variacao==1) passaro = passaro2; if((int) variacao==2) passaro = passaro3; if(variacao>2) variacao = 0; if(estadoJogo == 0){ if(Gdx.input.justTouched()){ estadoJogo = 1; } }else{ velocidadeQueda++; if(posicaoInicial>0 || velocidadeQueda < 0) posicaoInicial = posicaoInicial - velocidadeQueda; if(estadoJogo==1){ posicaoMovimentoCano = posicaoMovimentoCano - deltaTime*150; if(posicaoMovimentoCano< -canoBaixo.getWidth()){ posicaoMovimentoCano =larguraDispostivo; espacoEntreCanosRandom = numeroRandom.nextInt(400) - 200; marcouPonto = false; } if(posicaoMovimentoCano<120){ if(!marcouPonto){ pontuacao++; marcouPonto =true; } } if(Gdx.input.justTouched()){ velocidadeQueda = - 20; } if(posicaoInicial >= alturaDispostivo) posicaoInicial = alturaDispostivo; } } batch.setProjectionMatrix(camera.combined); batch.begin(); batch.draw(fundo,0,0, larguraDispostivo,alturaDispostivo); batch.draw(canoCima,posicaoMovimentoCano,alturaDispostivo/2 + espacoEntreCanos / 2 + espacoEntreCanosRandom); batch.draw(canoBaixo,posicaoMovimentoCano,alturaDispostivo/2 - canoBaixo.getHeight() - espacoEntreCanos / 2 + espacoEntreCanosRandom); batch.draw(passaro, 120,posicaoInicial); if(estadoJogo==1){ fonte.draw(batch, String.valueOf(pontuacao) , larguraDispostivo/2, alturaDispostivo-40); } if(estadoJogo==0){ fonte.draw(batch, String.valueOf(frase) , larguraDispostivo/2-200, alturaDispostivo-200); } if(estadoJogo==2){ fonte.getData().setScale(3); frase = "Toque para Recomeçar"; batch.draw(GameOver,larguraDispostivo/2 - (GameOver.getWidth()/2),alturaDispostivo/2 - (GameOver.getHeight()/2)); fonte.draw(batch, String.valueOf(frase) , larguraDispostivo/2-200, alturaDispostivo-200); } batch.end(); passaroCirculo.set(120 + (passaro.getWidth()/2), posicaoInicial + (passaro.getHeight()/2),passaro.getWidth()/2); CanoBaixoRet = new Rectangle( posicaoMovimentoCano,alturaDispostivo/2 - canoBaixo.getHeight() - espacoEntreCanos/2+espacoEntreCanosRandom, canoBaixo.getWidth(),canoBaixo.getHeight() ); CanoCimaRet = new Rectangle( posicaoMovimentoCano,alturaDispostivo/2 + espacoEntreCanos/2 + espacoEntreCanosRandom, canoCima.getWidth(),canoCima.getHeight() ); /*shape.begin(ShapeRenderer.ShapeType.Filled); shape.circle(passaroCirculo.x,passaroCirculo.y,passaroCirculo.radius); shape.rect(CanoBaixoRet.x,CanoBaixoRet.y,CanoBaixoRet.width,CanoBaixoRet.height); shape.rect(CanoCimaRet.x,CanoCimaRet.y,CanoCimaRet.width,CanoCimaRet.height); shape.setColor(Color.RED); shape.end();*/ if((Intersector.overlaps(passaroCirculo,CanoBaixoRet) || Intersector.overlaps(passaroCirculo,CanoCimaRet)) || posicaoInicial<=0 || posicaoInicial>=alturaDispostivo) { estadoJogo = 2; if(Gdx.input.justTouched()){ estadoJogo = 0; pontuacao = 0; velocidadeQueda = 0; posicaoInicial = alturaDispostivo/2; posicaoMovimentoCano = larguraDispostivo; } } } @Override public void resize(int width, int height){ viewport.update(width,height); } }
package model.bean.file; import java.io.Serializable; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; /** * * @author Andriy */ @Entity @Table(name = "file_manual", catalog = "testfield") public class FileManual implements Serializable { @EmbeddedId private FileManualId id; public FileManual() {} public FileManual(int fileId, int manualId) { id = new FileManualId(); id.setFileId(fileId); id.setManualId(manualId); } public FileManualId getId() { return id; } public void setId(FileManualId id) { this.id = id; } }
package com.tw; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class LibraryTest { @Test public void testSomeLibraryMethod() { Library classUnderTest = new Library(); assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod()); } private Library libraryMock,library; @Test public void testMockClass() throws Exception { // you can mock concrete classes, not only interfaces LinkedList mockedList = mock(LinkedList.class); // stubbing appears before the actual execution String value = "first"; when(mockedList.get(0)).thenReturn(value); assertEquals(mockedList.get(0), value); } @Before public void beforeTests() { libraryMock=mock(Library.class); library=new Library(); } @Test public void testCalculate() { Integer[] tmp= new Integer[]{1,3,7,8,9,2,4}; List<Integer> resulteOdd= Arrays.asList(tmp); Integer[] tmp2=new Integer[]{1,3,18,9,8,12}; List<Integer> resulteEve= Arrays.asList(tmp2); when(libraryMock.calculate(resulteOdd)).thenReturn(7); when(libraryMock.calculate(resulteEve)).thenReturn(8); } @Test public void testAddStudent() { String right="张三,1,数学:98,语文:67,英语:78,编程:78"; when(libraryMock.addStudent(right)).thenReturn(true); when(libraryMock.addStudent(anyString())).thenReturn(false); } @Test public void testPrintGrade() { String right1="23"; String right2="23,78"; when(libraryMock.printGrade(right1)).thenReturn(true); when(libraryMock.printGrade(right2)).thenReturn(true); when(libraryMock.printGrade(anyString())).thenReturn(false); } @Test public void testGetGrade() { String right="数学:78"; String wrong="语文,89"; when(libraryMock.getGrade(right)).thenReturn(78); when(libraryMock.getGrade(wrong)).thenReturn(-1); } }
package com.esum.wp.ims.uadacominfo.service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.esum.appframework.service.IBaseService; public interface IUadacomInfoService extends IBaseService { void saveUadacomInfoExcel(Object object, HttpServletRequest request, HttpServletResponse response) throws Exception; }
package objects; import java.util.ArrayList; import javax.swing.ImageIcon; public class Tile { private boolean _isOnTheBoard; private ArrayList<Boolean> _openedSide; // NESW private char _tileShape; private int[] _location; // tile index, if not on the board[100,100] private boolean _hasPlayerOnIt; private boolean _hasTokenOnIt; private ArrayList<Player> _playersOnIt; private Token _token; private ImageIcon _image; // private ArrayList<Tile> connectedTile; // add connected tiles to this // tile // 0 = N / 1 = E / 2 = S / 3 = W // ─ │ ┬ ┤ ┣ <- will use this kinds of letters. public Tile(int[] location, char ch) { this._isOnTheBoard = true; // this._location = new int[2]; this._location = location; this._isOnTheBoard = true; this._tileShape = ch; this._openedSide = new ArrayList<Boolean>(); setUpOpenedSide(_tileShape); this._playersOnIt = new ArrayList<Player>(); this._image = new ImageIcon("images/" + _tileShape + ".jpg"); } public void rotateClockWise() { Boolean temp = _openedSide.remove(_openedSide.size() - 1); _openedSide.add(0, temp); switch (_tileShape) { case '─': _tileShape = '│'; break; case '│': _tileShape = '─'; break; case '┌': _tileShape = '┐'; break; case '┐': _tileShape = '┘'; break; case '└': _tileShape = '┌'; break; case '┘': _tileShape = '└'; break; case '┬': _tileShape = '┤'; break; case '├': _tileShape = '┬'; break; case '┴': _tileShape = '├'; break; case '┤': _tileShape = '┴'; break; } } public void set_token(Token _token) { this._token = _token; } public ArrayList<Player> getPlayersOnIt() { return this._playersOnIt; } public void placePlayerOnTile(Player p) { _playersOnIt.add(p); } public void set_isOnTheBoard(boolean _isOnTheBoard) { this._isOnTheBoard = _isOnTheBoard; } public ArrayList<Boolean> setUpOpenedSide(char shape) { boolean[] openedSide = new boolean[4]; switch (shape) { case '─': // 북동남서 _openedSide.add(0, false); _openedSide.add(1, true); _openedSide.add(2, false); _openedSide.add(3, true); break; case '│': _openedSide.add(0, true); _openedSide.add(1, false); _openedSide.add(2, true); _openedSide.add(3, false); break; case '┴': // 0 = N / 1 = E / 2 = S / 3 = W _openedSide.add(0, true); _openedSide.add(1, true); _openedSide.add(2, true); _openedSide.add(3, false); break; case '┤': _openedSide.add(0, true); _openedSide.add(1, false); _openedSide.add(2, true); _openedSide.add(3, true); break; case '├': _openedSide.add(0, true); _openedSide.add(1, true); _openedSide.add(2, true); _openedSide.add(3, false); break; case '┬': _openedSide.add(0, false); _openedSide.add(1, true); _openedSide.add(2, true); _openedSide.add(3, true); break; case '┐': _openedSide.add(0, false); _openedSide.add(1, false); _openedSide.add(2, true); _openedSide.add(3, true); break; case '┘': _openedSide.add(0, true); _openedSide.add(1, false); _openedSide.add(2, false); _openedSide.add(3, true); break; case '┌': _openedSide.add(0, false); _openedSide.add(1, true); _openedSide.add(2, true); _openedSide.add(3, false); break; case '└': // 0 = N / 1 = E / 2 = S / 3 = W _openedSide.add(0, true); _openedSide.add(1, true); _openedSide.add(2, false); _openedSide.add(3, false); break; } return _openedSide; } // private char Character(int j) { // return 0; // } public char get_tileShape() {// get the shape of the tile, - kang return _tileShape; } public void set_tileShape(char _tileShape) {// set the shape of the tile - // kang this._tileShape = _tileShape; } // public int get_location() { // return _location; // } // public void set_location(int col, int row) { // this._location = ; // } public boolean is_hasPlayerOnIt() { return _hasPlayerOnIt; } public void set_hasPlayerOnIt(boolean _hasPlayerOnIt) { this._hasPlayerOnIt = _hasPlayerOnIt; } public boolean is_hasTokenOnIt() { return _hasTokenOnIt; } public void set_hasTokenOnIt(boolean _hasTokenOnIt) { this._hasTokenOnIt = _hasTokenOnIt; } public ImageIcon get_image() { return _image; } public Token get_token() { return _token; } public ArrayList<Boolean> get_openedSide() { return _openedSide; } public void set_openedSide(ArrayList<Boolean> _openedSide) { this._openedSide = _openedSide; } }
package com.codigo.smartstore.sdk.core.checksum.crc; /** * @author andrzej.radziszewski * @version 1.0.0.0 * @since 2018 * @category class */ final class CrcParameter implements ICrcParameter { /** * Atrybut obiektu określa długość generowanej sumy kontrolnej wyrażonej w * bitach */ private final int length; /** * Atrybut obiektu określa nazwę dla sumy kontrolnej */ private final String name; /** * Atrybut obiektu określa wartość wielomianu sumy kontrolnej */ private final int polynomial; /** * Atrybut obiektu określa wartość początkową sumy kontrolnej */ private final int initialValue; /** * Atrybut obiektu określa wartość finalną sumy kontrolnej */ private final int finalXorValue; /** * Atrybut obiektu określa czy bajty danych wejściowe mają być odczytywane w * odwrotnej kolejności */ private final boolean inputReflected; /** * Atrybut obiektu określa czy bajty danych wyjściowych mają być odczytywane w * odwrotnej kolejności */ private final boolean resultReflected; /** * Podstawowy konstruktor obiektu klasy <code>CrcParameter</code> * * @param length Długość sumy kontrolnej wyrażona w bitach * @param name Nazwa dla sumy kontrolnej * @param polynomial Wartość wielomianu sumy kontrolnej * @param initialValue Wartość początkowa sumy kontrolnej * @param finalXorValue Wartość finalna operatora xor sumy kontrolnej * @param inputReflected Flaga wskazuje czy bajty danych wejściowych odczytywać * w odwrotnej kolejności * @param resultReflected Flaga wskazuje czy bajty danych wyjściowych odczytywać * w odwrotnej kolejności */ public CrcParameter(final int length, final String name, final int polynomial, final int initialValue, final int finalXorValue, final boolean inputReflected, final boolean resultReflected) { this.length = length; this.name = name; this.polynomial = polynomial; this.initialValue = initialValue; this.finalXorValue = finalXorValue; this.inputReflected = inputReflected; this.resultReflected = resultReflected; } /* * (non-Javadoc) * @see com.codigo.aplios.checksum.core.crc.ICrcParameter#getLength() */ @Override public int getLength() { return this.length; } /* * (non-Javadoc) * @see com.codigo.aplios.checksum.core.crc.ICrcParameter#getName() */ @Override public String getName() { return this.name; } /* * (non-Javadoc) * @see com.codigo.aplios.checksum.core.crc.ICrcParameter#getPolynomial() */ @Override public int getPolynomial() { return this.polynomial; } /* * (non-Javadoc) * @see com.codigo.aplios.checksum.core.crc.ICrcParameter#getInitialValue() */ @Override public int getInitialValue() { return this.initialValue; } /* * (non-Javadoc) * @see com.codigo.aplios.checksum.core.crc.ICrcParameter#getFinalXorValue() */ @Override public int getFinalXorValue() { return this.finalXorValue; } /* * (non-Javadoc) * @see com.codigo.aplios.checksum.core.crc.ICrcParameter#isInputReflected() */ @Override public boolean isInputReflected() { return this.inputReflected; } /* * (non-Javadoc) * @see com.codigo.aplios.checksum.core.crc.ICrcParameter#isResultReflected() */ @Override public boolean isResultReflected() { return this.resultReflected; } }
package com.example.administrator.mvp_example.Presenter; /** * Created by Administrator on 2017-12-06. */ public interface MainPresenter { void setView(MainPresenter.View view); void onConfirm(); public interface View { void setConfirmText(String text); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.koshish.java.hibernate.ecommerce.DAO; import com.koshish.java.hibernate.ecommerce.entity.Customer; import java.util.List; /** * * @author Koshish Rijal */ public interface CustomerDAO { public List<Customer> getAll(); public Customer getById(int id); public int insert(Customer customer); public int update(Customer customer); public int delete(int id); }
/* Ara - capture species and specimen data * * Copyright (C) 2009 INBio (Instituto Nacional de Biodiversidad) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.ara.eao.reports.impl; import org.inbio.ara.eao.reports.*; import javax.ejb.Stateless; import javax.persistence.Query; import org.inbio.ara.eao.BaseEAOImpl; import org.inbio.ara.persistence.reports.PlinianCoreFlat; /** * * @author esmata */ @Stateless public class PlinianCoreFlatEAOImpl extends BaseEAOImpl<PlinianCoreFlat,String> implements PlinianCoreFlatEAOLocal { /** * Metodo que realiza el snapshot plinian core primario, el cual será * utilizado para los reportes y para crear snapshots personalizados */ public boolean reloadPlinianCoreTable(String dbSchema) { String creationString = "Create table "+dbSchema+".plinian_core_flat"+ "(GlobalUniqueIdentifier varchar,"+ "ScientificName varchar,"+ "InstitutionCode varchar,"+ "DateLastModified timestamp,"+ "TaxonRecordID varchar,"+ "Language varchar,"+ "Creators varchar,"+ "Distribution varchar,"+ "Abstract varchar,"+ "KingdomTaxon varchar,"+ "PhylumTaxon varchar,"+ "ClassTaxon varchar,"+ "OrderTaxon varchar,"+ "FamilyTaxon varchar,"+ "GenusTaxon varchar,"+ "Synonyms varchar,"+ "AuthorYearOfScientificName varchar,"+ "SpeciesPublicationReference varchar,"+ "CommonNames varchar,"+ "Typification varchar,"+ "Contributors varchar,"+ "DateCreated timestamp, "+ "Habit varchar,"+ "LifeCycle varchar,"+ "Reproduction varchar,"+ "AnnualCycle varchar,"+ "ScientificDescription varchar,"+ "BriefDescription varchar,"+ "Feeding varchar,"+ "Behavior varchar,"+ "Interactions varchar,"+ "ChromosomicNumberN varchar,"+ "MolecularData varchar,"+ "PopulationBiology varchar,"+ "ThreatStatus varchar,"+ "Legislation varchar,"+ "Habitat varchar,"+ "Territory varchar,"+ "Endemicity varchar,"+ "TheUses varchar,"+ "TheManagement varchar,"+ "Folklore varchar,"+ "TheReferences varchar,"+ "UnstructuredDocumentation varchar,"+ "OtherInformationSources varchar,"+ "Papers varchar,"+ "IdentificationKeys varchar,"+ "MigratoryData varchar,"+ "EcologicalSignificance varchar,"+ "UnstructuredNaturalHistory varchar,"+ "InvasivenessData varchar,"+ "TargetAudiences varchar,"+ "Version varchar,"+ "URLImage1 varchar,"+ "CaptionImage1 varchar,"+ "URLImage2 varchar,"+ "CaptionImage2 varchar,"+ "URLImage3 varchar,"+ "CaptionImage3 varchar,"+ "PRIMARY KEY ( GlobalUniqueIdentifier));"; String insertString = "Insert into "+dbSchema+".plinian_core_flat"+ "(GlobalUniqueIdentifier,"+ "ScientificName,"+ "InstitutionCode,"+ "DateLastModified ,"+ "TaxonRecordID ,"+ "Language,"+ "Creators ,"+ "Distribution,"+ "Abstract,"+ "KingdomTaxon,"+ "PhylumTaxon,"+ "ClassTaxon,"+ "OrderTaxon,"+ "FamilyTaxon,"+ "GenusTaxon,"+ "Synonyms,"+ "AuthorYearOfScientificName,"+ "SpeciesPublicationReference,"+ "CommonNames,"+ "Typification,"+ "Contributors,"+ "DateCreated, "+ "Habit,"+ "LifeCycle,"+ "Reproduction,"+ "AnnualCycle,"+ "ScientificDescription,"+ "BriefDescription,"+ "Feeding,"+ "Behavior,"+ "Interactions,"+ "ChromosomicNumberN,"+ "MolecularData,"+ "PopulationBiology,"+ "ThreatStatus,"+ "Legislation,"+ "Habitat,"+ "Territory ,"+ "Endemicity,"+ "TheUses,"+ "TheManagement,"+ "Folklore,"+ "TheReferences,"+ "UnstructuredDocumentation,"+ "OtherInformationSources,"+ "Papers,"+ "IdentificationKeys,"+ "MigratoryData,"+ "EcologicalSignificance,"+ "UnstructuredNaturalHistory ,"+ "InvasivenessData ,"+ "TargetAudiences ,"+ "Version ,"+ "URLImage1,"+ "CaptionImage1,"+ "URLImage2 ,"+ "CaptionImage2 ,"+ "URLImage3 ,"+ "CaptionImage3 )"+ "select to_char(td.taxon_id, '000000000000') || ':' || coalesce(rtrim(i.INSTITUTION_CODE), '') || ':' || to_char(td.taxon_description_sequence, '000000') as GlobalUniqueIdentifier,"+ "t.default_name as ScientificName,"+ "i.INSTITUTION_CODE as InstitutionCode,"+ "td.last_modification_date as DateLastModified,"+ "t.taxon_id as TaxonRecordID,"+ "cp.name as Language,"+ dbSchema+".species_record_person(td.taxon_id, td.taxon_description_sequence,', ') as Creators,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Distribution', 0, ' ') as distribution, "+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Abstract', 0, '') as Abstract,"+ "r.default_name as Kingdom,"+ "fl.default_name as Phylum,"+ "c.default_name as Class, "+ "tor.default_name as OrderRank,"+ "tf.default_name as Family,"+ "g.default_name as genus,"+ "'' as Synonyms,"+ "'' as AuthorYearOfScientificName,"+ "'' as SpeciesPublicationReference,"+ dbSchema+".taxon_nomenclatural_group_list(td.taxon_id, '; ') as CommonNames,"+ "'' as Typification,"+ "'' as Contributors,"+ "null as DateCreated,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Habit', 0, '') as Habit,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'LifeCycle', 0, '') as LifeCycle,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Reproduction', 0, '') as Reproduction,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'AnnualCycle', 0, '') as AnnualCycle,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'ScientificDescription', 0, '') as ScientificDescription,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'BriefDescription', 0, '') as BriefDescription,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Feeding', 0, '') as Feeding ,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Behavior', 0, '') as Behavior,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Interactions', 1, '. ') as Interactions,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'ChromosomicNumberN', 0, '') as ChromosomicNumberN,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'MolecularData', 0, '') as MolecularData,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'PopulationBiology', 0, '') as PopulationBiology,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'ThreatStatus', 1, ' ') as ThreatStatus,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Legislation', 1, ' ') as Legislation,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Habitat', 0, '') as Habitat,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Territory', 0, '') as Territory,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Endemicity', 1, ' ') as Endemicity ,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Uses', 0, '') as theUses,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Management', 0, '') as theManagement,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Folkclore', 0, '') as Folklore,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'References', 0, '. '),"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'UnstructuredDocumentation', 0, ' ') as UnstructuredDocumentation,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'OtherInformationSources', 0, ' ') as OtherInformationSources,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'Papers', 0, ' ') as Papers,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'IdentificationKeys', 0, ' ') as IdentificationKeys,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'MigratoryData', 0, ' ') as MigratoryData,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'EcologicalSignificance', 0, ' ') as EcologicalSignificance,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'UnstructuredNaturalHistory', 0, ' ') as UnstructuredNaturalHistory,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'InvasivenessData', 0, ' ') as InvasivenessData,"+ dbSchema+".taxon_description_audience_list(td.taxon_id, td.taxon_description_sequence ,'; ') as TargetAudiences,"+ "td.taxon_description_sequence as Version ,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'URLImage1', 0, '') as URLImage1,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'CaptionImage1', 0, '') as CaptionImage1,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'URLImage2', 0, '') as URLImage2 ,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'CaptionImage2', 0, '') as CaptionImage2 ,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'URLImage3', 0, '') as URLImage3 ,"+ dbSchema+".species_standard_element_content(td.taxon_id, td.taxon_description_sequence, 'CaptionImage3', 0, '') as CaptionImage3 "+ "from "+dbSchema+".taxon_description td "+ "left outer join "+dbSchema+".taxon t on (t.taxon_id = td.taxon_id)"+ "left outer join "+dbSchema+".language l on (l.language_id = td.language_id) "+ "left outer join "+dbSchema+".concept cp on (l.language_id = cp.concept_id) "+ "left outer join "+dbSchema+".taxon r on (r.taxon_id = t.kingdom_taxon_id)"+ "left outer join "+dbSchema+".taxon fl on (fl.taxon_id = t.phylum_division_taxon_id)"+ "left outer join "+dbSchema+".taxon c on (c.taxon_id = t.class_taxon_id )"+ "left outer join "+dbSchema+".taxon tor on (tor.taxon_id = t.order_taxon_id ) "+ "left outer join "+dbSchema+".taxon tf on (tf.taxon_id = t.family_taxon_id)"+ "left outer join "+dbSchema+".taxon g on (g.taxon_id = t.genus_taxon_id)"+ "left outer join "+dbSchema+".taxon s on (s.taxon_id = t.genus_taxon_id)"+ "left outer join "+dbSchema+".institution i on (td.institution_id = i.institution_id);"; try{ Query q1 = em.createNativeQuery("drop table "+dbSchema+".plinian_core_flat;"); System.out.println(q1.executeUpdate() + " drop plinian_core_flat"); } catch(Exception e){return false;} try{ Query q2 = em.createNativeQuery(creationString); System.out.println(q2.executeUpdate() + " create plinian_core_flat"); } catch(Exception e){return false;} try{ Query q3 = em.createNativeQuery(insertString); System.out.println(q3.executeUpdate() + " inserts plinian_core_flat"); } catch(Exception e){System.out.println(e.getCause());return false;} return true; } }
package com.example.admin.testingv1; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.nfc.Tag; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import org.w3c.dom.Text; import java.util.Calendar; public class addEvent extends AppCompatActivity implements View.OnClickListener { private static final String TAG = addEvent.class.getSimpleName(); private TextView theDate; private Button backToEventsToday; private FirebaseAuth firebaseAuth; private TextView startDate; private TextView endDate; private DatePickerDialog.OnDateSetListener startDateSetListener; private DatePickerDialog.OnDateSetListener endDateSetListener; private String date; private TextView startTime; private TextView endTime; private TimePickerDialog.OnTimeSetListener startTimeSetListener; private TimePickerDialog.OnTimeSetListener endTimeSetListener; private DatabaseReference eventDB; private Button addEventBtn; private EditText eventName; private EditText remarks; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_event); theDate = (TextView) findViewById(R.id.theDate); backToEventsToday = (Button) findViewById(R.id.backToEventsToday); addEventBtn = (Button) findViewById(R.id.addEvent); firebaseAuth = FirebaseAuth.getInstance(); Intent incomingIntent = getIntent(); date = incomingIntent.getStringExtra("date"); remarks = (EditText) findViewById(R.id.remarks); eventName = (EditText) findViewById(R.id.eventName); startTime = (TextView) findViewById(R.id.startTime); endTime = (TextView) findViewById(R.id.endTime); startTime.setText("08:00"); endTime.setText("09.00"); startTimeSetListener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Log.d(TAG, "onTimeSet: hh:mm " + hourOfDay + ":" + minute); String time = hourOfDay + ":" + minute; startTime.setText(time); } }; endTimeSetListener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Log.d(TAG, "onTimeSet: hh:mm " + hourOfDay + ":" + minute); String time = hourOfDay + ":" + minute; endTime.setText(time); } }; startDate = (TextView) findViewById(R.id.startDate); endDate = (TextView) findViewById(R.id.endDate); startDate.setText(date); endDate.setText(date); theDate.setText(date); startTime.setOnClickListener(this); endTime.setOnClickListener(this); startDate.setOnClickListener(this); endDate.setOnClickListener(this); backToEventsToday.setOnClickListener(this); addEventBtn.setOnClickListener(this); startDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { month = month + 1; Log.d(TAG,"onDateSet: mm/dd/yyyy: " + month + "/" + dayOfMonth + "/" + year); String date = month + "/" + dayOfMonth + "/" + year; startDate.setText(date); } }; endDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { month = month + 1; Log.d(TAG,"onDateSet: mm/dd/yyyy: " + month + "/" + dayOfMonth + "/" + year); String date = month + "/" + dayOfMonth + "/" + year; endDate.setText(date); } }; } public void onClick(View view) { if(view == backToEventsToday){ //will open login Intent intent = new Intent(addEvent.this, EventsToday.class); intent.putExtra("date", date); startActivity(intent); } if(view == startDate) { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog( this, android.R.style.Theme_Holo_Dialog, startDateSetListener, year, month, day); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); } if(view == endDate) { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog( this, android.R.style.Theme_Holo_Dialog, endDateSetListener, year, month, day); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); } if(view == startTime) { Calendar cal = Calendar.getInstance(); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); TimePickerDialog dialog = new TimePickerDialog( this, startTimeSetListener, hour, minute, true); dialog.show(); } if(view == endTime) { Calendar cal = Calendar.getInstance(); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); TimePickerDialog dialog = new TimePickerDialog( this, endTimeSetListener, hour, minute, true); dialog.show(); } if(view == addEventBtn) { Toast.makeText(addEvent.this, "Added Successfully!", Toast.LENGTH_SHORT).show(); String userId = firebaseAuth.getCurrentUser().getUid(); eventDB = FirebaseDatabase.getInstance().getReference().child("Users").child(userId).child("Events"); String eventId = eventDB.push().getKey(); String event_name = eventName.getText().toString().trim(); String start_time = startTime.getText().toString().trim(); String end_time = endTime.getText().toString().trim(); String start_date = startDate.getText().toString().trim(); String end_date = endDate.getText().toString().trim(); String remarks_ = remarks.getText().toString().trim(); Event event = new Event(event_name, start_time, end_time, start_date, end_date, remarks_, eventId); eventDB.child(eventId).setValue(event); Intent intent = new Intent(addEvent.this, EventsToday.class); intent.putExtra("date", date); startActivity(intent); } } }
package backtracking; import java.util.ArrayList; import java.util.Arrays; public class SubsetWithGivenSum { public void subsetUtil( ArrayList<ArrayList<Integer>> result, ArrayList<Integer> dummy, ArrayList<Integer> arr, int start, int end, int currentSum, int expectedSum) { System.out.println("Start: " + start + " Dummy: " + dummy.toString() + " currentSum: " + currentSum); if(currentSum == expectedSum && !dummy.isEmpty()){ result.add(new ArrayList<>(dummy)); return; } while(start <= end) { dummy.add(arr.get(start)); currentSum += arr.get(start); subsetUtil(result, dummy, arr, start+1, end, currentSum, expectedSum); start++; currentSum -= dummy.get(dummy.size() -1); dummy.remove(dummy.size() - 1); } } public ArrayList<ArrayList<Integer>> subsetWithGiveSum(ArrayList<Integer> arr, int sum) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> dummy = new ArrayList<Integer>(); subsetUtil(result, dummy, arr, 0, arr.size()-1, 0, sum); return result; } public static void main(String[] args) { Integer[] arr = {1, -4, 2, 3, -2}; ArrayList<Integer> list = new ArrayList<>(); list.addAll(Arrays.asList(arr)); SubsetWithGivenSum ssgs = new SubsetWithGivenSum(); ArrayList<ArrayList<Integer>> result = ssgs.subsetWithGiveSum(list, 0); for(ArrayList<Integer> innerList: result) { for(Integer a: innerList) { System.out.print(a + " "); } System.out.println(); } } }
/* Test 50: * * Istruzione while .. do */ package gimnasium; class s1 { void pippo() { int var1, var2; while (true) ; while (var1); // errore!!! var1 non e' boolean. while (var1 > var2) if (true); } }
package algorithms.strings.substring; import algorithms.context.AppTestContext; import algorithms.strings.alphabet.Alphabet; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Created by Chen Li on 2018/4/17. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppTestContext.class) public class RabinKarpSearcherTest extends SubstringSearcherTest { @Autowired private Alphabet numericAlphabet; @Autowired private Alphabet lowercaseAlphabet; @Override protected SubstringSearcher createInstance() { return new RabinKarpSearcher(lowercaseAlphabet, 1111111111111111111L); } @Test public void radix10Test() { SubstringSearcher searcher = new RabinKarpSearcher(numericAlphabet, 1111111111111111111L); searcher.compile("26535"); int index = searcher.search("3141592653589793"); Assert.assertEquals(6, index); } }
package baekjoon; import java.io.*; public class Num_1157 { public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String[] input=br.readLine().split(""); int ascii[]=new int[input.length]; int test[]=new int[91]; for(int i=0;i<91;i++) test[i]=0; for(int i=0;i<input.length;i++) { ascii[i]=input[i].charAt(0); if(ascii[i] >=97 && ascii[i] <=122) ascii[i] -= 32; test[ascii[i]] += 1; } int cnt=0; int max=0; for(int i=0;i<91;i++) { if(max < test[i]) { cnt=i; max=test[i]; } } for(int i=0;i<91;i++) { if(max == test[i] && cnt != i) { System.out.println("?"); cnt=0; break; } } if(cnt != 0) System.out.println((char)cnt); } }
package com.nextLevel.hero.mngCertificate.model.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.nextLevel.hero.mngCertificate.model.dao.MngCertificateMapper; import com.nextLevel.hero.mngCertificate.model.dto.CertificateMemberDTO; @Service("mngCertificateService") public class MngCertificateServiceImpl implements MngCertificateService { private final MngCertificateMapper mngCertificateMapper; @Autowired public MngCertificateServiceImpl(MngCertificateMapper mngCertificateMapper) { this.mngCertificateMapper = mngCertificateMapper; } @Override public List<CertificateMemberDTO> findAllMember(int companyNo) { return mngCertificateMapper.selectfindAllMember(companyNo); } }
/*********************************************************************** * Module:PerMng.java * Author:wod * Purpose: Defines the Class PerMng ***********************************************************************/ package com.infohold.els.model; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; import com.infohold.bdrp.Constants; import com.infohold.bdrp.tools.security.SecurityUtil; import com.infohold.bdrp.tools.security.impl.SecurityConstants; import com.infohold.core.model.BaseIdModel; import com.infohold.core.utils.StringUtils; @Entity @Table(name = "ELS_PAY_BATCHINFO") public class PayBatchinfo extends BaseIdModel { private static final long serialVersionUID = 5280554750433683890L; public static final String STATUS_WAIT = "0"; public static final String STATUS_SUCCESS = "1"; public static final String STATUS_FAIL = "2"; private String perId; private String batchId; private String batchNo; private String month; private String name; private String acctNo; private String acctNoEnc; private String acctNoHash; private BigDecimal amount; private String payTime; private String payState; private String stateMemo; public PayBatchinfo() { } public PayBatchinfo(PayPreview perview) { this.setAcctNo(perview.getAcctNo()); this.amount = perview.getAmount(); this.batchId = perview.getBatchId(); this.batchNo = perview.getBatchNo(); this.month = perview.getMonth(); this.name = perview.getName(); this.payState = "0"; this.perId = perview.getPerId(); } @Column( name = "PER_ID", length = 32 ) public String getPerId() { return perId; } public void setPerId(String perId) { this.perId = perId; } @Column( name = "BATCH_ID", length = 32 ) public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } @Column( name = "BATCH_NO", length = 20 ) public String getBatchNo() { return batchNo; } public void setBatchNo(String batchNo) { this.batchNo = batchNo; } @Column( name = "MONTH", length = 6 ) public String getMonth() { return month; } public void setMonth(String month) { this.month = month; } @Column( name = "NAME", length = 48 ) public String getName() { return name; } public void setName(String name) { this.name = name; } @Transient public String getAcctNo() { if(StringUtils.isNotEmpty(this.getAcctNoEnc())){ this.acctNo = SecurityUtil.decryptData(SecurityConstants.DATA_TYPE_ACCOUNT, Constants.APP_SUPER_ID, this.getAcctNoEnc(), SecurityConstants.KEY_MASTER_KEY_NAME, null); } return this.acctNo; } public void setAcctNo(String acctNo) { this.acctNo = acctNo; if(StringUtils.isNotEmpty(acctNo)){ String[] enc = SecurityUtil.encryptData(SecurityConstants.DATA_TYPE_ACCOUNT, Constants.APP_SUPER_ID, acctNo, SecurityConstants.KEY_MASTER_KEY_NAME, null).split(SecurityConstants.ARRAY_TOSTRING_SEP); this.setAcctNoEnc(enc[0]); this.setAcctNoHash(enc[1]); } } @Column(name = "ACCT_NO_ENC", length = 50) public String getAcctNoEnc() { return acctNoEnc; } public void setAcctNoEnc(String acctNoEnc) { this.acctNoEnc = acctNoEnc; } @Column(name = "ACCT_NO_HASH", length = 50) public String getAcctNoHash() { return acctNoHash; } public void setAcctNoHash(String acctNoHash) { this.acctNoHash = acctNoHash; } @Column( name = "AMOUNT" ) public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } @Column( name = "PAY_TIME", length = 19 ) public String getPayTime() { return payTime; } public void setPayTime(String payTime) { this.payTime = payTime; } @Column( name = "PAY_STATE", length = 1 ) public String getPayState() { return payState; } public void setPayState(String payState) { this.payState = payState; } @Column( name = "STATE_MEMO", length = 128 ) public String getStateMemo() { return stateMemo; } public void setStateMemo(String stateMemo) { this.stateMemo = stateMemo; } /** * 判断状态是否存在状态序列中 * * @param statusCode * @return */ public static boolean hasStatus(String statusCode) { return PayBatchinfo.STATUS_WAIT.equals(statusCode) || PayBatchinfo.STATUS_SUCCESS.equals(statusCode) || PayBatchinfo.STATUS_FAIL.equals(statusCode); } }
package com.logicbig.example; import org.apache.commons.collections.Bag; import org.apache.commons.collections.bag.HashBag; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @SpringBootApplication public class ApplicationExample { @Bean public MyBean myBean () { return new MyBean(); } public static void main (String[] args) { ApplicationContext ctx = SpringApplication.run(ApplicationExample.class, args); MyBean bean = ctx.getBean(MyBean.class); bean.doSomething(); } private static class MyBean { public void doSomething () { Bag bag = new HashBag(); bag.add("ONE", 6); System.out.println("Doing something in MyBean"); System.out.println(bag); } } }
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.node.admin.docker;// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. import com.yahoo.config.provision.NodeType; /** * The types of network setup for the Docker containers. * * @author hakon */ public enum DockerNetworking { /** Each container has an associated macvlan bridge. */ MACVLAN("vespa-macvlan"), /** Network Prefix-Translated networking. */ NPT("vespa-bridge"), /** A host running a single container in the host network namespace. */ HOST_NETWORK("host"); private final String dockerNetworkMode; DockerNetworking(String dockerNetworkMode) { this.dockerNetworkMode = dockerNetworkMode; } public String getDockerNetworkMode() { return dockerNetworkMode; } public static DockerNetworking from(String cloud, NodeType nodeType, boolean hostAdmin) { if (cloud.equalsIgnoreCase("aws")) { return DockerNetworking.NPT; } else if (nodeType == NodeType.confighost || nodeType == NodeType.proxyhost) { return DockerNetworking.HOST_NETWORK; } else if (hostAdmin) { return DockerNetworking.NPT; } else { return DockerNetworking.MACVLAN; } } }
//package com.xiangyang.controller; // //import com.fasterxml.jackson.annotation.JsonInclude; //import lombok.Data; // //@JsonInclude(JsonInclude.Include.NON_NULL) // //@Data //public class User { // private String name; // // private Integer age; // // private Integer id; // //}
package com.codecool.movieorganizer.repository.db; import com.codecool.movieorganizer.model.MovieCharacter; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Set; public interface MovieCharacterRepository extends JpaRepository<MovieCharacter, Long> { Set<MovieCharacter> findAllByNameIn(Set<String> names); }
package com.redstoner.remote_console.protected_classes; import java.util.UUID; import com.mojang.authlib.GameProfile; import net.minecraft.server.v1_11_R1.EntityPlayer; import net.minecraft.server.v1_11_R1.EnumProtocolDirection; import net.minecraft.server.v1_11_R1.MinecraftServer; import net.minecraft.server.v1_11_R1.PlayerConnection; import net.minecraft.server.v1_11_R1.PlayerInteractManager; import net.minecraft.server.v1_11_R1.WorldServer; /** This class creates a FakeEntityPlayer to be used for creating a FakePlayer without having an online player to start with. * * @author Pepich1851 */ public class FakeEntityPlayer extends EntityPlayer { /** Constructor to allow creation of a FakePlayer without an actual online player. * * @param minecraftserver the MinecraftServer instance * @param worldserver the WorldServer instance * @param gameprofile the GameProfile of the user * @param playerinteractmanager the PlayerInteractManager of the user */ public FakeEntityPlayer(MinecraftServer minecraftserver, WorldServer worldserver, GameProfile gameprofile, PlayerInteractManager playerinteractmanager, User owner) { super(minecraftserver, worldserver, gameprofile, playerinteractmanager); this.playerConnection = new PlayerConnection(minecraftserver, new CustomNetworkManager(EnumProtocolDirection.SERVERBOUND), this); this.bukkitEntity = new FakePlayer(uniqueID, owner, this); } /** Constructor to allow creation of a FakePlayer without an actual online player. * This version of the constructor will generate the missing values from the given UUID and displayName to invoke the original constructor. * * @param uuid the UUID of the player * @param displayName the displayName to be used for the player */ public FakeEntityPlayer(UUID uuid, String name, String displayname, User owner) { super(MinecraftServer.getServer(), MinecraftServer.getServer().getWorldServer(0), new GameProfile(uuid, name), new PlayerInteractManager(MinecraftServer.getServer().getWorld())); this.playerConnection = new PlayerConnection(MinecraftServer.getServer(), new CustomNetworkManager(EnumProtocolDirection.SERVERBOUND), this); this.bukkitEntity = new FakePlayer(uniqueID, owner, this); } }
package com._520it.dbutils; import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; import com._520it.utils.DataSourceUtils; public class DBUtilDemo { public static void main(String[] args) { //DBUtil实现事务 Connection connection=null; try { //1.核心类 QueryRunner qRunner=new QueryRunner(); //2.sql语句 String sql="insert into account values(null,?,?)"; //3.为占位符赋值 Object[] params = {"lucy",5000}; connection = DataSourceUtils.getConnection(); //开启事务 connection.setAutoCommit(false); //执行sql语句 qRunner.update(connection, sql, params); connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } } }
package com.test; import java.util.HashMap; import com.test.base.Solution; public class SolutionA implements Solution { @Override public int maxCoins(int[] nums) { if (null == nums) { return 0; } // i表示,当前路径下,最后一个气球 return fun(nums, 0, nums.length - 1); } private HashMap<Integer, Integer> cache = new HashMap<>(); private int fun(int[] nums, int start, int end) { if (start > end) { return 0; } final int key = start * nums.length + end; // 读取缓存 Integer value = cache.get(key); if (null != value) { return value; } final int startBorder = start == 0 ? 1 : nums[start - 1]; final int endBorder = end == nums.length - 1 ? 1 : nums[end + 1]; // i表示,当前路径下,最后一个气球 int max = Integer.MIN_VALUE; for (int i = start; i <= end; i++) { int tempMax = fun(nums, start, i - 1) + startBorder * nums[i] * endBorder + fun(nums, i + 1, end); max = Math.max(max, tempMax); } // 存入缓存 cache.put(key, max); return max; } }
package dataFactory.impl; import dataFactory.OrderDataHelper; import po.OrderEvaluationPO; import po.OrderPO; import java.sql.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by arloor on 16-11-22. */ public class OrderMysqlDataHelper implements OrderDataHelper { /* static String url= "jdbc:mysql://104.194.66.38:3306/hotelSystem?" + "user=ruangong&password=ruangong&useUnicode=true&characterEncoding=UTF8useSSL=true"; */ static String url= "jdbc:mysql://123.206.213.148:3306/hotelSystem?" + "user=root&password=root&useUnicode=true&characterEncoding=UTF8"; /* //使用本地数据库 static String url= "jdbc:mysql://localhost:3306/hotelSystem?" + "user=root&password=root&useUnicode=true&characterEncoding=UTF8&useSSL=true"; */ Connection conn; /** * 构造函数:初始化数据库连接 */ public OrderMysqlDataHelper(){ try { Class.forName( "com.mysql.jdbc.Driver" ); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("mysql驱动缺失"); } try { conn= DriverManager.getConnection(url ); System.out.println("数据库连接成功"); } catch (SQLException e) { e.printStackTrace(); } } /** * 测试已通过 * 获取订单评价列表 * @return */ @Override public Map<Integer, OrderEvaluationPO> getEvaluation() { Map<Integer, OrderEvaluationPO> map =new HashMap<Integer, OrderEvaluationPO>(); try{ Statement statement = conn.createStatement(); ResultSet resultSet=statement.executeQuery("SELECT orderID,pingfen,pingjia FROM orderInfo"); //statement.close();放在这里汇报错。。。。 while( resultSet.next() ){ int orderID=Integer.parseInt(resultSet.getString(1)); double pingfen=resultSet.getDouble("pingfen"); String pingjia=resultSet.getString("pingjia"); //只有pignfen部委0,评价部位空才加进去 if(pingfen!=0.0&&pingjia!=null) { //System.out.println(pingfen+" "+pingjia); OrderEvaluationPO oepo = new OrderEvaluationPO(orderID, pingfen, pingjia); map.put(orderID, oepo); } } statement.close(); resultSet.close(); return map; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * 测试已通过 * 获取订单列表 * @return */ @Override public Map<Integer, OrderPO> getOrderData() { Map<Integer, OrderPO> map =new HashMap<Integer, OrderPO>(); try { Statement statement = conn.createStatement(); ResultSet resultSet=statement.executeQuery("SELECT * FROM orderInfo"); while( resultSet.next() ){ int orderID=Integer.parseInt(resultSet.getString(1)); String memberID=resultSet.getString(2); String hotel=resultSet.getString(3); String status=resultSet.getString(4); String roomID=resultSet.getString(5); int roomNum=resultSet.getInt(6); int peopleNum=resultSet.getInt(7); String haschild=resultSet.getString(8); String lastCheckinTime=resultSet.getTimestamp(9).toString().substring(0,19); String checkinTime; try { checkinTime = resultSet.getTimestamp(10).toString().substring(0,19); }catch (NullPointerException e){ //System.out.println("入住时间默认为1970-01-01。。。尚未入住,入住时间为空,将checkinTime设置为空"); checkinTime="1970-01-01 00:00:01"; } String lastCheckoutTime=resultSet.getTimestamp(11).toString().substring(0,19); String CheckoutTime; try { CheckoutTime = resultSet.getTimestamp(12).toString().substring(0,19); /* if(CheckoutTime.equals("1970-01-01 00:00:01.0")||CheckoutTime.equals("1970-01-01 00:00:01")){ System.out.println("退房时间默认为1970-01-01。。。 尚未退房,退房时间为空,将checkoutTime设为空"); //CheckoutTime=""; }*/ }catch (NullPointerException e){ //System.out.println("尚未退房,退房时间为空,将checkoutTime设为空"); CheckoutTime="1970-01-01 00:00:01"; } double price=resultSet.getDouble(13); double charge=resultSet.getDouble(14); String cancelTime=resultSet.getTimestamp(15).toString().substring(0,19); //System.out.println(cancelTime); OrderPO opo=new OrderPO(orderID,memberID,hotel,status,roomID,roomNum,peopleNum,haschild,lastCheckinTime, checkinTime,lastCheckoutTime,CheckoutTime,price,charge,cancelTime); map.put(orderID,opo); } statement.close(); resultSet.close(); return map; } catch (SQLException e) { e.printStackTrace(); } return null; } /* @Override public OrderEvaluationPO getOrderEvaluationBiID(int orderID) { return null; }*/ /** * 测试已通过 * @param oepo * @return */ @Override public Map<Integer, OrderEvaluationPO> updateOrderEvaluation(OrderEvaluationPO oepo) { Map<Integer, OrderEvaluationPO> map=new HashMap<>(); String sql="UPDATE orderInfo " + "SET pingfen="+oepo.getPingfen()+",pingjia='"+oepo.getPingjia()+ "' WHERE orderID="+oepo.getOrderID(); try{ Statement statement = conn.createStatement(); statement.executeUpdate(sql); map=getEvaluation(); statement.close(); return map; }catch (SQLException e) { e.printStackTrace(); } return null; } /*@Override public ResultMessage insertOrderEvaluation(OrderEvaluationPO oepo) { return null; }*/ /** * 测试通过 * @param opo * @return */ @Override public Map<Integer,OrderPO> insertOrder(OrderPO opo) { Map<Integer,OrderPO> map=new HashMap<>(); //String sql=""; try { Statement statement = conn.createStatement(); statement.executeUpdate("INSERT INTO orderInfo (orderID,memberID,hotel,status,roomID,roomNum,peopleNum,hasChild,lastCheckinTime,lastCheckoutTime,price,charge) VALUES (" +opo.getOrderID()+",'"+ opo.getCustomerID()+"','" + opo.getHotel() + "','"+ opo.getStatus()+"','"+ opo.getRoomID()+"',"+ opo.getRoomNum()+","+ opo.getPeopleNum()+",'"+ opo.getHasChild()+"','" + opo.getLastCheckInTime()+"','"+ opo.getLastCheckoutTime()+"',"+ opo.getPrice()+","+ opo.getCharge()+ ")" ); /* statement.executeUpdate("INSERT INTO orderInfo (orderID,memberID,hotel,status,roomID,roomNum,peopleNum,hasChild,lastCheckinTime,checkoutTime,price,charge,creditChange)" + " VALUES ("+opo.getOrderID()+",'"+opo.getMemberID()+"','"+opo.getHotel() +"','"+opo.getStatus()+"','"+opo.getRoomType()+"',"+opo.getRoomNum()+","+opo.getPeopleNum()+",'"+opo.getHaschild()+"','" +opo.getLastCheckinTime()+"','"+opo.getCheckOutime()+"',"+opo.getPrice()+","+opo.getCharge()+","+opo.getCreditChange()+")"); */ statement.close(); map=getOrderData(); return map; }catch (SQLException e){ e.printStackTrace(); } return null; } /** * 撤销订单,已经测试过 * @param OrderID * @return */ @Override public Map<Integer, OrderPO> deleteOrderByID(int OrderID) { Map<Integer, OrderPO> map=new HashMap<>(); SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time =dateFormat.format(new Date()); try{ Statement statement = conn.createStatement(); statement.executeUpdate("UPDATE orderInfo " + "SET status='已撤销',cancelTime='"+ time+"' "+ "WHERE orderID="+OrderID); statement.close(); map=getOrderData(); return map; }catch (SQLException e) { e.printStackTrace(); } return null; } /** * 测试已通过 * @param opo * @return */ @Override public Map<Integer, OrderPO> updateOrder(OrderPO opo) { Map<Integer, OrderPO> map=new HashMap<>(); String sql="UPDATE orderInfo " + "SET lastCheckinTime='"+opo.getLastCheckInTime()+"'"+ ",checkoutTime='"+opo.getCheckOutTime()+"'"+ ",checkinTime='"+opo.getCheckInTime()+"'"+ ",LastCheckoutTime='"+opo.getLastCheckoutTime()+"'"+ ",status='"+opo.getStatus()+"'"+ ",cancelTime='"+opo.getCancelTime()+"'"+ " WHERE orderID="+opo.getOrderID(); try{ Statement statement = conn.createStatement(); statement.executeUpdate(sql); map=getOrderData(); statement.close(); return map; }catch (SQLException e) { e.printStackTrace(); } return null; } }
package com.easyway.fixinventory.utils.http; import com.easyway.fixinventory.model.AssetsTakeInventoryForPDABean; import com.easyway.fixinventory.model.InventoryInfoBean; import com.easyway.fixinventory.model.UserBean; import com.hanks.frame.base.BaseModel; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; /** * @author 侯建军 47466436@qq.com * @date 2018/6/4 * @description 所有请求的地址 和 请求的参数 */ public interface HttpApis { /** * 登陆 * * @param HRCode * @param Password * @return */ @FormUrlEncoded @POST("/api/EmployeeForPDA") Call<BaseModel<UserBean>> login( @Field("hrCode") String HRCode, @Field("pwd") String Password ); /** * 卡片信息获取 * * @param CardNo 主码 * @return */ @FormUrlEncoded @POST("/api/AssetsTakeInventoryInfoForPDA") Call<BaseModel<InventoryInfoBean>> AssetsTakeInventoryInfoForPDA( @Field("CardNo") String CardNo ); /** * 提交盘点信息 * * @param AssetID * @param UseStatus * @param IsAddress * @param PlaceAddress * @return */ @FormUrlEncoded @POST("/api/AssetsTakeInventoryForPDA") Call<BaseModel<AssetsTakeInventoryForPDABean>> AssetsTakeInventoryForPDA( @Field("AssetID") String AssetID, @Field("UseStatus") int UseStatus, @Field("IsAddress") int IsAddress, @Field("PlaceAddress") String PlaceAddress, @Field("HRCode") String HRCode ); }
/* Copyright 2015 Alfio Zappala 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 co.runrightfast.commons.utils; import co.runrightfast.exceptions.ApplicationException; import static co.runrightfast.exceptions.ApplicationExceptionSeverity.MAJOR; import co.runrightfast.services.IllegalServiceStateTransitionException; import com.google.common.util.concurrent.Service; import static com.google.common.util.concurrent.Service.State.NEW; import static com.google.common.util.concurrent.Service.State.RUNNING; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; /** * * @author alfio */ @Slf4j public final class ServiceUtils { private ServiceUtils() { } public static void start(@NonNull final Service service) { switch (service.state()) { case NEW: service.startAsync(); awaitRunning(service); return; case STARTING: service.awaitRunning(); awaitRunning(service); return; case RUNNING: return; default: throw new IllegalServiceStateTransitionException(service.state(), RUNNING); } } /** * * @param service if null, then do nothing */ public static void stop(final Service service) { if (service != null) { switch (service.state()) { case STARTING: case RUNNING: service.stopAsync(); awaitTerminated(service); return; case STOPPING: awaitTerminated(service); return; case NEW: case FAILED: case TERMINATED: log.debug("Service ({}) is not running: {}", service.getClass().getName(), service.state()); } } } public static void stopAsync(final Service service) { if (service != null) { switch (service.state()) { case STARTING: case RUNNING: service.stopAsync(); return; case STOPPING: return; case NEW: case FAILED: case TERMINATED: log.debug("Service ({}) is not running: {}", service.getClass().getName(), service.state()); } } } /** * Logs a warning every 10 seconds, waiting for the service to stop * * @param service Service */ public static void awaitTerminated(@NonNull final Service service) { for (int i = 1; true; i++) { try { service.awaitTerminated(10, TimeUnit.SECONDS); return; } catch (final TimeoutException ex) { final int elapsedTimeSeconds = i * 10; log.warn( String.format("Wating for service to terminate : %s : %d seconds", service.getClass().getName(), elapsedTimeSeconds), new ApplicationException(MAJOR, ex) ); } } } /** * Logs a warning every 10 seconds, waiting for the service to start * * @param service Service */ public static void awaitRunning(@NonNull final Service service) { for (int i = 1; true; i++) { try { service.awaitRunning(10, TimeUnit.SECONDS); return; } catch (final TimeoutException ex) { final int elapsedTimeSeconds = i * 10; log.warn( String.format("Wating for service to start : %s : %d seconds", service.getClass().getName(), elapsedTimeSeconds), new ApplicationException(MAJOR, ex) ); } } } }
package com.uog.miller.s1707031_ct6039.servlets.calendar; import com.uog.miller.s1707031_ct6039.beans.CalendarItemBean; import com.uog.miller.s1707031_ct6039.oracle.CalendarConnections; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; @WebServlet(name = "CalendarActions") public class CalendarActions extends HttpServlet { static final Logger LOG = Logger.getLogger(CalendarActions.class); //Get Event from DB to show info @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { String eventID = request.getParameter("eventId"); String user = (String) request.getSession(true).getAttribute("email"); if(eventID != null) { //Select redirect based on location LOG.debug("Found eventID: " + eventID + ", attempting to retrieve info."); removeAlerts(request); removeFormAlerts(request); CalendarConnections connections = new CalendarConnections(); CalendarItemBean bean = connections.getCalendarItemForUser(user, eventID); if(bean.getEventId() != null) { //Event found, return information. addEventSession(request, bean); redirectToCalendarSuccess(request, response, eventID); } else { //Event not found, alert user. redirectToCalendarFail(request, response); } } else { //Error, redirect. redirectToCalendarFail(request, response); } } private void addEventSession(HttpServletRequest request, CalendarItemBean bean) { request.getSession(true).setAttribute("eventId", bean.getEventId()); request.getSession(true).setAttribute("eventName", bean.getEventName()); request.getSession(true).setAttribute("eventUser", bean.getUser()); request.getSession(true).setAttribute("eventDate", bean.getEventDate()); request.getSession(true).setAttribute("eventUpdateDate", bean.getDateForUpdate()); } private void redirectToCalendarFail(HttpServletRequest request, HttpServletResponse response) { try { removeFormAlerts(request); removeAlerts(request); LOG.error("No eventID specified, returning to calendar."); request.getSession(true).setAttribute("formErrors", "Unable to retrieve information for the selected event."); response.sendRedirect(request.getContextPath() + "/jsp/actions/calendar/viewcalendar.jsp"); } catch (IOException e) { LOG.error("Unable to redirect to calendar page", e); } } private void redirectToCalendarSuccess(HttpServletRequest request, HttpServletResponse response, String eventId) { try { removeFormAlerts(request); LOG.debug("Successfully found event using ID: " + eventId ); request.getSession(true).setAttribute("formSuccess", "Retrieved information for the selected event."); response.sendRedirect(request.getContextPath() + "/jsp/actions/calendar/viewcalendar.jsp"); } catch (IOException e) { LOG.error("Unable to redirect to calendar page", e); } } private void removeAlerts(HttpServletRequest request) { request.getSession(true).removeAttribute("eventId"); request.getSession(true).removeAttribute("eventName"); request.getSession(true).removeAttribute("eventUser"); request.getSession(true).removeAttribute("eventDate"); request.getSession(true).removeAttribute("eventUpdateDate"); } private void removeFormAlerts(HttpServletRequest request) { request.getSession(true).removeAttribute("formErrors"); request.getSession(true).removeAttribute("formSuccess"); } }
package com.zhongyp.transaction; /** * project: demo * author: zhongyp * date: 2018/3/1 * mail: zhongyp001@163.com */ public class StockException extends Exception { private static final long serialVersionUID = 5377570098437361228L; public StockException() { super(); } public StockException(String message) { super(message); } }
package com.adidas.microservices.publicservice.entity; import com.adidas.microservices.publicservice.enums.Gender; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import java.time.LocalDate; @NoArgsConstructor @Data public class Subscription { @NotNull(message = "Id of campaign must be defined") private Long campaignId; @NotNull(message = "Date of birth must be defined in dd.MM.yyyy format") @Past(message = "Entered date of birth must be set in the past") @JsonFormat(pattern = "dd.MM.yyyy") private LocalDate dateOfBirth; private String firstName; private Gender gender; @NotNull(message = "Email must be defined in format email@host") @Email(message = "Email format is not valid. Please use format email@host") private String email; @AssertTrue(message = "You must consent to terms to be able to receive newsletter") private boolean consent; }
package generator.util.loop; public enum LoopDirection { FORWARD, BACKWARD; }
package org.jbehave.demo.pages; import org.jbehave.demo.domain.Flight; public class SearchFlightPage { public void select(Flight flight) { } }
package com.baidu.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RestController; /** * <p> * Created by mayongbin01 on 2017/1/17. * <p> * controller * <p> * process business logic */ @RestController public class ServerInfoController { private static Logger logger = LoggerFactory.getLogger(ServerController.class); }
/* There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1]. Return the minimum cost to fly every person to a city such that exactly N people arrive in each city. Example 1: Input: [[10,20],[30,200],[400,50],[30,20]] Output: 110 Explanation: The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. */ class Solution { public int twoCitySchedCost(int[][] costs) { /* sort according to distance between A and B first select person closer to A, then select person closer to B */ Arrays.sort(costs, (int[] a,int[] b) ->(a[0] - a[1] - (b[0] - b[1]))); int sum = 0; for(int i = 0; i < costs.length/2; i++){ sum += costs[i][0]; } for(int i = costs.length/2; i < costs.length; i++){ sum += costs[i][1]; } return sum; } }
package com.example.android.splitwise; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; /** * Created by siddharthverma on 3/30/17. */ public class BannerActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.banner_page); // Get the Intent that started this activity and extract the string Intent intent = getIntent(); String message = intent.getStringExtra("user_name"); // Capture the layout's TextView and set the string as its text TextView textView = (TextView) findViewById(R.id.name_banner); textView.setText(message+" !"); final Button button_choose_event = (Button) findViewById(R.id.choose_event); button_choose_event.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click Intent activityChangeIntent = new Intent(BannerActivity.this, CalculationEditorActivity.class); activityChangeIntent.putExtra("Event_type", "Event/Trip Title:"); BannerActivity.this.startActivity(activityChangeIntent); } }); final Button button_choose_apartment = (Button) findViewById(R.id.choose_apartment); button_choose_apartment.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click Intent activityChangeIntent = new Intent(BannerActivity.this, CalculationEditorActivity.class); activityChangeIntent.putExtra("Event_type", "Apartment Name:"); BannerActivity.this.startActivity(activityChangeIntent); } }); final Button button_home = (Button) findViewById(R.id.home); button_home.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click Intent activityChangeIntent = new Intent(BannerActivity.this, CalculationListActivityGroup.class); BannerActivity.this.startActivity(activityChangeIntent); } }); } }
/** * Missile.java * * @author Lovejit Kharod, Sebrianne Ferguson * Last edited: November 19, 2018 * Purpose: Allows for creation of missiles to shoot at the planes. */ class Missile extends FlyingObject { private static final int MISSILE_SPEED = 5; Missile(int x, int y, int dir) { // dir -> -1 = up, 0 = mid, 1 down super("resources/missile.png", 50, 30, x, y); dx = MISSILE_SPEED; dy = dir * MISSILE_SPEED; } }
package com.example.bob.health_helper.Bean; import com.google.gson.annotations.SerializedName; /** * Created by Bob on 2019/3/13. */ public class Error { @SerializedName("code") private String mCode; @SerializedName("msg") private String mMsg; public String getCode() { return mCode; } public void setCode(String code) { mCode = code; } public String getMsg() { return mMsg; } public void setMsg(String msg) { mMsg = msg; } @Override public String toString() { return "Error{" + "mCode='" + mCode + '\'' + ", mMsg='" + mMsg + '\'' + '}'; } }
package com.oblac.cleancodeworkshop.flagparameter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileWriterFlagExample { public static void main(String[] args) throws IOException { final File file = new File("C:\\temp\\example.txt"); // hard to understand ??? final FileWriter fileWriter = new FileWriter(file, true); final FileWriter fileWriter2 = new FileWriter(file, false); // define readable constants final boolean APPEND_MODE = true; final boolean OVERWRITE_MODE = false; final FileWriter appendingfileWriter = new FileWriter(file, APPEND_MODE); final FileWriter overwritingfileWriter = new FileWriter(file, OVERWRITE_MODE); } }
package com.eighteengray.procamera.model.imageloader; import android.widget.ImageView; /** * Created by lutao on 2017/9/28. * 图片加载的封装类,实现方法可以采用Fresco或Glide */ public class ImageLoader implements IImageLoader { private static final ImageLoader instance = new ImageLoader(); private int planNum = 2; //图像加载实现方案 private ImageLoader(){ } public static ImageLoader getInstance(){ return instance; } @Override public void loadImage(String uri, ImageView imageView){ switch (planNum){ case 0: UniverImageLoader.getInstance().loadImage(uri, imageView); break; case 1: FrescoImageLoader.getInstance().loadImage(uri, imageView); break; case 2: GlideImageLoader.getInstance().loadImage(uri, imageView); break; } } @Override public void loadImage(String uri, ImageView imageView, ImageLoadListener imageLoadListener){ switch (planNum){ case 0: UniverImageLoader.getInstance().loadImage(uri, imageView, imageLoadListener); break; case 1: FrescoImageLoader.getInstance().loadImage(uri, imageView, imageLoadListener); break; case 2: GlideImageLoader.getInstance().loadImage(uri, imageView, imageLoadListener); break; } } }
package com.marvell.usbsetting; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.util.Log; import android.os.Handler; import android.os.Bundle; import android.os.SystemProperties; import android.os.AsyncResult; import android.os.Message; import android.media.AudioManager; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; import com.android.internal.telephony.TelephonyIntents; import com.android.internal.telephony.TelephonyProperties; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; public class UsbSettingListActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener { private static final boolean DBG = true; private static final String TAG = "UsbSetting"; private static final String KEY_NETWORK_SETTING = "network_setting"; private static final String KEY_BAND_SETTING = "band_preference"; private static final String KEY_DIAG_SETTING = "diag_setting"; private static final String KEY_CAMERA_SETTING = "camera_setting"; private static final String KEY_LOOPBACK_SETTING = "loopback_setting"; private AudioManager mAudioManager; /* Need to align with arrays.xml */ private String DiagSettingCmds[] = {"diag_usb.cfg", "diag_sd.cfg", "diag_fs.cfg","diag_udp.cfg","diag_tcp.cfg"}; private String RatSettingCmds[] = { "copy_2G_nvm.sh", "copy_3G_nvm.sh", "copy_DRAT_2G_nvm.sh", "copy_DRAT_3G_nvm.sh" }; private String mCmdLine; private UsbSetting mUsbSetting; // private Handler mHandler = new Handler(); private SharedPreferences mPreferences; private int mRatSettingValue; private int mDiagSettingValue; private int mCameraSettingValue; private int mLoopbackSettingValue; private Phone mPhone = null; private MyHandler mHandler; private TelephonyManager mTelephonyManager; // UI objects private ListPreference mButtonPreferredNetworkMode; private PreferenceScreen mGsmBandSetting; private PreferenceScreen mWcdmaBandSetting; private PreferenceScreen mTdBandSetting; public static final int PREF_KEY_RAT_SETTING_DEFAULT_VALUE = Phone.PREFERRED_NT_MODE; //4; //index in arrays.xml, default: 3G linda change use android default value. public static final String PREF_KEY_RAT_SETTING_VALUE = "PREF_KEY_RAT_SETTING_VALUE"; public static final int PREF_KEY_DIAG_SETTING_DEFAULT_VALUE = 0; //index in arrays.xml, default:USB public static final String PREF_KEY_DIAG_SETTING_VALUE = "PREF_KEY_DIAG_SETTING_VALUE"; public static final int PREF_KEY_CAMERA_SETTING_DEFAULT_VALUE = 0; //index in arrays.xml, default: MAIN CAMERA public static final String PREF_KEY_CAMERA_SETTING_VALUE = "PREF_KEY_CAMERA_SETTING_VALUE"; public static final int PREF_KEY_LOOPBACK_SETTING_DEFAULT_VALUE = 0; //index in arrays.xml, default: MAIN CAMERA public static final String PREF_KEY_LOOPBACK_SETTING_VALUE = "PREF_KEY_LOOPBACK_SETTING_VALUE"; public void readFromNonVolatile(Context context) { // read stored value. mPreferences = context.getSharedPreferences("MarvellSetting", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); /* * mRatSettingValue = mPreferences.getInt(PREF_KEY_RAT_SETTING_VALUE, * PREF_KEY_RAT_SETTING_DEFAULT_VALUE); */ mRatSettingValue = android.provider.Settings.Secure.getInt(mPhone .getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, PREF_KEY_RAT_SETTING_DEFAULT_VALUE); mDiagSettingValue = mPreferences.getInt(PREF_KEY_DIAG_SETTING_VALUE, PREF_KEY_DIAG_SETTING_DEFAULT_VALUE); mCameraSettingValue = mPreferences.getInt( PREF_KEY_CAMERA_SETTING_VALUE, PREF_KEY_CAMERA_SETTING_DEFAULT_VALUE); mLoopbackSettingValue = mPreferences.getInt( PREF_KEY_LOOPBACK_SETTING_VALUE, PREF_KEY_LOOPBACK_SETTING_DEFAULT_VALUE); } public void saveToNonVolatile() { Editor preferenceEditor = mPreferences.edit(); preferenceEditor.putInt(PREF_KEY_DIAG_SETTING_VALUE, mDiagSettingValue); preferenceEditor.putInt(PREF_KEY_CAMERA_SETTING_VALUE, mCameraSettingValue); preferenceEditor.commit(); preferenceEditor.putInt(PREF_KEY_LOOPBACK_SETTING_VALUE, mLoopbackSettingValue); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPhone = PhoneFactory.getDefaultPhone(); mHandler = new MyHandler(); mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); addPreferencesFromResource(R.xml.usb_setting); readFromNonVolatile(getBaseContext()); /* * ListPreference ratSettingPreference = (ListPreference) * findPreference(KEY_NETWORK_SETTING); * ratSettingPreference.setValue(String.valueOf(mRatSettingValue)); * ratSettingPreference.setOnPreferenceChangeListener(this); */ mButtonPreferredNetworkMode = (ListPreference) findPreference(KEY_NETWORK_SETTING); mButtonPreferredNetworkMode.setValue(String.valueOf(mRatSettingValue)); mButtonPreferredNetworkMode.setOnPreferenceChangeListener(this); ListPreference DiagSettingPreference = (ListPreference) findPreference(KEY_DIAG_SETTING); DiagSettingPreference.setValue(String.valueOf(mDiagSettingValue)); DiagSettingPreference.setOnPreferenceChangeListener(this); ListPreference CameraSettingPreference = (ListPreference) findPreference(KEY_CAMERA_SETTING); CameraSettingPreference.setValue(String.valueOf(mCameraSettingValue)); CameraSettingPreference.setOnPreferenceChangeListener(this); ListPreference LoopbackSettingPreference = (ListPreference) findPreference(KEY_LOOPBACK_SETTING); LoopbackSettingPreference.setValue(String .valueOf(mLoopbackSettingValue)); LoopbackSettingPreference.setOnPreferenceChangeListener(this); mAudioManager = (AudioManager) this .getSystemService(Context.AUDIO_SERVICE); } @Override protected void onResume() { super.onResume(); if (DBG) { log("onResume"); } mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); // upon resumption from the sub-activity, make sure we re-enable the // preferences. getPreferenceScreen().setEnabled(true); if (getPreferenceScreen().findPreference(KEY_NETWORK_SETTING) != null) { mPhone .getPreferredNetworkType(mHandler .obtainMessage(MyHandler.MESSAGE_GET_PREFERRED_NETWORK_TYPE)); } } @Override protected void onPause() { super.onPause(); log("onPause"); } @Override protected void onDestroy() { super.onDestroy(); mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE); log("onDestroy"); } public void runCmdLine() { mUsbSetting = new UsbSetting(); mHandler.post(new Runnable() { public void run() { mUsbSetting.run(mCmdLine); } }); } public boolean onPreferenceChange(Preference preference, Object objValue) { if (KEY_NETWORK_SETTING.equals(preference.getKey())) { int value = Integer.parseInt((String) objValue); // mCmdLine = // "cd /data/data/com.marvell.usbsetting/; rm copy_cp_nvm.sh; ln -s /marvell/tel/" // + RatSettingCmds[value] + " copy_cp_nvm.sh"; mRatSettingValue = value; // linda use android set preferred network int settingsNetworkMode = android.provider.Settings.Secure.getInt( mPhone.getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, PREF_KEY_RAT_SETTING_DEFAULT_VALUE); if (value != settingsNetworkMode) { // Set the modem network mode mPhone .setPreferredNetworkType( value, mHandler .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE)); } return true; } else if (KEY_DIAG_SETTING.equals(preference.getKey())) { int value = Integer.parseInt((String) objValue); if (value == 2 || value == 3) { // mCmdLine = // "cd /data/data/com.marvell.usbsetting/; rm diag_bsp.cfg; rm run.sh;ln -s /marvell/tel/run_diag_net.sh run.sh; ln -s /marvell/tel/" // + DiagSettingCmds[value] + " diag_bsp.cfg"; } else { // mCmdLine = // "cd /data/data/com.marvell.usbsetting/; rm diag_bsp.cfg; ln -s /marvell/tel/" // + DiagSettingCmds[value] + " diag_bsp.cfg;" + // "rm run.sh; ln -s /marvell/tel/" + // UsbSettingCmds[mUsbSettingValue] + " run.sh"; } mCmdLine = "cd /data/data/com.marvell.usbsetting/; rm diag_bsp.cfg; ln -s /marvell/tel/" + DiagSettingCmds[value] + " diag_bsp.cfg"; mDiagSettingValue = value; } else if (KEY_CAMERA_SETTING.equals(preference.getKey())) { int value = Integer.parseInt((String) objValue); mCmdLine = "cd ./";// no ops String a = SystemProperties.get("service.camera.id"); Log.d(TAG, " getprop=" + a); mCameraSettingValue = value; Log.d(TAG, " mCameraSettingValue=" + mCameraSettingValue); SystemProperties.set("service.camera.id", Integer .toString(mCameraSettingValue)); // a = SystemProperties.get("service.camera.id"); // Log.d(TAG," getprop=" + a); } else if (KEY_LOOPBACK_SETTING.equals(preference.getKey())) { int value = Integer.parseInt((String) objValue); mCmdLine = "cd ./";// no ops mLoopbackSettingValue = value; Log.d(TAG, " mLoopbackSettingValue=" + mLoopbackSettingValue); mAudioManager.setParameters("Loopback=" + mLoopbackSettingValue); } runCmdLine(); // Log.d(TAG, mCmdLine); saveToNonVolatile(); return true; } private PhoneStateListener mPhoneStateListener = new PhoneStateListener() { @Override public void onDataConnectionStateChanged(int state) { Log.d(TAG, "onDataConnectionStateChanged"); updatePrefNetworkButton(); } }; private void updatePrefNetworkButton() { // upon resumption from the sub-activity, make sure we re-enable the // preferences. getPreferenceScreen().setEnabled(true); if (getPreferenceScreen().findPreference(KEY_NETWORK_SETTING) != null) { mPhone .getPreferredNetworkType(mHandler .obtainMessage(MyHandler.MESSAGE_GET_PREFERRED_NETWORK_TYPE)); } } private class MyHandler extends Handler { private static final int MESSAGE_GET_PREFERRED_NETWORK_TYPE = 0; private static final int MESSAGE_SET_PREFERRED_NETWORK_TYPE = 1; @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_GET_PREFERRED_NETWORK_TYPE: handleGetPreferredNetworkTypeResponse(msg); break; case MESSAGE_SET_PREFERRED_NETWORK_TYPE: handleSetPreferredNetworkTypeResponse(msg); break; } } private void handleGetPreferredNetworkTypeResponse(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; if (ar.exception == null) { int modemNetworkMode = ((int[]) ar.result)[0]; if (DBG) { log("handleGetPreferredNetworkTypeResponse: modemNetworkMode = " + modemNetworkMode); } int settingsNetworkMode = android.provider.Settings.Secure .getInt( mPhone.getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, PREF_KEY_RAT_SETTING_DEFAULT_VALUE); if (DBG) { log("handleGetPreferredNetworkTypeReponse: settingsNetworkMode = " + settingsNetworkMode); } // check that modemNetworkMode is from an accepted value if (modemNetworkMode == Phone.NT_MODE_WCDMA_PREF || modemNetworkMode == Phone.NT_MODE_GSM_ONLY || modemNetworkMode == Phone.NT_MODE_WCDMA_ONLY || modemNetworkMode == Phone.NT_MODE_GSM_UMTS || modemNetworkMode == Phone.NT_MODE_CDMA || modemNetworkMode == Phone.NT_MODE_CDMA_NO_EVDO || modemNetworkMode == Phone.NT_MODE_EVDO_NO_CDMA || modemNetworkMode == Phone.NT_MODE_GLOBAL || modemNetworkMode == 8) { if (DBG) { log("handleGetPreferredNetworkTypeResponse: if 1: modemNetworkMode = " + modemNetworkMode); } // check changes in modemNetworkMode and updates // settingsNetworkMode if (modemNetworkMode != settingsNetworkMode) { if (DBG) { log("handleGetPreferredNetworkTypeResponse: if 2: " + "modemNetworkMode != settingsNetworkMode"); } settingsNetworkMode = modemNetworkMode; if (DBG) { log("handleGetPreferredNetworkTypeResponse: if 2: " + "settingsNetworkMode = " + settingsNetworkMode); } // changes the Settings.System accordingly to // modemNetworkMode android.provider.Settings.Secure .putInt( mPhone.getContext() .getContentResolver(), android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, settingsNetworkMode); } // changes the mButtonPreferredNetworkMode accordingly to // modemNetworkMode mButtonPreferredNetworkMode.setValue(Integer .toString(modemNetworkMode)); } else { if (DBG) log("handleGetPreferredNetworkTypeResponse: else: reset to default"); resetNetworkModeToDefault(); } } } private void handleSetPreferredNetworkTypeResponse(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; if (ar.exception == null) { int networkMode = Integer.valueOf( mButtonPreferredNetworkMode.getValue()).intValue(); android.provider.Settings.Secure .putInt( mPhone.getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, networkMode); // changes the mButtonPreferredNetworkMode accordingly to // modemNetworkMode mButtonPreferredNetworkMode.setValue(Integer .toString(networkMode)); } else { mPhone .getPreferredNetworkType(obtainMessage(MESSAGE_GET_PREFERRED_NETWORK_TYPE)); } } private void resetNetworkModeToDefault() { // set the mButtonPreferredNetworkMode mButtonPreferredNetworkMode.setValue(Integer .toString(PREF_KEY_RAT_SETTING_DEFAULT_VALUE)); // set the Settings.System android.provider.Settings.Secure.putInt(mPhone.getContext() .getContentResolver(), android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, PREF_KEY_RAT_SETTING_DEFAULT_VALUE); // Set the Modem mPhone .setPreferredNetworkType( PREF_KEY_RAT_SETTING_DEFAULT_VALUE, this .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE)); } } private static void log(String msg) { Log.d(TAG, msg); } }
package org.jboss.devcon.cmd; import org.infinispan.Cache; public class DeleteCommand extends Command { private String key; public DeleteCommand(String key) { super(); this.key = key; } public String execute(Cache<String, String> cache) { try { cache.remove(key); return "DELETED \"" + key + "\""; } catch (Exception e) { return "ERROR: " + e.getMessage(); } } }
package com.stk123.common.util.pdf; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import com.stk123.common.CommonUtils; import lombok.AllArgsConstructor; import lombok.Data; import org.apache.commons.lang.StringUtils; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdfparser.PDFStreamParser; import org.apache.pdfbox.pdfwriter.ContentStreamWriter; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.pdmodel.fdf.FDFDocument; import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm; import org.apache.pdfbox.pdmodel.interactive.form.PDField; import org.apache.pdfbox.util.PDFOperator; import org.apache.pdfbox.util.PDFText2HTML; import org.apache.pdfbox.util.PDFTextStripper; public class PDFUtils { public static String getText(String file) throws Exception{ String s = null; String pdffile = file; PDDocument pdfdoc = null; try { pdfdoc = PDDocument.load(pdffile); PDFTextStripper stripper = new PDFTextStripper(); s = stripper.getText(pdfdoc); } finally { if(pdfdoc != null)pdfdoc.close(); } return s; } public static String getText2(String file) { String s = null; String pdffile = file; PDDocument pdfdoc = null; try { pdfdoc = PDDocument.load(pdffile); List<COSObject> list = pdfdoc.getDocument().getObjects(); PDFTextStripper stripper = new PDFTextStripper(); s = stripper.getText(pdfdoc); PDDocumentCatalog docCatalog = pdfdoc.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); List fields = acroForm.getFields(); //System.out.println(fields.size()); for(int i=0;i<fields.size();i++){ PDField field = (PDField)fields.get(i); //System.out.println(field.getValue()); } FDFDocument fdf = acroForm.exportFDF(); // Document luceneDocument = LucenePDFDocument.getDocument( ... ); } catch (IOException e) { e.printStackTrace(); } finally { try { if (pdfdoc != null) { pdfdoc.close(); } } catch (IOException e) { e.printStackTrace(); } } return s; } public static void toTextFile(String doc, String filename) throws Exception { PDDocument pdfdoc = null; try { pdfdoc = PDDocument.load(doc); PDFTextStripper stripper = new PDFTextStripper(); stripper.setWordSeparator("\\w"); stripper.setLineSeparator("\r\\r"); stripper.setArticleStart("@@"); stripper.setArticleEnd("##"); /*System.out.println("start="+stripper.getParagraphStart()); System.out.println("end="+stripper.getParagraphEnd()); System.out.println("bead="+stripper.getSeparateByBeads());*/ /*stripper.setParagraphStart("<"); stripper.setParagraphEnd(">");*/ PrintWriter pw = new PrintWriter(new FileWriter(filename)); stripper.writeText(pdfdoc, pw); pw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (pdfdoc != null) { pdfdoc.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void toHtmlFile(String doc, String filename) throws Exception { PDDocument pdfdoc = null; try { pdfdoc = PDDocument.load(doc); PDFText2HTML stripper = new PDFText2HTML("UTF-8"); PrintWriter pw = new PrintWriter(new FileWriter(filename)); stripper.writeText(pdfdoc, pw); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (pdfdoc != null) { pdfdoc.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { /*String sc = getText("D:/share/投资/上市公司报表/000997/63861351.PDF"); // System.out.print(sc);*/ /*toTextFile("D:/1200682312.PDF", "D:/solution.txt"); toHtmlFile("D:/1200682312.PDF", "D:/solution.html");*/ /*String spdf = PDFUtils.getText("D:/share/投资/研报/1200987692.PDF"); Set<String> sets = CommonUtils.getMatchStrings(spdf, "(为公司带来)( ?)[0-9]*(,)?[0-9]*( ?)(万元的净利润)"); System.out.print(sets);*/ String pdfContent = PDFUtils.getText("D:\\stk123\\stock\\600600\\notice\\1210859937.PDF"); String[] lines = StringUtils.split(pdfContent, "\n"); int l = 1; for(String line : lines){ System.out.println("["+(l++)+"]"+line); } List<String> pdf = Arrays.stream(lines).map(row -> StringUtils.trim(row)).collect(Collectors.toList()); System.out.println(sublines(pdf, new PDFUtils.Line("管理层讨论与分析", "第(.)节", null, "第三节管理层讨论与分析".length()), new PDFUtils.Line("公司治理", "第(.)节", null, "第四节公司治理".length()))); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Data @AllArgsConstructor public static class Line{ private String mustContain; private String mustRegex; private String notContain; private int lengthExcludeEmpty; public boolean equals(String line){ if(mustContain != null && !StringUtils.contains(line, mustContain)) { return false; } if(mustRegex != null && CommonUtils.getMatchString(line, mustRegex) == null){ return false; } if(notContain != null && StringUtils.contains(line, notContain)){ return false; } if(lengthExcludeEmpty != 0 && StringUtils.replace(line, " ", "").length() != lengthExcludeEmpty){ return false; } return true; } } public static List<String> sublines(List<String> lines, Line startLine, Line endLineExclude){ List<String> results = null; for(String line : lines){ if(results == null && startLine.equals(line)){ results = new ArrayList<>(); } if(endLineExclude.equals(line)){ break; }else if(results != null){ results.add(line); } } return results; } public void editPDF() { try { // pdfwithText PDDocument helloDocument = PDDocument.load(new File( "D:\\gloomyfish\\pdfwithText.pdf")); // PDDocument helloDocument = PDDocument.load(new // File("D:\\gloomyfish\\hello.pdf")); // int pageCount = helloDocument.getNumberOfPages(); PDPage firstPage = (PDPage) helloDocument.getDocumentCatalog() .getAllPages().get(0); // PDPageContentStream content = new // PDPageContentStream(helloDocument, firstPage); PDStream contents = firstPage.getContents(); PDFStreamParser parser = new PDFStreamParser(contents.getStream()); parser.parse(); List tokens = parser.getTokens(); for (int j = 0; j < tokens.size(); j++) { Object next = tokens.get(j); if (next instanceof PDFOperator) { PDFOperator op = (PDFOperator) next; // Tj and TJ are the two operators that display strings in a // PDF if (op.getOperation().equals("Tj")) { // Tj takes one operator and that is the string // to display so lets update that operator COSString previous = (COSString) tokens.get(j - 1); String string = previous.getString(); string = string.replaceFirst("Hello", "Hello World, fish"); // Word you want to change. Currently this code changes // word "Solr" to "Solr123" previous.reset(); previous.append(string.getBytes("ISO-8859-1")); } else if (op.getOperation().equals("TJ")) { COSArray previous = (COSArray) tokens.get(j - 1); for (int k = 0; k < previous.size(); k++) { Object arrElement = previous.getObject(k); if (arrElement instanceof COSString) { COSString cosString = (COSString) arrElement; String string = cosString.getString(); string = string.replaceFirst("Hello", "Hello World, fish"); // Currently this code changes word "Solr" to // "Solr123" cosString.reset(); cosString.append(string.getBytes("ISO-8859-1")); } } } } } // now that the tokens are updated we will replace the page content // stream. PDStream updatedStream = new PDStream(helloDocument); OutputStream out = updatedStream.createOutputStream(); ContentStreamWriter tokenWriter = new ContentStreamWriter(out); tokenWriter.writeTokens(tokens); firstPage.setContents(updatedStream); helloDocument.save("D:\\gloomyfish\\helloworld.pdf"); // Output file // name helloDocument.close(); // PDFTextStripper textStripper = new PDFTextStripper(); // System.out.println(textStripper.getText(helloDocument)); // helloDocument.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (COSVisitorException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.itheima.day_02.homework.feeder; public class Frog extends Animal implements Swimming { @Override void eat() { System.out.println("青蛙吃小虫"); } @Override void drink() { System.out.println("青蛙喝水"); } @Override public void swim() { System.out.println("青蛙会蛙泳"); } }
package connectors.solr; public interface SolrData { }
package com.pwc.brains; import com.pwc.brains.btree.ObjectSerializationException; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.UUID; public class Util { public static String getUuid() { return UUID.randomUUID().toString(); } public static ArrayList<Integer> randomRange(int s, int e) { ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = s; i < e; i++) { list.add(new Integer(i)); } Collections.shuffle(list); return list; } public static void serialize(String fileName, Object node) throws ObjectSerializationException { FileOutputStream os = null; ObjectOutputStream o = null; try { os = new FileOutputStream(fileName); o = new ObjectOutputStream(os); } catch (FileNotFoundException e) { throw new ObjectSerializationException("Unable to find or access the file:" + fileName, e); } catch (IOException e) { throw new ObjectSerializationException("Unable to write the file:" + fileName, e); } try { o.writeObject(node); o.flush(); } catch (IOException e) { throw new ObjectSerializationException(e.getMessage(), e); } finally { try { o.close(); } catch (IOException e) { // I don't how to handle this kind error, throw a checked exception? } } } public static void serialize(String fileName, Object node, String type) throws ObjectSerializationException { if (type == "xml") { } } public static Object deserialize(String fileName) throws ObjectSerializationException { Object object = null; FileInputStream input = null; try { input = new FileInputStream(fileName); ObjectInputStream objInput = new ObjectInputStream(input); object = (Object) objInput.readObject(); return object; } catch (Exception e) { throw new ObjectSerializationException("Unable to loadDictionary the node from file:", e); } finally { if (input != null) try { input.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return object; } } public static boolean isFileExists(String path) { File f = new File(path); return f.exists(); } public static void Print(int[][] prices) { int h = prices[0].length; int v = prices.length; for (int i = -1; i < v; i++) { if (i == -1) { printHead(h); } else { print(prices[i]); } System.out.println(""); } } private static void printHead(int h) { for (int i = 0; i < h; i++) { System.out.print(i + blank(String.valueOf(i))); } } private static void print(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + blank(String.valueOf(array[i]))); } } private static String blank(String s) { int total = 5; String result = ""; for (int i = 0; i < total - s.length(); i++) { result += " "; } return result; } }
package by.htp.cratemynewpc.controller; import by.htp.cratemynewpc.controller.CommandName; import by.htp.cratemynewpc.controller.command.Command; import by.htp.cratemynewpc.controller.command.impl.*; import java.util.HashMap; import java.util.Map; class CommandProvider { private Map<CommandName, Command> commands = new HashMap<>(); public CommandProvider() { commands.put(CommandName.MAIN_PAGE, new MainPage()); commands.put(CommandName.REG_PAGE, new RegPage()); commands.put(CommandName.SIGN_IN, new SignIn()); commands.put(CommandName.LOCALIZATION, new Localization()); commands.put(CommandName.REGISTRATION, new Rigistration()); commands.put(CommandName.SING_OUT, new SignOut()); commands.put(CommandName.DELETE_USER_PC, new DeleteUserPC()); } Command getCommand(String commandName) { Command command; command = commands.get(CommandName.valueOf(commandName.toUpperCase())); return command; } }
/** * generated by Xtext 2.20.0 */ package org.xtext.example.mydsl.myDsl.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EDataTypeEList; import org.xtext.example.mydsl.myDsl.EXEC_FORM; import org.xtext.example.mydsl.myDsl.Instruction; import org.xtext.example.mydsl.myDsl.MyDslPackage; import org.xtext.example.mydsl.myDsl.Statement; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Statement</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getKey <em>Key</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getPlatform_option <em>Platform option</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getName <em>Name</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getTag_or_digest <em>Tag or digest</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getExec_form <em>Exec form</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getShell_form <em>Shell form</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getPorts <em>Ports</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getPath <em>Path</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getKey_value_pairs <em>Key value pairs</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getChown_options <em>Chown options</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getFile <em>File</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getDirectory <em>Directory</em>}</li> * <li>{@link org.xtext.example.mydsl.myDsl.impl.StatementImpl#getStatement <em>Statement</em>}</li> * </ul> * * @generated */ public class StatementImpl extends MinimalEObjectImpl.Container implements Statement { /** * The default value of the '{@link #getKey() <em>Key</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getKey() * @generated * @ordered */ protected static final String KEY_EDEFAULT = null; /** * The cached value of the '{@link #getKey() <em>Key</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getKey() * @generated * @ordered */ protected String key = KEY_EDEFAULT; /** * The default value of the '{@link #getPlatform_option() <em>Platform option</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPlatform_option() * @generated * @ordered */ protected static final String PLATFORM_OPTION_EDEFAULT = null; /** * The cached value of the '{@link #getPlatform_option() <em>Platform option</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPlatform_option() * @generated * @ordered */ protected String platform_option = PLATFORM_OPTION_EDEFAULT; /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The default value of the '{@link #getTag_or_digest() <em>Tag or digest</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTag_or_digest() * @generated * @ordered */ protected static final String TAG_OR_DIGEST_EDEFAULT = null; /** * The cached value of the '{@link #getTag_or_digest() <em>Tag or digest</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTag_or_digest() * @generated * @ordered */ protected String tag_or_digest = TAG_OR_DIGEST_EDEFAULT; /** * The cached value of the '{@link #getExec_form() <em>Exec form</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExec_form() * @generated * @ordered */ protected EXEC_FORM exec_form; /** * The default value of the '{@link #getShell_form() <em>Shell form</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShell_form() * @generated * @ordered */ protected static final String SHELL_FORM_EDEFAULT = null; /** * The cached value of the '{@link #getShell_form() <em>Shell form</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShell_form() * @generated * @ordered */ protected String shell_form = SHELL_FORM_EDEFAULT; /** * The default value of the '{@link #getPorts() <em>Ports</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPorts() * @generated * @ordered */ protected static final String PORTS_EDEFAULT = null; /** * The cached value of the '{@link #getPorts() <em>Ports</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPorts() * @generated * @ordered */ protected String ports = PORTS_EDEFAULT; /** * The default value of the '{@link #getPath() <em>Path</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPath() * @generated * @ordered */ protected static final String PATH_EDEFAULT = null; /** * The cached value of the '{@link #getPath() <em>Path</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPath() * @generated * @ordered */ protected String path = PATH_EDEFAULT; /** * The cached value of the '{@link #getKey_value_pairs() <em>Key value pairs</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getKey_value_pairs() * @generated * @ordered */ protected EList<String> key_value_pairs; /** * The default value of the '{@link #getChown_options() <em>Chown options</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getChown_options() * @generated * @ordered */ protected static final String CHOWN_OPTIONS_EDEFAULT = null; /** * The cached value of the '{@link #getChown_options() <em>Chown options</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getChown_options() * @generated * @ordered */ protected String chown_options = CHOWN_OPTIONS_EDEFAULT; /** * The default value of the '{@link #getFile() <em>File</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFile() * @generated * @ordered */ protected static final String FILE_EDEFAULT = null; /** * The cached value of the '{@link #getFile() <em>File</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFile() * @generated * @ordered */ protected String file = FILE_EDEFAULT; /** * The default value of the '{@link #getDirectory() <em>Directory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDirectory() * @generated * @ordered */ protected static final String DIRECTORY_EDEFAULT = null; /** * The cached value of the '{@link #getDirectory() <em>Directory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDirectory() * @generated * @ordered */ protected String directory = DIRECTORY_EDEFAULT; /** * The cached value of the '{@link #getStatement() <em>Statement</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStatement() * @generated * @ordered */ protected Instruction statement; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected StatementImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MyDslPackage.Literals.STATEMENT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getKey() { return key; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setKey(String newKey) { String oldKey = key; key = newKey; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__KEY, oldKey, key)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getPlatform_option() { return platform_option; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setPlatform_option(String newPlatform_option) { String oldPlatform_option = platform_option; platform_option = newPlatform_option; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__PLATFORM_OPTION, oldPlatform_option, platform_option)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getTag_or_digest() { return tag_or_digest; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setTag_or_digest(String newTag_or_digest) { String oldTag_or_digest = tag_or_digest; tag_or_digest = newTag_or_digest; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__TAG_OR_DIGEST, oldTag_or_digest, tag_or_digest)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EXEC_FORM getExec_form() { return exec_form; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetExec_form(EXEC_FORM newExec_form, NotificationChain msgs) { EXEC_FORM oldExec_form = exec_form; exec_form = newExec_form; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__EXEC_FORM, oldExec_form, newExec_form); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setExec_form(EXEC_FORM newExec_form) { if (newExec_form != exec_form) { NotificationChain msgs = null; if (exec_form != null) msgs = ((InternalEObject)exec_form).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MyDslPackage.STATEMENT__EXEC_FORM, null, msgs); if (newExec_form != null) msgs = ((InternalEObject)newExec_form).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MyDslPackage.STATEMENT__EXEC_FORM, null, msgs); msgs = basicSetExec_form(newExec_form, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__EXEC_FORM, newExec_form, newExec_form)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getShell_form() { return shell_form; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setShell_form(String newShell_form) { String oldShell_form = shell_form; shell_form = newShell_form; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__SHELL_FORM, oldShell_form, shell_form)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getPorts() { return ports; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setPorts(String newPorts) { String oldPorts = ports; ports = newPorts; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__PORTS, oldPorts, ports)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getPath() { return path; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setPath(String newPath) { String oldPath = path; path = newPath; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__PATH, oldPath, path)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EList<String> getKey_value_pairs() { if (key_value_pairs == null) { key_value_pairs = new EDataTypeEList<String>(String.class, this, MyDslPackage.STATEMENT__KEY_VALUE_PAIRS); } return key_value_pairs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getChown_options() { return chown_options; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setChown_options(String newChown_options) { String oldChown_options = chown_options; chown_options = newChown_options; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__CHOWN_OPTIONS, oldChown_options, chown_options)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getFile() { return file; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setFile(String newFile) { String oldFile = file; file = newFile; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__FILE, oldFile, file)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getDirectory() { return directory; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setDirectory(String newDirectory) { String oldDirectory = directory; directory = newDirectory; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__DIRECTORY, oldDirectory, directory)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Instruction getStatement() { return statement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetStatement(Instruction newStatement, NotificationChain msgs) { Instruction oldStatement = statement; statement = newStatement; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__STATEMENT, oldStatement, newStatement); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setStatement(Instruction newStatement) { if (newStatement != statement) { NotificationChain msgs = null; if (statement != null) msgs = ((InternalEObject)statement).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MyDslPackage.STATEMENT__STATEMENT, null, msgs); if (newStatement != null) msgs = ((InternalEObject)newStatement).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MyDslPackage.STATEMENT__STATEMENT, null, msgs); msgs = basicSetStatement(newStatement, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.STATEMENT__STATEMENT, newStatement, newStatement)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MyDslPackage.STATEMENT__EXEC_FORM: return basicSetExec_form(null, msgs); case MyDslPackage.STATEMENT__STATEMENT: return basicSetStatement(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MyDslPackage.STATEMENT__KEY: return getKey(); case MyDslPackage.STATEMENT__PLATFORM_OPTION: return getPlatform_option(); case MyDslPackage.STATEMENT__NAME: return getName(); case MyDslPackage.STATEMENT__TAG_OR_DIGEST: return getTag_or_digest(); case MyDslPackage.STATEMENT__EXEC_FORM: return getExec_form(); case MyDslPackage.STATEMENT__SHELL_FORM: return getShell_form(); case MyDslPackage.STATEMENT__PORTS: return getPorts(); case MyDslPackage.STATEMENT__PATH: return getPath(); case MyDslPackage.STATEMENT__KEY_VALUE_PAIRS: return getKey_value_pairs(); case MyDslPackage.STATEMENT__CHOWN_OPTIONS: return getChown_options(); case MyDslPackage.STATEMENT__FILE: return getFile(); case MyDslPackage.STATEMENT__DIRECTORY: return getDirectory(); case MyDslPackage.STATEMENT__STATEMENT: return getStatement(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MyDslPackage.STATEMENT__KEY: setKey((String)newValue); return; case MyDslPackage.STATEMENT__PLATFORM_OPTION: setPlatform_option((String)newValue); return; case MyDslPackage.STATEMENT__NAME: setName((String)newValue); return; case MyDslPackage.STATEMENT__TAG_OR_DIGEST: setTag_or_digest((String)newValue); return; case MyDslPackage.STATEMENT__EXEC_FORM: setExec_form((EXEC_FORM)newValue); return; case MyDslPackage.STATEMENT__SHELL_FORM: setShell_form((String)newValue); return; case MyDslPackage.STATEMENT__PORTS: setPorts((String)newValue); return; case MyDslPackage.STATEMENT__PATH: setPath((String)newValue); return; case MyDslPackage.STATEMENT__KEY_VALUE_PAIRS: getKey_value_pairs().clear(); getKey_value_pairs().addAll((Collection<? extends String>)newValue); return; case MyDslPackage.STATEMENT__CHOWN_OPTIONS: setChown_options((String)newValue); return; case MyDslPackage.STATEMENT__FILE: setFile((String)newValue); return; case MyDslPackage.STATEMENT__DIRECTORY: setDirectory((String)newValue); return; case MyDslPackage.STATEMENT__STATEMENT: setStatement((Instruction)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MyDslPackage.STATEMENT__KEY: setKey(KEY_EDEFAULT); return; case MyDslPackage.STATEMENT__PLATFORM_OPTION: setPlatform_option(PLATFORM_OPTION_EDEFAULT); return; case MyDslPackage.STATEMENT__NAME: setName(NAME_EDEFAULT); return; case MyDslPackage.STATEMENT__TAG_OR_DIGEST: setTag_or_digest(TAG_OR_DIGEST_EDEFAULT); return; case MyDslPackage.STATEMENT__EXEC_FORM: setExec_form((EXEC_FORM)null); return; case MyDslPackage.STATEMENT__SHELL_FORM: setShell_form(SHELL_FORM_EDEFAULT); return; case MyDslPackage.STATEMENT__PORTS: setPorts(PORTS_EDEFAULT); return; case MyDslPackage.STATEMENT__PATH: setPath(PATH_EDEFAULT); return; case MyDslPackage.STATEMENT__KEY_VALUE_PAIRS: getKey_value_pairs().clear(); return; case MyDslPackage.STATEMENT__CHOWN_OPTIONS: setChown_options(CHOWN_OPTIONS_EDEFAULT); return; case MyDslPackage.STATEMENT__FILE: setFile(FILE_EDEFAULT); return; case MyDslPackage.STATEMENT__DIRECTORY: setDirectory(DIRECTORY_EDEFAULT); return; case MyDslPackage.STATEMENT__STATEMENT: setStatement((Instruction)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MyDslPackage.STATEMENT__KEY: return KEY_EDEFAULT == null ? key != null : !KEY_EDEFAULT.equals(key); case MyDslPackage.STATEMENT__PLATFORM_OPTION: return PLATFORM_OPTION_EDEFAULT == null ? platform_option != null : !PLATFORM_OPTION_EDEFAULT.equals(platform_option); case MyDslPackage.STATEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case MyDslPackage.STATEMENT__TAG_OR_DIGEST: return TAG_OR_DIGEST_EDEFAULT == null ? tag_or_digest != null : !TAG_OR_DIGEST_EDEFAULT.equals(tag_or_digest); case MyDslPackage.STATEMENT__EXEC_FORM: return exec_form != null; case MyDslPackage.STATEMENT__SHELL_FORM: return SHELL_FORM_EDEFAULT == null ? shell_form != null : !SHELL_FORM_EDEFAULT.equals(shell_form); case MyDslPackage.STATEMENT__PORTS: return PORTS_EDEFAULT == null ? ports != null : !PORTS_EDEFAULT.equals(ports); case MyDslPackage.STATEMENT__PATH: return PATH_EDEFAULT == null ? path != null : !PATH_EDEFAULT.equals(path); case MyDslPackage.STATEMENT__KEY_VALUE_PAIRS: return key_value_pairs != null && !key_value_pairs.isEmpty(); case MyDslPackage.STATEMENT__CHOWN_OPTIONS: return CHOWN_OPTIONS_EDEFAULT == null ? chown_options != null : !CHOWN_OPTIONS_EDEFAULT.equals(chown_options); case MyDslPackage.STATEMENT__FILE: return FILE_EDEFAULT == null ? file != null : !FILE_EDEFAULT.equals(file); case MyDslPackage.STATEMENT__DIRECTORY: return DIRECTORY_EDEFAULT == null ? directory != null : !DIRECTORY_EDEFAULT.equals(directory); case MyDslPackage.STATEMENT__STATEMENT: return statement != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuilder result = new StringBuilder(super.toString()); result.append(" (key: "); result.append(key); result.append(", platform_option: "); result.append(platform_option); result.append(", name: "); result.append(name); result.append(", tag_or_digest: "); result.append(tag_or_digest); result.append(", shell_form: "); result.append(shell_form); result.append(", ports: "); result.append(ports); result.append(", path: "); result.append(path); result.append(", key_value_pairs: "); result.append(key_value_pairs); result.append(", chown_options: "); result.append(chown_options); result.append(", file: "); result.append(file); result.append(", directory: "); result.append(directory); result.append(')'); return result.toString(); } } //StatementImpl
package vip.ph.vueapp.service; import vip.ph.vueapp.model.User; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author Just be alive * @since 2021-04-24 */ public interface UserService extends IService<User> { }
package cn.sharesdk.demo.platform.whatsapp; import com.mob.MobSDK; import cn.sharesdk.demo.entity.ResourcesManager; import cn.sharesdk.framework.Platform; import cn.sharesdk.framework.PlatformActionListener; import cn.sharesdk.framework.ShareSDK; import cn.sharesdk.whatsapp.WhatsApp; /** * Created by yjin on 2017/6/22. */ public class WhatsAppShare { private PlatformActionListener platformActionListener; public WhatsAppShare(PlatformActionListener mListener){ this.platformActionListener = mListener; } public void shareText(){ Platform platform = ShareSDK.getPlatform(WhatsApp.NAME); Platform.ShareParams shareParams = new Platform.ShareParams(); shareParams.setText(ResourcesManager.getInstace(MobSDK.getContext()).getText()); platform.setPlatformActionListener(platformActionListener); platform.share(shareParams); } public void shareImage(){ Platform platform = ShareSDK.getPlatform(WhatsApp.NAME); Platform.ShareParams shareParams = new Platform.ShareParams(); shareParams.setImagePath(ResourcesManager.getInstace(MobSDK.getContext()).getImagePath()); shareParams.setImageUrl(ResourcesManager.getInstace(MobSDK.getContext()).getImageUrl()); platform.setPlatformActionListener(platformActionListener); shareParams.setShareType(Platform.SHARE_IMAGE); platform.share(shareParams); } public void shareVideo(){ Platform platform = ShareSDK.getPlatform(WhatsApp.NAME); Platform.ShareParams shareParams = new Platform.ShareParams(); shareParams.setFilePath(ResourcesManager.getInstace(MobSDK.getContext()).getFilePath()); platform.setPlatformActionListener(platformActionListener); shareParams.setShareType(Platform.SHARE_VIDEO); platform.share(shareParams); } public void shareAddress(){ Platform platform = ShareSDK.getPlatform(WhatsApp.NAME); Platform.ShareParams shareParams = new Platform.ShareParams(); shareParams.setFilePath(ResourcesManager.ADDRESS); platform.setPlatformActionListener(platformActionListener); platform.share(shareParams); } }
package org.odk.collect.android.activities; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class startupbroadcastreceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent in) { // TODO Auto-generated method stub Intent intent = new Intent(context, alarm_invoked_broadcastreceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 234324243, intent, 0); AlarmManager alarmManager = (AlarmManager)context.getSystemService(context.ALARM_SERVICE); alarmManager.cancel(pendingIntent); //alarmManager.setTime(SystemClock.currentThreadTimeMillis()); Log.v("fantom", ""+ System.currentTimeMillis()); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + (3000), (5*1000), pendingIntent); } }
package edu.inheritance.gabriel.mitchell; import edu.jenks.dist.inheritance.*; public class SelfCheckout implements ItemHandler { private double expectedWeight; private double subTotal; private double taxTot; private boolean checkID; private double scale; public final double TAX_RATE; public SelfCheckout(double taxR){ TAX_RATE = taxR; } public double getScaleWeight(){ return scale; } public boolean isCheckID(){ return checkID; } public void setCheckID(boolean checkID){ this.checkID = checkID; } public double getExpectedWeight(){ return expectedWeight; } public boolean addItem(Buyable item){ return this.addItem(item, 0.0); } public boolean addItem(Buyable item, double scaleWeight){ scale = scaleWeight; item.initBuyable(this); subTotal += item.getPrice(); taxTot += item.getTax(TAX_RATE); if (!item.isBulk()){ expectedWeight += item.getWeight(); } return false; } public double getCheckoutTotal(){ return getSubtotal() + getTax(); } public double getSubtotal(){ return subTotal; } public double getTax(){ return taxTot; } }
package bankassignment; import javax.swing.*; import javax.swing.JTextField; public class ReportPanel extends JPanel { private JLabel prompt; private JButton generate; private JTextField textMax; private JTextField textMin ; public ReportPanel () { prompt = new JLabel("Your Account Reports") ; generate = new JButton("Generate reports"); textMax = new JTextField(30) ; textMax.setEditable(false); textMin = new JTextField(30) ; textMin.setEditable(false); add(prompt); add(textMax) ; add(textMin) ; add(generate); } }
package app.services; import app.entity.Bed; import app.entity.Hospital; import app.entity.Room; import app.repository.BedRepository; import app.repository.RoomRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BedService implements AbstractServiceInterface<Bed> { @Autowired private BedRepository bedRepository; @Autowired private RoomService roomService; @Override public void save(Bed room) { bedRepository.save(room); } @Override public void update(Bed room) { bedRepository.save(room); } @Override public boolean delete(long id) { Bed bed = bedRepository.findOne(id); if(bed != null) { bedRepository.delete(id); return true; } return false; } @Override public List<Bed> list() { return bedRepository.findAll(); } @Override public Bed findById(long id) { return bedRepository.findOne(id); } public List<Bed> findByRoomId(long id) { Room room = roomService.findById(id); return bedRepository.findByRoom(room); } /* public List<Room> findByHospital(long id) { return roomRepository.findByHospital(id); } */ }
/* * Copyright(C) 2019-2020 RINEARN (Fumihiro Matsui) * This software is released under the MIT License. */ package com.rinearn.rinpn.util; public enum RoundingTarget { SIGNIFICAND, AFTER_FIXED_POINT }
package dataStructures; public class StackLinkedList { public static Node top = null; public static class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } public Node() { } } public static void insertElement(int data) { /* * Node newNode = new Node(data); newNode.next = top; top=newNode; */ Node newNode = new Node(); newNode.data = data; newNode.next = top; top = newNode; } public static void displayElements() { Node tempNode = null; tempNode = top; while (tempNode != null) { System.out.println(tempNode.data); tempNode = tempNode.next; } } public static void peekElement() { Node tempNode = null; tempNode = top; if (tempNode == null) { System.out.println("Stack is empty"); } else { System.out.println(tempNode.data); } } public static void popElement() { if (top == null) { System.out.println("Stack is empty"); } else { System.out.println("Removed Element" + " " + top.data); top = top.next; } } public static void main(String[] args) { // TODO Auto-generated method stub insertElement(5); insertElement(8); insertElement(10); // displayElements(); peekElement(); popElement(); } }
package com.timewarp.games.onedroidcode.editor; import com.timewarp.engine.entities.GameObject; public class NodeCell extends GameObject { public NodeCellComponent cellComponent; public NodeCell() { } @Override public void init() { super.init(); this.cellComponent = this.addComponent(NodeCellComponent.class); } }
//package com.zhanwei.java.myqueue; // //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; // //import java.util.concurrent.atomic.AtomicInteger; // //public class CaptchaResource<T> implements ICaptchaResource<T> { // private static Logger picpoolLogger = LoggerFactory.getLogger("poollogger"); // // protected final static int maxLength; // protected AtomicInteger refreshBigCount; // protected AtomicInteger customBigCount; // protected Object[] big; // // public CaptchaResource() { // this.big = new Object[maxLength]; // refreshBigCount = new AtomicInteger(0); // customBigCount = new AtomicInteger(0); // } // // static { // int capacity = 1; // try { // while (capacity < Configuration.getInstance().getInt("PIC_POOL_CAPACITY")) { // capacity <<= 1; // } // } catch (ConfigurationException e) { // picpoolLogger.info("Configuration load data error ..."); // e.printStackTrace(); // } // maxLength = capacity; // picpoolLogger.info("CAPACITY : " + maxLength); // } // // // @SuppressWarnings("unchecked") // @Override // public T get() { // int tmp = customBigCount.getAndIncrement(); // int t = tmp&(maxLength-1); // if (big[t] == null) { // customBigCount.set(0); // t = 0; // } // return (T)big[t]; // } // // // @Override // public void set(T image) { // int tmp = refreshBigCount.getAndIncrement(); // int t = tmp&(maxLength-1); // big[t] = image; // } // // //}
package sesion3; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class SegundoServlet */ @WebServlet("/SegundoServlet") public class SegundoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SegundoServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub if(request.getSession()==null) { //Si la sesion no existe o ha terminado String url="/WebContent/FinSesion.html"; //Enviamos al usuario a fin de sesion getServletContext().getRequestDispatcher(url).forward(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession sesion=request.getSession(true); String nombre=request.getParameter("username"); String email=request.getParameter("email"); String direccion=request.getParameter("home"); UsuarioDTO user=new UsuarioDTO(nombre, email, direccion); request.setAttribute("user", user); sesion.setAttribute("user", user); sesion.setMaxInactiveInterval(5); // Indicamos el tiempo que queremos que dure la sesion String url="/WEB-INF/sesion.jsp"; // Enviamos al usuario al jsp sesion getServletContext().getRequestDispatcher(url).forward(request, response); doGet(request, response); } }
package io.github.stepheniskander.equationsolver; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ExpressionTest { private static final double EPSILON = 10E-6; @Test public void testEvaluateRpn() { Expression ex = Parser.parseExpression("(2+3)^5/16-(9*1.5)"); double result = ex.evaluateRpn().doubleValue(); assertEquals(result, 181.8125, EPSILON); } @Test public void testNegative() { Expression neg = Parser.parseExpression("2*-1"); double result = neg.evaluateRpn().doubleValue(); assertEquals(result, -2.0, EPSILON); } @Test public void testIntegral() { Expression ex = Parser.parseExpression("(2+3)^5/int(6x^2, 4, 10)+16-(9*1.5)"); double result = ex.evaluateRpn().doubleValue(); assertEquals(4.1693376068376068376068376068, result, EPSILON); } @Test public void testDerivative() { Expression ex = Parser.parseExpression("(2+3)^5/der(6x^2, 4)+16-(9*1.5)"); double result = ex.evaluateRpn().doubleValue(); assertEquals(67.6041666666666666666, result, EPSILON); } }
package com.example.narubibi.findate.Activities; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.narubibi.findate.Activities.Authentication.LoginActivity; import com.example.narubibi.findate.R; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.theartofdev.edmodo.cropper.CropImage; import com.theartofdev.edmodo.cropper.CropImageView; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static android.app.Activity.RESULT_OK; public class ProfileFragment extends Fragment { private static final int REQ_PROFILE_IMAGE = 1; private ImageView imageViewProfilePicture; private TextView textViewName; private FirebaseAuth firebaseAuth; private DatabaseReference userDb; private String userId, userName, profileImageUrl; private Uri resultUri; FloatingActionButton btnSetting, btnEditInfo; Button btnLogout, btnDeleteAccount; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_profile, container, false); btnSetting = view.findViewById(R.id.btn_Settings); btnSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent settingIntent = new Intent(getContext(), SettingActivity.class); getContext().startActivity(settingIntent); } }); btnEditInfo = view.findViewById(R.id.btn_adjustProfile); btnEditInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent editInfoIntent = new Intent(getContext(), EditInfoActivity.class); getContext().startActivity(editInfoIntent); } }); btnLogout = view.findViewById(R.id.btn_logOut); btnLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { logout(v); } }); imageViewProfilePicture = view.findViewById(R.id.iv_accountImage); textViewName = view.findViewById(R.id.tv_accountName); firebaseAuth = FirebaseAuth.getInstance(); userId = firebaseAuth.getCurrentUser().getUid(); userDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId); getUserInfo(); imageViewProfilePicture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CropImage.activity() .setGuidelines(CropImageView.Guidelines.ON) .setFixAspectRatio(true) .setAspectRatio(1, 1) .setMinCropWindowSize(300, 300) .start(getContext(), ProfileFragment.this); } }); return view; } private void getUserInfo() { userDb.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { if (dataSnapshot.exists()) { Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue(); if (dataSnapshot.getKey().equals("name")) { userName = dataSnapshot.getValue().toString(); textViewName.setText(userName); } if (dataSnapshot.getKey().equals("profile_image_url")) { profileImageUrl = dataSnapshot.getValue().toString(); Glide.with(getContext()).load(profileImageUrl).into(imageViewProfilePicture); } } } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { if (getContext() != null && dataSnapshot.exists()) { Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue(); if (dataSnapshot.getKey().equals("name")) { userName = dataSnapshot.getValue().toString(); textViewName.setText(userName); } if (dataSnapshot.getKey().equals("profile_image_url")) { profileImageUrl = dataSnapshot.getValue().toString(); Glide.with(getContext()).load(profileImageUrl).into(imageViewProfilePicture); } } } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { resultUri = result.getUri(); //imageViewProfilePicture.setImageURI(resultUri); saveUserInformation(); } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { Exception error = result.getError(); } } } private void saveUserInformation() { if (resultUri != null) { final StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("ProfileImages").child(userId); Bitmap bitmap = null; try { bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), resultUri); } catch (IOException e) { e.printStackTrace(); } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 20, byteArrayOutputStream); byte[] data = byteArrayOutputStream.toByteArray(); UploadTask uploadTask = storageReference.putBytes(data); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getContext(), "Error uploading!", Toast.LENGTH_LONG).show(); } }); uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl(); while (!urlTask.isSuccessful()); Uri downloadUrl = urlTask.getResult(); Map<String, Object> userInfo = new HashMap<>(); userInfo.put("profile_image_url", downloadUrl.toString()); userDb.updateChildren(userInfo); } }); } } public void logout(View view) { firebaseAuth.signOut(); Intent intent = new Intent(getActivity(), LoginActivity.class); getActivity().startActivity(intent); getActivity().finish(); } }
package com.bestone.util; public class Path { public final static String userPath="/Users/mahaibin/BestOnePicture/user/"; public final static String articlePath="/Users/mahaibin/BestOnePicture/article/"; public final static String handShotPath="/Users/mahaibin/BestOnePicture/touxiang/"; }
package cit360httpurl; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLExample { private final String USER_AGENT = "Mozilla/5.0"; public void sendGet() throws Exception { URL object = new URL("https://icanhazdadjoke.com/"); HttpURLConnection connect = (HttpURLConnection) object.openConnection(); connect.setRequestMethod("GET"); connect.setRequestProperty("User-Agent", USER_AGENT); connect.setRequestProperty("X-Requested-With", "Curl"); connect.addRequestProperty("Accept", "text/plain"); int respond_code = connect.getResponseCode(); if (respond_code == 200) { BufferedReader input = new BufferedReader(new InputStreamReader(connect.getInputStream())); String line = null; while((line = input.readLine()) != null) { System.out.println(line); } System.out.println(); } else { System.out.println("Oh no! The Dad Joke site seems to have an issue!\n"); } connect.disconnect(); } }
package com.goyalgadgets.musiclooper; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.HashMap; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.media.MediaMetadataRetriever; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.Toast; import com.tjeannin.apprate.AppRate; public class MusicLooperActivity extends ListActivity { private Context context; public static ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); final String MEDIA_PATH = new String("/sdcard/"); public static MediaPlayer mediaPlayer = new MediaPlayer(); private Button selectFile; Cursor musiccursor; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = this; setContentView(R.layout.main); new AppRate(this).setShowIfAppHasCrashed(false).setMinLaunchesUntilPrompt(3).init(); System.gc(); String[] proj = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Video.Media.SIZE }; musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null); for (int i = 0; i < musiccursor.getCount(); i++) { musiccursor.moveToPosition(i); String filename = musiccursor.getString(musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)); if (!filename.contains(".aac")) { HashMap<String, String> song = new HashMap<String, String>(); song.put("songTitle", musiccursor.getString(musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME))); song.put("songPath", filename); if (!songsList.contains(song)) songsList.add(song); } } // // File home = new File(MEDIA_PATH); // if (home.listFiles(new FileExtensionFilter()).length > 0) { // for (File file : home.listFiles(new FileExtensionFilter())) { // HashMap<String, String> song = new HashMap<String, String>(); // MediaMetadataRetriever mmr = new MediaMetadataRetriever(); // mmr.setDataSource(file.getPath()); // String titleOfSong = // mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); // song.put("songTitle", titleOfSong); // song.put("songPath", file.getPath()); // if (!songsList.contains(song)) // songsList.add(song); // } // } ListAdapter adapter = new MusicLooperAdapter(this, songsList); setListAdapter(adapter); selectFile = (Button) findViewById(R.id.button); selectFile.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent myintent = new Intent(MusicLooperActivity.this, FileDialog.class); startActivityForResult(myintent, 0); } }); } @Override public void onListItemClick(ListView l, View v, int position, long id) { HashMap<String, String> selection = new HashMap<String, String>(); selection = songsList.get(position); Intent intent = new Intent(context, SongPlayer.class); intent.putExtra("position", position); intent.putExtra("title", selection.get("songTitle")); intent.putExtra("path", selection.get("songPath")); startActivity(intent); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (data == null || data.getExtras() == null) return; String path = data.getExtras().getString(FileDialog.RESULT_PATH); MediaPlayer temp = MediaPlayer.create(MusicLooperActivity.this, Uri.parse(path)); if (temp == null) { Toast.makeText(this, "Must select a valid media file!", Toast.LENGTH_LONG).show(); return; } if (data == null || data.getExtras() == null || FileDialog.RESULT_PATH == null) return; Intent intent = new Intent(context, SongPlayer.class); intent.putExtra("title", path.substring(path.lastIndexOf("/") + 1)); intent.putExtra("path", path); startActivity(intent); } class FileExtensionFilter implements FilenameFilter { public boolean accept(File dir, String name) { return (name.endsWith(".mp3") || name.endsWith(".MP3") || name.endsWith(".aac") || name.endsWith(".m4a") || name.endsWith(".ogg")); } } }
package org.smart4j.util; import org.apache.commons.lang3.StringUtils; /** * Created by admin on 2017/12/13. * 字符串工具类 */ public final class StringUtil { /** * 判断字符串是否为空 */ public static boolean isEmpty(String str){ if (str!=null){ str=str.trim(); } return StringUtils.isEmpty(str); } /** * 判断字符串是否非空 */ public static boolean isNotEmpty(String str){ return !isEmpty(str); } }
/* * Copyright (C) 2019 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. */ import dalvik.system.InMemoryDexClassLoader; import java.lang.reflect.Method; import java.io.File; import java.nio.ByteBuffer; import java.util.Base64; public class Main { private static void check(boolean expected, boolean actual, String message) { if (expected != actual) { System.err.println( "ERROR: " + message + " (expected=" + expected + ", actual=" + actual + ")"); } } private static ClassLoader singleLoader() { return new InMemoryDexClassLoader( new ByteBuffer[] { ByteBuffer.wrap(DEX_BYTES_A), ByteBuffer.wrap(DEX_BYTES_B) }, /*parent*/null); } private static ClassLoader[] multiLoader() { ClassLoader clA = new InMemoryDexClassLoader(ByteBuffer.wrap(DEX_BYTES_A), /*parent*/ null); ClassLoader clB = new InMemoryDexClassLoader(ByteBuffer.wrap(DEX_BYTES_B), /*parent*/ clA); return new ClassLoader[] { clA, clB }; } private static void test(ClassLoader loader, boolean expectedHasVdexFile, boolean expectedBackedByOat, boolean invokeMethod) throws Exception { // If ART created a vdex file, it must have verified all the classes. // That happens if and only if we expect a vdex at the end of the test but // do not expect it to have been loaded. boolean expectedClassesVerified = expectedHasVdexFile && !expectedBackedByOat; waitForVerifier(); check(expectedClassesVerified, areClassesVerified(loader), "areClassesVerified"); check(expectedHasVdexFile, hasVdexFile(loader), "areClassesVerified"); check(expectedBackedByOat, isBackedByOatFile(loader), "isBackedByOatFile"); check(expectedBackedByOat, areClassesPreverified(loader), "areClassesPreverified"); if (invokeMethod) { loader.loadClass("art.ClassB").getDeclaredMethod("printHello").invoke(null); if (expectedBackedByOat) { String filter = getCompilerFilter(loader.loadClass("art.ClassB")); if (!("verify".equals(filter))) { throw new Error("Expected verify, got " + filter); } } } } public static void main(String[] args) throws Exception { System.loadLibrary(args[0]); ClassLoader[] loaders = null; // Feature only enabled for target SDK version Q and later. setTargetSdkVersion(/* Q */ 29); // Feature is disabled in debuggable mode because runtime threads are not // allowed to load classes. boolean featureEnabled = !isDebuggable(); // Data directory not set. Background verification job should not have run // and vdex should not have been created. test(singleLoader(), /*hasVdex*/ false, /*backedByOat*/ false, /*invokeMethod*/ true); // Set data directory for this process. setProcessDataDir(DEX_LOCATION); // Data directory is now set. Background verification job should have run, // should have verified classes and written results to a vdex. test(singleLoader(), /*hasVdex*/ featureEnabled, /*backedByOat*/ false, /*invokeMethod*/ true); test(singleLoader(), /*hasVdex*/ featureEnabled, /*backedByOat*/ featureEnabled, /*invokeMethod*/ true); // Test loading the two dex files with separate class loaders. // Background verification task should still verify all classes. loaders = multiLoader(); test(loaders[0], /*hasVdex*/ featureEnabled, /*backedByOat*/ false, /*invokeMethod*/ false); test(loaders[1], /*hasVdex*/ featureEnabled, /*backedByOat*/ false, /*invokeMethod*/ true); loaders = multiLoader(); test(loaders[0], /*hasVdex*/ featureEnabled, /*backedByOat*/ featureEnabled, /*invokeMethod*/ false); test(loaders[1], /*hasVdex*/ featureEnabled, /*backedByOat*/ featureEnabled, /*invokeMethod*/ true); // Change boot classpath checksum. appendToBootClassLoader(DEX_EXTRA, /*isCorePlatform*/ false); loaders = multiLoader(); test(loaders[0], /*hasVdex*/ featureEnabled, /*backedByOat*/ false, /*invokeMethod*/ false); test(loaders[1], /*hasVdex*/ featureEnabled, /*backedByOat*/ false, /*invokeMethod*/ true); loaders = multiLoader(); test(loaders[0], /*hasVdex*/ featureEnabled, /*backedByOat*/ featureEnabled, /*invokeMethod*/ false); test(loaders[1], /*hasVdex*/ featureEnabled, /*backedByOat*/ featureEnabled, /*invokeMethod*/ true); } private static native boolean isDebuggable(); private static native int setTargetSdkVersion(int version); private static native void setProcessDataDir(String path); private static native void waitForVerifier(); private static native boolean areClassesVerified(ClassLoader loader); private static native boolean hasVdexFile(ClassLoader loader); private static native boolean isBackedByOatFile(ClassLoader loader); private static native boolean areClassesPreverified(ClassLoader loader); private static native String getCompilerFilter(Class cls); // Defined in 674-hiddenapi. private static native void appendToBootClassLoader(String dexPath, boolean isCorePlatform); private static final String DEX_LOCATION = System.getenv("DEX_LOCATION"); private static final String DEX_EXTRA = new File(DEX_LOCATION, "692-vdex-inmem-loader-ex.jar").getAbsolutePath(); private static final byte[] DEX_BYTES_A = Base64.getDecoder().decode( "ZGV4CjAzNQBxYu/tdPfiHaRPYr5yaT6ko9V/xMinr1OwAgAAcAAAAHhWNBIAAAAAAAAAABwCAAAK" + "AAAAcAAAAAQAAACYAAAAAgAAAKgAAAAAAAAAAAAAAAMAAADAAAAAAQAAANgAAAC4AQAA+AAAADAB" + "AAA4AQAARQEAAEwBAABPAQAAXQEAAHEBAACFAQAAiAEAAJIBAAAEAAAABQAAAAYAAAAHAAAAAwAA" + "AAIAAAAAAAAABwAAAAMAAAAAAAAAAAABAAAAAAAAAAAACAAAAAEAAQAAAAAAAAAAAAEAAAABAAAA" + "AAAAAAEAAAAAAAAACQIAAAAAAAABAAAAAAAAACwBAAADAAAAGgACABEAAAABAAEAAQAAACgBAAAE" + "AAAAcBACAAAADgATAA4AFQAOAAY8aW5pdD4AC0NsYXNzQS5qYXZhAAVIZWxsbwABTAAMTGFydC9D" + "bGFzc0E7ABJMamF2YS9sYW5nL09iamVjdDsAEkxqYXZhL2xhbmcvU3RyaW5nOwABVgAIZ2V0SGVs" + "bG8AdX5+RDh7ImNvbXBpbGF0aW9uLW1vZGUiOiJkZWJ1ZyIsIm1pbi1hcGkiOjEsInNoYS0xIjoi" + "OTY2MDhmZDdiYmNjZGQyMjc2Y2Y4OTI4M2QyYjgwY2JmYzRmYzgxYyIsInZlcnNpb24iOiIxLjUu" + "NC1kZXYifQAAAAIAAIGABJACAQn4AQAAAAAADAAAAAAAAAABAAAAAAAAAAEAAAAKAAAAcAAAAAIA" + "AAAEAAAAmAAAAAMAAAACAAAAqAAAAAUAAAADAAAAwAAAAAYAAAABAAAA2AAAAAEgAAACAAAA+AAA" + "AAMgAAACAAAAKAEAAAIgAAAKAAAAMAEAAAAgAAABAAAACQIAAAMQAAABAAAAGAIAAAAQAAABAAAA" + "HAIAAA=="); private static final byte[] DEX_BYTES_B = Base64.getDecoder().decode( "ZGV4CjAzNQB+hWvce73hXt7ZVNgp9RAyMLSwQzsWUjV4AwAAcAAAAHhWNBIAAAAAAAAAAMwCAAAQ" + "AAAAcAAAAAcAAACwAAAAAwAAAMwAAAABAAAA8AAAAAUAAAD4AAAAAQAAACABAAA4AgAAQAEAAI4B" + "AACWAQAAowEAAKYBAAC0AQAAwgEAANkBAADtAQAAAQIAABUCAAAYAgAAHAIAACYCAAArAgAANwIA" + "AEACAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAAAgAAAAQAAAAAAAAACQAAAAYAAAAAAAAA" + "CgAAAAYAAACIAQAABQACAAwAAAAAAAAACwAAAAEAAQAAAAAAAQABAA0AAAACAAIADgAAAAMAAQAA" + "AAAAAQAAAAEAAAADAAAAAAAAAAEAAAAAAAAAtwIAAAAAAAABAAEAAQAAAHwBAAAEAAAAcBAEAAAA" + "DgACAAAAAgAAAIABAAAKAAAAYgAAAHEAAAAAAAwBbiADABAADgATAA4AFQAOlgAAAAABAAAABAAG" + "PGluaXQ+AAtDbGFzc0IuamF2YQABTAAMTGFydC9DbGFzc0E7AAxMYXJ0L0NsYXNzQjsAFUxqYXZh" + "L2lvL1ByaW50U3RyZWFtOwASTGphdmEvbGFuZy9PYmplY3Q7ABJMamF2YS9sYW5nL1N0cmluZzsA" + "EkxqYXZhL2xhbmcvU3lzdGVtOwABVgACVkwACGdldEhlbGxvAANvdXQACnByaW50SGVsbG8AB3By" + "aW50bG4AdX5+RDh7ImNvbXBpbGF0aW9uLW1vZGUiOiJkZWJ1ZyIsIm1pbi1hcGkiOjEsInNoYS0x" + "IjoiOTY2MDhmZDdiYmNjZGQyMjc2Y2Y4OTI4M2QyYjgwY2JmYzRmYzgxYyIsInZlcnNpb24iOiIx" + "LjUuNC1kZXYifQAAAAIAAYGABMACAQnYAgAAAAAAAAAOAAAAAAAAAAEAAAAAAAAAAQAAABAAAABw" + "AAAAAgAAAAcAAACwAAAAAwAAAAMAAADMAAAABAAAAAEAAADwAAAABQAAAAUAAAD4AAAABgAAAAEA" + "AAAgAQAAASAAAAIAAABAAQAAAyAAAAIAAAB8AQAAARAAAAEAAACIAQAAAiAAABAAAACOAQAAACAA" + "AAEAAAC3AgAAAxAAAAEAAADIAgAAABAAAAEAAADMAgAA"); }
package com.bofsoft.sdk.widget.layout; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressLint("ClickableViewAccessibility") public class AutoLinearLayout extends LinearLayout implements OnClickListener, View.OnTouchListener { private int mWidth; // Layout控件的宽 private int mHeight; // Layout控件的高 private int r; private int l; private CheckState state = CheckState.RADIO; private OnChangeListener listener; private View checkedView; static final String TAG = "AutoLinearLayout"; private int gap = 10; private boolean enable = true; private String toastMsg = null; private Map<Integer, Boolean> enableMap = new HashMap<Integer, Boolean>(); private Map<Integer, String> enableToastMap = new HashMap<Integer, String>(); // 固定列 private int cellCnt = 0; // 每列宽度 private int cWidth = 0; public void setGap(int gap) { this.gap = gap; } /** * 选择方式 单选,多选 */ public enum CheckState { RADIO, MULTI } /** * 未选中 选中 按下 抬起 */ public enum ChangeState { NORMAL, CHECKED, DOWN, UP } public AutoLinearLayout(Context context) { super(context); } public AutoLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { this.r = r; this.l = l; foo(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int cellWidthSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);// 让自控件自己按需撑开 int cellHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);// 让自控件自己按需撑开 int w = MeasureSpec.getSize(widthMeasureSpec); mWidth = w; int count = getChildCount(); for (int i = 0; i < count; i++) { View childView = getChildAt(i); try { childView.measure(cellWidthSpec, cellHeightSpec); } catch (NullPointerException e) { // 这个异常不影响展示 } } foo(); setMeasuredDimension(resolveSize(mWidth, widthMeasureSpec), resolveSize(mHeight, heightMeasureSpec)); } public void setCellNum(int cnt) { this.cellCnt = cnt; } private void foo() { if (mWidth == 0) mWidth = r - l;// 宽度是跟随父容器而定的 // 自身控件的padding int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); // 控件自身可以被用来显示自控件的宽度 int mDisplayWidth = mWidth - paddingLeft - paddingRight; // 自控件的margin int cellMarginLeft = 0; int cellMarginRight = 0; int cellMarginTop = 0; int cellMarginBottom = 0; int x = 0;// 子控件的默认左上角坐标x int y = 0;// 子控件的默认左上角坐标y int totalWidth = 0;// 计算每一行随着自控件的增加而变化的宽度 int count = getChildCount(); int cellWidth = 0;// 子控件的宽,包含padding int cellHeight = 0;// 自控件的高,包含padding int left = 0;// 子控件左上角的横坐标 int top = 0;// 子控件左上角的纵坐标 LayoutParams lp; if (cWidth <= 0 && cellCnt > 0) { cWidth = (int) ((mDisplayWidth - gap * (cellCnt - 1)) / cellCnt - 0.5); } for (int j = 0; j < count; j++) { final View childView = getChildAt(j); childView.setOnClickListener(this); childView.setOnTouchListener(this); childView.setId(j); // 获取子控件child的宽高 cellWidth = childView.getMeasuredWidth();// 测量自控件内容的宽度(这个时候padding有被计算进内) cellHeight = childView.getMeasuredHeight();// 测量自控件内容的高度(这个时候padding有被计算进内) lp = (LayoutParams) childView.getLayoutParams(); cellMarginLeft = lp.leftMargin; cellMarginRight = lp.rightMargin; cellMarginTop = lp.topMargin; cellMarginBottom = lp.bottomMargin; if (cWidth > 0) { cellWidth = cWidth; } // 动态计算子控件在一行里面占据的宽度 // 预判,先加上下一个要展示的子控件,计算这一行够不够放 totalWidth += cellMarginLeft + cellWidth + cellMarginRight; if (totalWidth >= mDisplayWidth) {// 不够放的时候需要换行 y += cellMarginTop + cellHeight + cellMarginBottom + gap;// 新增一行 totalWidth = cellMarginLeft + cellWidth + cellMarginRight;// 这时候这一行的宽度为这个子控件的宽度 x = 0;// 重置 } // 计算顶点横坐标 left = x + cellMarginLeft + paddingLeft; // 计算顶点纵坐标 top = y + cellMarginTop + paddingTop; // 绘制自控件 childView.layout(left, top, left + cellWidth, top + cellHeight); // 计算下一个横坐标 x += cellMarginLeft + cellWidth + cellMarginRight; x += gap; totalWidth += gap; } mHeight = paddingTop + y + cellMarginTop + cellHeight + cellMarginBottom + paddingBottom; } @Override public void addView(View child) { super.addView(child); child.setId(getChildCount() - 1); } public void setChecked(View v) { if (v == null) return; listener.change(v, v.getId(), ChangeState.CHECKED); v.setTag(1); if (state == CheckState.RADIO) { if (checkedView != null && v.getId() != checkedView.getId()) { listener.change(checkedView, checkedView.getId(), ChangeState.NORMAL); checkedView.setTag(0); } checkedView = v; } else { if (checkedView != null) { listener.change(checkedView, checkedView.getId(), ChangeState.NORMAL); checkedView.setTag(0); checkedView = null; } } } public void setChecked(int position) { int count = getChildCount(); if (count < 0 || position >= count) return; setChecked(getChildAt(position)); } public void cleanChecked(int position) { View v = getChildAt(position); listener.change(v, v.getId(), ChangeState.NORMAL); v.setTag(0); } public void cleanChecked() { checkedView = null; int cnt = getChildCount(); for (int i = 0; i < cnt; i++) { cleanChecked(i); } } public void setEnable(boolean enable, String toastMsg) { this.enable = enable; this.toastMsg = toastMsg; } public void setEnable(int position, boolean enable, String toastString) { enableMap.put(position, enable); enableToastMap.put(position, toastString); } public void cleanEnable() { this.enable = true; this.toastMsg = null; this.enableMap.clear(); this.enableToastMap.clear(); } @Override public void onClick(View v) { if (!enable) { if (toastMsg != null) { Toast.makeText(getContext(), toastMsg, Toast.LENGTH_SHORT).show(); } return; } checked(v); } private void checked(View v) { if (listener == null || state == null) return; int t = v.getTag() == null ? 0 : (Integer) v.getTag(); int position = v.getId(); Boolean enable = enableMap.get(position); String toastStr = enableToastMap.get(position); if (enable != null && !enable) { if (toastStr != null) Toast.makeText(getContext(), toastStr, Toast.LENGTH_SHORT).show(); return; } if (state == CheckState.MULTI) { if (t == 0) { listener.change(v, position, ChangeState.CHECKED); v.setTag(1); } else { listener.change(v, position, ChangeState.NORMAL); v.setTag(0); } checkedView = v; } else { if (checkedView != v) { listener.change(v, position, ChangeState.CHECKED); v.setTag(1); if (checkedView != null) { listener.change(checkedView, checkedView.getId(), ChangeState.NORMAL); checkedView.setTag(0); } checkedView = v; // } else { // listener.change(v, position, ChangeState.NORMAL); // v.setTag(0); // checkedView = null; } } } /** * 获取被点种的索引 * * @return */ public List<Integer> getSelected() { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < getChildCount(); i++) { View v = getChildAt(i); if (v.getTag() != null && Integer.valueOf(v.getTag().toString()) == 1) { list.add(v.getId()); } } return list; } /** * 获取未选中的 * * @return */ public List<Integer> getNormal() { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < getChildCount(); i++) { View v = getChildAt(i); if (v.getTag() == null && Integer.valueOf(v.getTag().toString()) == 0) { list.add(v.getId()); } } return list; } @Override public boolean onTouch(View v, MotionEvent event) { if (listener == null) return false; int id = v.getId(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: listener.change(v, id, ChangeState.DOWN); break; case MotionEvent.ACTION_UP: listener.change(v, id, ChangeState.UP); break; } return false; } public void setState(CheckState state) { this.state = state; foo(); } public void setOnChangeListener(OnChangeListener listener) { this.listener = listener; foo(); } public interface OnChangeListener { void change(View v, int position, ChangeState state); } }
package com.sam.sec.model; public class StepModel { private String saga; private String step; private String apiPath; private String capiPath; private String apiMethod; private String capiMethod; public String getSaga() { return saga; } public void setSaga(String saga) { this.saga = saga; } public String getStep() { return step; } public void setStep(String step) { this.step = step; } public String getApiPath() { return apiPath; } public void setApiPath(String apiPath) { this.apiPath = apiPath; } public String getCapiPath() { return capiPath; } public void setCapiPath(String capiPath) { this.capiPath = capiPath; } public String getApiMethod() { return apiMethod; } public void setApiMethod(String apiMethod) { this.apiMethod = apiMethod; } public String getCapiMethod() { return capiMethod; } public void setCapiMethod(String capiMethod) { this.capiMethod = capiMethod; } }
/* * 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 Interfaces; import Model.User; /** * * @author RolfMoikjær */ public interface AuthIF { boolean authCheck(String id, String pwd); User getUser(String id); //boolean addUser(String name, String id, String pwd, String gender, String age, String country); }
package com.company.classes; //EXAMPLE OF ENCAPSULATION public class Marsupial extends Animal{//extension is an example of polymorphism //all functions are examples of abstraction //name is an example of identity public Marsupial(String newName) { super(newName); } @Override public void roam(){} @Override public void sleep(){} }
package com.liujunbo.springbootdemo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.HashMap; import java.util.Map; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootDemoApplicationTests { @Test public void contextLoads() { } public static void main(String[] args) { Map<String,String> map = new HashMap<>(); map.put("1","11"); map.put("2","22"); map.put("3","33"); map.put("4","44"); map.forEach((key,value)->System.out.println("key:"+key+" value:"+value)); } }
package oasispv.pv; /** * Created by Usuario on 28/11/2016. */ public class variables { public static String ip; public static String cn; public static String un; public static String pw; public static String movi; public static String fase; public static String mesero; public static String movi_desc; public static String mesa; public static int sesion; public static int comensal; public static int tiempo; public static String cmd; public static int max_id; public static String modipv; public static String mandatory; public static String prdesc; public static String mesero_mesa; public static String comensal_name; public static String rva; public static String habi; public static int mesa_pax; public static int erroroc; public static int turno; public static float tprecio; }
/* * Created on 2005-8-10 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.aof.webapp.action.prm.report; import java.io.FileInputStream; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.Region; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.aof.component.prm.Bill.BillTransactionDetail; import com.aof.component.prm.Bill.ProjectBill; import com.aof.component.prm.payment.PaymentTransactionDetail; import com.aof.component.prm.payment.ProjectPayment; import com.aof.core.persistence.hibernate.Hibernate2Session; import com.aof.util.Constants; import com.aof.webapp.action.ActionErrorLog; /** * @author gus * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class PaymentInstructionExcelFormAction extends ReportBaseAction { protected ActionErrors errors = new ActionErrors(); protected ActionErrorLog actionDebug = new ActionErrorLog(); public ActionForward perform(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){ return ExportToExcel(mapping, form, request, response); } private ActionForward ExportToExcel (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ try { ActionErrors errors = this.getActionErrors(request.getSession()); String payId = request.getParameter("payId"); String category = request.getParameter("category"); if ((payId == null) || (payId.length() < 1)) actionDebug.addGlobalError(errors,"error.context.required"); if (!errors.empty()) { saveErrors(request, errors); return null; } DateFormat df = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH); NumberFormat numFormater = NumberFormat.getInstance(); numFormater.setMaximumFractionDigits(2); numFormater.setMinimumFractionDigits(2); //Get Excel Template Path String TemplatePath = GetTemplateFolder(); if (TemplatePath == null) return null; //Fetch related Data net.sf.hibernate.Session hs = Hibernate2Session.currentSession(); ProjectPayment pb = (ProjectPayment)hs.load(ProjectPayment.class, new Long(payId)); if (pb == null) return null; List CAFList = pb.getCAFDetails(); //List AllowanceList = pb.getAllowanceDetails(); List ExpenseList = pb.getExpenseDetails(); List AcceptanceList = pb.getPaymentDetails(); List CreditDownPaymentList = pb.getCreditDownPaymentDetails(); List DownPaymentList = pb.getDownPaymentDetails(); double CAFAmt = pb.getCAFAmount(); // double AllowanceAmt = pb.getAllowanceAmount(); double ExpenseAmt = pb.getExpenseAmount(); double AcceptanceAmt = pb.getPaymentAmount(); double CreditDownPaymentAmt = pb.getCreditDownPaymentAmount(); double DownPaymentAmt = pb.getDownPaymentAmount(); //for downpayment //Start to output the excel file response.reset(); response.setHeader("Content-Disposition", "attachment;filename=\""+ SaveToFileName + "\""); response.setContentType("application/octet-stream"); //Use POI to read the selected Excel Spreadsheet HSSFWorkbook wb = null; //Select the first worksheet if (category.equals(Constants.TRANSACATION_CATEGORY_DOWN_PAYMENT)) { wb = new HSSFWorkbook(new FileInputStream(TemplatePath+"\\"+DownPayExcelTemplate)); int ExcelRow4 = ListStartRow - 1 ; if (DownPaymentAmt!=0){ HSSFSheet DownPaymentsheet = wb.getSheet(FormSheetDownPayment); HSSFCell DownPaymentCell = null; DownPaymentsheet.addMergedRegion(new Region(2, (short) 1, 2, (short) 5)); DownPaymentCell = DownPaymentsheet.getRow(2).getCell((short)1); DownPaymentCell.setCellValue(pb.getProject().getProjId() + " : " +pb.getProject().getProjName()); DownPaymentsheet.addMergedRegion(new Region(2, (short) 7, 2, (short) 9)); DownPaymentCell = DownPaymentsheet.getRow(2).getCell((short)7); DownPaymentCell.setCellValue(pb.getPaymentCode()); DownPaymentsheet.addMergedRegion(new Region(3, (short) 1, 3, (short) 3)); DownPaymentCell = DownPaymentsheet.getRow(3).getCell((short)1); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(pb.getPayAddress().getDescription()); DownPaymentsheet.addMergedRegion(new Region(3, (short) 6, 3, (short) 9)); DownPaymentCell = DownPaymentsheet.getRow(3).getCell((short)6); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(pb.getProject().getVendor().getPartyId()+" : "+pb.getProject().getVendor().getDescription()); if (pb.getProject().getParentProject()!=null){ DownPaymentsheet.addMergedRegion(new Region(4, (short) 2, 4, (short) 7)); DownPaymentCell = DownPaymentsheet.getRow(4).getCell((short)2); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(pb.getProject().getParentProject().getProjId()+" : "+pb.getProject().getParentProject().getProjName()); DownPaymentsheet.addMergedRegion(new Region(5, (short) 2, 5, (short) 7)); // 7 DownPaymentCell = DownPaymentsheet.getRow(5).getCell((short)2); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(pb.getProject().getParentProject().getCustomer().getPartyId()+" : "+pb.getProject().getParentProject().getCustomer().getDescription()); } HSSFRow DownPaymentHRow = null; HSSFCellStyle Style5 = DownPaymentsheet.getRow(5).getCell((short)9).getCellStyle(); if (DownPaymentList != null && DownPaymentList.size() > 0) { //HSSFCellStyle Style1 = CAFsheet.getRow(ListStartRow).getCell((short)0).getCellStyle(); //HSSFCellStyle Style2 = CAFsheet.getRow(ListStartRow).getCell((short)6).getCellStyle(); //HSSFCellStyle Style3 = CAFsheet.getRow(ListStartRow).getCell((short)7).getCellStyle(); //HSSFCellStyle Style4 = CAFsheet.getRow(ListStartRow).getCell((short)8).getCellStyle(); int DownPaymentCount = 0; double DownPaymentTotal = 0; for (int i0 = 0; i0 < DownPaymentList.size(); i0++) { /* BillTransactionDetail btd = (BillTransactionDetail)AcceptanceList.get(i0); AcceptanceHRow = Acceptancesheet.createRow(ExcelRow3); Acceptancesheet.addMergedRegion(new Region(ExcelRow3, (short)0, ExcelRow3, (short)2 )); AcceptanceCell = AcceptanceHRow.createCell((short)0); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(btd.getDesc1() != null ? btd.getDesc1() : ""); AcceptanceCell.setCellStyle(Ss1); AcceptanceCell = AcceptanceHRow.createCell((short)1); AcceptanceCell.setCellStyle(Ss1); AcceptanceCell = AcceptanceHRow.createCell((short)2); AcceptanceCell.setCellStyle(Ss2); */ PaymentTransactionDetail btd = (PaymentTransactionDetail)DownPaymentList.get(i0); DownPaymentHRow = DownPaymentsheet.createRow(ExcelRow4); DownPaymentsheet.addMergedRegion(new Region(ExcelRow4, (short)0, ExcelRow4, (short)5 )); DownPaymentCell = DownPaymentHRow.createCell((short)0); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("DownPayment"); //DownPaymentCell.setCellStyle(Style1); //DownPaymentCell = DownPaymentHRow.createCell((short)1); //DownPaymentCell.setCellStyle(Style1); DownPaymentCell = DownPaymentHRow.createCell((short)6); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Amount : "); //DownPaymentCell.setCellStyle(Style1); //DownPaymentCell = DownPaymentHRow.createCell((short)3); //DownPaymentCell.setCellStyle(Style1); DownPaymentsheet.addMergedRegion(new Region(ExcelRow4, (short)7, ExcelRow4, (short)9 )); DownPaymentCell = DownPaymentHRow.createCell((short)7); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(btd.getAmount().doubleValue()); //DownPaymentCell.setCellStyle(Style1); //DownPaymentCell = DownPaymentHRow.createCell((short)5); //DownPaymentCell.setCellStyle(Style1); double total1 = btd.getAmount().doubleValue(); DownPaymentTotal = total1 + DownPaymentTotal; DownPaymentCount = i0+1; ExcelRow4++; } DownPaymentHRow = DownPaymentsheet.createRow(ExcelRow4); DownPaymentCell = DownPaymentHRow.createCell((short)8); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Total :"); //DownPaymentCell.setCellStyle(Style1); DownPaymentCell = DownPaymentHRow.createCell((short)9); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(DownPaymentTotal); //DownPaymentCell.setCellStyle(Style4); // footer DownPaymentHRow = DownPaymentsheet.createRow(ExcelRow4+2); // DownPaymentsheet.addMergedRegion(new Region(ExcelRow4+2, (short) 0, ExcelRow4+2, (short) 1)); DownPaymentCell = DownPaymentHRow.createCell((short)0); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Prepared By :"); DownPaymentCell.setCellStyle(Style5); DownPaymentsheet.addMergedRegion(new Region(ExcelRow4+2, (short) 1, ExcelRow4+2, (short) 2)); DownPaymentCell = DownPaymentHRow.createCell((short)1); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(pb.getCreateUser().getName()); DownPaymentCell.setCellStyle(Style5); DownPaymentCell = DownPaymentHRow.createCell((short)3); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Date :"); DownPaymentCell.setCellStyle(Style5); // DownPaymentsheet.addMergedRegion(new Region(ExcelRow4+2, (short) 7, ExcelRow4+2, (short) 8)); DownPaymentCell = DownPaymentHRow.createCell((short)4); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(df.format(new Date())); DownPaymentCell.setCellStyle(Style5); DownPaymentHRow = DownPaymentsheet.createRow(ExcelRow4+2); // DownPaymentsheet.addMergedRegion(new Region(ExcelRow4+2, (short) 0, ExcelRow4+2, (short) 1)); DownPaymentCell = DownPaymentHRow.createCell((short)0); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Approved By :"); DownPaymentCell.setCellStyle(Style5); DownPaymentCell = DownPaymentHRow.createCell((short)3); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Date :"); DownPaymentCell.setCellStyle(Style5); } } } else { wb = new HSSFWorkbook(new FileInputStream(TemplatePath+"\\"+ExcelTemplate)); int ExcelRow = ListStartRow; int ExcelRow1 = ListStartRow; int ExcelRow2 = ListStartRow; int ExcelRow3 = ListStartRow; int ExcelRow4 = ListStartRow - 1 ; // DownPayment --------------------------------------------------------------------------- if (CreditDownPaymentAmt!=0){ HSSFSheet DownPaymentsheet = wb.getSheet(FormSheetDownPayment); HSSFCell DownPaymentCell = null; DownPaymentsheet.addMergedRegion(new Region(2, (short) 1, 2, (short) 5)); DownPaymentCell = DownPaymentsheet.getRow(2).getCell((short)1); DownPaymentCell.setCellValue(pb.getProject().getProjId() + " : " +pb.getProject().getProjName()); DownPaymentsheet.addMergedRegion(new Region(2, (short) 7, 2, (short) 9)); DownPaymentCell = DownPaymentsheet.getRow(2).getCell((short)7); DownPaymentCell.setCellValue(pb.getPaymentCode()); DownPaymentsheet.addMergedRegion(new Region(3, (short) 1, 3, (short) 3)); DownPaymentCell = DownPaymentsheet.getRow(3).getCell((short)1); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(pb.getPayAddress().getDescription()); DownPaymentsheet.addMergedRegion(new Region(3, (short) 6, 3, (short) 9)); DownPaymentCell = DownPaymentsheet.getRow(3).getCell((short)6); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(pb.getProject().getVendor().getPartyId()+" : "+pb.getProject().getVendor().getDescription()); if (pb.getProject().getParentProject()!=null){ DownPaymentsheet.addMergedRegion(new Region(4, (short) 2, 4, (short) 7)); DownPaymentCell = DownPaymentsheet.getRow(4).getCell((short)2); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(pb.getProject().getParentProject().getProjId()+" : "+pb.getProject().getParentProject().getProjName()); DownPaymentsheet.addMergedRegion(new Region(5, (short) 2, 5, (short) 7)); // 7 DownPaymentCell = DownPaymentsheet.getRow(5).getCell((short)2); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(pb.getProject().getParentProject().getCustomer().getPartyId()+" : "+pb.getProject().getParentProject().getCustomer().getDescription()); } HSSFRow DownPaymentHRow = null; HSSFCellStyle Style5 = DownPaymentsheet.getRow(5).getCell((short)9).getCellStyle(); if (CreditDownPaymentList != null && CreditDownPaymentList.size() > 0) { //HSSFCellStyle Style1 = CAFsheet.getRow(ListStartRow).getCell((short)0).getCellStyle(); //HSSFCellStyle Style2 = CAFsheet.getRow(ListStartRow).getCell((short)6).getCellStyle(); //HSSFCellStyle Style3 = CAFsheet.getRow(ListStartRow).getCell((short)7).getCellStyle(); //HSSFCellStyle Style4 = CAFsheet.getRow(ListStartRow).getCell((short)8).getCellStyle(); int DownPaymentCount = 0; double DownPaymentTotal = 0; for (int i0 = 0; i0 < CreditDownPaymentList.size(); i0++) { /* BillTransactionDetail btd = (BillTransactionDetail)AcceptanceList.get(i0); AcceptanceHRow = Acceptancesheet.createRow(ExcelRow3); Acceptancesheet.addMergedRegion(new Region(ExcelRow3, (short)0, ExcelRow3, (short)2 )); AcceptanceCell = AcceptanceHRow.createCell((short)0); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(btd.getDesc1() != null ? btd.getDesc1() : ""); AcceptanceCell.setCellStyle(Ss1); AcceptanceCell = AcceptanceHRow.createCell((short)1); AcceptanceCell.setCellStyle(Ss1); AcceptanceCell = AcceptanceHRow.createCell((short)2); AcceptanceCell.setCellStyle(Ss2); */ PaymentTransactionDetail btd = (PaymentTransactionDetail)CreditDownPaymentList.get(i0); DownPaymentHRow = DownPaymentsheet.createRow(ExcelRow4); DownPaymentsheet.addMergedRegion(new Region(ExcelRow4, (short)0, ExcelRow4, (short)5 )); DownPaymentCell = DownPaymentHRow.createCell((short)0); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("DownPayment"); //DownPaymentCell.setCellStyle(Style1); //DownPaymentCell = DownPaymentHRow.createCell((short)1); //DownPaymentCell.setCellStyle(Style1); DownPaymentCell = DownPaymentHRow.createCell((short)6); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Amount : "); //DownPaymentCell.setCellStyle(Style1); //DownPaymentCell = DownPaymentHRow.createCell((short)3); //DownPaymentCell.setCellStyle(Style1); DownPaymentsheet.addMergedRegion(new Region(ExcelRow4, (short)7, ExcelRow4, (short)9 )); DownPaymentCell = DownPaymentHRow.createCell((short)7); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(btd.getAmount().doubleValue()); //DownPaymentCell.setCellStyle(Style1); //DownPaymentCell = DownPaymentHRow.createCell((short)5); //DownPaymentCell.setCellStyle(Style1); double total1 = btd.getAmount().doubleValue(); DownPaymentTotal = total1 + DownPaymentTotal; DownPaymentCount = i0+1; ExcelRow4++; } DownPaymentHRow = DownPaymentsheet.createRow(ExcelRow4); DownPaymentCell = DownPaymentHRow.createCell((short)8); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Total :"); //DownPaymentCell.setCellStyle(Style1); DownPaymentCell = DownPaymentHRow.createCell((short)9); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(DownPaymentTotal); //DownPaymentCell.setCellStyle(Style4); // footer DownPaymentHRow = DownPaymentsheet.createRow(ExcelRow4+2); // DownPaymentsheet.addMergedRegion(new Region(ExcelRow4+2, (short) 0, ExcelRow4+2, (short) 1)); DownPaymentCell = DownPaymentHRow.createCell((short)0); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Prepared By :"); DownPaymentCell.setCellStyle(Style5); DownPaymentsheet.addMergedRegion(new Region(ExcelRow4+2, (short) 1, ExcelRow4+2, (short) 2)); DownPaymentCell = DownPaymentHRow.createCell((short)1); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(pb.getCreateUser().getName()); DownPaymentCell.setCellStyle(Style5); DownPaymentCell = DownPaymentHRow.createCell((short)3); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Date :"); DownPaymentCell.setCellStyle(Style5); // DownPaymentsheet.addMergedRegion(new Region(ExcelRow4+2, (short) 7, ExcelRow4+2, (short) 8)); DownPaymentCell = DownPaymentHRow.createCell((short)4); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue(df.format(new Date())); DownPaymentCell.setCellStyle(Style5); DownPaymentHRow = DownPaymentsheet.createRow(ExcelRow4+2); // DownPaymentsheet.addMergedRegion(new Region(ExcelRow4+2, (short) 0, ExcelRow4+2, (short) 1)); DownPaymentCell = DownPaymentHRow.createCell((short)0); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Approved By :"); DownPaymentCell.setCellStyle(Style5); DownPaymentCell = DownPaymentHRow.createCell((short)3); DownPaymentCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 DownPaymentCell.setCellValue("Date :"); DownPaymentCell.setCellStyle(Style5); } }else{ wb.removeSheetAt(3); } // Acceptance --------------------------------------------------------------------------------- if(AcceptanceAmt!=0){ HSSFSheet Acceptancesheet = wb.getSheet(FormSheetAcceptance); HSSFCell AcceptanceCell = null; Acceptancesheet.addMergedRegion(new Region(2, (short) 1, 2, (short) 5)); AcceptanceCell = Acceptancesheet.getRow(2).getCell((short)1); AcceptanceCell.setCellValue(pb.getProject().getProjId() + " : " +pb.getProject().getProjName()); Acceptancesheet.addMergedRegion(new Region(2, (short) 7, 2, (short) 9)); AcceptanceCell = Acceptancesheet.getRow(2).getCell((short)7); AcceptanceCell.setCellValue(pb.getPaymentCode()); Acceptancesheet.addMergedRegion(new Region(3, (short) 1, 3, (short) 3)); AcceptanceCell = Acceptancesheet.getRow(3).getCell((short)1); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(pb.getPayAddress().getDescription()); Acceptancesheet.addMergedRegion(new Region(3, (short) 6, 3, (short) 9)); AcceptanceCell = Acceptancesheet.getRow(3).getCell((short)6); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(pb.getProject().getVendor().getPartyId()+" : "+pb.getProject().getVendor().getDescription()); if (pb.getProject().getParentProject()!=null){ Acceptancesheet.addMergedRegion(new Region(4, (short) 2, 4, (short) 7)); AcceptanceCell = Acceptancesheet.getRow(4).getCell((short)2); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(pb.getProject().getParentProject().getProjId()+" : "+pb.getProject().getParentProject().getProjName()); Acceptancesheet.addMergedRegion(new Region(5, (short) 2, 5, (short) 7)); // 7 AcceptanceCell = Acceptancesheet.getRow(5).getCell((short)2); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(pb.getProject().getParentProject().getCustomer().getPartyId()+" : "+pb.getProject().getParentProject().getCustomer().getDescription()); } HSSFRow AcceptanceHRow = null; if (AcceptanceList != null && AcceptanceList.size() > 0) { HSSFCellStyle Ss1 = Acceptancesheet.getRow(ListStartRow).getCell((short)0).getCellStyle(); HSSFCellStyle Ss2 = Acceptancesheet.getRow(ListStartRow).getCell((short)2).getCellStyle(); HSSFCellStyle Ss3 = Acceptancesheet.getRow(ListStartRow).getCell((short)3).getCellStyle(); HSSFCellStyle Ss4 = Acceptancesheet.getRow(ListStartRow).getCell((short)4).getCellStyle(); HSSFCellStyle Ss5 = Acceptancesheet.getRow(ListStartRow).getCell((short)5).getCellStyle(); HSSFCellStyle Ss6 = Acceptancesheet.getRow(ListStartRow).getCell((short)6).getCellStyle(); HSSFCellStyle Ss7 = Acceptancesheet.getRow(ListStartRow).getCell((short)7).getCellStyle(); HSSFCellStyle Ss8 = Acceptancesheet.getRow(ListStartRow).getCell((short)9).getCellStyle(); HSSFCellStyle Style5 = Acceptancesheet.getRow(5).getCell((short)9).getCellStyle(); int AllowanceCount = 0; double AllowanceTotal = 0; for (int i0 = 0; i0 < AcceptanceList.size(); i0++) { PaymentTransactionDetail btd = (PaymentTransactionDetail)AcceptanceList.get(i0); AcceptanceHRow = Acceptancesheet.createRow(ExcelRow3); Acceptancesheet.addMergedRegion(new Region(ExcelRow3, (short)0, ExcelRow3, (short)2 )); AcceptanceCell = AcceptanceHRow.createCell((short)0); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(btd.getDesc1() != null ? btd.getDesc1() : ""); AcceptanceCell.setCellStyle(Ss1); AcceptanceCell = AcceptanceHRow.createCell((short)1); AcceptanceCell.setCellStyle(Ss1); AcceptanceCell = AcceptanceHRow.createCell((short)2); AcceptanceCell.setCellStyle(Ss2); Acceptancesheet.addMergedRegion(new Region(ExcelRow3, (short)3, ExcelRow3, (short)4 )); AcceptanceCell = AcceptanceHRow.createCell((short)3); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(btd.getTransactionDate() != null ? df.format(btd.getTransactionDate()) : ""); AcceptanceCell.setCellStyle(Ss3); AcceptanceCell = AcceptanceHRow.createCell((short)4); AcceptanceCell.setCellStyle(Ss4); Acceptancesheet.addMergedRegion(new Region(ExcelRow3, (short)5, ExcelRow3, (short)6 )); AcceptanceCell = AcceptanceHRow.createCell((short)5); AcceptanceCell.setCellStyle(Ss5); AcceptanceCell = AcceptanceHRow.createCell((short)6); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(btd.getTransactionNum2() != null ? numFormater.format(btd.getTransactionNum2()) : ""); AcceptanceCell.setCellStyle(Ss6); Acceptancesheet.addMergedRegion(new Region(ExcelRow3, (short)7, ExcelRow3, (short)9 )); AcceptanceCell = AcceptanceHRow.createCell((short)7); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(btd.getAmount() != null ? numFormater.format(btd.getAmount()) : ""); AcceptanceCell.setCellStyle(Ss7); AcceptanceCell = AcceptanceHRow.createCell((short)8); AcceptanceCell.setCellStyle(Ss7); AcceptanceCell = AcceptanceHRow.createCell((short)9); AcceptanceCell.setCellStyle(Ss8); double total4 = btd.getAmount().doubleValue(); AllowanceTotal = total4 + AllowanceTotal; AllowanceCount = i0+1; ExcelRow3++; } AcceptanceHRow = Acceptancesheet.createRow(ListStartRow+AllowanceCount); Acceptancesheet.addMergedRegion(new Region((ListStartRow+AllowanceCount), (short)5, (ListStartRow+AllowanceCount), (short)6 )); AcceptanceCell = AcceptanceHRow.createCell((short)5); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellStyle(Ss5); AcceptanceCell = AcceptanceHRow.createCell((short)6); AcceptanceCell.setCellValue("Total :"); AcceptanceCell.setCellStyle(Ss6); Acceptancesheet.addMergedRegion(new Region((ListStartRow+AllowanceCount), (short)7, (ListStartRow+AllowanceCount), (short)9 )); AcceptanceCell = AcceptanceHRow.createCell((short)7); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(AllowanceTotal); AcceptanceCell.setCellStyle(Ss7); AcceptanceCell = AcceptanceHRow.createCell((short)8); AcceptanceCell.setCellStyle(Ss7); AcceptanceCell = AcceptanceHRow.createCell((short)9); AcceptanceCell.setCellStyle(Ss8); // footer AcceptanceHRow = Acceptancesheet.createRow(ListStartRow+AllowanceCount+2); //Acceptancesheet.addMergedRegion(new Region(ListStartRow+AllowanceCount+2, (short) 0, ListStartRow+AllowanceCount+2, (short) 1)); AcceptanceCell = AcceptanceHRow.createCell((short)0); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue("Prepared By :"); AcceptanceCell.setCellStyle(Style5); Acceptancesheet.addMergedRegion(new Region(ListStartRow+AllowanceCount+2, (short) 1, ListStartRow+AllowanceCount+2, (short) 2)); AcceptanceCell = AcceptanceHRow.createCell((short)1); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(pb.getCreateUser().getName()); AcceptanceCell.setCellStyle(Style5); AcceptanceCell = AcceptanceHRow.createCell((short)3); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue("Date :"); AcceptanceCell.setCellStyle(Style5); // Acceptancesheet.addMergedRegion(new Region(ListStartRow+AllowanceCount+2, (short) 7, ListStartRow+AllowanceCount+2, (short) 8)); AcceptanceCell = AcceptanceHRow.createCell((short)4); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue(df.format(new Date())); AcceptanceCell.setCellStyle(Style5); AcceptanceHRow = Acceptancesheet.createRow(ListStartRow+AllowanceCount+4); AcceptanceCell = AcceptanceHRow.createCell((short)0); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue("Approved By :"); AcceptanceCell.setCellStyle(Style5); AcceptanceCell = AcceptanceHRow.createCell((short)3); AcceptanceCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 AcceptanceCell.setCellValue("Date :"); AcceptanceCell.setCellStyle(Style5); } }else{ wb.removeSheetAt(2); } // Expense -------------------------------------------------------------------------- if(ExpenseAmt!=0){ HSSFSheet Expensesheet = wb.getSheet(FormSheetExpense); HSSFCell ExpenseCell = null; Expensesheet.addMergedRegion(new Region(2, (short) 1, 2, (short) 5)); ExpenseCell = Expensesheet.getRow(2).getCell((short)1); ExpenseCell.setCellValue(pb.getProject().getProjId() + " : " +pb.getProject().getProjName()); Expensesheet.addMergedRegion(new Region(2, (short) 7, 2, (short) 9)); ExpenseCell = Expensesheet.getRow(2).getCell((short)7); ExpenseCell.setCellValue(pb.getPaymentCode()); Expensesheet.addMergedRegion(new Region(3, (short) 1, 3, (short) 3)); ExpenseCell = Expensesheet.getRow(3).getCell((short)1); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(pb.getPayAddress().getDescription()); Expensesheet.addMergedRegion(new Region(3, (short) 6, 3, (short) 9)); ExpenseCell = Expensesheet.getRow(3).getCell((short)6); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(pb.getProject().getVendor().getPartyId()+" : "+pb.getProject().getVendor().getDescription()); if (pb.getProject().getParentProject()!=null){ Expensesheet.addMergedRegion(new Region(4, (short) 2, 4, (short) 7)); ExpenseCell = Expensesheet.getRow(4).getCell((short)2); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(pb.getProject().getParentProject().getProjId()+" : "+pb.getProject().getParentProject().getProjName()); Expensesheet.addMergedRegion(new Region(5, (short) 2, 5, (short) 7)); // 7 ExpenseCell = Expensesheet.getRow(5).getCell((short)2); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(pb.getProject().getParentProject().getCustomer().getPartyId()+" : "+pb.getProject().getParentProject().getCustomer().getDescription()); } HSSFRow ExpenseHRow = null; if (ExpenseList != null && ExpenseList.size() > 0) { HSSFCellStyle Ss1 = Expensesheet.getRow(ListStartRow).getCell((short)0).getCellStyle(); HSSFCellStyle Ss2 = Expensesheet.getRow(ListStartRow).getCell((short)4).getCellStyle(); HSSFCellStyle Ss3 = Expensesheet.getRow(ListStartRow).getCell((short)6).getCellStyle(); HSSFCellStyle Style5 = Expensesheet.getRow(5).getCell((short)9).getCellStyle(); int ExpenseCount = 0; double ExpenseTotal = 0; for (int i0 = 0; i0 < ExpenseList.size(); i0++) { PaymentTransactionDetail btd = (PaymentTransactionDetail)ExpenseList.get(i0); ExpenseHRow = Expensesheet.createRow(ExcelRow2); Expensesheet.addMergedRegion(new Region(ExcelRow2, (short) 0, ExcelRow2, (short) 1)); ExpenseCell = ExpenseHRow.createCell((short)0); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(btd.getDesc1() != null ? btd.getDesc1() : ""); ExpenseCell.setCellStyle(Ss1); ExpenseCell = ExpenseHRow.createCell((short)1); ExpenseCell.setCellStyle(Ss1); Expensesheet.addMergedRegion(new Region(ExcelRow2, (short) 2, ExcelRow2, (short) 3)); ExpenseCell = ExpenseHRow.createCell((short)2); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(btd.getTransactionUser() != null ? btd.getTransactionUser().getName() : ""); ExpenseCell.setCellStyle(Ss1); ExpenseCell = ExpenseHRow.createCell((short)3); ExpenseCell.setCellStyle(Ss1); Expensesheet.addMergedRegion(new Region(ExcelRow2, (short) 4, ExcelRow2, (short) 5)); ExpenseCell = ExpenseHRow.createCell((short)4); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(btd.getTransactionDate() != null ? df.format(btd.getTransactionDate()) : ""); ExpenseCell.setCellStyle(Ss2); ExpenseCell = ExpenseHRow.createCell((short)5); ExpenseCell.setCellStyle(Ss2); ExpenseCell = ExpenseHRow.createCell((short)6); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(btd.getAmount() != null ? numFormater.format(btd.getAmount()) : ""); ExpenseCell.setCellStyle(Ss3); Expensesheet.addMergedRegion(new Region(ExcelRow2, (short) 7, ExcelRow2, (short) 9)); ExpenseCell = ExpenseHRow.createCell((short)7); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(btd.getTransactionDate1() != null ? df.format(btd.getTransactionDate1()) : ""); ExpenseCell.setCellStyle(Ss2); ExpenseCell = ExpenseHRow.createCell((short)8); ExpenseCell.setCellStyle(Ss2); ExpenseCell = ExpenseHRow.createCell((short)9); ExpenseCell.setCellStyle(Ss2); double total3 = btd.getAmount().doubleValue(); ExpenseTotal = total3 + ExpenseTotal; ExpenseCount = i0+1; ExcelRow2++; } ExpenseHRow = Expensesheet.createRow(ListStartRow+ExpenseCount); Expensesheet.addMergedRegion(new Region((ListStartRow+ExpenseCount), (short) 4, (ListStartRow+ExpenseCount), (short) 5)); ExpenseCell = ExpenseHRow.createCell((short)4); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue("Total :"); ExpenseCell.setCellStyle(Ss1); ExpenseCell = ExpenseHRow.createCell((short)5); ExpenseCell.setCellStyle(Ss1); ExpenseCell = ExpenseHRow.createCell((short)6); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(ExpenseTotal); ExpenseCell.setCellStyle(Ss3); // footer ExpenseHRow = Expensesheet.createRow(ListStartRow+ExpenseCount+2); //Expensesheet.addMergedRegion(new Region(ListStartRow+ExpenseCount+2, (short) 0, ListStartRow+ExpenseCount+2, (short) 1)); ExpenseCell = ExpenseHRow.createCell((short)0); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue("Prepared By :"); ExpenseCell.setCellStyle(Style5); Expensesheet.addMergedRegion(new Region(ListStartRow+ExpenseCount+2, (short) 1, ListStartRow+ExpenseCount+2, (short) 2)); ExpenseCell = ExpenseHRow.createCell((short)1); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(pb.getCreateUser().getName()); ExpenseCell.setCellStyle(Style5); ExpenseCell = ExpenseHRow.createCell((short)3); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue("Date :"); ExpenseCell.setCellStyle(Style5); ExpenseCell = ExpenseHRow.createCell((short)4); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue(df.format(new Date())); ExpenseCell.setCellStyle(Style5); ExpenseHRow = Expensesheet.createRow(ListStartRow+ExpenseCount+4); ExpenseCell = ExpenseHRow.createCell((short)0); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue("Approved By :"); ExpenseCell.setCellStyle(Style5); ExpenseCell = ExpenseHRow.createCell((short)3); ExpenseCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 ExpenseCell.setCellValue("Date :"); ExpenseCell.setCellStyle(Style5); } }else{ wb.removeSheetAt(1); } // CAF --------------------------------------------------------------------------- if (CAFAmt!=0){ HSSFSheet CAFsheet = wb.getSheet(FormSheetCAF); HSSFCell CAFCell = null; CAFsheet.addMergedRegion(new Region(2, (short) 1, 2, (short) 5)); CAFCell = CAFsheet.getRow(2).getCell((short)1); CAFCell.setCellValue(pb.getProject().getProjId() + " : " +pb.getProject().getProjName()); CAFsheet.addMergedRegion(new Region(2, (short) 7, 2, (short) 9)); CAFCell = CAFsheet.getRow(2).getCell((short)7); CAFCell.setCellValue(pb.getPaymentCode()); CAFsheet.addMergedRegion(new Region(3, (short) 1, 3, (short) 3)); CAFCell = CAFsheet.getRow(3).getCell((short)1); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 CAFCell.setCellValue(pb.getPayAddress().getDescription()); CAFsheet.addMergedRegion(new Region(3, (short) 6, 3, (short) 9)); CAFCell = CAFsheet.getRow(3).getCell((short)6); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 CAFCell.setCellValue(pb.getProject().getVendor().getPartyId()+" : "+pb.getProject().getVendor().getDescription()); if (pb.getProject().getParentProject()!=null){ CAFsheet.addMergedRegion(new Region(4, (short) 2, 4, (short) 7)); CAFCell = CAFsheet.getRow(4).getCell((short)2); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 CAFCell.setCellValue(pb.getProject().getParentProject().getProjId()+" : "+pb.getProject().getParentProject().getProjName()); CAFsheet.addMergedRegion(new Region(5, (short) 2, 5, (short) 7)); // 7 CAFCell = CAFsheet.getRow(5).getCell((short)2); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 CAFCell.setCellValue(pb.getProject().getParentProject().getCustomer().getPartyId()+" : "+pb.getProject().getParentProject().getCustomer().getDescription()); } HSSFRow CAFHRow = null; if (CAFList != null && CAFList.size() > 0) { HSSFCellStyle Style1 = CAFsheet.getRow(ListStartRow).getCell((short)0).getCellStyle(); HSSFCellStyle Style2 = CAFsheet.getRow(ListStartRow).getCell((short)6).getCellStyle(); HSSFCellStyle Style3 = CAFsheet.getRow(ListStartRow).getCell((short)7).getCellStyle(); HSSFCellStyle Style4 = CAFsheet.getRow(ListStartRow).getCell((short)8).getCellStyle(); HSSFCellStyle Style5 = CAFsheet.getRow(5).getCell((short)9).getCellStyle(); int CAFCount = 0; double CAFTotal = 0; double dayTotal = 0; for (int i0 = 0; i0 < CAFList.size(); i0++) { PaymentTransactionDetail btd = (PaymentTransactionDetail)CAFList.get(i0); CAFHRow = CAFsheet.createRow(ExcelRow); CAFsheet.addMergedRegion(new Region(ExcelRow, (short) 0, ExcelRow, (short) 2)); CAFCell = CAFHRow.createCell((short)0); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(btd.getTransactionUser() != null ? btd.getTransactionUser().getName() : ""); CAFCell.setCellStyle(Style1); CAFCell = CAFHRow.createCell((short)1); CAFCell.setCellStyle(Style1); CAFCell = CAFHRow.createCell((short)2); CAFCell.setCellStyle(Style1); /* CAFsheet.addMergedRegion(new Region(ExcelRow, (short) 2, ExcelRow, (short) 3)); CAFCell = CAFHRow.createCell((short)2); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(btd.getDesc1() != null ? btd.getDesc1() : ""); CAFCell.setCellStyle(Style1); CAFCell = CAFHRow.createCell((short)3); CAFCell.setCellStyle(Style1); */ CAFsheet.addMergedRegion(new Region(ExcelRow, (short) 3, ExcelRow, (short) 5)); CAFCell = CAFHRow.createCell((short)3); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(btd.getDesc2() != null ? btd.getDesc2() : ""); CAFCell.setCellStyle(Style1); CAFCell = CAFHRow.createCell((short)4); CAFCell.setCellStyle(Style1); CAFCell = CAFHRow.createCell((short)5); CAFCell.setCellStyle(Style1); CAFCell = CAFHRow.createCell((short)6); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(btd.getTransactionDate() != null ? df.format(btd.getTransactionDate()) : ""); CAFCell.setCellStyle(Style2); double totalDay =btd.getTransactionNum1().doubleValue(); dayTotal = totalDay + dayTotal; CAFCell = CAFHRow.createCell((short)7); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(btd.getTransactionNum1() != null ? numFormater.format(btd.getTransactionNum1()) : ""); CAFCell.setCellStyle(Style3); CAFCell = CAFHRow.createCell((short)8); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(btd.getTransactionNum2() != null ? numFormater.format(btd.getTransactionNum2()) : ""); CAFCell.setCellStyle(Style4); CAFCell = CAFHRow.createCell((short)9); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(btd.getAmount() != null ? numFormater.format(btd.getAmount()) : ""); CAFCell.setCellStyle(Style4); double total1 = btd.getAmount().doubleValue(); CAFTotal = total1 + CAFTotal; CAFCount = i0+1; ExcelRow++; } CAFHRow = CAFsheet.createRow(ListStartRow+CAFCount); CAFCell = CAFHRow.createCell((short)6); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue("Total :"); CAFCell.setCellStyle(Style1); CAFCell = CAFHRow.createCell((short)7); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(dayTotal/8 + " days"); CAFCell.setCellStyle(Style4); CAFCell = CAFHRow.createCell((short)8); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellStyle(Style4); CAFCell = CAFHRow.createCell((short)9); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(CAFTotal); CAFCell.setCellStyle(Style4); // footer CAFHRow = CAFsheet.createRow(ListStartRow+CAFCount+2); // CAFsheet.addMergedRegion(new Region(ListStartRow+CAFCount+2, (short) 0, ListStartRow+CAFCount+2, (short) 1)); CAFCell = CAFHRow.createCell((short)0); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue("Prepared By :"); CAFCell.setCellStyle(Style5); CAFsheet.addMergedRegion(new Region(ListStartRow+CAFCount+2, (short) 1, ListStartRow+CAFCount+2, (short) 2)); CAFCell = CAFHRow.createCell((short)1); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(pb.getCreateUser().getName()); CAFCell.setCellStyle(Style5); CAFCell = CAFHRow.createCell((short)3); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue("Date :"); CAFCell.setCellStyle(Style5); CAFCell = CAFHRow.createCell((short)4); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue(df.format(new Date())); CAFCell.setCellStyle(Style5); CAFHRow = CAFsheet.createRow(ListStartRow+CAFCount+4); CAFCell = CAFHRow.createCell((short)0); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue("Approved By :"); CAFCell.setCellStyle(Style5); CAFCell = CAFHRow.createCell((short)3); CAFCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 CAFCell.setCellValue("Date :"); CAFCell.setCellStyle(Style5); } }else{ wb.removeSheetAt(0); } } //写入Excel工作表 wb.write(response.getOutputStream()); //关闭Excel工作薄对象 response.getOutputStream().close(); response.flushBuffer(); } catch (Exception e) { e.printStackTrace(); } return null; } private final static String DownPayExcelTemplate = "DownPaymentPaymentInstructionExcelForm.xls"; private final static String ExcelTemplate="PaymentInstructionExcelForm.xls"; private final static String FormSheetCAF="CAFForm"; //private final static String FormSheetAllowance="AllowanceForm"; private final static String FormSheetExpense="ExpenseForm"; private final static String FormSheetAcceptance="AcceptanceForm"; private final static String FormSheetDownPayment="DownPaymentForm"; private final static String SaveToFileName="Payment Instruction Excel Form.xls"; private final int ListStartRow = 8; }
package car_rent.rent; import javax.persistence.*; import java.time.LocalDateTime; import java.util.Set; @Entity @Table(name = "user") public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String lastName; private LocalDateTime birthday; private LocalDateTime licenseCarDate; @Transient private Boolean isExperienced; private String phoneNumber; @OneToMany (cascade = CascadeType.ALL, mappedBy = "customer") Set<Rent> rentSet; public Customer() { } public Customer(String name, String lastName, LocalDateTime birthday, LocalDateTime licenseCarDate, Boolean isExperienced, String phoneNumber) { this.name = name; this.lastName = lastName; this.birthday = birthday; this.licenseCarDate = licenseCarDate; this.isExperienced = isExperienced; this.phoneNumber = phoneNumber; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public LocalDateTime getBirthday() { return birthday; } public void setBirthday(LocalDateTime birthday) { this.birthday = birthday; } public LocalDateTime getLicenseCarDate() { return licenseCarDate; } public void setLicenseCarDate(LocalDateTime licenseCarDate) { this.licenseCarDate = licenseCarDate; } public Boolean getExperienced() { return isExperienced; } public void setExperienced(Boolean experienced) { isExperienced = experienced; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Set<Rent> getRentSet() { return rentSet; } public void setRentSet(Set<Rent> rentSet) { this.rentSet = rentSet; } }
package uk.co.mtford.jalp.abduction.rules; import org.junit.After; import org.junit.Before; import org.junit.Test; import uk.co.mtford.jalp.JALP; import uk.co.mtford.jalp.abduction.logic.instance.DenialInstance; import uk.co.mtford.jalp.abduction.logic.instance.IInferableInstance; import uk.co.mtford.jalp.abduction.logic.instance.PredicateInstance; import uk.co.mtford.jalp.abduction.logic.instance.term.CharConstantInstance; import uk.co.mtford.jalp.abduction.logic.instance.term.VariableInstance; import uk.co.mtford.jalp.abduction.tools.UniqueIdGenerator; import java.io.IOException; import java.util.LinkedList; /** * Created with IntelliJ IDEA. * User: mtford * Date: 07/06/2012 * Time: 17:20 * To change this template use File | Settings | File Templates. */ public class A2Test { public A2Test() { } @Before public void noSetup() { } @After public void noTearDown() { } /* Goal = {ic(X) :- ab(X,Y,Z), p(X)} Delta = {ab(a,b,c), ab(d,e,f), ba(g,h,i)} */ @Test public void test1() { UniqueIdGenerator.reset(); VariableInstance X = new VariableInstance("X"); VariableInstance Y = new VariableInstance("Y"); VariableInstance Z = new VariableInstance("Z"); VariableInstance N = new VariableInstance("N"); CharConstantInstance a = new CharConstantInstance("a"); CharConstantInstance b = new CharConstantInstance("b"); CharConstantInstance c = new CharConstantInstance("c"); CharConstantInstance d = new CharConstantInstance("d"); CharConstantInstance e = new CharConstantInstance("e"); CharConstantInstance f = new CharConstantInstance("f"); CharConstantInstance g = new CharConstantInstance("g"); CharConstantInstance h = new CharConstantInstance("h"); CharConstantInstance i = new CharConstantInstance("i"); PredicateInstance p1 = new PredicateInstance("p",X); PredicateInstance ab1 = new PredicateInstance("ab",X,Y,Z); PredicateInstance ab2 = new PredicateInstance("ab",a,b,c); PredicateInstance ab3 = new PredicateInstance("ab",d,e,f); PredicateInstance ba = new PredicateInstance("ba",g,h,i); DenialInstance denial = new DenialInstance(); denial.getUniversalVariables().add(X); denial.getBody().add(ab1); denial.getBody().add(p1); A2RuleNode A2Node = new A2RuleNode(); A2Node.getStore().abducibles.add(ab2); A2Node.getStore().abducibles.add(ab3); A2Node.getStore().abducibles.add(ba); A2Node.getGoals().add(denial); A2Node.setQuery(new LinkedList<IInferableInstance>(A2Node.getGoals())); try { JALP.applyRule(A2Node); } catch (Exception e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } try { JALP.getVisualizer("debug/rules/A2/Test1",A2Node); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }
/* * HDF5ByteGenotype */ package net.maizegenetics.dna.snp.genotypecall; import ch.systemsx.cisd.hdf5.IHDF5Reader; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import net.maizegenetics.dna.snp.GenotypeTable; import net.maizegenetics.dna.snp.NucleotideAlignmentConstants; import net.maizegenetics.taxa.TaxaList; import net.maizegenetics.taxa.TaxaListBuilder; import net.maizegenetics.util.Tassel5HDF5Constants; import java.util.concurrent.ExecutionException; /** * HDF5 implementation of GenotypeTable. Uses caching of GenotypeTable, alleleCounts, MAF, * and siteCoverage * * @author Ed Buckler * @author Terry Casstevens */ class HDF5ByteGenotypeCallTable extends AbstractGenotypeCallTable { private static final int SHIFT_AMOUNT = 16; private final String[] genotypePaths; /** * Byte representations of DNA sequences are stored in blocks of 65536 sites */ private static final int HDF5_GENOTYPE_BLOCK_SIZE = 1 << SHIFT_AMOUNT; public static final int SITE_BLOCK_MASK = ~(HDF5_GENOTYPE_BLOCK_SIZE - 1); private final IHDF5Reader myHDF5Reader; private final LoadingCache<Long, byte[]> myGenoCache; private final CacheLoader<Long, byte[]> myGenoLoader = new CacheLoader<Long, byte[]>() { public byte[] load(Long key) { long offset = getSiteStartFromKey(key) << SHIFT_AMOUNT; byte[] data; synchronized (myHDF5Reader) { data = myHDF5Reader.readAsByteArrayBlockWithOffset(getTaxaGenoPath(getTaxonFromKey(key)), HDF5_GENOTYPE_BLOCK_SIZE, offset); } return data; } }; private LoadingCache<Integer, SiteBlockAttr> mySiteAnnoCache; //key = site private CacheLoader<Integer, SiteBlockAttr> siteAnnotLoader = new CacheLoader<Integer, SiteBlockAttr>() { int lastCachedStartSite = Integer.MIN_VALUE; int[][] af; byte[][] afOrder; float[] maf; float[] paf; public SiteBlockAttr load(Integer key) { int startSite = getStartSite(key); int length = Math.min(HDF5_GENOTYPE_BLOCK_SIZE, numberOfSites() - startSite); System.out.println("Reading from HDF5 site anno:" + startSite); System.out.println(""); synchronized (myHDF5Reader) { af = myHDF5Reader.readIntMatrixBlockWithOffset(Tassel5HDF5Constants.ALLELE_CNT, 6, length, 0l, startSite); afOrder = myHDF5Reader.readByteMatrixBlockWithOffset(Tassel5HDF5Constants.ALLELE_FREQ_ORD, 6, length, 0l, startSite); maf = myHDF5Reader.readFloatArrayBlockWithOffset(Tassel5HDF5Constants.MAF, length, startSite); paf = myHDF5Reader.readFloatArrayBlockWithOffset(Tassel5HDF5Constants.SITECOV, length, startSite); lastCachedStartSite = startSite; } //perhaps kickoff a process to load the rest SiteBlockAttr sa = new SiteBlockAttr(startSite, afOrder, af, maf, paf); return sa; } }; private class SiteBlockAttr { private final int startSite; //4 private final byte[][] myAlleleFreqOrder; //[ private final int[][] myAlleleCnt; //2-6*4=24, sorted by allele frequency of myAlleleFreqOrder private final float[] maf; //4 private final float[] siteCov; //4 public SiteBlockAttr(int startSite, byte[][] myAlleleFreqOrder, int[][] myAlleleCnt, float[] maf, float[] siteCov) { this.startSite = startSite; this.myAlleleFreqOrder = myAlleleFreqOrder; this.myAlleleCnt = myAlleleCnt; this.maf = maf; this.siteCov = siteCov; } public int[][] getAllelesSortedByFrequency(int site) { int offset = site - startSite; int alleleCnt = 0; while (myAlleleFreqOrder[alleleCnt][offset] != GenotypeTable.UNKNOWN_ALLELE) { alleleCnt++; } int result[][] = new int[2][alleleCnt]; for (int i = 0; i < alleleCnt; i++) { result[0][i] = myAlleleFreqOrder[i][offset]; result[1][i] = myAlleleCnt[result[0][i]][offset]; } return result; } public float getMAF(int site) { return maf[site - startSite]; } public float getSiteCoverage(int site) { return siteCov[site - startSite]; } // public int getAlleleTotal(int site) { // int offset=site-startSite; // int total=0; // for (int b : myAlleleCnt) {total+=b;} // return total; // } } private static long getCacheKey(int taxon, int site) { return ((long) taxon << 33) + (site / HDF5_GENOTYPE_BLOCK_SIZE); } private static int getTaxonFromKey(long key) { return (int) (key >>> 33); } private static int getSiteStartFromKey(long key) { return (int) ((key << 33) >>> 33); } private static int getStartSite(int site) { return site & SITE_BLOCK_MASK; } private String getTaxaGenoPath(int taxon) { return genotypePaths[taxon]; } private HDF5ByteGenotypeCallTable(IHDF5Reader reader, int numTaxa, int numSites, boolean phased, String[][] alleleEncodings) { super(numTaxa, numSites, phased, alleleEncodings); genotypePaths = new String[numTaxa]; TaxaList tL = new TaxaListBuilder().buildFromHDF5Genotypes(reader); //not the most efficient thing to do, but ensures sort is the same. for (int i = 0; i < numTaxa; i++) { //genotypePaths[i] = Tassel5HDF5Constants.GENOTYPES + "/" + tL.taxaName(i); genotypePaths[i] = Tassel5HDF5Constants.getGenotypesCallsPath(tL.taxaName(i)); } myHDF5Reader = reader; myGenoCache = CacheBuilder.newBuilder() .maximumSize((3 * numberOfTaxa()) / 2) .build(myGenoLoader); mySiteAnnoCache = CacheBuilder.newBuilder() .maximumSize(150) .build(siteAnnotLoader); } static HDF5ByteGenotypeCallTable getInstance(IHDF5Reader reader) { int numTaxa = reader.getIntAttribute(Tassel5HDF5Constants.GENOTYPES_ATTRIBUTES_PATH, Tassel5HDF5Constants.GENOTYPES_NUM_TAXA); int numSites = reader.getIntAttribute(Tassel5HDF5Constants.POSITION_ATTRIBUTES_PATH, Tassel5HDF5Constants.POSITION_NUM_SITES); String[][] alleleEncodings = NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES; return new HDF5ByteGenotypeCallTable(reader, numTaxa, numSites, false, alleleEncodings); } @Override public byte genotype(int taxon, int site) { long key = getCacheKey(taxon, site); try { byte[] data = myGenoCache.get(key); return data[site % HDF5_GENOTYPE_BLOCK_SIZE]; } catch (ExecutionException e) { e.printStackTrace(); throw new IllegalStateException("HDF5ByteGenotype: getBase: Error getting base from cache."); } } @Override public String genotypeAsString(int taxon, int site) { return NucleotideAlignmentConstants.getNucleotideIUPAC(genotype(taxon, site)); } @Override public String diploidAsString(int site, byte value) { return NucleotideAlignmentConstants.getNucleotideIUPAC(value); } @Override public int[][] allelesSortedByFrequency(int site) { try { SiteBlockAttr sa = mySiteAnnoCache.get(getStartSite(site)); return sa.getAllelesSortedByFrequency(site); } catch (ExecutionException e) { e.printStackTrace(); throw new UnsupportedOperationException("Error in getMinorAlleleFrequency from cache"); } } @Override public double minorAlleleFrequency(int site) { try { SiteBlockAttr sa = mySiteAnnoCache.get(getStartSite(site)); return sa.getMAF(site); } catch (ExecutionException e) { e.printStackTrace(); throw new UnsupportedOperationException("Error in getMinorAlleleFrequency from cache"); } } @Override public void transposeData(boolean siteInnerLoop) { throw new UnsupportedOperationException("Not supported yet."); } }
/* WaitLock.java Purpose: Description: History: Wed Mar 2 10:55:54 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.util; import org.zkoss.lang.SystemException; import org.zkoss.lang.PotentialDeadLockException; /** * A simple lock used to implement load-on-deman mechanism. * Typical use: a thread, say A, checks whether a resource is loaded, and * put a WaitLock instance if not loaded yet. Then, another thread, say B, * if find WaitLock, it simply calls {@link #waitUntilUnlock} to wait. * Meanwhile, once A completes the loading, it put back the resouce * and calls {@link #unlock}. * * <pre><code>WaitLock lock = null; for (;;) { synchronized (map) { Object o = map.get(key); if (o == null) { map.put(key, lock = new WaitLock()); break; //go to load resource } } if (o instanceof MyResource) return (MyResource)o; if (!((Lock)o).waitUntilUnlock(60000)) log.waring("Takes too long"); } //load resource try { .... synchronized (map) { map.put(key, resource); } return resource; } catch (Throwable ex) { synchronized (map) { map.remove(key); } throw SystemException.Aide.wrap(ex); } finally { lock.unlock(); } </code></pre> * * Refer to i3sys's SketchPostImpl, zweb's JspLoaderServlet for examples. * * @author tomyeh */ public class WaitLock { private final Thread _locker = Thread.currentThread(); private boolean _unlocked; /** Once created, it is default to be locked. * In other words, other thread's invocation of {@link #waitUntilUnlock} * won't return until {@link #unlock} is called. */ public WaitLock() { } /** Waits this lock to unlock. * * @return whether it is unlocked successfully * @exception SystemException if this thread is interrupted * @exception PotentialDeadLockException if the thread itself creates * this lock. In other words, it tried to wait for itself to complete. */ synchronized public boolean waitUntilUnlock(int timeout) { if (!_unlocked) { if (Thread.currentThread().equals(_locker)) throw new PotentialDeadLockException("Wait for itself?"); try { this.wait(timeout); } catch (InterruptedException ex) { throw SystemException.Aide.wrap(ex); } } return _unlocked; } /** Unlocks any other threads blocked by {@link #waitUntilUnlock}. */ synchronized public void unlock() { _unlocked = true; this.notifyAll(); //wake up all pending } }
package com.recursively.engine.renderer.graphics2D; import org.lwjgl.opengl.GL12; import org.newdawn.slick.opengl.Texture; import static org.lwjgl.opengl.GL11.*; public class PrismaticEngine2D { private PrismaticEngine2D() { } public static void setClearColour(float r, float g, float b, float alpha) { glClearColor(r, g, b, alpha); } public static void enable2DTextures() { glEnable(GL_TEXTURE_2D); //TODO this isnt working correctly glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } public static void renderTexture(Texture texture, int x, int y, int width, int height, int offsetX, int offsetY, int spriteWidth, int spriteHeight) { // Binds the texture to the opengl context glBindTexture(GL_TEXTURE_2D, texture.getTextureID()); glBegin(GL_QUADS); float textureWidth = texture.getImageWidth(); float textureHeight = texture.getTextureHeight(); //TODO its to do with the opengl -1 -> 1 range and that i am running 16/9 resolution not a square one.. float leftX = ((offsetX * spriteWidth) + 7) / textureWidth; float rightX = (offsetX * spriteWidth + spriteWidth) / textureWidth; float topY = ((offsetY * spriteHeight) + 3) / textureHeight; // TODO why does this need an offset?!?!? float bottomY = (offsetY * spriteHeight + spriteHeight) / textureHeight; // Top left corner quad glTexCoord2f(leftX, topY); glVertex2i(x, y); // Top right corner of quad glTexCoord2f(rightX, topY); glVertex2i(x + width, y); // bottom right corner of quad glTexCoord2f(rightX, bottomY); glVertex2i(x + width, y + height); // bottom left corner of quad glTexCoord2f(leftX, bottomY); glVertex2i(x, y + height); glEnd(); // unbinds the texture from the context glBindTexture(GL_TEXTURE_2D, 0); } public static void drawTexture(Texture texture, int x, int y, int r) { int width = texture.getTextureWidth(); int height = texture.getTextureHeight(); glTranslatef(x + width / 2, y + height / 2, 0); glRotatef(r, 0, 0, 1); glBindTexture(GL_TEXTURE_2D, texture.getTextureID()); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(-width / 2, height / 2, 0); glTexCoord2f(1, 0); glVertex3f(width / 2, height / 2, 0); glTexCoord2f(1, 1); glVertex3f(width / 2, -height / 2, 0); glTexCoord2f(0, 1); glVertex3f(-width / 2, -height / 2, 0); glEnd(); glLoadIdentity(); } }