text
stringlengths
10
2.72M
package dnd; public interface Observer<T> { void onUpdate(T newState); }
package boj; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class BOJ_9663_N_Queen { private static int N; private static int count; private static int[][] map; private static int[] map2; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); map = new int[N][N]; map2 = new int[N]; //Arrays.fill(map2, -1); //dfs(0); dfs2(0); System.out.println(count); } /* public static void dfs(int r) { if(r == N) { for (int i = 0; i < N; i++) { System.out.println(Arrays.toString(map[i])); } System.out.println(); return; }else { for (int c = 0; c < N; c++) { if(isPromising(r,c)) { // 가능하다면! map[r][c] = 1; dfs(r+1); // 다음줄로 넘어간다. map[r][c] = 0; } } } } public static boolean isPromising(int r, int c) { for (int i = r-1, j=1; i >= 0; i--,j++) { if(c-j >=0 && map[i][c-j]==1) { return false; } if(c+j <N && map[i][c+j]==1) { return false; } if(map[i][c]==1) { return false; } } return true; }*/ public static void dfs2(int r) { /// r 은 놓을 퀸 row은 index와 비슷, if(r == N) { //System.out.println(Arrays.toString(map2)); count++; //System.out.println(); return; }else{ for (int c = 0; c < N; c++) { if(isPromising(r, c)) { // 가능하다면! map2[r] = c; dfs2(r+1); // 다음줄로 넘어간다. } } } } public static boolean isPromising(int row, int c) { for (int i = row-1; i >= 0; i--) { if(map2[i] == c) { return false; } if((row -i) == Math.abs(c- map2[i])) { return false; } } return true; } }
package com.carmona.springboot.springbootapi.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.carmona.springboot.springbootapi.entity.Employee; @Repository public interface EmployeeRepository extends JpaRepository<Employee, Integer> { }
package ga.islandcrawl.map; import java.util.ArrayList; import ga.islandcrawl.MainView; import ga.islandcrawl.controller.Commands; import ga.islandcrawl.controller.MouseInterface; import ga.islandcrawl.draw.Renderer; import ga.islandcrawl.draw.Shape; import ga.islandcrawl.object.AdvObject; import ga.islandcrawl.object.Cluster; import ga.islandcrawl.object.Object; import ga.islandcrawl.object.TimeListener; import ga.islandcrawl.object.unit.Unit; /** * Created by Ga on 7/10/2015. */ public class Observer { private static ArrayList<AdvObject> updatees; private static ArrayList<Object> drawees; private static ArrayList<Cluster> clustees; public static ArrayList<TimeListener> timees = new ArrayList<>(); private static ArrayList<O> light; private static ArrayList<Float> lightRange; public static O camera; public static Overlay overlay = new Overlay(); private static int time = 0; private static float[] matrix; public static void setCamera(O p){ camera = p; } public static boolean inScreen(float x, float y, float r){ return r >= 0 && (Math.abs(x-camera.x) < MainView.finalSizeX+r && Math.abs(y-camera.y)< MainView.finalSizeY+r); } public static boolean inZoomScreen(float x, float y, float r){ return r >= 0 && (Math.abs(x-camera.x) < ga.islandcrawl.draw.Renderer.ratio+.5f+r && Math.abs(y-camera.y)< 1.5f+r); } public static ArrayList wipe(){ ArrayList t; if (drawees != null) t = drawees; else t = new ArrayList(); updatees = new ArrayList<>(); drawees = new ArrayList<>(); clustees = new ArrayList<>(); light = new ArrayList<>(); lightRange = new ArrayList<>(); camera = new O(0,0); return t; } public static void remove(Object p){ updatees.remove(p); drawees.remove(p); clustees.remove(p); timees.remove(p); } public static void adjustDepth(Object p){ remove(p); add(p); } public static void add(Object p) { if (p instanceof AdvObject){ AdvObject t = (AdvObject) p; if (!addUpdatee(t)) updatees.add(t); } if (!addDrawee(p)) drawees.add(p); if (p instanceof Cluster) clustees.add((Cluster) p); } private static boolean addUpdatee(AdvObject p){ for (int i=0;i<updatees.size();i++){ if (p.getDepthReg() < updatees.get(i).getDepthReg()){ updatees.add(i, p); return true; } } return false; } private static boolean addDrawee(Object p){ for (int i=0;i<drawees.size();i++){ if (p.getDepthDraw() < drawees.get(i).getDepthDraw()){ drawees.add(i, p); return true; } } return false; } public static void addLight(O pos, float range){ light.add(pos); lightRange.add(range); } public static void removeLight(O p){ int index = light.indexOf(p); light.remove(index); lightRange.remove(index); } public static void setDraw(float[] p){ matrix = p; } public static void draw() { Object t; for (int i = 0; i < drawees.size(); i++) { t = drawees.get(i); if (inScreen(t.pos.x, t.pos.y, t.pos.r)) { t.draw(matrix); } } TileMarker.draw(matrix); TileMarker.wipe(); drawLight(matrix); } private static void drawLight(float[] matrix){ float[][] result = new float[8][]; for (int i=0;i<8;i++) result[i] = new float[]{0,0,-1}; O pos; float range; int li = 0; for (int i=0;i<light.size();i++) { pos = light.get(i); range = lightRange.get(i); if (inScreen(pos.x, pos.y, range)) { result[li] = new float[]{pos.x - camera.x, pos.y - camera.y, range}; li++; if (li == 8) break; } } overlay.draw(matrix, result); } public static void update(){ AdvObject t; Map.land.update(); Commands.update(); MouseInterface.update(); for (int i=0;i<updatees.size();i++){ t = updatees.get(i); if (t instanceof Unit || inScreen(t.pos.x, t.pos.y, t.pos.r)) { t.update(); } } Dimension.wipe(); time++; if (time > 15){ time = 0; overlay.nextMinute(); } } public static void disableShader(){ for (int i=0;i<drawees.size();i++){ Object t = drawees.get(i); t.getForm().setShader(0,""); } } public static void timeEvent(Time p){ if (p == Time.Midnight){ int clusteeSize = clustees.size(); for (int i = 0; i < clusteeSize; i++) clustees.get(i).duplicate(); //No concurrent add duplication } for (int i = 0; i < timees.size(); i++) timees.get(i).timeEvent(p); } }
package com.jobs.workbook.repositories; import com.jobs.workbook.entites.job.Job; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface JobRepository extends JpaRepository<Job, Integer> { @EntityGraph(attributePaths = {"location", "customer", "images"}) List<Job> findAllByUserId(long id); @EntityGraph(attributePaths = {"location", "customer", "images"}) List<Job> findAllByUserEmail(String email); @EntityGraph(attributePaths = {"location", "customer", "images"}) List<Job> findAllByUserEmailAndCustomerId(String email, long customerId); @EntityGraph(attributePaths = {"location", "customer", "images"}) List<Job> findAllByUserIdAndCustomerId(long userId, long customerId); @EntityGraph(attributePaths = {"location", "customer", "images"}) Optional<Job> findById(long id); }
/**Classe para armazenar os dados de cada elemento da tabela periodica. * */ package model; /**Periodic Table * * @author Marcos Nascimento * @version 1 * */ public class PeriodicTable { public static ChemicalElement[] tabela = new ChemicalElement[118]; static { try { tabela[0] = new ChemicalElement("Hidrogênio", "H", 1, 1, 1, Classification.NAO_METAIS); tabela[1] = new ChemicalElement("Lítio", "Li", 2, 1, 3, Classification.METAIS_ALCALINOS); tabela[2] = new ChemicalElement("Sódio", "Na", 3, 1, 11, Classification.METAIS_ALCALINOS); tabela[3] = new ChemicalElement("Potássio", "K", 4, 1, 19, Classification.METAIS_ALCALINOS); tabela[4] = new ChemicalElement("Rubídio", "Rb", 5, 1, 37, Classification.METAIS_ALCALINOS); tabela[5] = new ChemicalElement("Césio", "Cs", 6, 1, 55, Classification.METAIS_ALCALINOS); tabela[6] = new ChemicalElement("Frâncio", "Fr", 7, 1, 87, Classification.METAIS_ALCALINOS); tabela[7] = new ChemicalElement("Berílio", "Be", 2, 2, 4, Classification.METAIS_ALCALINOS_TERROSOS); tabela[8] = new ChemicalElement("Magnésio", "Mg", 3, 2, 12, Classification.METAIS_ALCALINOS_TERROSOS); tabela[9] = new ChemicalElement("Cálcio", "Ca", 4, 2, 20, Classification.METAIS_ALCALINOS_TERROSOS); tabela[10] = new ChemicalElement("Estrôncio", "Sr", 5, 2, 38, Classification.METAIS_ALCALINOS_TERROSOS); tabela[11] = new ChemicalElement("Bário", "Ba", 6,2, 56, Classification.METAIS_ALCALINOS_TERROSOS); tabela[12] = new ChemicalElement("Rádio", "Ra", 7, 2, 88, Classification.METAIS_ALCALINOS_TERROSOS); tabela[13] = new ChemicalElement("Escândio", "Sc", 4, 3, 21, Classification.METAIS_DE_TRANSICAO); tabela[14] = new ChemicalElement("Ítrio", "Y", 5, 3, 39, Classification.METAIS_DE_TRANSICAO); tabela[15] = new ChemicalElement("TitÂnio", "Ti", 4, 4, 22, Classification.METAIS_DE_TRANSICAO); tabela[16] = new ChemicalElement("Zircônio", "Zr", 5, 4, 40, Classification.METAIS_DE_TRANSICAO); tabela[17] = new ChemicalElement("Háfnio", "Hf", 6, 4, 72, Classification.METAIS_DE_TRANSICAO); tabela[18] = new ChemicalElement("Rutherfórdio", "Rf", 7, 4, 104, Classification.METAIS_DE_TRANSICAO); tabela[19] = new ChemicalElement("Vanádio", "V", 4, 5, 23, Classification.METAIS_DE_TRANSICAO); tabela[20] = new ChemicalElement("Nióbio", "Nb", 5, 5, 41, Classification.METAIS_DE_TRANSICAO); tabela[21] = new ChemicalElement("Tântalo", "Ta", 6, 5, 73, Classification.METAIS_DE_TRANSICAO); tabela[22] = new ChemicalElement("Dúbnio", "Db", 7, 5, 105, Classification.METAIS_DE_TRANSICAO); tabela[23] = new ChemicalElement("Cromo", "Cr", 4, 6, 24, Classification.METAIS_DE_TRANSICAO); tabela[24] = new ChemicalElement("Molibdênio", "Mo", 5, 6, 42, Classification.METAIS_DE_TRANSICAO); tabela[25] = new ChemicalElement("Tungstênio", "W", 6, 6, 74, Classification.METAIS_DE_TRANSICAO); tabela[26] = new ChemicalElement("Seabórgio", "Sg", 7, 6, 106, Classification.METAIS_DE_TRANSICAO); tabela[27] = new ChemicalElement("Manganês", "Mn", 4, 7, 25, Classification.METAIS_DE_TRANSICAO); tabela[28] = new ChemicalElement("Tecnécio", "Tc", 5, 7, 43, Classification.METAIS_DE_TRANSICAO); tabela[29] = new ChemicalElement("Rênio", "Re", 6, 7, 75, Classification.METAIS_DE_TRANSICAO); tabela[30] = new ChemicalElement("Bóhrio", "Bh", 7, 7, 107, Classification.METAIS_DE_TRANSICAO); tabela[31] = new ChemicalElement("Ferro", "Fe", 4, 8, 26, Classification.METAIS_DE_TRANSICAO); tabela[32] = new ChemicalElement("Rutênio", "Ru", 5, 8, 44, Classification.METAIS_DE_TRANSICAO); tabela[33] = new ChemicalElement("Ósmio", "Os", 6, 8, 76, Classification.METAIS_DE_TRANSICAO); tabela[34] = new ChemicalElement("Hássio", "Hs", 7, 8, 108, Classification.METAIS_DE_TRANSICAO); tabela[35] = new ChemicalElement("Cobalto", "Co", 4, 9, 27, Classification.METAIS_DE_TRANSICAO); tabela[36] = new ChemicalElement("Ródio", "Rh", 5, 9, 45, Classification.METAIS_DE_TRANSICAO); tabela[37] = new ChemicalElement("Irídio", "Ir", 6, 9, 77, Classification.METAIS_DE_TRANSICAO); tabela[38] = new ChemicalElement("Meitnério", "Mt", 7, 9, 109, Classification.METAIS_DE_TRANSICAO); tabela[39] = new ChemicalElement("Níquel", "Ni", 4, 10, 28, Classification.METAIS_DE_TRANSICAO); tabela[40] = new ChemicalElement("Poládio", "Pd", 5, 10, 46, Classification.METAIS_DE_TRANSICAO); tabela[41] = new ChemicalElement("Platina", "Pt", 6, 10, 78, Classification.METAIS_DE_TRANSICAO); tabela[42] = new ChemicalElement("Darmstádio", "Ds", 7, 10, 110, Classification.METAIS_DE_TRANSICAO); tabela[43] = new ChemicalElement("Cobre", "Cu", 4, 11, 29, Classification.METAIS_DE_TRANSICAO); tabela[44] = new ChemicalElement("Prata", "Ag", 5, 11, 47, Classification.METAIS_DE_TRANSICAO); tabela[45] = new ChemicalElement("Ouro", "Au", 6, 11, 79, Classification.METAIS_DE_TRANSICAO); tabela[46] = new ChemicalElement("Roentgênio", "Rg", 7, 11, 111, Classification.METAIS_DE_TRANSICAO); tabela[47] = new ChemicalElement("Zinco", "Zn", 4, 12, 30, Classification.METAIS_DE_TRANSICAO); tabela[48] = new ChemicalElement("Cadmio", "Cd", 5, 12, 48, Classification.METAIS_DE_TRANSICAO); tabela[49] = new ChemicalElement("Mercúrio", "Hg", 6, 12, 80, Classification.METAIS_DE_TRANSICAO); tabela[50] = new ChemicalElement("Copérnico", "Cn", 7, 12, 112, Classification.METAIS_DE_TRANSICAO); tabela[51] = new ChemicalElement("Boro", "B", 2, 13, 5, Classification.SEMI_METAIS); tabela[52] = new ChemicalElement("Alumínio", "Al", 3, 13, 13, Classification.METAIS_REPRESENTATIVOS); tabela[53] = new ChemicalElement("Gálio", "Ga", 4, 13, 31, Classification.METAIS_REPRESENTATIVOS); tabela[54] = new ChemicalElement("Índio", "In", 5, 13, 49, Classification.METAIS_REPRESENTATIVOS); tabela[55] = new ChemicalElement("Tálio", "Tl", 6, 13, 81, Classification.METAIS_REPRESENTATIVOS); tabela[56] = new ChemicalElement("Ununtrio", "Uut", 7, 13, 113, Classification.METAIS_REPRESENTATIVOS); tabela[57] = new ChemicalElement("Carbono", "C", 2, 14, 6, Classification.NAO_METAIS); tabela[58] = new ChemicalElement("Silício", "Si", 3, 14, 14, Classification.SEMI_METAIS);//OLHAR z DEPOIS tabela[59] = new ChemicalElement("Germânio", "Ge", 4, 14, 32, Classification.SEMI_METAIS); tabela[60] = new ChemicalElement("Estanho", "Sn", 5, 14, 50, Classification.METAIS_REPRESENTATIVOS); tabela[61] = new ChemicalElement("Chumbo", "Pb", 6, 14, 82, Classification.METAIS_REPRESENTATIVOS); tabela[62] = new ChemicalElement("Ununquádio", "Uuq", 7, 14, 114, Classification.METAIS_REPRESENTATIVOS); tabela[63] = new ChemicalElement("Nitrigênio", "N", 2, 15, 7, Classification.NAO_METAIS); tabela[64] = new ChemicalElement("Fosfóro", "P", 3, 15, 15, Classification.NAO_METAIS); tabela[65] = new ChemicalElement("Arsênio", "As", 4, 15, 33, Classification.NAO_METAIS); tabela[66] = new ChemicalElement("Antimônio","Sb", 5, 15, 51, Classification.SEMI_METAIS); tabela[67] = new ChemicalElement("Bismuto", "Bi", 6, 15, 83, Classification.METAIS_REPRESENTATIVOS); tabela[68] = new ChemicalElement("Ununpentio", "Uup", 7, 15, 115, Classification.METAIS_REPRESENTATIVOS); tabela[69] = new ChemicalElement("Oxigênio", "O", 2, 16, 8, Classification.NAO_METAIS); tabela[70] = new ChemicalElement("Enxofre", "S", 3, 16, 16, Classification.NAO_METAIS); tabela[71] = new ChemicalElement("Selênio", "Se", 4, 16, 34, Classification.NAO_METAIS); tabela[72] = new ChemicalElement("Telúrio", "Te", 5, 16, 52, Classification.SEMI_METAIS); tabela[73] = new ChemicalElement("Polônio", "Po", 6, 16, 84, Classification.NAO_METAIS); tabela[74] = new ChemicalElement("Ununhéxio", "Uuh", 7, 16, 116, Classification.METAIS_REPRESENTATIVOS); tabela[75] = new ChemicalElement("Flúor", "F", 2, 17, 9, Classification.HALOGENIOS); tabela[76] = new ChemicalElement("Cloro", "Cl", 3, 17, 17, Classification.HALOGENIOS); tabela[77] = new ChemicalElement("Bromo", "Br", 4, 17, 35, Classification.HALOGENIOS); tabela[78] = new ChemicalElement("Iodo", "I", 5, 17, 53, Classification.HALOGENIOS); tabela[79] = new ChemicalElement("Astato", "At", 6, 17, 85, Classification.HALOGENIOS); tabela[80] = new ChemicalElement("Ununséptio", "Uus", 7, 17, 117, Classification.HALOGENIOS); tabela[81] = new ChemicalElement("Hélio", "He", 1, 18, 2, Classification.GASES_NOBRES); tabela[82] = new ChemicalElement("Neônio", "Ne", 2, 18, 10, Classification.GASES_NOBRES); tabela[83] = new ChemicalElement("Argônio", "Ar", 3, 18, 18, Classification.GASES_NOBRES); tabela[84] = new ChemicalElement("Criptônio", "Kr", 4, 18, 36, Classification.GASES_NOBRES); tabela[85] = new ChemicalElement("Xenônio", "Xe", 5, 18, 54, Classification.GASES_NOBRES); tabela[86] = new ChemicalElement("Radônio", "Rn", 6, 18, 86, Classification.GASES_NOBRES); tabela[87] = new ChemicalElement("Ununóctio", "Uuo", 7, 18, 118, Classification.GASES_NOBRES); tabela[88] = new ChemicalElement("Lantânio", "La", 9, 4, 57, Classification.LANTANIDEOS); tabela[89] = new ChemicalElement("Cério", "Ce", 9, 5, 58, Classification.LANTANIDEOS); tabela[90] = new ChemicalElement("Praseodímio", "Pr", 9, 6, 59, Classification.LANTANIDEOS); tabela[91] = new ChemicalElement("Neodímio", "Nd", 9, 7, 60, Classification.LANTANIDEOS); tabela[92] = new ChemicalElement("Promécio", "Pm", 9, 8, 61, Classification.LANTANIDEOS); tabela[93] = new ChemicalElement("Samário", "Sm", 9, 9, 62, Classification.LANTANIDEOS); tabela[94] = new ChemicalElement("Európio", "Eu", 9, 10, 63, Classification.LANTANIDEOS); tabela[95] = new ChemicalElement("Gadolínio", "Gd", 9, 11, 64, Classification.LANTANIDEOS); tabela[96] = new ChemicalElement("Térbio", "Tb", 9, 12, 65, Classification.LANTANIDEOS); tabela[97] = new ChemicalElement("Disprósio", "Dy", 9, 13, 66, Classification.LANTANIDEOS); tabela[98] = new ChemicalElement("Hólmio", "Ho", 9, 14, 67, Classification.LANTANIDEOS); tabela[99] = new ChemicalElement("Érbio", "Er", 9, 15, 68, Classification.LANTANIDEOS); tabela[100] = new ChemicalElement("Túlio", "Tm", 9, 16, 69, Classification.LANTANIDEOS); tabela[101] = new ChemicalElement("Itérbio", "Yb", 9, 17, 70, Classification.LANTANIDEOS); tabela[102] = new ChemicalElement("Lutécio", "Lu", 9, 18, 71, Classification.LANTANIDEOS); tabela[103] = new ChemicalElement("Actínio", "Ac", 10, 4, 89, Classification.ACTINIDEOS); tabela[104] = new ChemicalElement("Tório", "Th", 10, 5, 90, Classification.ACTINIDEOS); tabela[105] = new ChemicalElement("Protactínio", "Pa", 10, 6, 91, Classification.ACTINIDEOS); tabela[106] = new ChemicalElement("Urânio", "U", 10, 7, 92, Classification.ACTINIDEOS); tabela[107] = new ChemicalElement("Neptúnio", "Np", 10, 8, 93, Classification.ACTINIDEOS); tabela[108] = new ChemicalElement("Plutônio", "Pu", 10, 9, 94, Classification.ACTINIDEOS); tabela[109] = new ChemicalElement("Amerício", "Am", 10, 10, 95, Classification.ACTINIDEOS); tabela[110] = new ChemicalElement("Cúrio", "Cm", 10, 11, 96, Classification.ACTINIDEOS); tabela[111] = new ChemicalElement("Berquélio", "Bk", 10, 12, 97, Classification.ACTINIDEOS); tabela[112] = new ChemicalElement("Califórnio", "Cf", 10, 13, 98, Classification.ACTINIDEOS); tabela[113] = new ChemicalElement("Einstênio", "Es", 10, 14, 99, Classification.ACTINIDEOS); tabela[114] = new ChemicalElement("Férmio", "Fm", 10, 15, 100, Classification.ACTINIDEOS); tabela[115] = new ChemicalElement("Mendelévio", "Md", 10, 16, 101, Classification.ACTINIDEOS); tabela[116] = new ChemicalElement("Nobélio", "No", 10, 17, 102, Classification.ACTINIDEOS); tabela[117] = new ChemicalElement("Laurêncio", "Lr", 10, 18, 103, Classification.ACTINIDEOS); } catch(Exception e) { e.printStackTrace(); } } }
package org.training.issuetracker.dao.hibernate; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Order; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.training.issuetracker.dao.entities.Priority; import org.training.issuetracker.dao.interfaces.PriorityDAO; @Repository("priorityDAO") @Transactional public class HibernatePriorityDAO implements PriorityDAO { private static final Logger logger = Logger.getLogger(HibernatePriorityDAO.class); private static final String TAG = HibernatePriorityDAO.class.getSimpleName(); @Autowired protected SessionFactory sessionFactory; @SuppressWarnings("unchecked") @Override public List<Priority> getPriorities() { List<Priority> priorities = null; final Session session = sessionFactory.getCurrentSession(); try { Criteria criteria = session.createCriteria(Priority.class); criteria.addOrder(Order.asc(Priority.COLUMN_ID)); priorities = (List<Priority>) criteria.list(); } catch (Exception e) { logger.error(TAG + " Getting all priorities failed!", e); throw e; } return priorities; } @Override public Priority getPriorityById(int priorityId) { Priority priority = null; final Session session = sessionFactory.getCurrentSession(); try { priority = (Priority) session.get(Priority.class, priorityId); } catch (Exception e) { logger.error(TAG + " Getting Priority by id failed!", e); throw e; } return priority; } @Override public boolean createPriority(Priority priority) { boolean success = false; Priority newPriority = new Priority(); newPriority.setPriorityId(priority.getPriorityId()); newPriority.setName(priority.getName()); final Session session = sessionFactory.getCurrentSession(); try { session.save(newPriority); success = true; } catch(Exception e) { logger.error(TAG + " Creating Priority-object failed!", e); } return success; } @Override public boolean updatePriority(Priority priority) { boolean success = false; Priority newPriority = new Priority(); newPriority.setPriorityId(priority.getPriorityId()); newPriority.setName(priority.getName()); final Session session = sessionFactory.getCurrentSession(); try { session.update(newPriority); success = true; } catch(Exception e) { logger.error(TAG + " Updating Priority-object with id=" + priority.getPriorityId() + " failed!", e); } return success; } @Override public boolean deletePriority(int priorityId) { boolean success = false; Priority deletingPriority = new Priority(); deletingPriority.setPriorityId(priorityId); final Session session = sessionFactory.getCurrentSession(); try { session.delete(deletingPriority); success = true; } catch(Exception e) { logger.error(TAG + " Deleting Priority-object with id=" + priorityId + " failed!", e); } return success; } }
package com.dns.feedbox.util; import com.dns.feedbox.entity.Description; import com.dns.feedbox.entity.Feed; import com.rometools.rome.feed.synd.SyndEntry; import org.springframework.messaging.Message; import java.util.stream.Collectors; /** * Created by dinusha on 10/12/16. */ public class FeedTransformer { public Feed transformToFeed(Message<SyndEntry> message){ SyndEntry entity = message.getPayload(); System.out.println(entity); Feed feed = new Feed(); feed.setTitle(entity.getTitle()); feed.setUrl(entity.getLink()); feed.setTags(entity.getCategories().stream().map( c-> c.getName()).collect(Collectors.toList())); System.out.println("catogorises :"+entity.getCategories().size()); feed.setPublishDate(entity.getPublishedDate()); Description des = new Description(entity.getDescription().getType(),entity.getDescription().getValue()); feed.setDescription(des); return feed; } public String transform(Message<SyndEntry> message){ SyndEntry entity = message.getPayload(); Feed feed = new Feed(); feed.setTitle(entity.getTitle()); feed.setUrl(entity.getLink()); return feed.getTitle()+" - "+feed.getUrl(); } }
package com.interceptor; import java.util.Enumeration; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class SQLInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("************************* In SQLInterceptor preHandle()**************************"); //RequestDispatcher rd = request.getRequestDispatcher("login"); boolean chk=true; String name=null,value=null; String qry = request.getQueryString(); //System.out.println("URL query string : "+qry); // ATTACK PATTERNS String[] AttackPattern={"1'","1' "," 1'","1' OR","1' OR '1'=1","1'%20","1 '%20","'%20","'%20OR","' OR","'%20OR%20'1","'%20'1","1 '%20OR%20'1'%3d'1","'%20OR%20'1'%3d'1"," '%20", " CREATE"," ALTER"," DROP"," RENAME"," SELECT"," INSERT"," INSERT INTO"," UPDATE1"," DELETE"," DELETE FROM"," REVOKE"," @@VERSION", " EXEC"," UNION"," WAITFOR"," GROUP BY"," ORDER BY"," SHUTDOWN"," RESTART"}; // Delete from the above list "AND", " OR", " GRANT" "'"," '", ";"," CHAR"," INT" int i=0,fnd; for(i=0;i<AttackPattern.length;i++) { if(qry!=null) { fnd=(qry.toLowerCase()).indexOf(AttackPattern [i].toLowerCase()); if (fnd!=-1) { chk=false; //Attack Pattern Present //System.out.println("Attack Pattern Present (SQL Injection @ Qry String): Patter Value="+AttackPattern [i]+"\n Qry String="+qry); //System.out.println("RequestURL : "+req1.getRequestURL()); break; } } } // AttackPattern.length for loop (i for loop) if (chk==true) { // Get the values of all request parameters Enumeration enumm = request.getParameterNames(); for (; enumm.hasMoreElements(); ) { // Get the name of the request parameter name = (String)enumm.nextElement(); // Get the value of the request parameter value = request.getParameter(name); //System.out.println("value="+value); String arr[]=value.split(" "); for(i=0;i<AttackPattern.length;i++) { for(int j=0;j<arr.length;j++) { //if(value!=null) if(arr[j]!=null && !arr[j].equals("") && !arr[j].equals(" ")) { //fnd=(value.toString().toLowerCase().trim()).indexOf(AttackPattern [i].toLowerCase().trim()); //if (fnd!=-1) //System.out.println("Param value="+arr[j]); if(arr[j].equalsIgnoreCase(AttackPattern [i].toLowerCase().trim())) { chk=false; //Attack Pattern Present //System.out.println("Attack Pattern Present (SQL Injection @ request parameter): Param name="+name+", Param value="+arr[j]+", Pattern value="+AttackPattern[i]+", Index="+i); //System.out.println("RequestURL : "+req1.getRequestURL()); break; } } } if (chk==false) { break; } } if (chk==false) { break; } } // for loop enumm } // if chk = true if (chk==true) { //new ModelAndView("logout"); return true; } else { System.out.println("Failed the REquest "); new ModelAndView("logout"); return false; //rd.forward(request, response); //Redirect to session expire page //new ModelAndView("logout"); // System.out.println("FAiled the REquest1 "); } //return false; } }
/** * */ package com.fhzz.psop.util; /** * @author Administrator * */ public class ProcessKey { public static final String VACATION_PROCESS = "vacationProcess"; }
package com.example.ahmed.octopusmart.Utils.transition; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Context; import android.transition.TransitionValues; import android.transition.Visibility; import android.util.AttributeSet; import android.view.View; import android.view.ViewAnimationUtils; import android.view.ViewGroup; /** * Created by sotra on 8/26/2016. */ public class CircularReveal extends Visibility { public CircularReveal() { } public CircularReveal(Context context, AttributeSet attrs) { super(context, attrs); } @Override public Animator onAppear(ViewGroup sceneRoot, final View view, TransitionValues startValues, TransitionValues endValues) { float radius = calculateMaxRadius(view); final float originalAlpha = view.getAlpha(); view.setAlpha(0f); Animator reveal = createAnimator(view, 0, radius); reveal.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { view.setAlpha(originalAlpha); } }); return reveal; } @Override public Animator onDisappear(ViewGroup sceneRoot, View view, TransitionValues startValues, TransitionValues endValues) { float radius = calculateMaxRadius(view); return createAnimator(view, radius, 0); } private Animator createAnimator(View view, float startRadius, float endRadius) { int centerX = view.getWidth() / 2; int centerY = view.getHeight() / 2; Animator reveal = ViewAnimationUtils.createCircularReveal(view, centerX, centerY, startRadius, endRadius); return new AnimUtils.NoPauseAnimator(reveal); } static float calculateMaxRadius(View view) { float widthSquared = view.getWidth() * view.getWidth(); float heightSquared = view.getHeight() * view.getHeight(); float radius = (float )Math.sqrt(widthSquared + heightSquared) / 2; return radius; } }
package options; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( plugin = {"pretty", "html:target/cucumber","com.cucumber.listener.ExtentCucumberFormatter:target/html/ExtentReport.html"}, format = {"json:target/Destination/cucumber.json"}, glue = {"stepdefs"}, features = {"src/test/features"}) public class CucumberTests {}
/** * @Title: ResourceServiceImpl.java * @package com.rofour.baseball.bll.resourcescenter * @Project: axp-bll * @Description: (用一句话描述该文件做什么) * @author WJ * @date 2016年3月28日 下午7:16:17 * @version V1.0 * ────────────────────────────────── * Copyright (c) 2016, 指端科技. */ package com.rofour.baseball.service.resource.impl; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.rofour.baseball.common.AttachConstant; import com.rofour.baseball.common.Constant; import com.rofour.baseball.common.HttpClientUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Base64Utils; import com.aliyun.oss.OSSClient; import com.rofour.baseball.common.ConstantFunction; import com.rofour.baseball.controller.model.ResultInfo; import com.rofour.baseball.controller.model.resource.CredentialInfo; import com.rofour.baseball.controller.model.resource.CredentialURLInfo; import com.rofour.baseball.controller.model.resource.ServerInfo; import com.rofour.baseball.controller.model.resource.SignInfo; import com.rofour.baseball.dao.resource.bean.AttachmentBean; import com.rofour.baseball.dao.resource.bean.ServerBean; import com.rofour.baseball.dao.resource.mapper.ResourceMapper; import com.rofour.baseball.dao.user.mapper.UserMapper; import com.rofour.baseball.exception.BusinessException; import com.rofour.baseball.service.resource.ResourceService; /** * @author WJ * @ClassName: ResourceServiceImpl * @Description: * @date 2016年3月28日 下午7:16:17 */ @Service("resourceService") public class ResourceServiceImpl implements ResourceService { @Autowired private ResourceMapper resourceMapper; @Autowired private UserMapper userMapper; /** * @param attachmentTypeId 附件类型id * @return ServerInfo 服务器信息 * @Description: 获取服务器信息 * @author WJ * @date 2016年3月29日 下午1:02:31 */ @Override public ServerInfo getServerInfo(String attachmentTypeId) { //暂时只有一个服务器,如果以后有多个,需要根据服务器id来查询 ServerBean bean = resourceMapper.getServer(ConstantFunction.getOssServerPic()); ServerInfo info = null; if (bean != null) {//节省下远程调用 String bucketName = resourceMapper.getBucketName(attachmentTypeId); if (!StringUtils.isBlank(bucketName)) { info = new ServerInfo(bean.getServerId(), bean.getEndpoint(), bean.getAccessKeyId(), bean.getAccessKeySecret(), bucketName); } } return info; } /** * @param bean * @Method: saveFileInfo * @Description: 保存附件信息 * @date 2016年3月31日 上午10:41:51 **/ @Override public void saveFileInfo(AttachmentBean bean) { resourceMapper.insertAttachment(bean); } /** * @param bean 附件信息 * @return void 返回类型 * @Method: updateFileInfo * @Description: 更新附件信息表 * @author WJ * @date 2016年3月31日 下午3:04:12 **/ @Override public void updateFileInfo(AttachmentBean bean) { resourceMapper.updateAttachment(bean); } /** * @param fileUrl * @return boolean 返回类型 * @Description: 是否是重复上传的, 重复上传说明记录已经存在 * @author WJ * @date 2016年3月31日 下午3:04:38 **/ @Override public boolean ifExist(String fileUrl, Long userId) { Map<String, String> map = new HashMap<>(); map.put("fileUrl", fileUrl); map.put("userId", userId.toString()); int count = resourceMapper.ifExist(map); return count != 0; } /** * @param sourceId * @param serverId * @param typeId * @param fileKey * @param fileName * @param length * @param userId * @param username * @Description: 插入附件信息表 */ private void insertFileInfo(String sourceId, String serverId, String typeId, String fileKey, String fileName, Long length, Long userId, String username) { String suffix = "";// 默认没有后缀名时 if (fileName.contains(".")) { suffix = fileName.substring(fileName.lastIndexOf(".") + 1); } AttachmentBean bean = new AttachmentBean(sourceId, serverId, typeId, fileKey, fileName, suffix, length, userId, username, new Date()); // 如果重复插入,那么要覆盖之前的 if (ifExist(bean.getFileUrl(), userId)) { updateFileInfo(bean); } else { saveFileInfo(bean); } } /** * @param serverInfo * @param fileKey * @param toUpload * @Description: oss上传 */ private void ossUpload(ServerInfo serverInfo, String fileKey, InputStream toUpload) { OSSClient client = null; try { client = new OSSClient(serverInfo.getEndpoint(), serverInfo.getAccessKeyId(), serverInfo.getAccessKeySecret()); client.putObject(serverInfo.getBucketName(), fileKey, toUpload); } catch (Exception e) { throw e; } finally { if (client != null) { client.shutdown(); } } } @Override public ResultInfo uploadSign(SignInfo signInfo) { if (StringUtils.isBlank(signInfo.getFile()) || !validSignInfo(signInfo)) { throw new BusinessException("111"); } //获取服务器信息 ServerInfo serverInfo = getServerInfo(signInfo.getAttachmentTypeId()); if (serverInfo != null) { //base64解码 ByteArrayInputStream in = getDecodeStream(signInfo.getFile()); //oss上传 ossUpload(serverInfo, signInfo.getFileKey(), in); //插入附件信息 insertFileInfo(signInfo.getSourceId(), serverInfo.getAttachmentServerId(), signInfo.getAttachmentTypeId(), signInfo.getFileKey(), signInfo.getFileName(), (long) in.available(), signInfo.getUserId(), signInfo.getUserName()); } else { throw new BusinessException("07001"); } return new ResultInfo(0, "", "上传成功"); } /** * @param credentialInfo * @return * @throws Exception * @Description: 上传用户证件信息 */ public ResultInfo uploadCredential(CredentialInfo credentialInfo) throws Exception { vlidCredentialInfo(credentialInfo); //检查审核状态 ,0:未上传,1:审核中,2为审核通过,3审核失败 Integer status = userMapper.queryVerifyStatus(credentialInfo.getUserId()); if (status != null && status == 2) { throw new BusinessException("02023"); } String sourceId; if (credentialInfo.getSourceId().equals("1")) { sourceId = ConstantFunction.getSourceAndroid(); // 安卓需要转码(临时) credentialInfo.setFile(java.net.URLDecoder.decode(credentialInfo.getFile(), "utf-8")); } else { sourceId = ConstantFunction.getSourceIos(); } String attachmentTypeId = ConstantFunction.getAtmTypeUserauth(); ServerInfo serverInfo = getServerInfo(attachmentTypeId); if (serverInfo != null) { //base64解码 ByteArrayInputStream in = getDecodeStream(credentialInfo.getFile()); int size = in.available(); //生成文件名 StringBuilder fileName = new StringBuilder().append(ConstantFunction.getExp()).append("/").append(credentialInfo.getUserId()).append("/"); if (credentialInfo.getType().equals("1")) { fileName.append(ConstantFunction.getCredentialTypeIdHold()); } else if (credentialInfo.getType().equals("2")) { fileName.append(ConstantFunction.getCredentialTypeId()); } else { fileName.append(ConstantFunction.getCredentialTypeOther()); } String originName = credentialInfo.getFileName(); if (originName.contains(".") && originName.lastIndexOf(".") != originName.length() - 1) { fileName.append(".").append(originName.substring(originName.lastIndexOf(".") + 1)); } else { throw new BusinessException("07004"); } String fileKey = fileName.toString(); //oss上传 ossUpload(serverInfo, fileKey, in); //插入附件信息 insertFileInfo(sourceId, serverInfo.getAttachmentServerId(), attachmentTypeId, fileKey, credentialInfo.getFileName(), (long) size, credentialInfo.getUserId(), credentialInfo.getUserName()); } else { throw new BusinessException("07001"); } return new ResultInfo(0, "", "上传成功"); } /** * @param userId * @return 操作结果 * @Description: 获取已上传的用户证件的url */ public ResultInfo getCredentialUrls(Long userId) { try { Map<String, Object> map = new HashMap<String, Object>(); map.put("bizId", userId); map.put("attachType", AttachConstant.TYPE_AUTH_EXP); String url = Constant.axpurl.get("resource_getOriginAttachList_serv"); // 定义反序列化 数据格式 final TypeReference<ResultInfo<?>> TypeRef = new TypeReference<ResultInfo<?>>() { }; ResultInfo credentialUrls = (ResultInfo<?>) HttpClientUtils.post(url, map, TypeRef); return new ResultInfo(0, "", "操作成功", credentialUrls.getData()); } catch (Exception e) { return new ResultInfo(-1, "", ""); } } /** * @param userId * @param creType identityCard studentCard * @return */ public ResultInfo getCredentialUrls(Long userId, String creType) { Map<String, String> map = new HashMap<>(); map.put("userId", userId.toString()); map.put("typeId", ConstantFunction.getAtmTypeUserauth()); List<String> fileKeys = resourceMapper.getCredentialFileKey(map); if (fileKeys == null || fileKeys.isEmpty()) { return new ResultInfo(-1, "07005", ""); } OSSClient client = null; try { ServerInfo serverInfo = getServerInfo(ConstantFunction.getAtmTypeUserauth()); client = new OSSClient(serverInfo.getEndpoint(), serverInfo.getAccessKeyId(), serverInfo.getAccessKeySecret()); List<CredentialURLInfo> urls = new ArrayList<>(); for (String fileKey : fileKeys) { //过期时间5分钟 URL url = client.generatePresignedUrl(serverInfo.getBucketName(), fileKey, new Date(System.currentTimeMillis() + 60 * 1000 * 5)); int type = 0; // if (fileKey.contains(creType)){不要这个业务条件了 //货源 if (fileKey.contains("packet")) { if (fileKey.contains(ConstantFunction.getCredentialTypeIdHold())) { type = 1; } else if (fileKey.contains(ConstantFunction.getCredentialTypeId())) { type = 2; } } // else { // //理论上不可能,除非是手动干预了数据库的数据 // throw new BusinessException("07005"); // } // } urls.add(new CredentialURLInfo(type, url.toString())); } return new ResultInfo(0, "", "操作成功", urls); } catch (Exception e) { throw e; } finally { if (client != null) { client.shutdown(); } } } /** * @param credentialInfo * @Description: 校验方法 */ private void vlidCredentialInfo(CredentialInfo credentialInfo) { if (StringUtils.isBlank(credentialInfo.getType()) || StringUtils.isBlank(credentialInfo.getSourceId()) || StringUtils.isBlank(credentialInfo.getFileName()) || StringUtils.isBlank(credentialInfo.getFile())) { throw new BusinessException("111"); } else if (!credentialInfo.getType().matches("^(1|2|3){1}$")) { throw new BusinessException("07003"); } else if (!credentialInfo.getSourceId().matches("^(1|2){1}$")) { throw new BusinessException("07002"); } } /** * @param file * @return * @Description: 解码base64后的字节流 */ private ByteArrayInputStream getDecodeStream(String file) { byte[] fileBytes = Base64Utils.decodeFromString(file); ByteArrayInputStream in = new ByteArrayInputStream(fileBytes); return in; } /** * @param signInfo * @return boolean 返回类型 * @Method: valid * @Description: 校验signinfo参数 * @author WJ * @date 2016年4月4日 上午11:57:14 **/ private boolean validSignInfo(SignInfo signInfo) { if (StringUtils.isBlank(signInfo.getAttachmentTypeId()) || StringUtils.isBlank(signInfo.getFileKey()) || StringUtils.isBlank(signInfo.getFileName()) || StringUtils.isBlank(signInfo.getSourceId()) || StringUtils.isBlank(signInfo.getUserName()) || signInfo.getUserId() == null) { return false; } return true; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.insat.gl5.crm_pfa.web; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Named; import org.primefaces.model.chart.CartesianChartModel; import org.primefaces.model.chart.ChartSeries; import org.primefaces.model.chart.MeterGaugeChartModel; import org.primefaces.model.chart.PieChartModel; /** * * @author Mu7ammed 3li -- mohamed.ali.affes@gmail.com -- */ @Named @RequestScoped public class ChartBean implements Serializable { private PieChartModel pieModelAchat; private PieChartModel pieModelVente; private MeterGaugeChartModel meterGaugeModel; private CartesianChartModel categoryModel; private CartesianChartModel categoryModelClient; /** * Creates a new instance of ChartBean */ public ChartBean() { createPieModelAchat(); createPieModelVente(); createMeterGaugeModel(); createCategoryModel(); createCategoryClientModel(); } public PieChartModel getPieModelAchat() { return pieModelAchat; } public PieChartModel getPieModelVente() { return pieModelVente; } public MeterGaugeChartModel getMeterGaugeModel() { return meterGaugeModel; } public CartesianChartModel getCategoryModel() { return categoryModel; } public CartesianChartModel getCategoryModelClient() { return categoryModelClient; } private void createPieModelAchat() { pieModelAchat = new PieChartModel(); pieModelAchat.set("Demandes", 43); pieModelAchat.set("Attente de validation", 5); pieModelAchat.set("En commande", 12); } private void createPieModelVente() { pieModelVente = new PieChartModel(); pieModelVente.set("En cours", 25); pieModelVente.set("A relancer", 7); pieModelVente.set("Terminée", 43); } private void createMeterGaugeModel() { List<Number> intervals = new ArrayList<Number>() { { add(40); add(70); add(90); add(100); } }; meterGaugeModel = new MeterGaugeChartModel("% CA Atteint", 68, intervals); } private void createCategoryModel() { categoryModel = new CartesianChartModel(); ChartSeries produits = new ChartSeries(); produits.setLabel("Produits"); produits.set("Etude", 10); produits.set("Production", 75); produits.set("Fin de vie", 3); ChartSeries services = new ChartSeries(); services.setLabel("Services"); services.set("Etude", 5); services.set("Production", 25); services.set("Fin de vie", 10); categoryModel.addSeries(produits); categoryModel.addSeries(services); } private void createCategoryClientModel() { categoryModelClient = new CartesianChartModel(); ChartSeries client = new ChartSeries(); client.setLabel("Clients"); client.set("Propects", 70); client.set("Standard", 35); client.set("Premium", 6); categoryModelClient.addSeries(client); } }
package com.facebook.react.uimanager; import android.view.View; import com.facebook.common.e.a; import com.facebook.react.bridge.ReadableMapKeySetIterator; import java.util.HashMap; import java.util.Map; public class ViewManagerPropertyUpdater { private static final Map<Class<?>, ShadowNodeSetter<?>> SHADOW_NODE_SETTER_MAP; private static final Map<Class<?>, ViewManagerSetter<?, ?>> VIEW_MANAGER_SETTER_MAP = new HashMap<Class<?>, ViewManagerSetter<?, ?>>(); static { SHADOW_NODE_SETTER_MAP = new HashMap<Class<?>, ShadowNodeSetter<?>>(); } public static void clear() { ViewManagersPropertyCache.clear(); VIEW_MANAGER_SETTER_MAP.clear(); SHADOW_NODE_SETTER_MAP.clear(); } private static <T> T findGeneratedSetter(Class<?> paramClass) { StringBuilder stringBuilder; String str = paramClass.getName(); try { null = new StringBuilder(); null.append(str); null.append("$$PropsSetter"); return (T)Class.forName(null.toString()).newInstance(); } catch (ClassNotFoundException classNotFoundException) { stringBuilder = new StringBuilder("Could not find generated setter for "); stringBuilder.append(paramClass); a.b("ViewManagerPropertyUpdater", stringBuilder.toString()); return null; } catch (InstantiationException instantiationException) { StringBuilder stringBuilder1 = new StringBuilder("Unable to instantiate methods getter for "); stringBuilder1.append((String)stringBuilder); throw new RuntimeException(stringBuilder1.toString(), instantiationException); } catch (IllegalAccessException illegalAccessException) { StringBuilder stringBuilder1 = new StringBuilder("Unable to instantiate methods getter for "); stringBuilder1.append((String)stringBuilder); throw new RuntimeException(stringBuilder1.toString(), illegalAccessException); } } private static <T extends ViewManager, V extends View> ViewManagerSetter<T, V> findManagerSetter(Class<? extends ViewManager> paramClass) { ViewManagerSetter<ViewManager, View> viewManagerSetter2 = (ViewManagerSetter)VIEW_MANAGER_SETTER_MAP.get(paramClass); ViewManagerSetter<ViewManager, View> viewManagerSetter1 = viewManagerSetter2; if (viewManagerSetter2 == null) { viewManagerSetter2 = findGeneratedSetter(paramClass); viewManagerSetter1 = viewManagerSetter2; if (viewManagerSetter2 == null) viewManagerSetter1 = new FallbackViewManagerSetter<ViewManager, View>(paramClass); VIEW_MANAGER_SETTER_MAP.put(paramClass, viewManagerSetter1); } return (ViewManagerSetter)viewManagerSetter1; } private static <T extends ReactShadowNode> ShadowNodeSetter<T> findNodeSetter(Class<? extends ReactShadowNode> paramClass) { ShadowNodeSetter<ReactShadowNode> shadowNodeSetter2 = (ShadowNodeSetter)SHADOW_NODE_SETTER_MAP.get(paramClass); ShadowNodeSetter<ReactShadowNode> shadowNodeSetter1 = shadowNodeSetter2; if (shadowNodeSetter2 == null) { shadowNodeSetter2 = findGeneratedSetter(paramClass); shadowNodeSetter1 = shadowNodeSetter2; if (shadowNodeSetter2 == null) shadowNodeSetter1 = new FallbackShadowNodeSetter<ReactShadowNode>(paramClass); SHADOW_NODE_SETTER_MAP.put(paramClass, shadowNodeSetter1); } return (ShadowNodeSetter)shadowNodeSetter1; } public static Map<String, String> getNativeProps(Class<? extends ViewManager> paramClass, Class<? extends ReactShadowNode> paramClass1) { // Byte code: // 0: ldc com/facebook/react/uimanager/ViewManagerPropertyUpdater // 2: monitorenter // 3: new java/util/HashMap // 6: dup // 7: invokespecial <init> : ()V // 10: astore_2 // 11: aload_0 // 12: invokestatic findManagerSetter : (Ljava/lang/Class;)Lcom/facebook/react/uimanager/ViewManagerPropertyUpdater$ViewManagerSetter; // 15: aload_2 // 16: invokeinterface getProperties : (Ljava/util/Map;)V // 21: aload_1 // 22: invokestatic findNodeSetter : (Ljava/lang/Class;)Lcom/facebook/react/uimanager/ViewManagerPropertyUpdater$ShadowNodeSetter; // 25: aload_2 // 26: invokeinterface getProperties : (Ljava/util/Map;)V // 31: ldc com/facebook/react/uimanager/ViewManagerPropertyUpdater // 33: monitorexit // 34: aload_2 // 35: areturn // 36: astore_0 // 37: ldc com/facebook/react/uimanager/ViewManagerPropertyUpdater // 39: monitorexit // 40: aload_0 // 41: athrow // Exception table: // from to target type // 3 31 36 finally } public static <T extends ReactShadowNode> void updateProps(T paramT, ReactStylesDiffMap paramReactStylesDiffMap) { ShadowNodeSetter<ReactShadowNode> shadowNodeSetter = findNodeSetter((Class)paramT.getClass()); ReadableMapKeySetIterator readableMapKeySetIterator = paramReactStylesDiffMap.mBackingMap.keySetIterator(); while (readableMapKeySetIterator.hasNextKey()) shadowNodeSetter.setProperty((ReactShadowNode)paramT, readableMapKeySetIterator.nextKey(), paramReactStylesDiffMap); } public static <T extends ViewManager, V extends View> void updateProps(T paramT, V paramV, ReactStylesDiffMap paramReactStylesDiffMap) { ViewManagerSetter<ViewManager, View> viewManagerSetter = findManagerSetter((Class)paramT.getClass()); ReadableMapKeySetIterator readableMapKeySetIterator = paramReactStylesDiffMap.mBackingMap.keySetIterator(); while (readableMapKeySetIterator.hasNextKey()) viewManagerSetter.setProperty((ViewManager)paramT, (View)paramV, readableMapKeySetIterator.nextKey(), paramReactStylesDiffMap); } static class FallbackShadowNodeSetter<T extends ReactShadowNode> implements ShadowNodeSetter<T> { private final Map<String, ViewManagersPropertyCache.PropSetter> mPropSetters; private FallbackShadowNodeSetter(Class<? extends ReactShadowNode> param1Class) { this.mPropSetters = ViewManagersPropertyCache.getNativePropSettersForShadowNodeClass(param1Class); } public void getProperties(Map<String, String> param1Map) { for (ViewManagersPropertyCache.PropSetter propSetter : this.mPropSetters.values()) param1Map.put(propSetter.getPropName(), propSetter.getPropType()); } public void setProperty(ReactShadowNode param1ReactShadowNode, String param1String, ReactStylesDiffMap param1ReactStylesDiffMap) { ViewManagersPropertyCache.PropSetter propSetter = this.mPropSetters.get(param1String); if (propSetter != null) propSetter.updateShadowNodeProp(param1ReactShadowNode, param1ReactStylesDiffMap); } } static class FallbackViewManagerSetter<T extends ViewManager, V extends View> implements ViewManagerSetter<T, V> { private final Map<String, ViewManagersPropertyCache.PropSetter> mPropSetters; private FallbackViewManagerSetter(Class<? extends ViewManager> param1Class) { this.mPropSetters = ViewManagersPropertyCache.getNativePropSettersForViewManagerClass(param1Class); } public void getProperties(Map<String, String> param1Map) { for (ViewManagersPropertyCache.PropSetter propSetter : this.mPropSetters.values()) param1Map.put(propSetter.getPropName(), propSetter.getPropType()); } public void setProperty(T param1T, V param1V, String param1String, ReactStylesDiffMap param1ReactStylesDiffMap) { ViewManagersPropertyCache.PropSetter propSetter = this.mPropSetters.get(param1String); if (propSetter != null) propSetter.updateViewProp((ViewManager)param1T, (View)param1V, param1ReactStylesDiffMap); } } public static interface Settable { void getProperties(Map<String, String> param1Map); } public static interface ShadowNodeSetter<T extends ReactShadowNode> extends Settable { void setProperty(T param1T, String param1String, ReactStylesDiffMap param1ReactStylesDiffMap); } public static interface ViewManagerSetter<T extends ViewManager, V extends View> extends Settable { void setProperty(T param1T, V param1V, String param1String, ReactStylesDiffMap param1ReactStylesDiffMap); } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\reac\\uimanager\ViewManagerPropertyUpdater.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package org.sero.cash.superzk.crypto.enc; public class Chacha20 { public static byte[] encode(byte[] data, byte[] key) { Chacha20 chacha = new Chacha20(key, nonce, 0); byte[] ret = new byte[data.length]; chacha.encrypt(ret, data); return ret; } private static byte[] nonce = new byte[16]; private int[] input; public Chacha20(byte[] key, byte[] nonce, int counter) { this.input = new int[16]; this.input[0] = 1634760805; this.input[1] = 857760878; this.input[2] = 2036477234; this.input[3] = 1797285236; this.input[4] = Chacha20.U8TO32_LE(key, 0); this.input[5] = Chacha20.U8TO32_LE(key, 4); this.input[6] = Chacha20.U8TO32_LE(key, 8); this.input[7] = Chacha20.U8TO32_LE(key, 12); this.input[8] = Chacha20.U8TO32_LE(key, 16); this.input[9] = Chacha20.U8TO32_LE(key, 20); this.input[10] = Chacha20.U8TO32_LE(key, 24); this.input[11] = Chacha20.U8TO32_LE(key, 28); if (nonce.length == 12) { this.input[12] = counter; this.input[13] = Chacha20.U8TO32_LE(nonce, 0); this.input[14] = Chacha20.U8TO32_LE(nonce, 4); this.input[15] = Chacha20.U8TO32_LE(nonce, 8); } else { this.input[12] = counter; this.input[13] = 0; this.input[14] = Chacha20.U8TO32_LE(nonce, 0); this.input[15] = Chacha20.U8TO32_LE(nonce, 4); } } public void encrypt(byte[] dst, byte[] src) { assert (dst.length == src.length); int[] x = new int[16]; byte[] output = new byte[64]; int i, dpos = 0, spos = 0; int len = dst.length; while (len > 0) { for (i = 16; i-- > 0;) x[i] = this.input[i]; for (i = 20; i > 0; i -= 2) { this.quarterRound(x, 0, 4, 8, 12); this.quarterRound(x, 1, 5, 9, 13); this.quarterRound(x, 2, 6, 10, 14); this.quarterRound(x, 3, 7, 11, 15); this.quarterRound(x, 0, 5, 10, 15); this.quarterRound(x, 1, 6, 11, 12); this.quarterRound(x, 2, 7, 8, 13); this.quarterRound(x, 3, 4, 9, 14); } for (i = 16; i-- > 0;) x[i] += this.input[i]; for (i = 16; i-- > 0;) Chacha20.U32TO8_LE(output, 4 * i, x[i]); this.input[12] += 1; if (this.input[12] == 0) { this.input[13] += 1; } if (len <= 64) { for (i = len; i-- > 0;) { dst[i + dpos] = (byte) (src[i + spos] ^ output[i]); } return; } for (i = 64; i-- > 0;) { dst[i + dpos] = (byte) (src[i + spos] ^ output[i]); } len -= 64; spos += 64; dpos += 64; } } private void quarterRound(int[] x, int a, int b, int c, int d) { x[a] += x[b]; x[d] = Chacha20.ROTATE(x[d] ^ x[a], 16); x[c] += x[d]; x[b] = Chacha20.ROTATE(x[b] ^ x[c], 12); x[a] += x[b]; x[d] = Chacha20.ROTATE(x[d] ^ x[a], 8); x[c] += x[d]; x[b] = Chacha20.ROTATE(x[b] ^ x[c], 7); } private static int U8TO32_LE(byte[] x, int i) { return (x[i] & 0xff) | ((x[i + 1] & 0xff) << 8) | ((x[i + 2] & 0xff) << 16) | ((x[i + 3] & 0xff) << 24); } private static void U32TO8_LE(byte[] x, int i, int u) { x[i] = (byte) u; u >>>= 8; x[i + 1] = (byte) u; u >>>= 8; x[i + 2] = (byte) u; u >>>= 8; x[i + 3] = (byte) u; } private static int ROTATE(int v, int c) { return (v << c) | (v >>> (32 - c)); } }
package pl.edu.charzynm; public enum WeakVerbConjugationSuffixes { //Partizip I präsens DER("der"), DES("des"), DE("de"), //Imperfekt (Präteritum) TEST("test"), //Präsens EST("est"), //Partizip II (Perfekt) TER("ter"), TES("tes"), //Imperfekt (Präteritum) TEN("ten"), TET("tet"), //Präsens EN("en"), //Imperfekt (Präteritum) TE("te"), //Präsens ST("st"), ET("et"), //Partizip II (Perfekt), Präsens T("t"), //Partizip I präsens D("d"), //Präsens E("e"); private String value; WeakVerbConjugationSuffixes(String value) { this.value = value; } public String getValue() { return value; } }
package filesBasics; import java.util.*; import java.io.*; public class FileDemo { //byte b1[]=new byte[10]; void writeFile() throws FileNotFoundException { Scanner scan=new Scanner(System.in); FileOutputStream fo=new FileOutputStream("text2.text",true); String s=""; System.out.println("enter message:"); try { while(!s.equals("n")){ //System.out.println("enter message:"); s=scan.nextLine(); if(!s.equals("n")) { fo.write(s.getBytes()); fo.write("\r\n".getBytes()); } } fo.close(); } catch(Exception e) { System.out.println(e); } } void readFile() throws FileNotFoundException { FileInputStream f=new FileInputStream("text2.text"); try { byte[] b=new byte[100]; f.read(b); String str=new String(b); System.out.println(str.trim()); f.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub FileDemo obj=new FileDemo(); obj.writeFile(); obj.readFile(); } }
package com.sarthaksavasil.notificationtracker; import androidx.appcompat.app.AppCompatActivity; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.text.Html; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; 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 java.util.ArrayList; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity { TableLayout tab; DatabaseReference databaseDataL; List<Data> dataL; ListView listViewDatas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // tab = (TableLayout)findViewById(R.id.tab); listViewDatas = findViewById(R.id.listViewDatas); databaseDataL = FirebaseDatabase.getInstance().getReference("data"); dataL = new ArrayList<>(); NotificationManager n = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(n.isNotificationPolicyAccessGranted()) { }else{ startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)); } } LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg")); } private BroadcastReceiver onNotice= new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_control, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } @Override protected void onStart() { super.onStart(); //attaching value event listener databaseDataL.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //clearing the previous artist list dataL.clear(); //iterating through all the nodes for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { //getting artist Data data = postSnapshot.getValue(Data.class); //adding artist to the list dataL.add(data); } //creating adapter Collections.reverse(dataL); DataList datatAdapter = new DataList(MainActivity.this, dataL); //attaching adapter to the listview listViewDatas.setAdapter(datatAdapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); } }
package org.com.ramboindustries.corp.sql; public final class SQLConstants { private SQLConstants() { } public static final String INSERT = " INSERT INTO "; public static final String UPDATE = " UPDATE "; public static final String FROM = " FROM "; public static final String SET = " SET "; public static final String WHERE = " WHERE "; public static final String VALUES = " VALUES "; public static final String EQUAL = " = "; public static final String AND = " AND "; public static final String CREATE_TABLE = " CREATE TABLE "; public static final String AUTO_INCREMENT = " AUTO_INCREMENT "; public static final String NOT_NULL = " NOT NULL "; public static final String updateSQL(String table, String updateScript, String whereConditions) { return UPDATE + table + SET + updateScript + whereConditions; } public static final String insertSQL(String table, String columns, String values) { return INSERT + table + "(" + columns + ")" + VALUES + "(" + values + ")"; } }
package com.example.security.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import com.example.security.jwt.JwtConfigurer; import com.example.security.jwt.JwtTokenProvider; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { private final JwtTokenProvider jwtTokenProvider; private static final String REGISTRATION = "/registration"; private static final String LOGIN = "/login"; private static final String H2_CONSOLE = "/h2-console/**"; @Autowired public SecurityConfig(JwtTokenProvider jwtTokenProvider) { this.jwtTokenProvider = jwtTokenProvider; } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic().disable().headers().frameOptions().disable().and().csrf().disable().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests() .antMatchers(H2_CONSOLE).permitAll().antMatchers(REGISTRATION).permitAll().antMatchers(LOGIN) .permitAll().anyRequest().authenticated().and().apply(new JwtConfigurer(jwtTokenProvider)); } }
package Semana11; public class TestePagamento { public static void main(String[] args) { Pagamento pag = new Pagamento("Felipe", "35503071875", 251.26); System.out.println(pag); CartaoDeCredito cred = new CartaoDeCredito("Helio", "19052399680", 330.00, "3363598546781256"); System.out.println(cred); Cheque cheq = new Cheque("Matheus", "40659963897", (double)50, "2020365891"); System.out.println(cheq); Boleto bol = new Boleto("Simone", "27740647837", (double)560, "1"); System.out.println(bol); } }
import java.util.Arrays; public class Solution { static int minnumber; /** * 回溯法 超时 * @param coins 硬币面额 * @param amount 总金额 * @return */ public int coinChange(int[] coins, int amount) { if(coins.length==0) return -1; if(amount==0) return 0; int k = 0; for(int i= 1;i<coins.length;i++){//插入排序,从大到小排列 int j = i; k = coins[i]; while(j>0&&coins[j-1]<k){ coins[j] = coins[j-1]; j--; } coins[j] = k; } minnumber = -1; dfs(coins,0,0,amount); return minnumber; } private static void dfs(int[] a,int low,int number,int amount){ if(amount==0&&number>0){ if(minnumber>0) minnumber = number<minnumber?number:minnumber; else if(minnumber==-1) minnumber = number; } for(int i = low;i<a.length;i++){ dfs(a,i+1,number,amount); if(amount-a[i]>=0){ while(amount-a[i]>=0){ amount = amount-a[i]; number++; dfs(a,i+1,number,amount); } } } } /** * 动态规划 * @param coins * @param amount * @return */ public int coinChange_2(int[] coins, int amount) { if(coins.length==0) return -1; int[] mun = new int[amount+1]; //return sum_1(coins,amount,mun); return sum_2(coins,amount); } /** * 自顶向下 * @param coins 面值数组 * @param amount 总金额 * @param minnum 记录最少硬币次数,长度为总金额+1 * @return */ private int sum_1(int[] coins,int amount,int[] minnum){ if(amount==0) return 0; if(amount<0) return -1; if(minnum[amount]!=0) return minnum[amount]; int min = Integer.MAX_VALUE;//方便识别特殊情况 for(int key : coins){ int val = sum_1(coins,amount-key,minnum); if(val>=0 && min>val) min = val; } minnum[amount] = (min==Integer.MAX_VALUE)?-1: (min+1); return minnum[amount]; } /** *自底向上的解答 * @param coins 面值数组 * @param amount 总金额 * @return */ private int sum_2(int[] coins,int amount){ if(amount==0) return 0; if(amount<0) return -1; int[] minnum = new int[amount+1]; int max = amount+1; Arrays.fill(minnum,max);//填充数组,方便判断特殊情况。 minnum[0] = 0; for (int i = 1;i<max;i++){ for(int key: coins){ if(i>=key){ //要大于等于 if(minnum[i-key]>=0) minnum[i] = Math.min(minnum[i],minnum[i-key]+1); } } } return minnum[amount]>amount?-1:minnum[amount]; } }
package distance3; import java.awt.image.BufferedImage; import org.ejml.data.DenseMatrix64F; import org.ejml.ops.CommonOps; import boofcv.abst.feature.disparity.StereoDisparity; import boofcv.abst.geo.triangulate.WrapTwoViewsTriangulateDLT; import boofcv.alg.distort.ImageDistort; import boofcv.alg.distort.RemoveRadialPtoN_F64; import boofcv.alg.geo.PerspectiveOps; import boofcv.alg.geo.RectifyImageOps; import boofcv.alg.geo.rectify.RectifyCalibrated; import boofcv.core.image.ConvertBufferedImage; import boofcv.factory.feature.disparity.DisparityAlgorithms; import boofcv.factory.feature.disparity.FactoryStereoDisparity; import boofcv.io.image.UtilImageIO; import boofcv.struct.calib.IntrinsicParameters; import boofcv.struct.calib.StereoParameters; import boofcv.struct.image.ImageFloat32; import boofcv.struct.image.ImageUInt8; import georegression.geometry.GeometryMath_F64; import georegression.struct.point.Point2D_F64; import georegression.struct.point.Point3D_F64; import georegression.struct.se.Se3_F64; public class CalculateDistance { /** * Rektifikáció: a kép kiegyenesítése, eltünteti a lencsetorzítást * Diszparitás: x koordináták különbsége a két képen, fordítottan arányos a z-vel */ private StereoParameters param; private BufferedImage origLeft; private BufferedImage origRight; private ImageUInt8 rectLeft; private ImageUInt8 rectRight; private RectifyCalibrated rectAlg; private DenseMatrix64F rectK; private DenseMatrix64F rectR; private ImageFloat32 dispMap; /** * Egy sztereo képpárt és a kalibrációs adatokat tartalmazó xml-t vár * @param origLeft * @param origRight * @param param */ public CalculateDistance(BufferedImage origLeft, BufferedImage origRight, StereoParameters param) { this.origLeft = origLeft; this.origRight = origRight; this.param = param; prepareDistanceCalculation(); } /** * Rektifikálja a képeket és elkészít egy diszparitás térképet */ private void prepareDistanceCalculation() { ImageUInt8 distLeft = ConvertBufferedImage.convertFrom(origLeft, (ImageUInt8) null); ImageUInt8 distRight = ConvertBufferedImage.convertFrom(origRight, (ImageUInt8) null); // kepek rektifikacioja rectLeft = new ImageUInt8(distLeft.width, distLeft.height); rectRight = new ImageUInt8(distRight.width, distRight.height); rectAlg = rectify(distLeft, distRight, param, rectLeft, rectRight); BufferedImage outLeft = ConvertBufferedImage.convertTo(rectLeft, null, true); BufferedImage outRight = ConvertBufferedImage.convertTo(rectRight, null, true); UtilImageIO.saveImage(outLeft, "outLeft.ppm"); UtilImageIO.saveImage(outRight, "outRight.ppm"); rectK = rectAlg.getCalibrationMatrix(); rectR = rectAlg.getRectifiedRotation(); //Minimum és maximum diszparitás értéket kell megadni, sajnos jelen formájában nem sokat tudunk kezdeni vele :( dispMap = denseDisparitySubpixel(getRectLeft(), getRectRight(), 3, 0, 200); } /** * Rectified the input images using known calibration. */ public static RectifyCalibrated rectify(ImageUInt8 origLeft, ImageUInt8 origRight, StereoParameters param, ImageUInt8 rectLeft, ImageUInt8 rectRight) { // Compute rectification RectifyCalibrated rectifyAlg = RectifyImageOps.createCalibrated(); Se3_F64 leftToRight = param.getRightToLeft().invert(null); // original camera calibration matrices DenseMatrix64F K1 = PerspectiveOps.calibrationMatrix(param.getLeft(), null); DenseMatrix64F K2 = PerspectiveOps.calibrationMatrix(param.getRight(), null); rectifyAlg.process(K1, new Se3_F64(), K2, leftToRight); // rectification matrix for each image DenseMatrix64F rect1 = rectifyAlg.getRect1(); DenseMatrix64F rect2 = rectifyAlg.getRect2(); // New calibration matrix, DenseMatrix64F rectK = rectifyAlg.getCalibrationMatrix(); // Adjust the rectification to make the view area more useful RectifyImageOps.allInsideLeft(param.left, rect1, rect2, rectK); // undistorted and rectify images ImageDistort<ImageUInt8, ImageUInt8> imageDistortLeft = RectifyImageOps.rectifyImage(param.getLeft(), rect1, ImageUInt8.class); ImageDistort<ImageUInt8, ImageUInt8> imageDistortRight = RectifyImageOps.rectifyImage(param.getRight(), rect2, ImageUInt8.class); imageDistortLeft.apply(origLeft, rectLeft); imageDistortRight.apply(origRight, rectRight); return rectifyAlg; } /** * Egy torzított képpontból kiszámolja a torzítatlan képpontot * @param distPoint Képpont az eredeti torzított képen * @param camParam Kamera paraméterek * @return Torzítatlan pont */ public static Point2D_F64 removeDistortionFromPoint(Point2D_F64 distPoint, IntrinsicParameters camParam){ Point2D_F64 undistPoint = new Point2D_F64(); RemoveRadialPtoN_F64 magic = new RemoveRadialPtoN_F64(); magic.set(camParam.fx, camParam.fy, camParam.skew, camParam.cx, camParam.cy, camParam.radial); magic.compute(distPoint.x, distPoint.y, undistPoint); return undistPoint; } /** * Kiszámolja egy pont 3D koordinátáit a torzított képeken kiválasztott pontokból. * @param leftPixel * @param rightPixel * @param stereoParam * @return */ public static Point3D_F64 triangulate(Point2D_F64 leftPixel, Point2D_F64 rightPixel, StereoParameters stereoParam){ Point3D_F64 result = new Point3D_F64(); //miből számolja a torzítást? melyik kamera paraméterek kellenek? Point2D_F64 undistLeftPoint = removeDistortionFromPoint(leftPixel, stereoParam.getLeft()); Point2D_F64 undistRightPoint = removeDistortionFromPoint(rightPixel, stereoParam.getRight()); WrapTwoViewsTriangulateDLT magic = new WrapTwoViewsTriangulateDLT(); //Vagy fordítva???? magic.triangulate(undistRightPoint, undistLeftPoint, stereoParam.rightToLeft, result); return result; } /** * Kiszámolja egy pont 3D koordinátáit (ajánlott inkább a twoPixelsTo3dPoint-ot használni) * @param leftPixel Képpont a bal képen * @param dispValue A megadott ponthoz tartozó diszparitás érték * @return 3D pont */ public Point3D_F64 disparityTo3dPoint(Point2D_F64 leftPixel, double dispValue) { double baseline = param.getBaseline(); double fx = rectK.get(0, 0); double fy = rectK.get(1, 1); double cx = rectK.get(0, 2); double cy = rectK.get(1, 2); Point3D_F64 myPointRect = new Point3D_F64(); myPointRect.z = baseline * fx / dispValue; myPointRect.x = myPointRect.z * (leftPixel.x - cx) / fx; myPointRect.y = myPointRect.z * (leftPixel.y - cy) / fy; return myPointRect; } /** * Kiszámolja egy pont 3D koordinátáit. A két pontot a rektifikált képről kell megadni. (Ha helyesen lett megadva a két pont, y koordinátái megegyeznek.) * @param leftPixel Képpont a bal képen * @param rightPixel Képpont a jobb képen * @return 3D pont */ public Point3D_F64 twoPixelsTo3dPoint(Point2D_F64 leftPixel, Point2D_F64 rightPixel) { double dispValue = Math.abs(leftPixel.x - rightPixel.x); return disparityTo3dPoint(leftPixel, dispValue); } public ImageUInt8 getRectLeft() { return rectLeft; } public ImageUInt8 getRectRight() { return rectRight; } public StereoParameters getStereoParams(){ return param; } /** * Visszaadja egy megadott bal-képbeli pont diszparitás értékét (a diszp. térkép alapján). Nagyon pontatlan lehet! * @param x * @param y * @return */ @Deprecated public double getDispValue(int x, int y){ return dispMap.get(x, y); } /** * Kiszámolja egy megadott 3D pont origótól vett távolságát * @param point * @return Distance (m) */ public static double distanceFrom3dPoint(Point3D_F64 point) { return (Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2) + Math.pow(point.z, 2))) / 1000; } /** * Kiszámolja két megadott 3D pont egymástól való távolságát * @param point1 * @param point2 * @return Distance (m) */ public static double distanceOf3dPoints(Point3D_F64 point1, Point3D_F64 point2) { return (Math.sqrt( Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2) + Math.pow(point1.z - point2.z, 2))) / 1000; } /** * Elkészít egy diszparitás térképet * @param rectLeft Bal sztereo kép (rektifikált) * @param rectRight Jobb sztereo kép (rektifikált) * @param regionSize * @param minDisparity Minimum diszparitás érték, amit számol * @param maxDisparity Maximum diszparitás érték, amit számol * @return Diszparitás térkép */ public static ImageFloat32 denseDisparitySubpixel(ImageUInt8 rectLeft, ImageUInt8 rectRight, int regionSize, int minDisparity, int maxDisparity) { // A slower but more accuracy algorithm is selected // All of these parameters should be turned StereoDisparity<ImageUInt8, ImageFloat32> disparityAlg = FactoryStereoDisparity.regionSubpixelWta( DisparityAlgorithms.RECT_FIVE, minDisparity, maxDisparity, regionSize, regionSize, 25, 6, 0.1, ImageUInt8.class); // process and return the results disparityAlg.process(rectLeft, rectRight); return disparityAlg.getDisparity(); } }
package view.callassistant; import descriptionfiles.Description; import scriptinterface.ParameterTuple; import view.argumentcomponents.ArgumentComponentManager; import view.argumentcomponents.ArgumentsPanelSettings; import view.guicomponents.ButtonPanel; import view.guicomponents.GraphanaButton; import view.guicomponents.TitledPanel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; /** * A panel that includes an arguments panel and panel containing buttons to confirm or abort the input. * * @author Andreas Fender */ public class CallBorder extends JPanel implements KeyListener { private static final long serialVersionUID = 1L; private ArgumentsPanel callPanel; private ButtonPanel southPanel; private GraphanaButton cancelButton; private GraphanaButton insertButton; private GraphanaButton executeButton; private HelpPanel helpPanel; private Object okSignal; public CallBorder() { okSignal = new Object(); callPanel = new ArgumentsPanel(); southPanel = new ButtonPanel(); } /** * Initializes and builds this and the inner components * * @param description the description of the operation, script or similar to call * @param settings specifies which buttons to offer to the user * @param parameterTuple the parameters * @param argumentComponentManager the argument component manager to create the argument components * @param actionListener the listener for the buttons */ public void init(Description description, ArgumentsPanelSettings settings, ParameterTuple parameterTuple, ArgumentComponentManager argumentComponentManager, ActionListener actionListener) { this.setLayout(new BorderLayout()); cancelButton = new GraphanaButton("Cancel"); cancelButton.setPreferredSize(ButtonPanel.BUTTON_SIZE); cancelButton.addActionListener(actionListener); callPanel.init(parameterTuple, argumentComponentManager); callPanel.addKeyListener(this); //helpPanel.setHelp(argumentComponentManager.getMainControl().getOperationSet().getDescFiles().getDesc // (signature.getMainKey())); int callHeight = 0; int helpHeight = 0; if (description != null) { helpPanel = new HelpPanel(); helpPanel.setHelp(description); TitledPanel helpTitledPanel = new TitledPanel("Description", helpPanel, false); this.add(helpTitledPanel, BorderLayout.NORTH); helpHeight = helpTitledPanel.getPreferredSize().height; } if (callPanel.hasArguments()) { TitledPanel callTitledPanel = new TitledPanel("Arguments", callPanel, description != null); this.add(callTitledPanel, BorderLayout.CENTER); callHeight = callTitledPanel.getPreferredSize().height; } southPanel.setPreferredSize(new Dimension(0, 38)); if (settings.isExecuteOption()) { if (settings.isUseOKButton()) executeButton = new GraphanaButton("OK"); else executeButton = new GraphanaButton("Execute"); executeButton.setToolTipText("Execute directly."); executeButton.addActionListener(actionListener); executeButton.setPreferredSize(cancelButton.getPreferredSize()); southPanel.add(executeButton); } if (settings.isInsertOption()) { if (settings.isUseOKButton()) insertButton = new GraphanaButton("OK"); else insertButton = new GraphanaButton("Insert"); insertButton.setToolTipText("Insert into console input."); insertButton.addActionListener(actionListener); insertButton.setPreferredSize(cancelButton.getPreferredSize()); southPanel.add(insertButton); } if (!settings.isExecuteOption() && !settings.isInsertOption()) cancelButton.setText("Close"); southPanel.add(cancelButton); this.add(southPanel, BorderLayout.SOUTH); this.setPreferredSize(new Dimension(Math.max((int) callPanel.getPreferredSize().getWidth(), 400) + ArgumentsPanel.LABEL_WIDTH, (int) (helpHeight + callHeight + southPanel.getPreferredSize().getHeight ()))); this.setMinimumSize(new Dimension(this.getPreferredSize().width, this.getPreferredSize().height - helpHeight / 2)); } /** * Returns the inner call panel */ public ArgumentsPanel getCallPanel() { return this.callPanel; } /** * Returns the object which is notified once the user clicks a button */ public Object getOkSignal() { return okSignal; } /** * Returns the execute button. Might be null if not created due to the settings */ public GraphanaButton getExecuteButton() { return this.executeButton; } /** * Returns the insert button. Might be null if not created due to the settings */ public GraphanaButton getInsertButton() { return this.insertButton; } /** * Returns the cancel button. Might be null if not created due to the settings */ public GraphanaButton getCancelButton() { return cancelButton; } /** * Returns the panel that contains the description. Might be null, if the operation, script or similar does not * have a description */ public HelpPanel getHelpPanel() { return helpPanel; } @Override public void keyPressed(KeyEvent ev) { if (ev.getKeyCode() == KeyEvent.VK_ENTER) { if (executeButton != null) executeButton.doClick(); else if (insertButton != null) insertButton.doClick(); else cancelButton.doClick(); } if (ev.getKeyCode() == KeyEvent.VK_ESCAPE) { cancelButton.doClick(); } } @Override public void keyReleased(KeyEvent ev) { } @Override public void keyTyped(KeyEvent ev) { } }
package com.jinshu.xuzhi.feeling; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.io.IOException; import c.b.BP; import tyrantgit.explosionfield.ExplosionField; /** * A placeholder fragment containing a simple view. */ public class MainActivityFragment extends Fragment { private final String LOG_TAG = this.getClass().getSimpleName(); final MediaPlayer mp = new MediaPlayer(); public MainActivityFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_main, container, false); final ImageView feelingImage = (ImageView) rootView.findViewById(R.id.feelingImage); /*ExplosionField*/ final ExplosionField explosionField = ExplosionField.attach2Window(getActivity()); /*play audio*/ mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mp) { mp.start(); } }); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { Fragment f = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment); if (f instanceof com.jinshu.xuzhi.feeling.MenuFragment) { return; } Fragment fragment = new com.jinshu.xuzhi.feeling.MenuFragment(); FragmentManager manager = getActivity().getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); transaction.replace(R.id.fragment, fragment); transaction.commit(); } }); feelingImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { explosionField.explode(feelingImage); feelingImage.setClickable(false); /*play audio*/ try { mp.reset(); int id = getActivity().getResources().getIdentifier("dabaozha", "raw", "com.jinshu.xuzhi.feeling"); String uriString = Util.CONSTANTS_RES_PREFIX + Integer.toString(id); Log.v(LOG_TAG,uriString); mp.setDataSource(getActivity(), Uri.parse(uriString)); mp.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } }); Util.getScreenSize(getActivity()); BP.init("00"); return rootView; } @Override public void onDestroy() { mp.release(); Log.v(LOG_TAG, "onDestroy"); super.onDestroy(); } }
/* * @autor: Mentor Bibaj * @tema: Metoda GaussSeidel * @data: 04.13.2016 * */ import java.text.*; public class GaussSeidel { public static double distancaEuklidiane(double[] v1,double[] v2, char tipi){ double distanca = 0; double temp = 0; for(int i = 0; i < v1.length ; i++){ switch(tipi){ case '2': //System.out.println("v1" + v2[i]); temp += Math.pow(v1[i] - v2[i],2); break; case 'i': if(Math.abs(v1[i] - v2[i]) > temp){ temp = Math.abs(v1[i] - v2[i]); } break; } } switch(tipi){ case '2': distanca = Math.sqrt(temp); break; case 'i': distanca = temp; break; } return distanca; } public static double[] GaussSeideli(double[][] A, double[] x0, double[] b, int N, double TOL) { int n = A.length; int iter = 0; double[] x = new double[n]; double sum; double sum1; loop: for(int k = 1; k<N; k++) { System.out.println(" "); for (int i = 0; i < n; i++) { sum = 0; sum1 = 0; for (int j = i+1; j < n; j++) { if (i != j) { sum += A[i][j] * x0[j]; } } for (int j = 0; j < i-1; j++) { if (i != j) { sum1 += A[i][j] * x[j]; } } x[i] = ((b[i] - (sum+sum1)) / A[i][i]); System.out.print(" x"+(i+1) + "(" + k + ") = " + x[i] + " \n"); if((distancaEuklidiane(x, x0,'2') < TOL) && i == (n-1)){ //2 norma '2'; i norma 'infinit' iter = k; break loop; } x0[i] = x[i]; } //for(int i = 0; i < n; i++) } return x; } public static void main(String[] args) { double[][] A = {{ 3,-1,1 }, { 3, 6,2 }, { 3,3,7 }}; double[] x0 = {0,0,0};// double[] b = { 1,0,4 };// int N = 100; double TOL = Math.pow(10,-6); double[] zgjidhja = GaussSeideli(A,x0,b,N,TOL); System.out.println("\nZgjidhja e Perafruar e Sistemit me Gauss-Seidel eshte:"); System.out.print(" x = ( "); DecimalFormat df = new DecimalFormat("0.00000"); for(int i = 0; i < A.length; i++){ if(i != A.length-1) System.out.print(df.format(zgjidhja[i])+", "); else System.out.print(df.format(zgjidhja[i])+" "); } System.out.print(")^t"); } }
package org.employee.controller; import java.io.IOException; import org.employee.dao.EmployeeDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class DeleteEmployeeController { @Autowired private EmployeeDao employeeDao; @RequestMapping(value = "/delete/{id}") public ModelAndView deleteStudentById(ModelAndView mv, @PathVariable("id") int id) throws IOException { int counter = employeeDao.delete(id); if (counter > 0) { mv.addObject("msg", "Student records deleted against student id: " + id); } else { mv.addObject("msg", "Error- check the console log."); } mv.setViewName("delete"); return mv; } }
package ru.spb.iac.cud.services.audit; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; import ru.spb.iac.cud.exceptions.GeneralFailure; import ru.spb.iac.cud.exceptions.TokenExpired; import ru.spb.iac.cud.items.AuditFunction; import ru.spb.iac.cud.items.Function; import ru.spb.iac.cud.items.Group; import ru.spb.iac.cud.items.ISUsers; import ru.spb.iac.cud.items.Role; import ru.spb.iac.cud.items.UserAttributes; @WebService(targetNamespace = AuditService.NS) //@XmlSeeAlso({ObjectFactory.class}) public interface AuditService { public static final String NS = "http://audit.services.cud.iac.spb.ru/"; @WebMethod public void audit( // @WebParam(name = "login", targetNamespace = NS) String login, @WebParam(name = "uidUser", targetNamespace = NS) String uidUser, @WebParam(name = "userFunctions", targetNamespace = NS) List<AuditFunction> userFunctions) throws GeneralFailure; @WebMethod @WebResult(targetNamespace = NS) public Group testAB(@WebParam(name = "testGroupId", targetNamespace = NS) String sTestGrpId) throws GeneralFailure; }
package com.sinata.rwxchina.component_home.entity; import com.chad.library.adapter.base.entity.MultiItemEntity; import java.util.List; /** * @author:wj * @datetime:2017/12/26 * @describe: * @modifyRecord: */ public class IconMoreEntity { /** * name : 周边查询 * list : [{"id":"9","title":"加油站","img":"/Uploads/App/icon/jyz.png","is_url":"0","url":"","describe":"周边查询","shop_type":"","shop_type_labels":"","icon_label":"map_jyz"},{"id":"10","title":"医院","img":"/Uploads/App/icon/yy.png","is_url":"0","url":"","describe":"周边查询","shop_type":"","shop_type_labels":"","icon_label":"map_yy"},{"id":"11","title":"检测站","img":"/Uploads/App/icon/jcz.png","is_url":"0","url":"","describe":"周边查询","shop_type":"","shop_type_labels":"","icon_label":"map_jcz"},{"id":"12","title":"交警队","img":"/Uploads/App/icon/jjd.png","is_url":"0","url":"","describe":"周边查询","shop_type":"","shop_type_labels":"","icon_label":"map_jjd"}] */ private String name; private List<ListBean> list; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class ListBean { /** * id : 9 * title : 加油站 * img : /Uploads/App/icon/jyz.png * is_url : 0 * url : * describe : 周边查询 * shop_type : * shop_type_labels : * icon_label : map_jyz */ private String id; private String title; private String img; private String is_url; private String url; private String describe; private String shop_type; private String shop_type_labels; private String icon_label; public static final int PERIMETER = 1; public static final int SERVICE = 2; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getIs_url() { return is_url; } public void setIs_url(String is_url) { this.is_url = is_url; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescribe() { return describe; } public void setDescribe(String describe) { this.describe = describe; } public String getShop_type() { return shop_type; } public void setShop_type(String shop_type) { this.shop_type = shop_type; } public String getShop_type_labels() { return shop_type_labels; } public void setShop_type_labels(String shop_type_labels) { this.shop_type_labels = shop_type_labels; } public String getIcon_label() { return icon_label; } public void setIcon_label(String icon_label) { this.icon_label = icon_label; } } }
package hwardak.shiftlog; /** * Created by HWardak on 2017-07-29. */ class ShiftLogSettings { }
package lib.kh; public class studycore { public static int asdf; public static int toInteger(String a) { return Integer.parseInt(a); } public static int toInteger(double a) { return (int) (a); } public static double toDouble(String a) { return Double.parseDouble(a); } public static double toDouble(int a) { return (double) (a); } public static String toString(int a) { return Integer.toString(a); } public static String toString(double a) { return Double.toString(a); } }
/* * Copyright (c) 2011, 2020, Frank Jiang and/or its affiliates. All rights * reserved. ParameterOneClass.java is PROPRIETARY/CONFIDENTIAL built in 2013. * Use is subject to license terms. */ package com.frank.svm.config; import libsvm.svm_parameter; /** * The configuration of one-class SVM: distribution evaluation support vector * machine. * * @author <a href="mailto:jiangfan0576@gmail.com">Frank Jiang</a> * @version 1.0.0 */ public class ParameterOneClass extends AbstractParameter { /** * The support vector limit parameter &nu;. &nu;&isin;(0,1] (default 0.5). * <p> * &nu; parameter limits the amount of support vectors to * &nu;&times;old_amount * </p> */ protected double nu; /** * Construct a default <tt>ParameterOneClass</tt>. */ public ParameterOneClass() { this(0.5); } /** * Construct an instance of <tt>ParameterOneClass</tt> with specified * <code>&nu;</code> parameter. * * @param nu * the support vector limit parameter &nu;. &nu;&isin;(0,1] * (default 0.5) */ public ParameterOneClass(double nu) { if (nu <= 0 || nu > 1) throw new IllegalArgumentException(String.format( "ν(%g) must be the in the region of (0,1].", nu)); setNu(nu); svmType = svm_parameter.ONE_CLASS; } /** * Returns the support vector limit paramter <code>&nu;</code>, * <code>&nu;</code>&isin;(0,1] (default 0.5) * * @return the <code>&nu;</code> */ public double getNu() { return nu; } /** * Set the support vector limit paramter <code>&nu;</code>, * <code>&nu;</code>&isin;(0,1] (default 0.5). * * @param nu * the value of <code>&nu;</code> */ public void setNu(double nu) { if (nu <= 0 || nu > 1) throw new IllegalArgumentException(String.format( "ν(%g) must be the in the region of (0,1].", nu)); this.nu = nu; } }
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2016.05.11 um 01:33:35 PM CEST // package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java-Klasse für MaterialFehlerType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="MaterialFehlerType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Id" type="{http://www.w3.org/2001/XMLSchema}unsignedLong"/> * &lt;element name="System" type="{http://www-fls.thyssen.com/xml/schema/qcs}SystemEnum"/> * &lt;element name="Typ" type="{http://www-fls.thyssen.com/xml/schema/qcs}FehlerSchluesselType"/> * &lt;element name="Art" type="{http://www-fls.thyssen.com/xml/schema/qcs}FehlerArtType"/> * &lt;element name="Lage" type="{http://www-fls.thyssen.com/xml/schema/qcs}FehlerLageType"/> * &lt;element name="FehlerPosition" type="{http://www-fls.thyssen.com/xml/schema/qcs}FehlerPositionType" minOccurs="0"/> * &lt;element name="FehlerHaeufigkeit" type="{http://www-fls.thyssen.com/xml/schema/qcs}FehlerHaeufigkeitType" minOccurs="0"/> * &lt;element name="FehlerPeriodizitaet" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/> * &lt;element name="FehlerSeitenBezug" type="{http://www-fls.thyssen.com/xml/schema/qcs}FehlerSeitenBezugEnum" minOccurs="0"/> * &lt;element name="Bemerkung" type="{http://www-fls.thyssen.com/xml/schema/qcs}StringMax1000" minOccurs="0"/> * &lt;element name="EntstehungsZeitpunkt" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;element name="Verursacher" type="{http://www-fls.thyssen.com/xml/schema/qcs}StringMax2" minOccurs="0"/> * &lt;element name="Mandant" type="{http://www-fls.thyssen.com/xml/schema/qcs}FehlerMandantEnum"/> * &lt;element name="Erfasser" type="{http://www-fls.thyssen.com/xml/schema/qcs}StringMax40" minOccurs="0"/> * &lt;element name="ErfassungsAggregat" type="{http://www-fls.thyssen.com/xml/schema/qcs}AggregateSchluesselType" minOccurs="0"/> * &lt;element name="Gewichtung" type="{http://www-fls.thyssen.com/xml/schema/qcs}GewichtungEnum" minOccurs="0"/> * &lt;element name="SperrKz" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;element name="IsDispositiv" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;element name="IsBandbeobachtung" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MaterialFehlerType", propOrder = { "id", "system", "typ", "art", "lage", "fehlerPosition", "fehlerHaeufigkeit", "fehlerPeriodizitaet", "fehlerSeitenBezug", "bemerkung", "entstehungsZeitpunkt", "verursacher", "mandant", "erfasser", "erfassungsAggregat", "gewichtung", "sperrKz", "isDispositiv", "isBandbeobachtung" }) public class MaterialFehlerType { @XmlElement(name = "Id", required = true) @XmlSchemaType(name = "unsignedLong") protected BigInteger id; @XmlElement(name = "System", required = true) protected SystemEnum system; @XmlElement(name = "Typ", required = true) protected String typ; @XmlElement(name = "Art", required = true) protected FehlerArtType art; @XmlElement(name = "Lage", required = true) protected String lage; @XmlElement(name = "FehlerPosition") protected FehlerPositionType fehlerPosition; @XmlElement(name = "FehlerHaeufigkeit") protected Short fehlerHaeufigkeit; @XmlElement(name = "FehlerPeriodizitaet") protected Double fehlerPeriodizitaet; @XmlElement(name = "FehlerSeitenBezug") protected FehlerSeitenBezugEnum fehlerSeitenBezug; @XmlElement(name = "Bemerkung") protected String bemerkung; @XmlElement(name = "EntstehungsZeitpunkt", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar entstehungsZeitpunkt; @XmlElement(name = "Verursacher") protected String verursacher; @XmlElement(name = "Mandant", required = true) protected FehlerMandantEnum mandant; @XmlElement(name = "Erfasser") protected String erfasser; @XmlElement(name = "ErfassungsAggregat") protected String erfassungsAggregat; @XmlElement(name = "Gewichtung") protected GewichtungEnum gewichtung; @XmlElement(name = "SperrKz") protected boolean sperrKz; @XmlElement(name = "IsDispositiv") protected boolean isDispositiv; @XmlElement(name = "IsBandbeobachtung") protected Boolean isBandbeobachtung; /** * Ruft den Wert der id-Eigenschaft ab. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getId() { return id; } /** * Legt den Wert der id-Eigenschaft fest. * * @param value * allowed object is * {@link BigInteger } * */ public void setId(BigInteger value) { this.id = value; } /** * Ruft den Wert der system-Eigenschaft ab. * * @return * possible object is * {@link SystemEnum } * */ public SystemEnum getSystem() { return system; } /** * Legt den Wert der system-Eigenschaft fest. * * @param value * allowed object is * {@link SystemEnum } * */ public void setSystem(SystemEnum value) { this.system = value; } /** * Ruft den Wert der typ-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getTyp() { return typ; } /** * Legt den Wert der typ-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setTyp(String value) { this.typ = value; } /** * Ruft den Wert der art-Eigenschaft ab. * * @return * possible object is * {@link FehlerArtType } * */ public FehlerArtType getArt() { return art; } /** * Legt den Wert der art-Eigenschaft fest. * * @param value * allowed object is * {@link FehlerArtType } * */ public void setArt(FehlerArtType value) { this.art = value; } /** * Ruft den Wert der lage-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getLage() { return lage; } /** * Legt den Wert der lage-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setLage(String value) { this.lage = value; } /** * Ruft den Wert der fehlerPosition-Eigenschaft ab. * * @return * possible object is * {@link FehlerPositionType } * */ public FehlerPositionType getFehlerPosition() { return fehlerPosition; } /** * Legt den Wert der fehlerPosition-Eigenschaft fest. * * @param value * allowed object is * {@link FehlerPositionType } * */ public void setFehlerPosition(FehlerPositionType value) { this.fehlerPosition = value; } /** * Ruft den Wert der fehlerHaeufigkeit-Eigenschaft ab. * * @return * possible object is * {@link Short } * */ public Short getFehlerHaeufigkeit() { return fehlerHaeufigkeit; } /** * Legt den Wert der fehlerHaeufigkeit-Eigenschaft fest. * * @param value * allowed object is * {@link Short } * */ public void setFehlerHaeufigkeit(Short value) { this.fehlerHaeufigkeit = value; } /** * Ruft den Wert der fehlerPeriodizitaet-Eigenschaft ab. * * @return * possible object is * {@link Double } * */ public Double getFehlerPeriodizitaet() { return fehlerPeriodizitaet; } /** * Legt den Wert der fehlerPeriodizitaet-Eigenschaft fest. * * @param value * allowed object is * {@link Double } * */ public void setFehlerPeriodizitaet(Double value) { this.fehlerPeriodizitaet = value; } /** * Ruft den Wert der fehlerSeitenBezug-Eigenschaft ab. * * @return * possible object is * {@link FehlerSeitenBezugEnum } * */ public FehlerSeitenBezugEnum getFehlerSeitenBezug() { return fehlerSeitenBezug; } /** * Legt den Wert der fehlerSeitenBezug-Eigenschaft fest. * * @param value * allowed object is * {@link FehlerSeitenBezugEnum } * */ public void setFehlerSeitenBezug(FehlerSeitenBezugEnum value) { this.fehlerSeitenBezug = value; } /** * Ruft den Wert der bemerkung-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getBemerkung() { return bemerkung; } /** * Legt den Wert der bemerkung-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setBemerkung(String value) { this.bemerkung = value; } /** * Ruft den Wert der entstehungsZeitpunkt-Eigenschaft ab. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getEntstehungsZeitpunkt() { return entstehungsZeitpunkt; } /** * Legt den Wert der entstehungsZeitpunkt-Eigenschaft fest. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setEntstehungsZeitpunkt(XMLGregorianCalendar value) { this.entstehungsZeitpunkt = value; } /** * Ruft den Wert der verursacher-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getVerursacher() { return verursacher; } /** * Legt den Wert der verursacher-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setVerursacher(String value) { this.verursacher = value; } /** * Ruft den Wert der mandant-Eigenschaft ab. * * @return * possible object is * {@link FehlerMandantEnum } * */ public FehlerMandantEnum getMandant() { return mandant; } /** * Legt den Wert der mandant-Eigenschaft fest. * * @param value * allowed object is * {@link FehlerMandantEnum } * */ public void setMandant(FehlerMandantEnum value) { this.mandant = value; } /** * Ruft den Wert der erfasser-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getErfasser() { return erfasser; } /** * Legt den Wert der erfasser-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setErfasser(String value) { this.erfasser = value; } /** * Ruft den Wert der erfassungsAggregat-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getErfassungsAggregat() { return erfassungsAggregat; } /** * Legt den Wert der erfassungsAggregat-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setErfassungsAggregat(String value) { this.erfassungsAggregat = value; } /** * Ruft den Wert der gewichtung-Eigenschaft ab. * * @return * possible object is * {@link GewichtungEnum } * */ public GewichtungEnum getGewichtung() { return gewichtung; } /** * Legt den Wert der gewichtung-Eigenschaft fest. * * @param value * allowed object is * {@link GewichtungEnum } * */ public void setGewichtung(GewichtungEnum value) { this.gewichtung = value; } /** * Ruft den Wert der sperrKz-Eigenschaft ab. * */ public boolean isSperrKz() { return sperrKz; } /** * Legt den Wert der sperrKz-Eigenschaft fest. * */ public void setSperrKz(boolean value) { this.sperrKz = value; } /** * Ruft den Wert der isDispositiv-Eigenschaft ab. * */ public boolean isIsDispositiv() { return isDispositiv; } /** * Legt den Wert der isDispositiv-Eigenschaft fest. * */ public void setIsDispositiv(boolean value) { this.isDispositiv = value; } /** * Ruft den Wert der isBandbeobachtung-Eigenschaft ab. * * @return * possible object is * {@link Boolean } * */ public Boolean isIsBandbeobachtung() { return isBandbeobachtung; } /** * Legt den Wert der isBandbeobachtung-Eigenschaft fest. * * @param value * allowed object is * {@link Boolean } * */ public void setIsBandbeobachtung(Boolean value) { this.isBandbeobachtung = value; } }
package com.example.ass_boss.locationlist; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.LocationManager; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import com.google.android.gms.location.places.PlaceDetectionClient; import com.google.android.gms.location.places.PlaceLikelihoodBufferResponse; import com.google.android.gms.location.places.Places; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import static android.app.Activity.RESULT_OK; public class LocationHelper { private PlaceDetectionClient placeDetectionClient; private static final int REQUEST_CODE = 465; @SuppressLint("MissingPermission") public void getCurrentPlaceData(Activity activity, final onLoadPlaceListCallBack callBack) throws Exception { if (isCanGetLocation(activity)) { placeDetectionClient = Places.getPlaceDetectionClient(activity); Task<PlaceLikelihoodBufferResponse> placeResponse = placeDetectionClient.getCurrentPlace(null); placeResponse.addOnCompleteListener(new OnCompleteListener<PlaceLikelihoodBufferResponse>() { @Override public void onComplete(@NonNull Task<PlaceLikelihoodBufferResponse> task) { if (task.isSuccessful() && task.getResult() != null) { callBack.onCompleteLoad(task.getResult()); } else { callBack.onFailLoad(); } } }); } else { if (!isLocationAccessPermitted(activity)) { requestAccessPermission(activity); } if (isLocationProviderEnable(activity)) { requestLocationProvider(activity); } } } private void requestLocationProvider(final Activity activity) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage(activity.getResources().getString(R.string.gps_provider_disabled)); builder.setPositiveButton(R.string.open_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { activity.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setCancelable(false); builder.show(); } private void requestAccessPermission(Activity activity) { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE); } private boolean isCanGetLocation(Activity activity) throws Exception { return isLocationProviderEnable(activity) && isLocationAccessPermitted(activity); } private boolean isLocationAccessPermitted(Activity activity) { return ContextCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; } private boolean isLocationProviderEnable(Activity activity) throws Exception { boolean gpsEnable = false; boolean networkEnable = false; LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE); try { gpsEnable = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ignored) { throw new Exception(ignored); } try { networkEnable = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ignored) { throw new Exception(ignored); } return gpsEnable && networkEnable; } public static void activityResult(int requestCode, int resultCode, Intent data){ if (requestCode == REQUEST_CODE) { if (resultCode == RESULT_OK) { //getCurrentPlaceData(); } } } }
package com.shopify.admin.statis; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; @JsonIgnoreProperties(ignoreUnknown = true) @Data public class AdminStatisData { private String state; // 배송상태 private String masterCodeList; // 화면에서 넘어온 변수 private String volumeWeightList; // 화면 - 부피무게 리스트 private String volumeCheckList; // 화면 : 마스터코드|부피무게 private String[] arrMasterCodeList; // SQL IN 쿼리용 변수 private String paymentDate; private String courierCompany; private String courier; private String courierId; private int payment; private int paymentVat; // private int saleVat; // 매입부가세 private int totalPayment; // private int feesPrice; private int salePrice; // private int salePriceVat; private int totalSalePrice; private int pickupPrice; // 조한두 private String paymentCode; private String masterCode; private String sellerEmail; private String company; private String rankId; private int shopIdx; private String shopName; private int totalWeight; private String weight; // ***** private String buyerCountryCode; private String courierCompanyName; private String courierName; private String payType; private int rankPrice; private String boxType; private int totalCount; private int sumPayment; private int sumRankPrice; private int sumPaymentVat; private int sumSaleVat; // 매입부가세 private int sumTotalPayment; private int sumSalePrice; private int sumFeesPrice; private int sumPrice; private int sumPriceVat; private int sumTotalPrice; private int sumPickupPrice; // 조한두 private int sumPaymentVatPrice; // 조한두 private int sumAddFeesPrice; private int sumAddSalePrice; private int sumTotalFeesPrice; private int sumTotalSalePrice; private int addFeesPrice; // private int addSalePrice; // private int feesTotal; // private int saleTotal; // private int payCount; private int realPayment; private int calculCompanyPrice; private int calculSellerPrice; private int calculCompanyCount; private int calculSellerCount; private String addFeesInfo; // 매출추가요금사유 private String addSaleInfo; // 매입추가요금사유 private String calculType; // 정산 타입 : COMPANY, SELLER //private boolean companyCalcul; // 택배사 정산 여부 //private boolean sellerCalcul; // 셀러정산 여부 private String companyCalcul; private String sellerCalcul; private String companyCalculDesc; // 택배사 정산 여부 private String sellerCalculDesc; // 셀러정산 여부 //검색 관련 param private String searchPaymentCode; // 결제코드 (DO:국내, NA,ND:국외, EW:매출초과요금, SW:매입초과요금 ) private String searchSeller; private String searchCompany; private String searchCourier; private String searchDatetype; private String searchMonthStart; private String searchMonthEnd; private String searchDateStart; private String searchDateEnd; private String nowDate; //페이징관련 param private int currentPage; private int startRow; private int pageSize; private int totalPageNum; private int pageBlockSize; }
package com.vilio.plms.service.query; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.vilio.plms.dao.QueryDao; import com.vilio.plms.exception.ErrorException; import com.vilio.plms.glob.Fields; import com.vilio.plms.service.base.BaseService; import com.vilio.plms.service.base.CommonService; import com.vilio.plms.service.base.MessageService; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 类名: Plms100033<br> * 功能:贷款业务查询-公证抵押<br> * 版本: 1.0<br> * 日期: 2017年7月7日<br> * 作者: xiezhilei<br> * 版权:vilio<br> * 说明:<br> */ @Service public class Plms100033 extends BaseService { private static final Logger logger = Logger.getLogger(Plms100033.class); @Resource QueryService queryService; /** * 参数验证 * * @param body */ public void checkParam(Map<String, Object> body) throws ErrorException { } /** * 主业务流程空实现 * * @param head * @param body */ @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public void busiService(Map<String, Object> head, Map<String, Object> body, Map<String, Object> resultMap) throws ErrorException, Exception { resultMap.put("notarialAndMortgage",queryService.queryNotarialAndMortgage(body)); } }
package com.example.demo.dip.ok; public class Game { private GUI ihm; public Game(GUI ihm) { this.ihm = ihm; System.out.println("start game"); this.startInterface(); } private void startInterface() { this.ihm.start(); } public static void main(String[] args) { GUI text = () -> System.out.println("IHM Text"); new Game(text); new Game(new TextGraphic()); new Game(new IHMGraphic()); } } @FunctionalInterface interface GUI { void start(); } class IHMGraphic implements GUI { @Override public void start() { System.out.println("IHM Graphic"); } } class TextGraphic implements GUI { @Override public void start() { System.out.println("IHM Graphic"); } }
package com.github.hippo.chain; import org.apache.commons.lang3.StringUtils; import java.util.Objects; import java.util.UUID; /** * Created by hanruofei on 16/8/30. 串起rpc调用链 */ public enum ChainThreadLocal { INSTANCE; /** * 存放chainId */ private ThreadLocal<String> chainId = new ThreadLocal<>(); private ThreadLocal<String> spanId = new ThreadLocal<>(); /** * 存放chainOrder (调用链顺序) */ private ThreadLocal<Integer> chainOrder = new ThreadLocal<>(); public void clearTL() { chainId.remove(); spanId.remove(); } public void clearSpanId() { spanId.remove(); } /** * 获取ThreadLocal中的chainId value * * @return chainId */ public String getChainId() { if (StringUtils.isBlank(chainId.get())) { chainId.set(UUID.randomUUID().toString()); } return chainId.get(); } /** * 获取ThreadLocal中的requestId value * * @return requestId */ public String getSpanId() { if (StringUtils.isBlank(spanId.get())) { spanId.set(UUID.randomUUID().toString()); } return spanId.get(); } /** * 获取ThreadLocal中的chainOrder value * * @return chainOrder */ public int getChainOrder() { if (Objects.isNull(chainOrder.get())) { chainOrder.set(1); } return chainOrder.get(); } /** * 插入ThreadLocal中的value * * @param chainId chainId */ public void setChainId(String chainId) { this.chainId.set(chainId); } public void setSpanId(String spanId) { this.spanId.set(spanId); } /** * chainOrder+1 * * @param co chainOrder */ public void incChainOrder(int co) { this.chainOrder.set(co + 1); } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.util.Date; /** * MAssortDetail generated by hbm2java */ public class MAssortDetail implements java.io.Serializable { private String uniqueid; private String assortnum; private String qualitynum; private String drawingid; private String partName; private String model; private String materialqtySum; private String materialqty; private String partModel; private Date reqDate; public MAssortDetail() { } public MAssortDetail(String uniqueid) { this.uniqueid = uniqueid; } public MAssortDetail(String uniqueid, String assortnum, String qualitynum, String drawingid, String partName, String model, String materialqtySum, String materialqty, String partModel, Date reqDate) { this.uniqueid = uniqueid; this.assortnum = assortnum; this.qualitynum = qualitynum; this.drawingid = drawingid; this.partName = partName; this.model = model; this.materialqtySum = materialqtySum; this.materialqty = materialqty; this.partModel = partModel; this.reqDate = reqDate; } public String getUniqueid() { return this.uniqueid; } public void setUniqueid(String uniqueid) { this.uniqueid = uniqueid; } public String getAssortnum() { return this.assortnum; } public void setAssortnum(String assortnum) { this.assortnum = assortnum; } public String getQualitynum() { return this.qualitynum; } public void setQualitynum(String qualitynum) { this.qualitynum = qualitynum; } public String getDrawingid() { return this.drawingid; } public void setDrawingid(String drawingid) { this.drawingid = drawingid; } public String getPartName() { return this.partName; } public void setPartName(String partName) { this.partName = partName; } public String getModel() { return this.model; } public void setModel(String model) { this.model = model; } public String getMaterialqtySum() { return this.materialqtySum; } public void setMaterialqtySum(String materialqtySum) { this.materialqtySum = materialqtySum; } public String getMaterialqty() { return this.materialqty; } public void setMaterialqty(String materialqty) { this.materialqty = materialqty; } public String getPartModel() { return this.partModel; } public void setPartModel(String partModel) { this.partModel = partModel; } public Date getReqDate() { return this.reqDate; } public void setReqDate(Date reqDate) { this.reqDate = reqDate; } }
package com.jim.multipos.ui.mainpospage.presenter; import android.content.Context; import android.os.Bundle; import com.jim.mpviews.model.PaymentTypeWithService; import com.jim.multipos.R; import com.jim.multipos.core.BasePresenterImpl; import com.jim.multipos.data.DatabaseManager; import com.jim.multipos.data.db.model.PaymentType; import com.jim.multipos.data.db.model.customer.Customer; import com.jim.multipos.data.db.model.customer.Debt; import com.jim.multipos.data.db.model.order.Order; import com.jim.multipos.data.db.model.order.PayedPartitions; import com.jim.multipos.data.prefs.PreferencesHelper; import com.jim.multipos.ui.mainpospage.view.PaymentView; import com.jim.multipos.utils.DecimalUtils; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; /** * Created by Portable-Acer on 27.10.2017. */ public class PaymentPresenterImpl extends BasePresenterImpl<PaymentView> implements PaymentPresenter { private DatabaseManager databaseManager; List<PaymentType> paymentTypes; private Context context; private PreferencesHelper preferencesHelper; PaymentType currentPayment; List<PayedPartitions> payedPartitions; private Order order; double lastPaymentAmountState = 0; private Customer customer = null; private PaymentType debtPayment; @Inject public PaymentPresenterImpl(PaymentView paymentView, DatabaseManager databaseManager, Context context, PreferencesHelper preferencesHelper) { super(paymentView); this.databaseManager = databaseManager; paymentTypes = databaseManager.getPaymentTypes(); this.context = context; this.preferencesHelper = preferencesHelper; debtPayment = databaseManager.getDebtPaymentType().blockingGet(); } /** * special for sending local datas to Debt dialog, now not have any data */ @Override public void onDebtBorrowClicked() { if (debt == null) { view.openAddDebtDialog(databaseManager, order, customer, order.getForPayAmmount() - totalPayed()); } else { debt = null; removeDebtPaymentPartition(); view.showDebtDialog(); } } /** * change payment type for state */ @Override public void changePayment(int positionPayment) { currentPayment = paymentTypes.get(positionPayment); } /** * method for remove payed partition from list payed partition */ @Override public void removePayedPart(int removedPayedPart) { if (payedPartitions.get(removedPayedPart).getPaymentType().getTypeStaticPaymentType() == PaymentType.DEBT_PAYMENT_TYPE) { debt = null; view.showDebtDialog(); } payedPartitions.remove(removedPayedPart); view.updatePaymentList(); view.updateViews(order, totalPayed()); updateChange(); view.onPayedPartition(); } /** * init payment types to view */ @Override public void onCreateView(Bundle bundle) { super.onCreateView(bundle); ArrayList<PaymentTypeWithService> paymentTypeWithServices = new ArrayList<>(); for (int i = 0; i < paymentTypes.size(); i++) { PaymentTypeWithService paymentTypeWithService = new PaymentTypeWithService(paymentTypes.get(i).getName(), ""); paymentTypeWithServices.add(paymentTypeWithService); } view.initPaymentTypes(paymentTypeWithServices); } /** * it will work when getting datas from order list, for init or update view */ @Override public void incomeNewData(Order order, List<PayedPartitions> payedPartitions) { this.order = order; this.payedPartitions = payedPartitions; view.updatePaymentList(payedPartitions); view.updateViews(order, totalPayed()); updateChange(); } /** * last payment amount automatic parsed when typing payment amount */ @Override public void typedPayment(double paymentTyped) { lastPaymentAmountState = paymentTyped; updateChange(); } boolean isPay = true; /** * calculation change amount and decision making what should we view */ private void updateChange() { if (order == null) return; double change = DecimalUtils.roundDouble(order.getForPayAmmount() - totalPayed() - lastPaymentAmountState); change *= -1; if (order.getSubTotalValue() == 0) { isPay = false; view.updateCloseText(); return; } if (change <= -0.01) { //it is not enough money isPay = true; view.updateBalanceView(change * -1); } else if (change >= 0.01) { //it is enough money isPay = false; view.updateChangeView(change); } else { //it is enough money, payment amount equals balance due isPay = false; view.updateBalanceZeroText(); } } /** * pressed first optional button */ @Override public void pressFirstOptional() { double firstOptionalValue = preferencesHelper.getFirstOptionalPaymentButton(); view.updatePaymentText(lastPaymentAmountState + firstOptionalValue); } /** * pressed second optional button */ @Override public void pressSecondOptional() { double secondOptionalValue = preferencesHelper.getSecondOptionalPaymentButton(); view.updatePaymentText(lastPaymentAmountState + secondOptionalValue); } /** * pressed all amount button */ @Override public void pressAllAmount() { double payment = order.getForPayAmmount() - totalPayed(); if (payment < 0) payment = 0; view.updatePaymentText(payment); } @Override public void payButtonPressed() { if (order.getSubTotalValue() == 0) { view.closeSelf(); return; } if (isPay) { boolean hasOpenTill = databaseManager.hasOpenTill().blockingGet(); if (!hasOpenTill) { view.openWarningDialog(context.getString(R.string.opened_till_wnt_found_pls_open_till)); return; } //PAY //it is pay operation, because payment amount not enough for close order if (lastPaymentAmountState <= 0) return; for (PayedPartitions payedPartition : payedPartitions) { if (payedPartition.getPaymentType().getId().equals(currentPayment.getId())) { payedPartition.setValue(payedPartition.getValue() + lastPaymentAmountState); view.updateViews(order, totalPayed()); view.updatePaymentList(); view.onPayedPartition(); return; } } PayedPartitions payedPartition = new PayedPartitions(); payedPartition.setPaymentType(currentPayment); payedPartition.setValue(lastPaymentAmountState); payedPartitions.add(payedPartition); view.updateViews(order, totalPayed()); view.updatePaymentList(); view.onPayedPartition(); } else { boolean hasOpenTill = databaseManager.hasOpenTill().blockingGet(); if (!hasOpenTill) { view.openWarningDialog(context.getString(R.string.opened_till_wnt_found_pls_open_till)); return; } //DONE //it is done operation for close order. Because payment amount enough for close order if (order.getForPayAmmount() - totalPayed() <= 0) { view.updateViews(order, totalPayed()); view.updatePaymentList(); view.onPayedPartition(); view.closeOrder(order, payedPartitions, debt); return; } if (order.getForPayAmmount() == 0) { //FREE ORDER view.updateViews(order, totalPayed()); view.updatePaymentList(); view.onPayedPartition(); view.closeOrder(order, payedPartitions, debt); return; } for (PayedPartitions payedPartition : payedPartitions) { if (payedPartition.getPaymentType().getId().equals(currentPayment.getId())) { payedPartition.setValue(payedPartition.getValue() + lastPaymentAmountState); view.updateViews(order, totalPayed()); view.updatePaymentList(); view.onPayedPartition(); view.closeOrder(order, payedPartitions, debt); return; } } PayedPartitions payedPartition = new PayedPartitions(); payedPartition.setPaymentType(currentPayment); payedPartition.setValue(lastPaymentAmountState); payedPartitions.add(payedPartition); view.updateViews(order, totalPayed()); view.updatePaymentList(); view.onPayedPartition(); view.closeOrder(order, payedPartitions, debt); } } @Override public void setCustomer(Customer customer) { this.customer = customer; if (customer == null) { //DELETE DEBT debt = null; view.showDebtDialog(); } } Debt debt; @Override public void onDebtSave(Debt debt) { //add Debt To order customer = debt.getCustomer(); this.debt = debt; PayedPartitions payedPartition = new PayedPartitions(); payedPartition.setPaymentType(debtPayment); payedPartition.setValue(debt.getDebtAmount()); payedPartitions.add(payedPartition); view.updateViews(order, totalPayed()); view.updatePaymentList(); view.onPayedPartition(); view.updateCustomer(debt.getCustomer()); view.hideDebtDialog(); } private void removeDebtPaymentPartition() { for (int i = 0; i < payedPartitions.size(); i++) { if (payedPartitions.get(i).getPaymentType().getTypeStaticPaymentType() == PaymentType.DEBT_PAYMENT_TYPE) { payedPartitions.remove(i); } } view.updateViews(order, totalPayed()); view.updatePaymentList(); view.onPayedPartition(); } @Override public void onClickedTips() { if (order.getTips() == 0) { view.openTipsDialog((value, account) -> { order.setTipsAccount(account); order.setTips(value); view.updateViews(order, totalPayed()); view.updateOrderListDetialsPanel(); view.disableTipsButton(); }, ((order.getForPayAmmount() - totalPayed() - lastPaymentAmountState) >= 0) ? 0 : (order.getForPayAmmount() - totalPayed() - lastPaymentAmountState) * -1); } else { order.setTips(0); view.updateViews(order, totalPayed()); view.updateOrderListDetialsPanel(); view.enableTipsButton(); } } @Override public void onNewOrder() { debt = null; customer = null; view.enableTipsButton(); view.showDebtDialog(); } @Override public void sendDataToPaymentFragmentWhenEdit(Order order, List<PayedPartitions> payedPartitions, Debt debt) { this.payedPartitions = payedPartitions; this.debt = debt; if (debt == null) view.showDebtDialog(); else view.hideDebtDialog(); if (order.getTips() == 0) { view.enableTipsButton(); } else { view.disableTipsButton(); } view.updatePaymentList(payedPartitions); view.updateViews(order, totalPayed()); updateChange(); } @Override public void onHoldOrderClicked() { //IF WANT: PUL KIRITGANDA HOLDNI BOSSA KRIITILGAN PULAM MAYMENT BOB KETISHINI HOHLASA LOGIKANI SHU YERGA DOPISAVAT QILISH KERE view.onHoldOrderSendingData(order, payedPartitions, debt); } /** * method for sum payed partitions */ private double totalPayed() { double totalPayed = 0; for (PayedPartitions payedPartition : payedPartitions) { totalPayed += payedPartition.getValue(); } return totalPayed; } }
package se.ericthelin.bootstrap; public class MessageDescriptionMessageFactory implements MessageFactory { @Override public String createMessage(MessageDescription description) { if (!description.hasArguments()) { return description.getIdentifier(); } StringBuilder builder = new StringBuilder(description.getIdentifier()); builder.append(": "); boolean tail = false; for (MessageArgument argument : description.getArguments()) { if (tail) { builder.append(", "); } builder.append(argument); tail = true; } return builder.toString(); } }
/* * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.openrtb.snippet; import com.google.common.base.MoreObjects; import com.google.openrtb.OpenRtb.BidRequestOrBuilder; import com.google.openrtb.OpenRtb.BidResponse; import com.google.openrtb.OpenRtb.BidResponse.SeatBid.Bid; import com.google.openrtb.util.ProtoUtils; /** * Context for {@link SnippetProcessor}. * * <p>This class is NOT threadsafe. */ public class SnippetProcessorContext { private final BidRequestOrBuilder request; private final BidResponse.Builder response; private final StringBuilder builder; private Bid.Builder bid; public SnippetProcessorContext(BidRequestOrBuilder request, BidResponse.Builder response) { this(request, response, new StringBuilder(0)); } public SnippetProcessorContext(BidRequestOrBuilder request, BidResponse.Builder response, StringBuilder builder) { this.request = request; this.response = response; this.builder = builder; } public final BidRequestOrBuilder request() { return request; } public final BidResponse.Builder response() { return response; } public final void setBid(Bid.Builder bid) { this.bid = bid; } public final Bid.Builder getBid() { return bid; } public final StringBuilder builder() { return builder; } public SnippetProcessorContext rec() { return new SnippetProcessorContext(request, response); } @Override public String toString() { return MoreObjects.toStringHelper(this).omitNullValues() .add("request", request) .add("response", ProtoUtils.built(response)) .add("bid", ProtoUtils.built(bid)) .toString(); } }
import javax.swing.*; public class MyFrame extends JFrame { MyFrame() { setTitle("첫번째 프레임"); setSize(500, 300); setVisible(true); } public static void main(String [] args) { MyFrame mf = new MyFrame(); } }
package rest.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.http.HttpStatus; import rest.model.Usuarios; import rest.repository.UsuariosRepository; @Controller @RequestMapping(path="/rest-user") public class UsuariosController { @Autowired private UsuariosRepository usuariosRepository; @GetMapping(path="/getAllUsers") public @ResponseBody Iterable<Usuarios> getAllUsers() { // This returns a JSON or XML with the users return usuariosRepository.findAll(); } @GetMapping(path="/getUserById/{id}") public ResponseEntity getUserById(@PathVariable Long id) { if(!usuariosRepository.exists(id)){ return new ResponseEntity("Usuario nao encontrado :(.\n ID informado: " + id, HttpStatus.NOT_FOUND); } else{ return new ResponseEntity(usuariosRepository.findOne(id),HttpStatus.OK); } } @PostMapping(path="/createNewUser") public ResponseEntity createNewUser(@RequestBody Usuarios user){ try{ usuariosRepository.save(user); return new ResponseEntity("Usuario cadastrado com sucesso! ;)", HttpStatus.OK); }catch(Exception ex){ return new ResponseEntity("Ocorreu um erro a criar o usuario. :( \n" + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } @PutMapping(path="/updateUser/{id}") public ResponseEntity updateUser(@PathVariable Long id,@RequestBody Usuarios user) { Usuarios userOld = null; if(!usuariosRepository.exists(id)){ return new ResponseEntity("Usuario nao encontrado :(.\n ID informado: " + id, HttpStatus.NOT_FOUND); } else { userOld = usuariosRepository.findOne(id); userOld.setNomeCompleto(user.getNomeCompleto()); userOld.setEmail(user.getEmail()); userOld.setDataNascimento(user.getDataNascimento()); userOld.setIdTimeCoracao(user.getIdTimeCoracao()); } try{ usuariosRepository.save(userOld); return new ResponseEntity("Usuario atualizado com sucesso! ;)", HttpStatus.OK); }catch(Exception ex){ return new ResponseEntity("Ocorreu um erro a atualizar o usuario. :( \n" + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } @DeleteMapping(path="/deleteUser/{id}") public ResponseEntity deleteUser(@PathVariable Long id) { try{ usuariosRepository.delete(id); return new ResponseEntity("Usuario deletado com sucesso! ;)", HttpStatus.OK); } catch(Exception ex){ return new ResponseEntity("Ocorreu um erro a deletar o usuario. :( \n" + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } }
import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import kovaUtils.OpalDialog.ChoiceItem; import kovaUtils.OpalDialog.kovaDialog; import kovaUtils.OpalDialog.kovaDialog.OpalDialogType; import kovaUtils.Panels.BlurredPanel; import kovaUtils.Panels.DarkPanel; import kovaUtils.TextAssist.TextAssist; import kovaUtils.TextAssist.TextAssistContentProvider; import net.miginfocom.swt.MigLayout; import org.eclipse.jface.dialogs.DialogTray; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DateTime; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolTip; import org.eclipse.swt.widgets.Tray; import org.eclipse.swt.widgets.TrayItem; import org.jfree.ui.RefineryUtilities; import javax.swing.Timer; @SuppressWarnings("static-access") public class mainFrame extends DEF implements FocusListener, KeyListener, VerifyListener, SelectionListener, MouseListener { static Boolean flgAdmin = false; static List<String> lista; static List<String> lista2; static String[] EUROZONE2; static TextAssistContentProvider contentProvider; static SimpleDateFormat sdf = new SimpleDateFormat( "dd.MMMM.yyyy , HH:mm:ss"); static Timer timer; static String SQLquery = ""; static String datum; static String sTablica = "racuni"; static String selectedDir; static int IDbroj = 0; static int optIndex; static int tempSelect; static int tempIDbroj; static double ukIznos = 0; static double iznNeg = 0; static ResultSet rs; static ResultSet rsMenu; final Image icona; private Label lblStatusIcon; private Label lblFast; private Menu fileHelp; private MenuItem tabHelp; private MenuItem itemAbout; private MenuItem itemManual; private Menu helpMenu; private MenuItem itemAppLogg; static Image icon; static Shell shell; static Shell s; static Display display; static MigLayout layout = new MigLayout(); static MigLayout layout2 = new MigLayout(); static MigLayout layoutComp = new MigLayout(); static MigLayout layout3 = new MigLayout(); static MigLayout layout4 = new MigLayout("", "", "1[]7[]7[]1"); static MigLayout layout5 = new MigLayout("", "", "1[]15[]15[]15"); static MigLayout layoutStatus = new MigLayout("", "1[]1[]1[]1", "1[]1[]1[]1"); static Composite comp; static Composite comp2; static Composite compStatus; static Group group; static Group group2; static Group group3; static DateTime dtp; static DateTime dtp2; static Text txtBrRata; static Text txtUkupRata; static TextAssist txtMjesto; static TextAssist txtSvrha; static Text txtIznos; static Text txtNet; static Label sep; static Label lbl; static Label lblKategs; static Label lblDatum; static Label lblNet; static Label lblUkIznos; static Label lblMjesto; static Label lblIznos; static Label lblSvrha; static Label lblBrRata; static Label lblIznosU; static Label lblStatus; static Label lblStatus2; static Label lblStatus3; static Tray tray; static TrayItem trayItem; static DialogTray tray2; static ToolTip tip; static Button cmdGraph; static Button[] opt; static Button cmdSpremi; static Button cmdDEL; static Button cmdLogg; static Button cmdOper; static Button cmdExit; static Button cmdIspis; static Button cmdPrew; static Button cmdNext; static Button cmdExp; static Button chkAdmin; static ImageCombo cmbKategs; static kovaTable table; static TableColumn colSort; static TableColumn IDCol, svrhaCol, datumCol, mjestoCol, colTip, colPinTrans, colR, colG, colB, colIznos, colCateg; static private Listener listener; static Menu mnu; static Menu categMenu; static Menu fileMenuStat; static Menu menuBar, fileMenu, adminMenu; static MenuItem separ; static MenuItem tabFile, tabEdit, itemIspis, itemIzlaz, itemIzvoz, itemKategorije; static MenuItem tabStat, itemMonth, itemMonth2, itemYear; static MenuItem tabAdmin, itemBalance, itemPregLogg, itemPregErrLogg, itemPregOper, itemOpcije, itemBackup, itemRestore; static MenuItem itemC; static MenuItem itemSep; static Color red; static Color white; static Color gray; static Color black; static Color blueish; private static String[][] val; private static int iRed; private static boolean flgSort; static Listener armListener; static Listener showListener; static Listener hideListener; static DarkPanel p; static BlurredPanel p2; public mainFrame() { shell = new Shell(display, SWT.TITLE | SWT.MIN); display = shell.getDisplay(); shell = new Shell(display, SWT.TITLE | SWT.MIN); RSet.setOperIn(getgUserID()); // logger.logg(getLabel("logg5")); tip = new ToolTip(shell, SWT.BALLOON | SWT.ICON_INFORMATION); icona = new Image(display, "library/icons/boue.ico"); shell.setImage(icona); p = new DarkPanel(shell); p2 = new BlurredPanel(shell); red = display.getSystemColor(SWT.COLOR_RED); white = display.getSystemColor(SWT.COLOR_WHITE); black = display.getSystemColor(SWT.COLOR_BLACK); gray = display.getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW); blueish = (new Color(shell.getDisplay(), new RGB(191, 216, 255))); shell.setText(appName + " - " + appVer); shell.setBackground(white); if (login.getgPrava() == 2) { // admin prava flgAdmin = true; shell.setSize(520, 750); } else { flgAdmin = false; shell.setSize(520, 750); } CenterScreen(shell, display); shell.setLayout(layout); armListener = new Listener() { public void handleEvent(Event event) { MenuItem item = (MenuItem) event.widget; lblStatus.setText(item.getText()); lblStatus.update(); } }; showListener = new Listener() { public void handleEvent(Event event) { Menu menu = (Menu) event.widget; MenuItem item = menu.getParentItem(); if (item != null) { lblStatus.setText(item.getText()); lblStatus.update(); } } }; hideListener = new Listener() { public void handleEvent(Event event) { lblStatus.setText(""); lblStatus.update(); } }; shell.addListener(SWT.Close, new Listener() { public void handleEvent(final Event event) { p2.show(); boolean confirm = kovaDialog.isConfirmed(getLabel("mess26"), getLabel("mess26txt")); if (confirm == true) { System.exit(1); RSet.setOperOut(getgUserID()); // logger.logg(getLabel("logg6") + confirm); } else { event.doit = false; p2.hide(); } // int odg=ALERT.open(shell, "?", "Isključiti "+ appName // +" aplikaciju?", "Želite li izaći iz aplikacije?", // "Izlaz|Odustani", 0); // // boolean confirm = // kovaDialog.isConfirmed("Želite li izaći iz aplikacije?", // "Molim sačekajte prije izlaza!"); // if (confirm==true){ // System.exit(1); // RSet.setOperOut(getgUserID()); // logger.logg("Osoba izašla iz aplikacije, odabrano" + // confirm); // } // // // if (odg==0 || odg==-1){ // event.doit=true; // try { // System.runFinalization(); // } catch (Throwable e) { // e.printStackTrace(); // logger.loggErr("mainFrame " + e.getMessage()); // } // // RSet.setOperOut(getgUserID()); // logger.logg("Osoba izašla iz aplikacije"); // // }else{ // event.doit=false; // } // } } }); createWidgets(); // setLanguage(shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } // if (icona != null) // icona.dispose(); display.dispose(); } protected void finalize() throws Throwable { super.finalize(); // not necessary if extending Object. } // public static void main(String[] args) { // // new mainFrame(); // } // private void createWidgets() { optIndex = 1; menuBar = new Menu(shell, SWT.BAR); tabFile = new MenuItem(menuBar, SWT.CASCADE); tabFile.setText(getLabel("Application")); fileMenu = new Menu(shell, SWT.DROP_DOWN); fileMenu.addListener(SWT.Hide, hideListener); fileMenu.addListener(SWT.Show, showListener); itemKategorije = new MenuItem(fileMenu, SWT.PUSH); itemKategorije.setText(getLabel("Categories")); itemKategorije.addSelectionListener(new MenuItemListener()); itemKategorije.addListener(SWT.Arm, armListener); itemKategorije.addListener(SWT.Hide, hideListener); itemKategorije.addListener(SWT.Show, showListener); itemSep = new MenuItem(fileMenu, SWT.SEPARATOR); itemIspis = new MenuItem(fileMenu, SWT.PUSH); itemIspis.setText(getLabel("Print")); itemIspis.addSelectionListener(new MenuItemListener()); itemIspis.addListener(SWT.Arm, armListener); itemIspis.addListener(SWT.Hide, hideListener); itemIspis.addListener(SWT.Show, showListener); itemIzvoz = new MenuItem(fileMenu, SWT.CASCADE); itemIzvoz.setText(getLabel("Export")); itemIzvoz.addSelectionListener(new MenuItemListener()); itemIzvoz.addListener(SWT.Arm, armListener); itemIzvoz.addListener(SWT.Hide, hideListener); itemIzvoz.addListener(SWT.Show, showListener); itemSep = new MenuItem(fileMenu, SWT.SEPARATOR); itemIzlaz = new MenuItem(fileMenu, SWT.PUSH); itemIzlaz.setText(getLabel("Exit")); itemIzlaz.addSelectionListener(new MenuItemListener()); itemIzlaz.addListener(SWT.Arm, armListener); itemIzlaz.addListener(SWT.Hide, hideListener); itemIzlaz.addListener(SWT.Show, showListener); tabFile.setMenu(fileMenu); tabStat = new MenuItem(menuBar, SWT.CASCADE); tabStat.setText(getLabel("Stat")); tabStat.setData(""); fileMenuStat = new Menu(shell, SWT.DROP_DOWN); fileMenuStat.addListener(SWT.Hide, hideListener); fileMenuStat.addListener(SWT.Show, showListener); itemMonth = new MenuItem(fileMenuStat, SWT.PUSH); itemMonth.setText(getLabel("MonthStat1")); itemMonth.setData(""); itemMonth.addSelectionListener(new MenuItemListener()); itemMonth.addListener(SWT.Arm, armListener); itemMonth.addListener(SWT.Hide, hideListener); itemMonth.addListener(SWT.Show, showListener); itemMonth2 = new MenuItem(fileMenuStat, SWT.PUSH); itemMonth2.setText(getLabel("MonthStat2")); itemMonth2.addSelectionListener(new MenuItemListener()); itemMonth2.addListener(SWT.Arm, armListener); itemMonth2.addListener(SWT.Hide, hideListener); itemMonth2.addListener(SWT.Show, showListener); itemSep = new MenuItem(fileMenuStat, SWT.SEPARATOR); itemYear = new MenuItem(fileMenuStat, SWT.PUSH); itemYear.setText(getLabel("YearStat")); itemYear.addSelectionListener(new MenuItemListener()); itemYear.addListener(SWT.Arm, armListener); itemYear.addListener(SWT.Hide, hideListener); itemYear.addListener(SWT.Show, showListener); tabStat.setMenu(fileMenuStat); if (flgAdmin == true) { tabAdmin = new MenuItem(menuBar, SWT.CASCADE); tabAdmin.setText(getLabel("Admin")); adminMenu = new Menu(shell, SWT.DROP_DOWN); adminMenu.addListener(SWT.Hide, hideListener); adminMenu.addListener(SWT.Show, showListener); itemBalance = new MenuItem(adminMenu, SWT.PUSH); itemBalance.setText(getLabel("Balance")); itemBalance.addSelectionListener(new MenuItemListener()); itemBalance.addListener(SWT.Arm, armListener); itemBalance.addListener(SWT.Hide, hideListener); itemBalance.addListener(SWT.Show, showListener); itemSep = new MenuItem(adminMenu, SWT.SEPARATOR); itemPregLogg = new MenuItem(adminMenu, SWT.PUSH); itemPregLogg.setText(getLabel("LogPrew")); itemPregLogg.addSelectionListener(new MenuItemListener()); itemPregLogg.addListener(SWT.Arm, armListener); itemPregLogg.addListener(SWT.Hide, hideListener); itemPregLogg.addListener(SWT.Show, showListener); itemPregErrLogg = new MenuItem(adminMenu, SWT.PUSH); itemPregErrLogg.setText(getLabel("LogErrPrew")); itemPregErrLogg.addSelectionListener(new MenuItemListener()); itemPregErrLogg.addListener(SWT.Arm, armListener); itemPregErrLogg.addListener(SWT.Hide, hideListener); itemPregErrLogg.addListener(SWT.Show, showListener); itemSep = new MenuItem(adminMenu, SWT.SEPARATOR); itemPregOper = new MenuItem(adminMenu, SWT.PUSH); itemPregOper.setText(getLabel("Oper")); itemPregOper.addSelectionListener(new MenuItemListener()); itemPregOper.addListener(SWT.Arm, armListener); itemPregOper.addListener(SWT.Hide, hideListener); itemPregOper.addListener(SWT.Show, showListener); itemSep = new MenuItem(adminMenu, SWT.SEPARATOR); itemOpcije = new MenuItem(adminMenu, SWT.PUSH); itemOpcije.setText(getLabel("Option")); itemOpcije.addSelectionListener(new MenuItemListener()); itemOpcije.addListener(SWT.Arm, armListener); itemOpcije.addListener(SWT.Hide, hideListener); itemOpcije.addListener(SWT.Show, showListener); tabAdmin.setMenu(adminMenu); itemSep = new MenuItem(adminMenu, SWT.SEPARATOR); itemBackup = new MenuItem(adminMenu, SWT.PUSH); itemBackup.setText(getLabel("Backup")); itemBackup.addSelectionListener(new MenuItemListener()); itemBackup.addListener(SWT.Arm, armListener); itemBackup.addListener(SWT.Hide, hideListener); itemBackup.addListener(SWT.Show, showListener); itemRestore = new MenuItem(adminMenu, SWT.PUSH); itemRestore.setText(getLabel("Restore")); itemRestore.addSelectionListener(new MenuItemListener()); itemRestore.addListener(SWT.Arm, armListener); itemRestore.addListener(SWT.Hide, hideListener); itemRestore.addListener(SWT.Show, showListener); } tabHelp = new MenuItem(menuBar, SWT.CASCADE); tabHelp.setText(getLabel("help")); helpMenu = new Menu(shell, SWT.DROP_DOWN); helpMenu.addListener(SWT.Hide, hideListener); helpMenu.addListener(SWT.Show, showListener); itemAppLogg = new MenuItem(helpMenu, SWT.PUSH); itemAppLogg.setText(getLabel("appLogg")); itemAppLogg.addSelectionListener(new MenuItemListener()); itemAppLogg.addListener(SWT.Arm, armListener); itemAppLogg.addListener(SWT.Hide, hideListener); itemAppLogg.addListener(SWT.Show, showListener); itemSep = new MenuItem(helpMenu, SWT.SEPARATOR); itemAbout = new MenuItem(helpMenu, SWT.PUSH); itemAbout.setText(getLabel("about")); itemAbout.addSelectionListener(new MenuItemListener()); itemAbout.addListener(SWT.Arm, armListener); itemAbout.addListener(SWT.Hide, hideListener); itemAbout.addListener(SWT.Show, showListener); itemSep = new MenuItem(helpMenu, SWT.SEPARATOR); itemManual = new MenuItem(helpMenu, SWT.PUSH); itemManual.setText(getLabel("manual")); itemManual.addSelectionListener(new MenuItemListener()); itemManual.addListener(SWT.Arm, armListener); itemManual.addListener(SWT.Hide, hideListener); itemManual.addListener(SWT.Show, showListener); tabHelp.setMenu(helpMenu); shell.setMenuBar(menuBar); group = new Group(shell, SWT.None); group.setText(getLabel("GR1")); group.setBackground(white); group.setForeground(display.getSystemColor(SWT.COLOR_BLUE)); group.setLayoutData("width 500, wrap"); group.setLayout(layout2); // comp = new Composite(group, SWT.None); comp.setBackground(white); comp.setLayout(layoutComp); comp.setData("COMP"); comp2 = new Composite(group, SWT.None); comp2.setBackground(white); comp2.setLayout(layoutComp); comp2.setData("COMP2"); // // listener = new Listener() { public void handleEvent(Event e) { Button bt = (Button) e.widget; for (int i = 0; i < 4; i++) { if (bt.equals(opt[i])) { optIndex = i; break; } } switch (optIndex) { case 0: iznNeg = 0; iznNeg = getReal(txtIznos.getText()); iznNeg = Math.abs(iznNeg); txtIznos.setText(String.valueOf(iznNeg)); txtIznos.setText(FormatCur(txtIznos.getText())); lblBrRata.setVisible(false); txtBrRata.setVisible(false); lblIznosU.setVisible(false); txtUkupRata.setVisible(false); txtMjesto.setSize(260, 20); lblNet.setVisible(false); txtNet.setVisible(false); break; case 1: iznNeg = 0; iznNeg = Math.abs(getReal(txtIznos.getText())); iznNeg = (iznNeg * -1); txtIznos.setText(String.valueOf(iznNeg)); txtIznos.setText(FormatCur(txtIznos.getText())); lblBrRata.setVisible(false); txtBrRata.setVisible(false); lblIznosU.setVisible(false); txtUkupRata.setVisible(false); txtMjesto.setSize(260, 20); lblNet.setVisible(false); txtNet.setVisible(false); break; case 2: iznNeg = 0; iznNeg = Math.abs(getReal(txtIznos.getText())); iznNeg = (iznNeg * -1); txtIznos.setText(String.valueOf(iznNeg)); txtIznos.setText(FormatCur(txtIznos.getText())); String sUK = String.valueOf(Round( getReal(txtIznos.getText()) / getReal(txtBrRata.getText()), 2)); txtUkupRata.setText(FormatCur(sUK)); lblBrRata.setVisible(true); txtBrRata.setVisible(true); lblIznosU.setVisible(true); txtUkupRata.setVisible(true); lblNet.setVisible(false); txtNet.setVisible(false); txtMjesto.setSize(260, 20); break; case 3: iznNeg = 0; iznNeg = Math.abs(getReal(txtIznos.getText())); iznNeg = (iznNeg * -1); txtIznos.setText(String.valueOf(iznNeg)); txtIznos.setText(FormatCur(txtIznos.getText())); txtMjesto.setSize(170, 20); txtMjesto.setRedraw(true); lblNet.setLocation(270, 90); lblNet.setVisible(true); txtNet.setLocation(300, 88); txtNet.setVisible(true); lblBrRata.setVisible(false); txtBrRata.setVisible(false); lblIznosU.setVisible(false); txtUkupRata.setVisible(false); break; } } }; String optText[] = { "Prihodi", "Rashodi", "Rate", "NetBanking" }; opt = new Button[4]; for (int i = 0; i < opt.length; i++) { opt[i] = new Button(comp, SWT.RADIO); opt[i].setText(getLabel("opt" + i)); opt[i].setLayoutData("width 30px"); opt[i].setBackground(white); opt[i].addListener(SWT.Selection, listener); } opt[0].setLayoutData("split 4"); opt[3].setLayoutData("wrap"); opt[1].setSelection(true); sep = new Label(comp, SWT.SEPARATOR | SWT.SHADOW_IN | SWT.HORIZONTAL); sep.setLayoutData("width 400px,wrap"); sep.setData("SEP"); lblKategs = new Label(comp, SWT.NONE); lblKategs.setText(getLabel("lblKategs")); lblKategs.setData(""); lblKategs.setLayoutData("width 70px,split 2,gapleft 2px"); lblKategs.setBackground(white); cmbKategs = new ImageCombo(comp, SWT.READ_ONLY | SWT.BORDER); cmbKategs.setLayoutData("width 150px,gapleft 5px,wrap"); fillKategs(); lblDatum = new Label(comp, SWT.NONE); lblDatum.setText(getLabel("lblDatum")); lblDatum.setLayoutData("width 70px,split2,gapright 6px,gapleft 2px"); lblDatum.setBackground(white); dtp = new DateTime(comp, SWT.DATE | SWT.DROP_DOWN); dtp.setLayoutData("width 100px"); dtp.setDate(getToday().getYear(), getToday().getMonth(), getToday() .getDay()); dtp.setMonth(getToday().getMonth()); dtp.setYear(getToday().getYear()); dtp.addSelectionListener(this); dtp.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: dtp2.setDate(dtp.getYear(), dtp.getMonth(), dtp.getDay()); datum = dtp.getYear() + "-" + dtp.getMonth() + "-" + dtp.getDay(); freshTable(); break; } } }); // samo za NetBanking lblNet = new Label(comp, SWT.NONE); lblNet.setText(getLabel("lblNet")); lblNet.setLayoutData("width 30px"); lblNet.setBackground(white); lblNet.setVisible(false); txtNet = new Text(comp, SWT.BORDER); txtNet.setTextLimit(11); txtNet.setLayoutData("width 75px,wrap"); txtNet.addFocusListener(this); txtNet.addKeyListener(this); txtNet.setVisible(false); lblMjesto = new Label(comp, SWT.NONE); lblMjesto.setText(getLabel("lblMjesto")); lblMjesto .setLayoutData("width 70px,split2,gapright 6px,gapleft 2px,span2"); lblMjesto.setBackground(white); rs = RSet .openRS("select distinct mjesto from racuni where Mjesto is not null "); lista = new ArrayList<String>(); int i = 0; try { while (rs.next()) { lista.add(rs.getString("mjesto")); i++; } } catch (SQLException e2) { e2.printStackTrace(); kovaDialog.showException(e2); } contentProvider = new TextAssistContentProvider() { // private final String[] EUROZONE = new String[] { // "Austria","Albanija","Australija","Amerika","Azerbejđan","Argentina","BIH","Belgium", // "Cyprus", "Estonia", "Finland", "France", "Germany", "Greece", // "Ireland", "Italy", "Luxembourg", "Malta", "Netherlands", // "Portugal", "Slovakia", "Slovenia", "Spain" }; @Override public List<String> getContent(final String entry) { List<String> returnedList = new ArrayList<String>(); for (String country : lista) { if (country.toLowerCase().startsWith(entry.toLowerCase())) { returnedList.add(country); } } return returnedList; } }; txtMjesto = new TextAssist(comp, SWT.BORDER, contentProvider); // txtMjesto // = new // Text // (comp, // SWT.BORDER); txtMjesto.setTextLimit(50); txtMjesto.setLayoutData("width 290px,wrap"); // txtMjesto.addFocusListener(this); // txtMjesto.addKeyListener(this); lblSvrha = new Label(comp, SWT.NONE); lblSvrha.setText(getLabel("lblSvrha")); lblSvrha.setLayoutData("width 62px,split2,gapright 14px,gapleft 2px,span"); lblSvrha.setBackground(white); rs = RSet .openRS("select distinct svrha from racuni where svrha is not null "); lista2 = new ArrayList<String>(); try { while (rs.next()) { lista2.add(rs.getString("svrha")); } } catch (SQLException e2) { e2.printStackTrace(); kovaDialog.showException(e2); } contentProvider = new TextAssistContentProvider() { // private final String[] EUROZONE = new String[] { // "Austria","Albanija","Australija","Amerika","Azerbejđan","Argentina","BIH","Belgium", // "Cyprus", "Estonia", "Finland", "France", "Germany", "Greece", // "Ireland", "Italy", "Luxembourg", "Malta", "Netherlands", // "Portugal", "Slovakia", "Slovenia", "Spain" }; @Override public List<String> getContent(final String entry) { List<String> returnedList = new ArrayList<String>(); for (String country : lista2) { if (country.toLowerCase().startsWith(entry.toLowerCase())) { returnedList.add(country); } } return returnedList; } }; txtSvrha = new TextAssist(comp, SWT.SINGLE | SWT.BORDER, contentProvider); txtSvrha.setTextLimit(50); txtSvrha.setLayoutData("width 290px,wrap"); // txtSvrha.addFocusListener(this); // txtSvrha.addKeyListener(this); lblIznos = new Label(comp, SWT.NONE); lblIznos.setText(getLabel("lblIznos")); lblIznos.setLayoutData("width 61px,split6,gapright 15px,gapleft 2px,span"); lblIznos.setBackground(white); txtIznos = new Text(comp, SWT.BORDER | SWT.RIGHT); txtIznos.setText("0,00"); txtIznos.setTextLimit(15); txtIznos.setLayoutData("width 85px,span"); txtIznos.addFocusListener(this); txtIznos.addKeyListener(this); txtIznos.addVerifyListener(this); // samo za rate... // ---------------------------------------------------------------------------------// lblBrRata = new Label(comp, SWT.NONE); lblBrRata.setText(getLabel("lblBrRata")); lblBrRata.setLayoutData("width 22px"); lblBrRata.setBackground(white); lblBrRata.setVisible(false); txtBrRata = new Text(comp, SWT.BORDER); txtBrRata.setTextLimit(3); txtBrRata.setText("12"); txtBrRata.setVisible(false); txtBrRata.addFocusListener(this); txtBrRata.addKeyListener(this); txtBrRata.addVerifyListener(this); lblIznosU = new Label(comp, SWT.NONE); lblIznosU.setText(getLabel("lblIznosU")); lblIznosU.setLayoutData("width 75px,split2,gapright 2px"); lblIznosU.setBackground(white); lblIznosU.setVisible(false); txtUkupRata = new Text(comp, SWT.BORDER | SWT.RIGHT | SWT.READ_ONLY); txtUkupRata.setLayoutData("width 65px,span,wrap"); txtUkupRata.setText("0,00"); txtUkupRata.setVisible(false); txtUkupRata.addFocusListener(this); txtUkupRata.addKeyListener(this); txtUkupRata.addVerifyListener(this); // ---------------------------------------------------------------------------------// sep = new Label(comp, SWT.SEPARATOR | SWT.SHADOW_IN | SWT.HORIZONTAL); sep.setData("sep2"); sep.setLayoutData("width 400px,wrap"); // final Image icoSpremi= new Image(display,"library/icons/Save24.ico"); cmdSpremi = new Button(comp, SWT.PUSH); cmdSpremi.setText(getLabel("cmdSpremi")); cmdSpremi.setLayoutData("width 105px,split 2"); cmdSpremi.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { } }); cmdSpremi.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: int rateID = 0; if (checkValues() == true) { if (optIndex == 2) { int god = dtp.getYear(); int mj = dtp.getMonth(); int dan = dtp.getDay(); String datum; rs = RSet.openRS("select max(id)as Uk from racuni"); try { while (rs.next()) { rateID = rs.getInt("uk"); } } catch (SQLException e1) { e1.printStackTrace(); // logger.loggErr("mainFrame " + // e1.getMessage()); kovaDialog.showException(e1); } RSet.closeAll(); for (int i = 0; i < Integer.parseInt(txtBrRata .getText()); i++) { if (mj == 12) { god += 1; mj = 1; datum = god + "-" + mj + "-" + dtp.getDay(); } else { mj += 1; datum = god + "-" + mj + "-" + dtp.getDay(); } String col = "datum,mjesto,svrha,iznos,tip,PINtrans,oper,rateID,kategorija"; String val = "'" + datum + "','" + txtMjesto.getText() + "','" + txtSvrha.getText() + " " + (i + 1) + ".rata" + "','" + getReal(txtUkupRata.getText()) + "'," + optIndex + ",'" + iNull(txtNet.getText() + "','" + getgUserID() + "'," + rateID + ",0"); RSet.addRS2(sTablica, col, val); logger.logg(getLabel("logg7") + " " + sTablica); gBroj = 0; } } else { int categ = 0; rs = RSet.openRS("select id,name from categories"); try { while (rs.next()) { if (cmbKategs.getText().equalsIgnoreCase( rs.getString("name"))) { categ = rs.getInt("id"); break; } } rs.close(); } catch (SQLException e2) { e2.printStackTrace(); kovaDialog.showException(e2); } String col = "datum,mjesto,svrha,iznos,tip,PINtrans,oper,rateID,kategorija"; String val = "'" + dtp.getYear() + "-" + (dtp.getMonth() + 1) + "-" + dtp.getDay() + "','" + txtMjesto.getText() + "','" + txtSvrha.getText() + "','" + getReal(txtIznos.getText()) + "'," + optIndex + ",'" + iNull(txtNet.getText() + "','" + getgUserID() + "'," + rateID + "," + categ); RSet.addRS2(sTablica, col, val); logger.logg(getLabel("logg8") + " " + sTablica); gBroj = 0; // RSet.setDefaultBase(); // ResultSet rs=RSet.openRS(SQLquery + // "order by ID desc limit 1"); // System.out.println(SQLquery + // "order by ID desc limit 1"); // final TableItem created = // table.insertItem(SWT.NONE,table.fillVal2(rs)); // table.setSelection(created); // // freshTable(); } dtp.setDate(getToday().getYear(), getToday().getMonth(), getToday().getDay()); dtp2.setMonth(dtp.getMonth()); dtp2.setYear(dtp.getYear()); txtMjesto.setText(""); txtIznos.setText("0,00"); txtSvrha.setText(""); txtBrRata.setText("12"); txtNet.setText(""); cmbKategs.select(0); // ALERT.open(shell, "i", "Unos podataka...", // "Vrijednosti uspješno unešene!", "Nastavak",0); kovaDialog.inform(getLabel("mess25"), getLabel("mess25txt")); } else { kovaDialog.inform(getLabel("mess27"), getLabel("mess27txt")); // ALERT.open(shell, "!", "Unos podataka...", // "Nisu popunjena sva potrebna polja!", "Nastavak",0); } } } }); cmdDEL = new Button(comp, SWT.PUSH); cmdDEL.setText(getLabel("cmdDEL")); cmdDEL.setLayoutData("width 105px,span 2"); cmdDEL.setEnabled(false); cmdDEL.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { int tip = Integer.parseInt(getColVal(5)); if (tip == 2) { // int odg = // ALERT.open(shell,"?","Brisanje?","Želite li obrisati rate?","Sve rate|Jednu ratu|Odustani",2); int odg = kovaDialog.choice(getLabel("mess28"), "", 1, new ChoiceItem(getLabel("ch281"), getLabel("ch2812")), new ChoiceItem( getLabel("ch282"), getLabel("ch2822")), new ChoiceItem(getLabel("ch283"), getLabel("ch2832"))); int rateBr = 0; switch (odg) { case 0: // sve rate rs = RSet.openRS("select max(id)as Uk from racuni"); try { while (rs.next()) { rateBr = rs.getInt("uk"); } } catch (SQLException e1) { e1.printStackTrace(); logger.loggErr("mainFrame " + e1.getMessage()); kovaDialog.showException(e1); } RSet.closeAll(); RSet.deleteRS(rateBr, sTablica, "rateID"); freshTable(); break; case 1: // jednu ratu RSet.deleteRSid(IDbroj, sTablica); freshTable(); break; case 2: // odustani break; } } else { // int odg = // ALERT.open(shell,"?","Brisanje?","Molimo potvrdite brisanje!", // "Obriši|Odustani", 1); // final boolean confirm = // kovaDialog.isConfirmed("Želite li obrisati stavku pod rednim brojem "+ // IDbroj + "?",="Mjesto: <b>"+ iNull(getColVal(3)) + // "</b><br/> Svrha: <b>" + iNull(getColVal(4))+ // "</b><br/>Iznos: <b>"+ FormatCur(iNull0(getColVal(10)))+ // "</b><br/>" ); final boolean confirm = kovaDialog.isConfirmed( getLabel("mess1N"), getLabel("mess1T")); if (confirm == true) { RSet.deleteRSid(IDbroj, sTablica); freshTable(); cmdDEL.setEnabled(false); logger.logg(getLabel("logg9") + " " + IDbroj + "!"); } else { cmdDEL.setEnabled(false); } } } }); // *****************************TABLICA******************************// group2 = new Group(shell, SWT.None); group2.setText(getLabel("GR2")); group2.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); group2.setLayoutData("span,wrap"); group2.setForeground(display.getSystemColor(SWT.COLOR_BLUE)); group2.setLayout(layout3); // ************************************kreiranje // tablice********************************************// cmdPrew = new Button(group2, SWT.PUSH); cmdPrew.setText(getLabel("cmdPrew")); cmdPrew.setLayoutData("width 100px,split 3"); cmdPrew.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { if (dtp2.getMonth() == 0) { dtp2.setDate(dtp2.getYear() - 1, 11, dtp2.getDay()); dtp.setDate(dtp2.getYear(), 11, dtp2.getDay()); freshTable(); } else { dtp2.setDate(dtp2.getYear(), dtp2.getMonth() - 1, dtp2.getDay()); dtp.setDate(dtp.getYear(), dtp2.getMonth(), dtp2.getDay()); freshTable(); } } }); dtp2 = new DateTime(group2, SWT.DATE | SWT.SHORT | SWT.BORDER); dtp2.setForeground(display.getSystemColor(SWT.COLOR_BLUE)); dtp2.setBackground(display.getSystemColor(SWT.COLOR_BLUE)); dtp2.setLayoutData("width 265px"); dtp2.setData("DTP2"); dtp2.setDay(getToday().getDay()); dtp2.setMonth(getToday().getMonth()); dtp2.setYear(getToday().getYear()); dtp2.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: dtp.setDay(dtp.getDay()); dtp.setMonth(dtp2.getMonth()); dtp.setYear(dtp2.getYear()); datum = dtp.getYear() + "-" + dtp.getMonth() + "-" + dtp.getDay(); freshTable(); break; } } }); cmdNext = new Button(group2, SWT.PUSH); cmdNext.setText(getLabel("cmdNext")); cmdNext.setLayoutData("width 100px,wrap"); cmdNext.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { if (dtp2.getMonth() == 11) { dtp2.setDate(dtp2.getYear() + 1, 0, dtp2.getDay()); dtp.setDate(dtp2.getYear(), 0, dtp2.getDay()); freshTable(); } else { dtp2.setDate(dtp2.getYear(), dtp2.getMonth() + 1, dtp2.getDay()); dtp.setDate(dtp2.getYear(), dtp2.getMonth(), dtp2.getDay()); freshTable(); } } }); table = fillKovaTable(group2); makePopUp(); lblUkIznos = new Label(group2, SWT.RIGHT); lblUkIznos.setLayoutData("width 120px,span,gapleft 340"); lblUkIznos.setBackground(white); lblFast = new Label(group2, SWT.NONE); lblFast.setText(getLabel("lblFast")); lblFast.setLayoutData("width 70px,split 2"); lblFast.setBackground(white); table.createSearchField(group2, SWT.BORDER).setLayoutData("growx,wrap"); table.contentTable.addMouseListener(this); table.contentTable.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { if (table.contentTable.getSelectionIndex() != -1) { IDbroj = Integer.parseInt(table.getItem( table.contentTable.getSelectionIndex()).getText(1)); cmdDEL.setEnabled(true); } else { IDbroj = 0; cmdDEL.setEnabled(false); } } }); colCateg = table.getColumn(0); colCateg.setData(""); colCateg.setWidth(15); colCateg.addSelectionListener(this); colCateg.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { colSort = table.getColumn(0); setSort(); table.applyFilter(); } }); IDCol = table.getColumn(1); IDCol.setText(getLabel("IDCol")); IDCol.setWidth(50); IDCol.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { colSort = table.getColumn(1); setSort(); table.applyFilter(); } }); datumCol = table.getColumn(2); datumCol.setText(getLabel("datumCol")); datumCol.setWidth(70); datumCol.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { colSort = datumCol; setSort(); table.applyFilter(); } }); mjestoCol = table.getColumn(3); mjestoCol.setText(getLabel("mjestoCol")); mjestoCol.setWidth(120); mjestoCol.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { colSort = table.getColumn(3); setSort(); table.applyFilter(); } }); svrhaCol = table.getColumn(4); svrhaCol.setText(getLabel("svrhaCol")); svrhaCol.setWidth(145); svrhaCol.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { colSort = table.getColumn(4); setSort(); table.applyFilter(); } }); colTip = table.getColumn(5); colTip.setData("COL6"); colTip.setWidth(0); colPinTrans = table.getColumn(6); colPinTrans.setData("COL7"); colPinTrans.setWidth(0); colR = table.getColumn(7); colR.setData("COL8"); colR.setWidth(0); colG = table.getColumn(8); colG.setData("COL9"); colG.setWidth(0); colB = table.getColumn(9); colB.setData("COL10"); colB.setWidth(0); colIznos = table.getColumn(10); colIznos.setText(getLabel("colIznos")); colIznos.setWidth(70); colIznos.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { colSort = table.getColumn(10); setSort(); table.applyFilter(); } }); table.setLayoutData("width 470px,height 300px,span"); table.setEditable(false, 1, 2, 3); table.addColorListener(new Listener() { public void handleEvent(final Event event) { for (TableItem item : table.getItems()) { applyColors(item); } } }); for (TableItem cIznos : table.getItems()) { double iznos = Double.parseDouble(cIznos.getText(10)); ukIznos = ukIznos + iznos; } if (ukIznos < 0) { lblUkIznos.setForeground(display.getSystemColor(SWT.COLOR_RED)); } else { lblUkIznos.setForeground(display .getSystemColor(SWT.COLOR_DARK_GREEN)); } lblUkIznos.setText(FormatCur(String.valueOf(Round(ukIznos, 2)))); // initial coloring for (TableItem singleItem : table.getItems()) { applyColors(singleItem); } cmdIspis = new Button(group2, SWT.PUSH); cmdIspis.setText(getLabel("cmdIspis")); cmdIspis.setLayoutData("width 105px,split 4"); cmdIspis.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { p2.show(); JasperTest.ispis(getLabel("mess29") + (dtp.getMonth() + 1) + "/" + dtp.getYear(), RSet.getOsoba(getgUserID()), SQLquery, 0); // new Categories(); p2.hide(); } }); cmdExp = new Button(group2, SWT.PUSH); cmdExp.setText(getLabel("cmdExp")); cmdExp.setLayoutData("width 105px"); cmdExp.addListener(SWT.Selection, new Listener() { private String fileName; public void handleEvent(Event e) { p2.show(); String filePath = ""; filePath = saveDialog.open(shell); fileName = saveDialog.getFileName(); if (iNull(filePath) != "") { if (fileExists(filePath) == true) { // int odg = // ALERT.open(shell,"i","Izvoz datoteke!","Datoteka \""+ // saveDialog.getFilePath()+ // "\" već postoji!\nŽelite li presnimiti datoteku!","Presnimi|Odustani", // 0); int odg = ALERT .show(getLabel("mess2N"), "?", getLabel("mess2T") + " " + saveDialog.getFilePath() + "\"", OpalDialogType.OK_CANCEL, "", ""); //$NON-NLS-7$ if (odg == 0) { if (iNull(filePath) != "") { JasperTest.export( getLabel("mess29") + (dtp.getMonth() + 1) + "/" + dtp.getYear(), RSet.getOsoba(getgUserID()), SQLquery, 0, saveDialog.getFileType(), filePath, fileName); } p2.hide(); } else { p2.hide(); } } else { if (iNull(filePath) != "") { JasperTest.export( getLabel("mess30") + (dtp.getMonth() + 1) + "/" + dtp.getYear(), RSet.getOsoba(getgUserID()), SQLquery, 0, saveDialog.getFileType(), filePath, fileName); // ALERT.open(shell, "i", appName +" - " // + "Izvoz datoteke...", "Izvoz datoteka \"" // + fileName + "\" uspješno izvršen!", // "Nastavak", 0); kovaDialog.inform(appName + " - " + getLabel("mess31"), getLabel("mess32") + fileName + getLabel("mess33")); p2.hide(); } p2.hide(); } p2.hide(); } p2.hide(); } }); // lblStatus = new Label(shell,SWT.NONE); // lblStatus.setBackground(display.getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT)); // lblStatus.setLayoutData("south,width " + shell.getBounds().width // +",top "+ shell.getBounds().height); compStatus = new Composite(shell, SWT.NONE); compStatus.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); compStatus.setLayout(layoutStatus); compStatus.setLayoutData("south,width " + (shell.getBounds().width) + ",top " + shell.getBounds().height + ",split 4"); lblStatus = new Label(compStatus, SWT.NONE); lblStatus.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); lblStatus.setLayoutData("width 240"); lblStatusIcon = new Label(compStatus, SWT.NONE); lblStatusIcon.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); lblStatusIcon.setLayoutData("width 10"); // lblStatusIcon.setImage(createIcon(blueish)); // lblStatusIcon.setImage(new // Image(display,"library/icons/Public.ico")); lblStatus2 = new Label(compStatus, SWT.NONE); lblStatus2.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); lblStatus2.setLayoutData("width 90,center"); lblStatus2.setText(RSet.getOsoba(getgUserID())); lblStatusIcon = new Label(compStatus, SWT.NONE); lblStatusIcon.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); lblStatusIcon.setLayoutData("width 10"); // lblStatusIcon.setImage(createIcon(blueish)); // lblStatusIcon.setImage(new // Image(display,"library/icons/Calendar.ico")); lblStatus3 = new Label(compStatus, SWT.NONE); lblStatus3.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); lblStatus3.setLayoutData("width 100"); // lblStatus3.setText(RSet.getOsoba(getgUserID())); lblStatus3.setText(sdf.format(new Date(System.currentTimeMillis()))); final int time = 1000; Runnable timer = new Runnable() { public void run() { lblStatus3.setText(sdf.format(new Date(System .currentTimeMillis()))); display.timerExec(time, this); } }; display.timerExec(time, timer); Image image = null; String sPrava; switch (login.getgPrava()) { case 0: sPrava = getLabel("RIGHTS0"); break; case 1: sPrava = getLabel("RIGHTS1"); break; case 2: sPrava = getLabel("RIGHTS2"); break; case 3: sPrava = getLabel("RIGHTS3"); break; default: sPrava = getLabel("RIGHTS0"); break; } final ToolTip tip = new ToolTip(shell, SWT.BALLOON | SWT.ICON_INFORMATION); tip.setMessage(getLabel("welcome2") + " " + RSet.getOsoba(getgUserID()) + " " + getLabel("welcome3") + " " + appName + " " + getLabel("welcome4") + appVer + "\n " + getLabel("welcome5") + RSet.getSQLDBase() + "\n " + getLabel("welcome6") + getDate() + "\n " + getLabel("welcome7") + sPrava); tray = display.getSystemTray(); if (tray != null) { TrayItem item = new TrayItem(display.getSystemTray(), SWT.NONE); // image = new Image(display, "library/icons/boue.ico"); item.setImage(image); tip.setText(appName + "..."); item.setToolTip(tip); final Menu menu = new Menu(shell, SWT.POP_UP); MenuItem mi = new MenuItem(menu, SWT.PUSH); mi.setText(getLabel("notif")); // MenuItem sep = new MenuItem(menu, SWT.SEPARATOR); MenuItem mi2 = new MenuItem(menu, SWT.PUSH); mi2.setText(getLabel("notif2")); item.addListener(SWT.MenuDetect, new Listener() { public void handleEvent(Event event) { menu.setVisible(true); } }); item.addListener(SWT.Show, new Listener() { public void handleEvent(Event event) { } }); item.addListener(SWT.Hide, new Listener() { public void handleEvent(Event event) { } }); item.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { } }); } else { tip.setText("Notification from anywhere"); tip.setLocation(400, 400); } tip.setVisible(true); } private static void freshTable() { String EOMdate = getEOM(dtp.getYear(), dtp.getMonth(), dtp.getDay()); SQLquery = "select C.name,R.ID,R.Datum,R.Mjesto,R.Svrha,R.Tip,R.pintrans,C.R,C.G,C.B,R.Iznos from racuni R left OUTER JOIN " + " categories C on R.kategorija=C.ID" + " where R.datum between " + "'" + dtp.getYear() + "-" + (dtp.getMonth() + 1) + "-1' and '" + EOMdate + "' "; // + System.out.println(SQLquery); rs = RSet.openRS(SQLquery); val = kovaTable.fillVal(rs); table.resetValues(kovaTable.fillVal(rs)); if (flgSort == true) { table.lastDescendingColumn = null; } else { table.lastDescendingColumn = colSort; } fillKategs(); table.sortTable(colSort); table.applyFilter(); // // sum ukIznos = 0; for (TableItem cIznos : table.getItems()) { double iznos = Double.parseDouble(cIznos.getText(10)); ukIznos = ukIznos + iznos; ukIznos = Round(ukIznos, 2); } if (ukIznos < 0) { lblUkIznos.setForeground(display.getSystemColor(SWT.COLOR_RED)); } else { lblUkIznos.setForeground(display .getSystemColor(SWT.COLOR_DARK_GREEN)); } lblUkIznos.setText(FormatCur(String.valueOf(ukIznos))); cmdDEL.setEnabled(false); } // uređivanje boja i uvjeta za bojanje static void applyColors(final TableItem target) { if (Double.parseDouble(target.getText(10)) > 0) { target.setForeground(target.getDisplay().getSystemColor( SWT.COLOR_DARK_GREEN)); } if (iRed == 0) { if (target.getText(7) != "") { try { icon = createIcon(new Color(shell.getDisplay(), new RGB( Integer.parseInt(target.getText(7)), Integer.parseInt(target.getText(8)), Integer.parseInt(target.getText(9))))); } catch (Exception e) { e.printStackTrace(); logger.loggErr("mainFrame " + e.getMessage()); kovaDialog.showException(e); } target.setImage(0, icon); } else { target.setText(""); } target.setBackground(white); iRed = 1; } else { if (target.getText(7) != "") { icon = createIcon(new Color(shell.getDisplay(), new RGB( Integer.parseInt(target.getText(7)), Integer.parseInt(target.getText(8)), Integer.parseInt(target.getText(9))))); target.setImage(0, icon); } else { target.setText(""); } target.setBackground(blueish); iRed = 0; } } @Override public void focusGained(FocusEvent e) { if (e.widget instanceof Text) { Text t = (Text) e.widget; t.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); t.selectAll(); // }else if (e.widget instanceof TextAssist){ // Text ta = (Text) e.widget; // ta.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); // ta.selectAll (); } else if (e.widget instanceof kovaTable) { } } @Override public void focusLost(FocusEvent e) { String UK = "0,00"; if (e.widget instanceof Text) { Text t = (Text) e.widget; t.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); if (e.widget == txtIznos || e.widget == txtBrRata) { if (optIndex == 2) { UK = String.valueOf(Round(getReal(txtIznos.getText()) / getReal(txtBrRata.getText()), 2)); } else if (optIndex != 0 && e.widget == txtIznos) { iznNeg = 0; iznNeg = Math.abs(getReal(txtIznos.getText())); iznNeg = (iznNeg * -1); txtIznos.setText(String.valueOf(iznNeg)); } else if (optIndex == 0 && e.widget == txtIznos) { iznNeg = 0; iznNeg = Math.abs(getReal(txtIznos.getText())); iznNeg = Math.abs(iznNeg); txtIznos.setText(String.valueOf(iznNeg)); } txtIznos.setText(FormatCur(txtIznos.getText())); txtUkupRata.setText(FormatCur(UK)); } // }else if (e.widget instanceof TextAssist){ // Text ta = (Text) e.widget; // ta.setBackground(display.getSystemColor(SWT.COLOR_WHITE)); } else if (e.widget instanceof Table) { Table tbl = (Table) e.widget; cmdDEL.setEnabled(false); } } public void keyPressed(KeyEvent e) { if (e.widget instanceof Text) { Text t = (Text) e.widget; if (e.keyCode == 16777218) {// dolje t.traverse(SWT.TRAVERSE_TAB_NEXT); } else if (e.keyCode == 16777217) {// gore t.traverse(SWT.TRAVERSE_TAB_PREVIOUS); } // }else if (e.widget instanceof TextAssist){ // TextAssist ta = (TextAssist) e.widget; // // if (e.keyCode==16777218){//dolje // System.out.println("dolje"); // ta.traverse(SWT.TRAVERSE_TAB_NEXT); // }else if (e.keyCode==16777217){//gore // System.out.println("gore"); // ta.traverse(SWT.TRAVERSE_TAB_PREVIOUS); // } } else if (e.widget instanceof Table) { Table tbl = (Table) e.widget; } } // @Override // public void keyReleased(KeyEvent e) { // if(e.widget==txtSvrha) // setAutoCompletion(txtSvrha,"svrha","racuni"); // // // if(e.widget==txtMjesto) // // setAutoCompletion(txtMjesto,"mjesto","racuni"); // } @Override public void verifyText(VerifyEvent e) { // iznos if (e.widget == txtIznos || e.widget == txtUkupRata) { String string = e.text; char[] chars = new char[string.length()]; string.getChars(0, chars.length, chars, 0); for (int i = 0; i < chars.length; i++) { if (!('0' <= chars[i] && chars[i] <= '9' || '.' == chars[i] || '-' == chars[i] || ',' == chars[i])) e.doit = false; return; } } else if (e.widget == txtBrRata) { String string = e.text; char[] chars = new char[string.length()]; string.getChars(0, chars.length, chars, 0); for (int i = 0; i < chars.length; i++) { if (!('0' <= chars[i] && chars[i] <= '9')) e.doit = false; return; } } } private static boolean checkValues() { Boolean flgFields = false; int chk = 0; switch (optIndex) { case 2: if (txtBrRata.getText().length() != 0 || txtBrRata.getText() != "0") chk += 1; case 3: if (txtNet.getText().length() != 0) chk += 1; default: if (txtIznos.getText() != "0,00" || txtIznos.getText() != "-0,00" || txtIznos.getText().length() != 0) chk += 1; if (txtMjesto.getText().length() != 0 || txtMjesto.getText() != "") chk += 1; if (txtSvrha.getText().length() != 0 || txtSvrha.getText() != "") chk += 1; } switch (optIndex) { case 2: if (chk == 4) flgFields = true; case 3: if (chk == 4) flgFields = true; default: if (chk == 3) flgFields = true; } return flgFields; } @Override public void widgetDefaultSelected(SelectionEvent e) { System.out.println(e.widget); } @Override public void widgetSelected(SelectionEvent e) { if (e.widget instanceof TableItem) { TableColumn kolona = (TableColumn) e.widget; if (kolona == IDCol) { colSort = table.getColumn(0); } else if (kolona == colIznos) { colSort = colIznos; } else if (kolona == svrhaCol) { colSort = svrhaCol; } else if (kolona == datumCol) { colSort = datumCol; } else if (kolona == colCateg) { colSort = colCateg; } else if (kolona == mjestoCol) { colSort = mjestoCol; } } } class MenuItemListener extends SelectionAdapter { private Menu categMenu; public void widgetSelected(SelectionEvent e) { if (((MenuItem) e.widget).getText().equals("E&xit")) { shell.close(); } if (e.widget == itemIzlaz) { p2.show(); boolean confirm = kovaDialog.isConfirmed(getLabel("mess34"), getLabel("mess34txt")); System.out.println("Choice is..." + confirm); if (confirm == true) { System.exit(1); RSet.setOperOut(getgUserID()); logger.logg(getLabel("logg10") + confirm); } p2.hide(); } else if (e.widget == itemIspis) { p2.show(); JasperTest.ispis(getLabel("jasper") + (dtp.getMonth() + 1) + "/" + dtp.getYear(), RSet.getOsoba(getgUserID()), SQLquery, 0); p2.hide(); } else if (e.widget == itemBalance) { p2.show(); new balanceForm(shell, dtp.getMonth() + 1, dtp.getYear()); p2.hide(); } else if (e.widget == itemPregLogg) { p2.show(); new loggerView(shell, 0); p2.hide(); } else if (e.widget == itemPregErrLogg) { p2.show(); new loggerView(shell, 1); p2.hide(); } else if (e.widget == itemPregOper) { p2.show(); new operPregledNew(shell); p2.hide(); gBroj = 0; } else if (e.widget == itemOpcije) { p2.show(); new opcije(shell); p2.hide(); // setLanguage(shell); } else if (e.widget == itemBackup) { p2.show(); new underConstruction(shell); p2.hide(); } else if (e.widget == itemRestore) { p2.show(); new underConstruction(shell); p2.hide(); } else if (e.widget == itemIzvoz) { p2.show(); String filePath = ""; String fileName = ""; filePath = saveDialog.open(shell); fileName = saveDialog.getFileName(); if (iNull(filePath) != "") { if (fileExists(filePath) == true) { // int odg = ALERT.open(shell, "i", "Izvoz datoteke!", // "Datoteka već postoji!\nŽelite li presnimiti datoteku \""+ // saveDialog.getFilePath()+ "\"?", "Presnimi|Odustani", // 0); int odg = ALERT.show( getLabel("mess35"), "i", getLabel("mess35txt") + saveDialog.getFilePath() + "\"?", OpalDialogType.OK_CANCEL, "", ""); if (odg == 0) { if (iNull(filePath) != "") { JasperTest.export( getLabel("jasper2") + (dtp.getMonth() + 1) + "/" + dtp.getYear(), RSet.getOsoba(getgUserID()), SQLquery, 0, saveDialog.getFileType(), filePath, fileName); p2.hide(); } p2.hide(); } p2.hide(); } else { if (iNull(filePath) != "") { JasperTest.export( getLabel("jasper3") + (dtp.getMonth() + 1) + "/" + dtp.getYear(), RSet.getOsoba(getgUserID()), SQLquery, 0, saveDialog.getFileType(), filePath, fileName); } p2.hide(); } p2.hide(); } p2.hide(); } else if (e.widget == itemKategorije) { p2.show(); tempSelect = table.getSelectionIndex(); gBroj = IDbroj; new Categories(shell); p2.hide(); makePopUp(); freshTable(); table.contentTable.select(tempSelect); table.contentTable.showSelection(); } else if (e.widget == itemMonth) { p2.show(); final graphMonth graph = new graphMonth(getLabel("jasper4") + (dtp.getMonth() + 1) + getLabel("jasper4txt"), 0, dtp.getMonth() + 1); graph.pack(); RefineryUtilities.centerFrameOnScreen(graph); graph.setVisible(true); p2.hide(); } else if (e.widget == itemMonth2) { p2.show(); final graphMonth graph2 = new graphMonth(getLabel("jasper5") + (dtp.getMonth() + 1) + getLabel("jasper5txt"), 1, dtp.getMonth() + 1); graph2.pack(); RefineryUtilities.centerFrameOnScreen(graph2); graph2.setVisible(true); p2.hide(); } else if (e.widget == itemYear) { p2.show(); graphYear demo = new graphYear(getLabel("jasper6")); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); p2.hide(); } else if (e.widget == itemAppLogg) { p2.show(); new appLogg(shell); p2.hide(); } else if (e.widget == itemAbout) { p2.show(); new about(shell); p2.hide(); } else if (e.widget == itemManual) { p2.show(); // Process p; // try { // p = // Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler /library/upute/Upute.pdf"); // p.waitFor(); // } catch (IOException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // kovaDialog.showException(e1); // } catch (InterruptedException e2) { // // TODO Auto-generated catch block // e2.printStackTrace(); // kovaDialog.showException(e2); // } try { File myFile = new File("library/upute/Upute.pdf"); Desktop.getDesktop().open(myFile); } catch (IOException ex) { // no application registered for PDFs } p2.hide(); } } } private static String getColVal(int kolona) { String val = ""; if (table.contentTable.getSelectionCount() > 0) { val = table.getItem(table.contentTable.getSelectionIndex()) .getText(kolona); } return val; } @Override public void mouseDoubleClick(MouseEvent e) { p2.show(); tempSelect = table.getSelectionIndex(); gBroj = IDbroj; new editForm(shell); p2.hide(); freshTable(); table.contentTable.select(tempSelect); table.contentTable.showSelection(); } @Override public void mouseDown(MouseEvent e) { // System.out.println(table.getSelectionIndex()); } @Override public void mouseUp(MouseEvent arg0) { // TODO Auto-generated method stub } static Image createIcon(Color color) { Image image = new Image(display, 10, 10); GC gc = new GC(image); gc.setBackground(color); gc.fillRectangle(0, 0, 10, 10); gc.dispose(); ImageData imageData = image.getImageData(); PaletteData palette = new PaletteData(new RGB[] { new RGB(255, 0, 0), new RGB(0xFF, 0xFF, 0xFF), }); ImageData maskData = new ImageData(10, 10, 1, palette); Image mask = new Image(display, maskData); gc = new GC(mask); // gc.setBackground(red); // gc.fillRectangle(0,0, 0, 0); // gc.fillOval(0,0,50,50); gc.fillRectangle(0, 0, 80, 80); gc.dispose(); maskData = mask.getImageData(); final Image icon = new Image(display, imageData, maskData); return icon; } private static void makePopUp() { Menu popupMenu = new Menu(table.contentTable); MenuItem itemCateg = new MenuItem(popupMenu, SWT.CASCADE); itemCateg.setText(getLabel("Categories")); MenuItem itemEdit = new MenuItem(popupMenu, SWT.NONE); itemEdit.setText(getLabel("Edit")); itemEdit.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { tempSelect = table.getSelectionIndex(); gBroj = IDbroj; tempIDbroj = IDbroj; p2.show(); new editForm(shell); p2.hide(); freshTable(); table.contentTable.select(tempSelect); table.contentTable.showSelection(); } }); MenuItem itemDel = new MenuItem(popupMenu, SWT.NONE); itemDel.setText(getLabel("Delete")); itemDel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int tip = Integer.parseInt(getColVal(5)); if (tip == 2) { // int odg = // ALERT.open(shell,"?","Brisanje?","Želite li obrisati rate?","Sve rate|Jednu ratu|Odustani",2); int odg = kovaDialog.choice(getLabel("mess36"), "", 1, new ChoiceItem(getLabel("ch36"), getLabel("ch36txt")), new ChoiceItem( getLabel("ch361"), getLabel("ch361txt")), new ChoiceItem(getLabel("ch362"), getLabel("ch363txt"))); int rateBr = 0; switch (odg) { case 0: // sve rate rs = RSet.openRS("select max(id)as Uk from racuni"); try { while (rs.next()) { rateBr = rs.getInt("uk"); } } catch (SQLException e1) { e1.printStackTrace(); logger.loggErr("mainFrame " + e1.getMessage()); kovaDialog.showException(e1); } RSet.closeAll(); RSet.deleteRS(rateBr, sTablica, "rateID"); freshTable(); break; case 1: // jednu ratu RSet.deleteRSid(IDbroj, sTablica); freshTable(); break; case 2: // odustani break; } } else { // int odg = // ALERT.open(shell,"?","Brisanje?","Želite li obrisati stavku pod rednim brojem "+ // IDbroj + "?\n\n Mjesto: " + iNull(getColVal(3)) + // "\n Svrha: " + iNull(getColVal(4))+ "\n Iznos: "+ // FormatCur(iNull0(getColVal(10)))+ "", "Obriši|Odustani", // 1); final boolean confirm = kovaDialog.isConfirmed( getLabel("mess38") + IDbroj + "?", getLabel("mess38txt") + iNull(getColVal(3)) + getLabel("mess381txt") + iNull(getColVal(4)) + getLabel("mess382txt") + "<b>" + FormatCur(iNull0(getColVal(10))) + "</b><br/>"); if (confirm == true) { RSet.deleteRSid(IDbroj, sTablica); freshTable(); cmdDEL.setEnabled(false); logger.logg(getLabel("mess39") + IDbroj + "!"); } else { cmdDEL.setEnabled(false); } } } }); categMenu = new Menu(popupMenu); itemCateg.setMenu(categMenu); int i = 1; rs = RSet.openRS("select id,name,r,g,b from categories"); try { while (rs.next()) { itemC = new MenuItem(categMenu, SWT.NONE); itemC.setText(rs.getString("name")); itemC.setData(rs.getInt("id")); itemC.setImage(createIcon(new Color(shell.getDisplay(), new RGB(rs.getInt("R"), rs.getInt("G"), rs.getInt("B"))))); itemC.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { MenuItem item = (MenuItem) e.widget; tempSelect = table.getSelectionIndex(); if (getColVal(7) == "") { RSet.updateRS("update racuni set kategorija= " + item.getData() + " where ID=" + IDbroj); } else { RSet.updateRS("update racuni set kategorija=0 where ID=" + IDbroj); } freshTable(); table.contentTable.select(tempSelect); table.contentTable.showSelection(); } }); i++; } rs.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); logger.loggErr("mainFrame " + e1.getMessage()); kovaDialog.showException(e1); } MenuItem itemCategories = new MenuItem(categMenu, SWT.NONE); itemCategories.setText(getLabel("Edit")); // final Image icos= new Image(display,"library/icons/icos.ico"); // itemCategories.setImage(icos); itemCategories.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { p2.show(); new Categories(shell); p2.hide(); tempSelect = table.getSelectionIndex(); makePopUp(); freshTable(); table.contentTable.select(tempSelect); table.contentTable.showSelection(); } }); table.contentTable.setMenu(popupMenu); } private static void fillKategs() { rs = RSet.openRS("select name,R,G,B from categories order by name"); try { cmbKategs.removeAll(); cmbKategs.add(getLabel("NoCateg"), null); while (rs.next()) { cmbKategs .add(rs.getString("name"), createIcon(new Color(shell.getDisplay(), new RGB(rs.getInt("R"), rs.getInt("G"), rs.getInt("B"))))); } cmbKategs.select(0); rs.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); logger.loggErr("mainFrame " + e1.getMessage()); kovaDialog.showException(e1); } } private static kovaTable fillKovaTable(final Composite parent) { // može ovako, a može se i iz metaData-e izčitati final String[] header = { "", "ID", "Datum", "Mjesto", "Svrha", "tip", "Pintrans", "", "", "", "Iznos" }; final String EOMdate = getEOM(dtp.getYear(), dtp.getMonth(), dtp.getDay()); SQLquery = "select C.name,R.ID,R.Datum,R.Mjesto,R.Svrha,R.Tip,R.pintrans,C.R,C.G,C.B,R.Iznos from racuni R left OUTER JOIN " + " categories C on R.kategorija=C.ID" + " where R.datum between " + "'" + dtp.getYear() + "-" + (dtp.getMonth() + 1) + "-1' and '" + EOMdate + "' "; System.out.println("FILL: " + SQLquery); rs = RSet.openRS(SQLquery); val = kovaTable.fillVal(rs); // create the table itself final kovaTable table = kovaTable.createKovaTable(parent, SWT.FULL_SELECTION | SWT.MULTI, header, val); table.setLayoutData("width 470px,height 345px,span"); // kovaTable.setColumnsMeta(rs,table); // table.setEditable(false, 1, 2, 3); // initial coloring for (TableItem singleItem : table.getItems()) { applyColors(singleItem); } table.sortTable(table.getColumn(1)); return table; } private static void setSort() { flgSort = (flgSort) ? false : true; table.lastDescendingColumn = (flgSort) ? colSort : null; } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } }
package com.flutterwave.raveandroid.rave_presentation.data.events; import com.flutterwave.raveandroid.rave_logger.Event; import static com.flutterwave.raveandroid.rave_logger.Event.EVENT_TITLE_ERROR; public class ErrorEvent { Event event; public ErrorEvent(String errorMessage) { event = new Event(EVENT_TITLE_ERROR, "Error: " + errorMessage); } public Event getEvent() { return event; } }
package com.example.kripajha.recyclerproject; import android.app.Activity; import android.app.Dialog; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; public class MessageDialog { public void showDialog(Activity activity,String message){ final Dialog dialog=new Dialog(activity); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setContentView(R.layout.dialogmessage); TextView textViewForMessage= dialog.findViewById(R.id.dialogTextView); textViewForMessage.setText(message); Button dialogButton=dialog.findViewById(R.id.closeDialog); dialogButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); } }
package com.snow.gk.core.ui.drivers; import com.snow.gk.core.utils.Config; import com.snow.gk.core.log.LogEventListener; import com.snow.gk.core.log.Logger; import org.openqa.selenium.UnexpectedAlertBehaviour; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.events.EventFiringWebDriver; import java.util.concurrent.TimeUnit; public class DriverSetup { private static final ThreadLocal<WebDriver> webDriverThreadLocal; private static WebDriver driver = null; public static boolean browserInitialized = false; static { webDriverThreadLocal = new ThreadLocal<>(); } /** * To initialize the Driver * @param browser * - Browser (e.g. Chrome, Firefox IE etc) * @return */ public static void initializeDriver(String browser) { if (("chromedriver").equalsIgnoreCase(browser)) { driver = initiateChromeDriver(); Logger.info("Started Chrome Browser successfully."); } else if (("firefox").equalsIgnoreCase(browser)) { driver = initiateFireFoxDriver(); Logger.info("Started Firefox Browser successfully."); } driver = new EventFiringWebDriver(driver).register(new LogEventListener()); setDriver(driver); browserInitialized = true; } /** * To initialize the Chrome Driver * @param * @return driver * - chrome driver */ private static WebDriver initiateChromeDriver() { WebDriver driver = null; try { String chromePath = Config.getConfig().getConfigProperty("webdriver.chrome.driver"); System.setProperty("webdriver.chrome.driver", chromePath); ChromeDriverService chromeService = ChromeDriverService.createDefaultService(); String commandSwitches = "WebDriverCommandSwitch"; DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT); if (!commandSwitches.isEmpty() || commandSwitches.contains("--")) { Logger.info("User had specified [" + commandSwitches + "] command switch for Chrome Browser"); ChromeOptions options = new ChromeOptions(); String[] commandList = commandSwitches.split(","); for (String command : commandList) { options.addArguments(command); options.addArguments("--test-type"); options.addArguments("chrome.switches", "--disable-extensions"); } capabilities.setCapability(ChromeOptions.CAPABILITY, options); driver = new ChromeDriver(chromeService, capabilities); Logger.info("Started Google Chrome Driver with command switches successfully"); } else { Logger.debug("Starting the Chrome Driver"); driver = new ChromeDriver(chromeService); Logger.info("Started Google Chrome Browser successfully"); } driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } catch (Exception e) { Logger.error("Failed to initiate Chrome Driver"+e); } return driver; } private static WebDriver initiateFireFoxDriver() { return null; } private static void setDriver(WebDriver driver){ webDriverThreadLocal.set(driver); } public static WebDriver getDriver() { driver = webDriverThreadLocal.get(); if (driver == null) throw new IllegalStateException("Driver not set..."); return driver; } public static void gotoUrl(String url) { driver.get(url); Logger.info("Navigated to " + url + " link"); } }
package ch.fhnw.edu.cpib.scanner; import ch.fhnw.edu.cpib.scanner.enumerations.Terminals; import ch.fhnw.edu.cpib.scanner.interfaces.IToken; public class Base implements IToken { private final Terminals terminal; public Base(Terminals terminal) { this.terminal = terminal; } public Terminals getTerminal() { return terminal; } @Override public String toString() { return getTerminal().toString(); } }
package com.tencent.mm.plugin.appbrand.g.a; import java.nio.ByteBuffer; class i$4 implements a { final /* synthetic */ i geD; i$4(i iVar) { this.geD = iVar; } public final int aky() { return this.geD.fef.aaL(); } public final ByteBuffer jA(int i) { return this.geD.fef.jA(i); } public final void a(int i, ByteBuffer byteBuffer) { this.geD.fef.a(i, byteBuffer); } }
package com.example.martinzou.android_exp_3; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; /** * Created by 10630 on 2018/4/27. */ public class RelativeActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.relativelayouttest); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.eclipse.servers; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.eclipse.Activator; import org.apache.hadoop.eclipse.ErrorMessageDialog; import org.apache.hadoop.eclipse.server.HadoopServer; import org.apache.hadoop.eclipse.server.JarModule; import org.apache.hadoop.mapred.JobConf; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.launching.IRuntimeClasspathEntry; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; /** * Wizard for publishing a job to a Hadoop server. */ public class RunOnHadoopWizard extends Wizard { private MainWizardPage mainPage; private HadoopLocationWizard createNewPage; /** * The file resource (containing a main()) to run on the Hadoop location */ private IFile resource; /** * The launch configuration to update */ private ILaunchConfigurationWorkingCopy iConf; private IProgressMonitor progressMonitor; public RunOnHadoopWizard(IFile resource, ILaunchConfigurationWorkingCopy iConf) { this.resource = resource; this.iConf = iConf; setForcePreviousAndNextButtons(true); setNeedsProgressMonitor(true); setWindowTitle("Run on Hadoop"); } /** * This wizard contains 2 pages: * <li> the first one lets the user choose an already existing location * <li> the second one allows the user to create a new location, in case it * does not already exist */ /* @inheritDoc */ @Override public void addPages() { addPage(this.mainPage = new MainWizardPage()); addPage(this.createNewPage = new HadoopLocationWizard()); } /** * Performs any actions appropriate in response to the user having pressed * the Finish button, or refuse if finishing now is not permitted. */ /* @inheritDoc */ @Override public boolean performFinish() { /* * Create a new location or get an existing one */ HadoopServer location = null; if (mainPage.createNew.getSelection()) { location = createNewPage.performFinish(); } else if (mainPage.table.getSelection().length == 1) { location = (HadoopServer) mainPage.table.getSelection()[0].getData(); } if (location == null) return false; /* * Get the base directory of the plug-in for storing configurations and * JARs */ File baseDir = Activator.getDefault().getStateLocation().toFile(); // Package the Job into a JAR File jarFile = JarModule.createJarPackage(resource); if (jarFile == null) { ErrorMessageDialog.display("Run on Hadoop", "Unable to create or locate the JAR file for the Job"); return false; } /* * Generate a temporary Hadoop configuration directory and add it to the * classpath of the launch configuration */ File confDir; try { confDir = File.createTempFile("hadoop-conf-", "", baseDir); confDir.delete(); confDir.mkdirs(); if (!confDir.isDirectory()) { ErrorMessageDialog.display("Run on Hadoop", "Cannot create temporary directory: " + confDir); return false; } } catch (IOException ioe) { ioe.printStackTrace(); return false; } // Prepare the Hadoop configuration JobConf conf = new JobConf(location.getConfiguration()); conf.setJar(jarFile.getAbsolutePath()); // Write it to the disk file try { // File confFile = File.createTempFile("core-site-", ".xml", // confDir); File confFile = new File(confDir, "core-site.xml"); FileOutputStream fos = new FileOutputStream(confFile); conf.writeXml(fos); fos.close(); } catch (IOException ioe) { ioe.printStackTrace(); return false; } // Setup the Launch class path List<String> classPath; try { classPath = iConf.getAttribute( IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, new ArrayList()); IPath confIPath = new Path(confDir.getAbsolutePath()); IRuntimeClasspathEntry cpEntry = JavaRuntime.newArchiveRuntimeClasspathEntry(confIPath); classPath.add(0, cpEntry.getMemento()); iConf.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classPath); iConf.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, mainPage.argumentsText.getText()); } catch (CoreException e) { e.printStackTrace(); return false; } // location.runResource(resource, progressMonitor); return true; } private void refreshButtons() { getContainer().updateButtons(); } /** * Allows finish when an existing server is selected or when a new server * location is defined */ /* @inheritDoc */ @Override public boolean canFinish() { if (mainPage != null) return mainPage.canFinish(); return false; } /** * This is the main page of the wizard. It allows the user either to choose * an already existing location or to indicate he wants to create a new * location. */ public class MainWizardPage extends WizardPage { private Button createNew; private Table table; private Text argumentsText; private Button chooseExisting; public MainWizardPage() { super("Select or define server to run on"); setTitle("Select Hadoop location"); setDescription("Select a Hadoop location to run on."); } /* @inheritDoc */ @Override public boolean canFlipToNextPage() { return createNew.getSelection(); } /* @inheritDoc */ public void createControl(Composite parent) { Composite panel = new Composite(parent, SWT.NONE); panel.setLayout(new GridLayout(1, false)); // Label Label label = new Label(panel, SWT.NONE); label.setText("Select a Hadoop Server to run on."); GridData gData = new GridData(GridData.FILL_BOTH); gData.grabExcessVerticalSpace = false; label.setLayoutData(gData); // Create location button createNew = new Button(panel, SWT.RADIO); createNew.setText("Define a new Hadoop server location"); createNew.setLayoutData(gData); createNew.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { setPageComplete(true); RunOnHadoopWizard.this.refreshButtons(); } }); createNew.setSelection(true); // Select existing location button chooseExisting = new Button(panel, SWT.RADIO); chooseExisting .setText("Choose an existing server from the list below"); chooseExisting.setLayoutData(gData); chooseExisting.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { if (chooseExisting.getSelection() && (table.getSelectionCount() == 0)) { if (table.getItems().length > 0) { table.setSelection(0); } } RunOnHadoopWizard.this.refreshButtons(); } }); // Table of existing locations Composite serverListPanel = new Composite(panel, SWT.FILL); gData = new GridData(GridData.FILL_BOTH); gData.horizontalSpan = 1; serverListPanel.setLayoutData(gData); FillLayout layout = new FillLayout(); layout.marginHeight = layout.marginWidth = 12; serverListPanel.setLayout(layout); table = new Table(serverListPanel, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); table.setHeaderVisible(true); table.setLinesVisible(true); TableColumn nameColumn = new TableColumn(table, SWT.LEFT); nameColumn.setText("Location"); nameColumn.setWidth(450); TableColumn hostColumn = new TableColumn(table, SWT.LEFT); hostColumn.setText("Master host name"); hostColumn.setWidth(250); // If the user select one entry, switch to "chooseExisting" table.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { chooseExisting.setSelection(true); createNew.setSelection(false); setPageComplete(table.getSelectionCount() == 1); RunOnHadoopWizard.this.refreshButtons(); } }); // Label Label argumentsLabel = new Label(panel, SWT.NONE); argumentsLabel.setText("Arguments:"); GridData gDataArgumentsLabel = new GridData(GridData.FILL_BOTH); gDataArgumentsLabel.grabExcessVerticalSpace = false; argumentsLabel.setLayoutData(gDataArgumentsLabel); // Textbox argumentsText = new Text(panel, SWT.NONE); try { argumentsText.setText(iConf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, "")); } catch (CoreException e1) { e1.printStackTrace(); } GridData gDataArgumentsText = new GridData(GridData.FILL_BOTH); gDataArgumentsText.grabExcessVerticalSpace = false; argumentsText.setLayoutData(gDataArgumentsText); TableViewer viewer = new TableViewer(table); HadoopServerSelectionListContentProvider provider = new HadoopServerSelectionListContentProvider(); viewer.setContentProvider(provider); viewer.setLabelProvider(provider); viewer.setInput(new Object()); // don't care, get from singleton server registry this.setControl(panel); } /** * Returns whether this page state allows the Wizard to finish or not * * @return can the wizard finish or not? */ public boolean canFinish() { if (!isControlCreated()) return false; if (this.createNew.getSelection()) return getNextPage().isPageComplete(); return this.chooseExisting.getSelection(); } } /** * @param progressMonitor */ public void setProgressMonitor(IProgressMonitor progressMonitor) { this.progressMonitor = progressMonitor; } }
package app.util; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.util.Optional; public class HTMLQuery { private static final String CHARSET_NAME = "utf8"; private Document document; public HTMLQuery(String filePath) throws IOException { this(new File(filePath)); } public HTMLQuery(File htmlFile) throws IOException { document = Jsoup.parse( htmlFile, CHARSET_NAME, htmlFile.getAbsolutePath()); } public Document getDocument() { return document; } public Optional<Element> findById(String cssId) { return Optional.ofNullable(document.getElementById(cssId)); } public Optional<Elements> findElements(String cssQuery) { return Optional.ofNullable(document.select(cssQuery)); } public Optional<Element> findFirst(String cssQuery) { return Optional.ofNullable(document.selectFirst(cssQuery)); } }
/* * Copyright (c) 2014 Anthony Benavente * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package com.ambenavente.origins.gameplay.entities; import org.newdawn.slick.Animation; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; /** * Represents an entity that has animations for each direction it faces * * @author Anthony Benavente * @version 2/10/14 */ public abstract class AnimatedEntity extends StaticEntity { /** * The animations for the entity while it is moving */ private Animation[] movingAnimations; /** * The animations for the entity while it is standing still */ private Animation[] stillAnimations; public AnimatedEntity(float x, float y) { super(x, y); this.movingAnimations = new Animation[Direction.values().length]; this.stillAnimations = new Animation[Direction.values().length]; } @Override public void render(Graphics g) { if (!isDead()) { if (!isMoving()) { Animation anim = stillAnimations[getDirection().ordinal()]; if (anim != null) { anim.draw(getX(), getY()); drawShadow(g); } else { super.render(g); } } else { Animation anim = movingAnimations[getDirection().ordinal()]; if (anim != null) { anim.draw(getX(), getY()); drawShadow(g); } else { Entity.NO_TEX.draw(getX(), getY()); } } } } /* ------------------------ */ /* Methods to be overloaded */ /* ------------------------ */ @Override public abstract void update(GameContainer container, int delta); /* ------------------------ */ /** * Sets the standing still animation object at the specified direction * * @param dir The direction to set the animation for * @param animation The animation to insert */ protected void setStillAnimation(Direction dir, Animation animation) { stillAnimations[dir.ordinal()] = animation; } /** * Sets the moving animation object at the specified direction * * @param dir The direction to set the animation for * @param animation The animation to insert */ protected void setMovingAnimation(Direction dir, Animation animation) { movingAnimations[dir.ordinal()] = animation; } /** * Gets the moving animation at the specified direction * * @param dir The direction to get the animation from * @return The animation for the object's moving at the specified * direction */ public Animation getMovingAnimation(Direction dir) { return movingAnimations[dir.ordinal()]; } /** * Gets the still animation at the specified direction * * @param dir The direction to get the animation from * @return The animation for the object's standing still at the specified * direction */ public Animation getStillAnimation(Direction dir) { return stillAnimations[dir.ordinal()]; } }
package com.xworkz.rental.service; import java.util.Date; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import com.xworkz.rental.dto.CompanyGadgetsDTO; import com.xworkz.rental.entity.CompanyGadgetListEntity; import com.xworkz.rental.entity.RegistrationEntity; import com.xworkz.rental.repository.CompanyGadgetRepository; import com.xworkz.rental.repository.RegistrationRepository; import com.xworkz.rental.utility.response.Response; @Service public class CompanyGadgetsServiceImpl implements CompanyGadgetsService { @Autowired private Environment environment; @Autowired private RegistrationRepository registrationRepository; @Autowired private CompanyGadgetRepository companyGadgetRepository; private Logger logger = LoggerFactory.getLogger(getClass()); public CompanyGadgetsServiceImpl() { logger.info("invoking ---------" + this.getClass().getSimpleName()); } @Override public Response addGadgets(@Valid CompanyGadgetsDTO gadgetsDTO) { logger.info("invoking CompanyGadgetsServiceImpl addGadgets()"); RegistrationEntity entity = null; CompanyGadgetListEntity listEntity = new CompanyGadgetListEntity(); logger.info(""+gadgetsDTO); try { entity = registrationRepository.findByCompanyName(gadgetsDTO.getCompanyName()); logger.info("checking for company details"); if (entity != null) { logger.info("Company found"); BeanUtils.copyProperties(gadgetsDTO, listEntity); logger.info("copy properteies from dto to entity"); listEntity.setDateOfAssigne(new Date()); logger.info("Setting todays date"); listEntity = companyGadgetRepository.save(listEntity); logger.info("gadgets list added successfully"); return new Response(environment.getProperty("GADGETS_ADDE"), environment.getProperty("SERVER_CODE_SUCCESS"), listEntity); }else { logger.info("Company not found"); return new Response(environment.getProperty("CLIENT_NOT_FOUND"), environment.getProperty("SERVER_CODE_ERROR")); } } catch (Exception e) { logger.error(e.getMessage(), e); return new Response(environment.getProperty("CLIENT_NOT_FOUND"), environment.getProperty("SERVER_CODE_ERROR")); } } }
package org.crama.burrhamilton.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WriteController { @RequestMapping(value="/write", method=RequestMethod.GET) public String writePage() { return "write"; } }
package chess; import static chess.ListHelpers.toPositionList; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import chess.pieces.Moves; public class MovesTest { private GameState emptyState; private GameState initialState; @Before public void setUp() { emptyState = new GameState(); initialState = new GameState(); initialState.reset(); initialState.movePiece(new Position("a2"), new Position("a3")); initialState.movePiece(new Position("b2"), new Position("b3")); initialState.movePiece(new Position("c2"), new Position("c3")); initialState.movePiece(new Position("h2"), new Position("h3")); initialState.movePiece(new Position("g2"), new Position("g3")); initialState.movePiece(new Position("f2"), new Position("f3")); initialState.movePiece(new Position("f7"), new Position("f2")); initialState.movePiece(new Position("c7"), new Position("c2")); } // north @Test public void returnsNorthMoves() { assertThat(Moves.getNorth(Player.White, emptyState, new Position("d1"), 2), is(toPositionList("d2","d3"))); } @Test public void returnsNorthMovesWithinBoard() { assertThat(Moves.getNorth(Player.White, emptyState, new Position("d1"), 10), is(toPositionList("d2","d3","d4","d5","d6","d7","d8"))); } @Test public void returnsNoNorthMoves() { assertThat(Moves.getNorth(Player.White, emptyState, new Position("d1"), 0), is(toPositionList())); } @Test public void returnsNorthMovesToEmptyOrOpponentPositions() { assertThat(Moves.getNorth(Player.White, initialState, new Position("d1"), 8), is(toPositionList())); assertThat(Moves.getNorth(Player.White, initialState, new Position("d2"), 8), is(toPositionList("d3","d4","d5","d6","d7","d8"))); } // south @Test public void returnsSouthMoves() { assertThat(Moves.getSouth(Player.Black, emptyState, new Position("d8"), 2), is(toPositionList("d7","d6"))); } @Test public void returnsSouthMovesWithinBoard() { assertThat(Moves.getSouth(Player.Black, emptyState, new Position("d8"), 10), is(toPositionList("d7","d6","d5","d4","d3","d2","d1"))); } @Test public void returnsNoSouthMoves() { assertThat(Moves.getSouth(Player.Black, emptyState, new Position("d8"), 0), is(toPositionList())); } @Test public void returnsSouthMovesToEmptyOrOpponentPositions() { assertThat(Moves.getSouth(Player.Black, initialState, new Position("d8"), 8), is(toPositionList())); assertThat(Moves.getSouth(Player.Black, initialState, new Position("d7"), 8), is(toPositionList("d6","d5","d4","d3","d2","d1"))); } // west @Test public void returnsWestMoves() { assertThat(Moves.getWest(Player.White, emptyState, new Position("h2"), 2), is(toPositionList("g2","f2"))); } @Test public void returnsWestMovesWithinBoard() { assertThat(Moves.getWest(Player.White, emptyState, new Position("h3"), 10), is(toPositionList("g3","f3","e3","d3","c3","b3","a3"))); } @Test public void returnsNoWestMoves() { assertThat(Moves.getWest(Player.White, emptyState, new Position("h2"), 0), is(toPositionList())); } @Test public void returnsWestMovesToEmptyOrOpponentPositions() { assertThat(Moves.getWest(Player.White, initialState, new Position("h1"), 8), is(toPositionList())); assertThat(Moves.getWest(Player.White, initialState, new Position("h2"), 3), is(toPositionList("g2","f2"))); } // east @Test public void returnsEastMoves() { assertThat(Moves.getEast(Player.White, emptyState, new Position("a2"), 2), is(toPositionList("b2","c2"))); } @Test public void returnsEastMovesWithinBoard() { assertThat(Moves.getEast(Player.White, emptyState, new Position("a3"), 10), is(toPositionList("b3","c3","d3","e3","f3","g3","h3"))); } @Test public void returnsNoEastMoves() { assertThat(Moves.getEast(Player.White, emptyState, new Position("a2"), 0), is(toPositionList())); } @Test public void returnsEastMovesToEmptyOrOpponentPositions() { assertThat(Moves.getEast(Player.White, initialState, new Position("a2"), 3), is(toPositionList("b2","c2"))); } // northeast @Test public void returnsNorthEastMoves() { assertThat(Moves.getNorthEast(Player.White, emptyState, new Position("a2"), 2), is(toPositionList("b3","c4"))); } @Test public void returnsNorthEastMovesWithinBoard() { assertThat(Moves.getNorthEast(Player.White, emptyState, new Position("a2"), 10), is(toPositionList("b3","c4","d5","e6","f7","g8"))); } @Test public void returnsNoNorthEastMoves() { assertThat(Moves.getNorthEast(Player.White, emptyState, new Position("a2"), 0), is(toPositionList())); } @Test public void returnsNorthEastEmptyMoves() { assertThat(Moves.getNorthEast(Player.White, initialState, new Position("a2"), 3), is(toPositionList())); assertThat(Moves.getNorthEast(Player.White, initialState, new Position("a1"), 3), is(toPositionList("b2"))); } // northeast @Test public void returnsNorthWestMoves() { assertThat(Moves.getNorthWest(Player.White, emptyState, new Position("h2"), 2), is(toPositionList("g3","f4"))); } @Test public void returnsNorthWestMovesWithinBoard() { assertThat(Moves.getNorthWest(Player.White, emptyState, new Position("h2"), 10), is(toPositionList("g3","f4","e5","d6","c7","b8"))); } @Test public void returnsNoNorthWestMoves() { assertThat(Moves.getNorthWest(Player.White, emptyState, new Position("h2"), 0), is(toPositionList())); } @Test public void returnsNorthWestEmptyMoves() { assertThat(Moves.getNorthWest(Player.White, initialState, new Position("e1"), 3), is(toPositionList())); assertThat(Moves.getNorthWest(Player.White, initialState, new Position("h1"), 3), is(toPositionList("g2"))); } // southEast @Test public void returnsSouthEastMoves() { assertThat(Moves.getSouthEast(Player.Black, emptyState, new Position("a7"), 2), is(toPositionList("b6","c5"))); } @Test public void returnsSouthEastMovesWithinBoard() { assertThat(Moves.getSouthEast(Player.Black, emptyState, new Position("a7"), 10), is(toPositionList("b6","c5","d4","e3","f2","g1"))); } @Test public void returnsNoSouthEastMoves() { assertThat(Moves.getSouthEast(Player.Black, emptyState, new Position("a7"), 0), is(toPositionList())); } @Test public void returnsSouthEastEmptyMoves() { assertThat(Moves.getSouthEast(Player.Black, initialState, new Position("a8"), 3), is(toPositionList())); assertThat(Moves.getSouthEast(Player.Black, initialState, new Position("c3"), 3), is(toPositionList("d2","e1"))); } // southWest @Test public void returnsSouthWestMoves() { assertThat(Moves.getSouthWest(Player.Black, emptyState, new Position("h7"), 2), is(toPositionList("g6","f5"))); } @Test public void returnsSouthWestMovesWithinBoard() { assertThat(Moves.getSouthWest(Player.Black, emptyState, new Position("h7"), 10), is(toPositionList("g6","f5","e4","d3","c2","b1"))); } @Test public void returnsNoSouthWestMoves() { assertThat(Moves.getSouthWest(Player.Black, emptyState, new Position("h7"), 0), is(toPositionList())); } @Test public void returnsSouthWestEmptyMoves() { assertThat(Moves.getSouthWest(Player.Black, initialState, new Position("h8"), 3), is(toPositionList())); assertThat(Moves.getSouthWest(Player.Black, initialState, new Position("h3"), 3), is(toPositionList("g2","f1"))); } }
package com.practice.heliguang.livewallpaper; import android.opengl.GLSurfaceView; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import com.practice.heliguang.opengles2library.OpenGLES20; public class MainActivity extends AppCompatActivity { public static final String TAG = "MainActivity"; private GLSurfaceView glSurfaceView; private LiveWallPaperRenderer renderer; private boolean rendererSet = false; private View.OnTouchListener onTouchListener = new View.OnTouchListener() { float previousX, previousY; @Override public boolean onTouch(View v, MotionEvent event) { if (event != null) { if (event.getAction() == MotionEvent.ACTION_DOWN) { previousX = event.getX(); previousY = event.getY(); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { final float deltaX = event.getX() - previousX; final float deltaY = event.getY() - previousY; previousX = event.getX(); previousY = event.getY(); glSurfaceView.queueEvent(new Runnable() { @Override public void run() { renderer.handleTouchDrag(deltaX, deltaY); } }); } return true; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (OpenGLES20.supportsEs2(this)) { glSurfaceView = new GLSurfaceView(this); glSurfaceView.setEGLContextClientVersion(2); renderer = new LiveWallPaperRenderer(this); glSurfaceView.setRenderer(renderer); glSurfaceView.setOnTouchListener(onTouchListener); rendererSet = true; setContentView(glSurfaceView); } else { Logger.e(TAG, "This device doesn't support OpenGL ES 2.0."); } } @Override protected void onPause() { super.onPause(); if (rendererSet) glSurfaceView.onPause(); } @Override protected void onResume() { super.onResume(); if (rendererSet) glSurfaceView.onResume(); } }
package com.cat.dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.cat.bean.House; import com.cat.dao.HouseDao; @Repository public class HouseDaoImpl implements HouseDao { // 注入sessionFactory @Autowired private SessionFactory sessionFactory; @SuppressWarnings("unchecked") @Override public List<House> findHouses() { Query query = sessionFactory.getCurrentSession().createQuery( "from House order by houseCreateTime desc"); return query.list(); } @Override public void addHouse(House house) { Session session = (Session) sessionFactory.getCurrentSession(); session.save(house); } @Override public House findHouseById(int houseId) { String hql = "from House where houseId=:houseId"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger("houseId", houseId); return (House) query.uniqueResult(); } @Override public void deleteHouse(House house) { sessionFactory.getCurrentSession().delete(house); } @Override public void updateHouse(House house) { sessionFactory.getCurrentSession().update(house); } @SuppressWarnings("unchecked") @Override public List<House> findHouses(int pageSize, int pageNow) { Query query = sessionFactory.getCurrentSession().createQuery( "from House order by houseCreateTime desc"); query.setFirstResult(pageNow); query.setMaxResults(pageSize); return query.list(); } @Override public Long queryAllCount() { String hql = "select count(*) from House"; Query query = sessionFactory.getCurrentSession().createQuery(hql); return (Long) query.uniqueResult(); } }
package com.nv95.ficbook; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceManager; import org.jsoup.nodes.Document; import java.io.IOException; public class SwitchModerTask extends AsyncTask<Boolean,Void,Boolean>{ ProgressDialog pd; Preference preference; boolean qm; public SwitchModerTask(Preference preference) { this.preference = preference; pd = new ProgressDialog(preference.getContext()); } @Override protected Boolean doInBackground(Boolean... booleans) { try { Document doc = new FbSession(preference.getContext()).getPage("http://mobile.ficbook.net/moderation"); if (doc.select("DIV.center_switcher").size()==0) return false; else { qm = (doc.getElementsByAttributeValueEnding("href","moderation_type=rules_and_quality").size()==0); return true; } } catch (IOException e) { return false; } } @Override protected void onPreExecute() { super.onPreExecute(); preference.setEnabled(false); pd.setIndeterminate(true); pd.setMessage(preference.getContext().getString(R.string.str_loading)); pd.setCancelable(false); pd.show(); } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); pd.dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(preference.getContext()); builder.setCancelable(true) .setTitle(R.string.title_moderation) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } } ); if (aBoolean) builder.setMessage(preference.getContext().getString(R.string.moderationon_succ) + "\n\nПроверка качества: " + (qm?"да":"нет")); else builder.setMessage(preference.getContext().getString(R.string.moderationon_fail)); builder.create().show(); preference.getEditor().putBoolean("moderation", aBoolean).commit(); PreferenceManager.getDefaultSharedPreferences(preference.getContext()).edit().putBoolean("qm",qm).commit(); ((CheckBoxPreference)preference).setChecked(aBoolean); preference.setEnabled(true); } }
package com.pkjiao.friends.mm.activity; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.pkjiao.friends.mm.R; import com.pkjiao.friends.mm.adapter.DynamicInfoListAdapter; import com.pkjiao.friends.mm.adapter.DynamicInfoListAdapter.onReplyBtnClickedListener; import com.pkjiao.friends.mm.base.CommentsItem; import com.pkjiao.friends.mm.base.ContactsInfo; import com.pkjiao.friends.mm.base.ReplysItem; import com.pkjiao.friends.mm.common.CommonDataStructure; import com.pkjiao.friends.mm.common.CommonDataStructure.HeaderBackgroundEntry; import com.pkjiao.friends.mm.database.MarrySocialDBHelper; import com.pkjiao.friends.mm.dialog.ProgressLoadDialog; import com.pkjiao.friends.mm.dialog.SelectBackgroundPicDialog; import com.pkjiao.friends.mm.dialog.SelectHeaderPicDialog; import com.pkjiao.friends.mm.dialog.SelectBackgroundPicDialog.OnSelectPicBtnClickListener; import com.pkjiao.friends.mm.dialog.SelectHeaderPicDialog.OnSmallItemClickListener; import com.pkjiao.friends.mm.roundedimageview.RoundedImageView; import com.pkjiao.friends.mm.services.UploadCommentsAndBravosAndReplysIntentService; import com.pkjiao.friends.mm.utils.ImageUtils; import com.pkjiao.friends.mm.utils.Utils; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.FeatureInfo; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextClock; import android.widget.TextView; import android.widget.Toast; public class ContactsInfoActivity extends Activity implements OnClickListener { private static final String TAG = "ContactsInfoActivity"; private static final int TAKE_PICTURE_FROM_CAMERA = 0; private static final int CHOOSE_PICTURE_FROM_GALLERY = 1; private static final int NEED_CROP = 2; private static final int CROP_PICTURE = 3; private static final int CHOOSE_BACKGROUND_PICTURE = 4; private static final int CHANGE_HEAD_BACKGROUND = 0; private static final int POOL_SIZE = 10; private static final int START_TO_UPLOAD = 100; private static final int UPLOAD_FINISH = 101; private static final int RELOAD_DATA_SOURCE = 102; private static final int DOWNLOAD_HEADER_BKG_FINISH = 103; private final static int START_TO_LOAD_BRAVO_REPLY = 104; private final static int UPDATE_DYNAMIC_INFO = 105; private final static int NETWORK_INVALID = 106; private final static int SEND_REPLY_FINISH = 107; private final static int SHOW_SOFT_INPUT_METHOD = 108; private final static int SELECT_SPECIFIED_LIST_ITEM = 109; private final static int TOUCH_FING_UP = 110; private final static int TOUCH_FING_DOWN = 111; private final static int REFRESH_HEADER_PIC = 112; private final static int UPLOAD_COMMENT = 113; private float mTouchDownY = 0.0f; private float mTouchMoveY = 0.0f; private boolean mIsFingUp = false; private static final String[] CONTACTS_PROJECTION = { MarrySocialDBHelper.KEY_UID, MarrySocialDBHelper.KEY_PHONE_NUM, MarrySocialDBHelper.KEY_NICKNAME, MarrySocialDBHelper.KEY_REALNAME, MarrySocialDBHelper.KEY_FIRST_DIRECT_FRIEND, MarrySocialDBHelper.KEY_DIRECT_FRIENDS, MarrySocialDBHelper.KEY_INDIRECT_ID, MarrySocialDBHelper.KEY_DIRECT_FRIENDS_COUNT, MarrySocialDBHelper.KEY_HEADPIC, MarrySocialDBHelper.KEY_GENDER, MarrySocialDBHelper.KEY_ASTRO, MarrySocialDBHelper.KEY_HOBBY, MarrySocialDBHelper.KEY_HEADER_BACKGROUND_INDEX, MarrySocialDBHelper.KEY_INTRODUCT }; private final String[] COMMENTS_PROJECTION = { MarrySocialDBHelper.KEY_UID, MarrySocialDBHelper.KEY_BUCKET_ID, MarrySocialDBHelper.KEY_CONTENTS, MarrySocialDBHelper.KEY_AUTHOR_NICKNAME, MarrySocialDBHelper.KEY_PHOTO_COUNT, MarrySocialDBHelper.KEY_BRAVO_STATUS, MarrySocialDBHelper.KEY_ADDED_TIME, MarrySocialDBHelper.KEY_COMMENT_ID }; private static final String[] HEAD_PICS_PROJECTION = { MarrySocialDBHelper.KEY_UID, MarrySocialDBHelper.KEY_HEAD_PIC_BITMAP, MarrySocialDBHelper.KEY_PHOTO_REMOTE_ORG_PATH, MarrySocialDBHelper.KEY_PHOTO_REMOTE_THUMB_PATH }; private static final String[] HEAD_BACKGROUND_PROJECTION = { MarrySocialDBHelper.KEY_PHOTO_NAME, MarrySocialDBHelper.KEY_PHOTO_LOCAL_PATH, MarrySocialDBHelper.KEY_PHOTO_REMOTE_ORG_PATH, MarrySocialDBHelper.KEY_HEADER_BACKGROUND_INDEX }; private static final String[] HEAD_BKG_PROJECTION = { MarrySocialDBHelper.KEY_PHOTO_NAME, MarrySocialDBHelper.KEY_PHOTO_LOCAL_PATH, MarrySocialDBHelper.KEY_PHOTO_REMOTE_ORG_PATH, MarrySocialDBHelper.KEY_CURRENT_STATUS }; private final String[] BRAVOS_PROJECTION = { MarrySocialDBHelper.KEY_ID, MarrySocialDBHelper.KEY_UID, MarrySocialDBHelper.KEY_AUTHOR_NICKNAME }; private final String[] REPLYS_PROJECTION = { MarrySocialDBHelper.KEY_UID, MarrySocialDBHelper.KEY_AUTHOR_NICKNAME, MarrySocialDBHelper.KEY_REPLY_CONTENTS, MarrySocialDBHelper.KEY_ADDED_TIME }; private String mUserInfoUid; private ContactsInfo mUserInfo; private String mAuthorUid; private String mAuthorName; private ListView mListView; private DynamicInfoListAdapter mListViewAdapter; private ArrayList<CommentsItem> mCommentEntrys = new ArrayList<CommentsItem>(); private HashMap<String, String> mBravoEntrys = new HashMap<String, String>(); private HashMap<String, ArrayList<ReplysItem>> mReplyEntrys = new HashMap<String, ArrayList<ReplysItem>>(); private HashMap<String, ContactsInfo> mUserInfoEntrys = new HashMap<String, ContactsInfo>(); private RelativeLayout mReturnBtn; private RelativeLayout mHeaderLayoutBkg; private LinearLayout mHeaderLayoutDetail; private TextView mUserName; private TextView mFriendName; private RoundedImageView mUserPic; private TextView mFriendsDesc; private ImageView mUserGender; private ImageView mUserAstro; private ImageView mUserHobby; private Button mChatButton; private TextView mEditUserInfo; private RelativeLayout mReplyFoot; private ImageView mReplySendBtn; private EditText mReplyContents; private int mReplyCommentsPosition; private TranslateAnimation mHideChatBtnTransAnimation; private TranslateAnimation mShowChatBtnTransAnimation; private MarrySocialDBHelper mDBHelper; private ExecutorService mExecutorService; private Bitmap mUserHeadPic = null; private Bitmap mCropPhoto = null; private String mCropPhotoName; private DataSetChangeObserver mChangeObserver; private DataSetChangeObserver mHeaderPicChangeObserver; private ProgressLoadDialog mUploadProgressDialog; private SelectBackgroundPicDialog mSelectBkgDialog; private SelectHeaderPicDialog mSelectHeaderPicDialog; private View mContactsInfoHeader; // private int mContactsInfoHeaderWidth; // private int mContactsInfoHeaderHeight; private String mHeadBkgPath; private Context mContext; private Handler mHandler = new Handler() { @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case TOUCH_FING_UP: { hideChatBtn(); hideReplyFootBar(); Utils.hideSoftInputMethod(mReplyFoot); break; } case TOUCH_FING_DOWN: { showChatBtn(); hideReplyFootBar(); Utils.hideSoftInputMethod(mReplyFoot); break; } case START_TO_UPLOAD: { mUploadProgressDialog = new ProgressLoadDialog(mContext); mUploadProgressDialog.setText("正在上传头像,请稍后..."); mUploadProgressDialog.show(); mExecutorService.execute(new UploadHeadPics(mUserInfoUid)); break; } case UPLOAD_FINISH: { mUserHeadPic = mCropPhoto; mUserPic.setImageBitmap(mUserHeadPic); mUploadProgressDialog.dismiss(); break; } case REFRESH_HEADER_PIC: { mListViewAdapter.clearHeadPicsCache(); mListViewAdapter.notifyDataSetChanged(); break; } case DOWNLOAD_HEADER_BKG_FINISH: { Bitmap thumbHeader = Utils.decodeThumbnail(mHeadBkgPath, null, Utils.mThumbPhotoWidth); // Bitmap cropHeader = Utils.cropImages(thumbHeader, // mContactsInfoHeaderWidth, mContactsInfoHeaderHeight, // true); // mHeaderLayoutBkg.setBackground(ImageUtils // .bitmapToDrawable(cropHeader)); if (thumbHeader != null) { mHeaderLayoutBkg.setBackground(ImageUtils .bitmapToDrawable(thumbHeader)); } else { mHeaderLayoutBkg .setBackgroundResource(R.drawable.person_default_bkg); } } case START_TO_LOAD_BRAVO_REPLY: { if (mCommentEntrys != null && mCommentEntrys.size() != 0) { for (CommentsItem comment : mCommentEntrys) { mExecutorService.execute(new LoadBravoAndReplyContents( comment.getCommentId())); } } break; } case UPDATE_DYNAMIC_INFO: { mListViewAdapter.notifyDataSetChanged(); break; } case NETWORK_INVALID: { Toast.makeText(ContactsInfoActivity.this, R.string.network_not_available, Toast.LENGTH_SHORT) .show(); break; } case SEND_REPLY_FINISH: { mReplyContents.setText(null); showChatBtn(); hideReplyFootBar(); Utils.hideSoftInputMethod(mReplyFoot); break; } case SHOW_SOFT_INPUT_METHOD: { Utils.showSoftInputMethod(mReplyContents); break; } case SELECT_SPECIFIED_LIST_ITEM: { mListView.setSelection(msg.arg1); break; } case UPLOAD_COMMENT: { // uploadCommentsOrBravosOrReplys(CommonDataStructure.KEY_COMMENTS); mCommentEntrys.clear(); mCommentEntrys.addAll(loadUserCommentsFromDB(mUserInfoUid)); mListViewAdapter.notifyDataSetChanged(); Log.e(TAG, "nannan UPLOAD_COMMENT.."); break; } default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.contacts_info_layout); mContext = this; mShowChatBtnTransAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 2.0f, Animation.RELATIVE_TO_SELF, 0.0f); mShowChatBtnTransAnimation .setInterpolator(new AccelerateDecelerateInterpolator()); mShowChatBtnTransAnimation.setDuration(500); mShowChatBtnTransAnimation.setFillAfter(true); mHideChatBtnTransAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 2.0f); mHideChatBtnTransAnimation .setInterpolator(new AccelerateDecelerateInterpolator()); mHideChatBtnTransAnimation.setDuration(500); mHideChatBtnTransAnimation.setFillAfter(true); mDBHelper = MarrySocialDBHelper.newInstance(this); generateDBData(); loadContactsFromDB(); Intent data = getIntent(); mUserInfoUid = data.getStringExtra(MarrySocialDBHelper.KEY_UID); mUserInfo = mUserInfoEntrys.get(mUserInfoUid); mUserHeadPic = loadUserHeadPicFromDB(mUserInfoUid); mReturnBtn = (RelativeLayout) findViewById(R.id.contacts_info_return); mUserName = (TextView) findViewById(R.id.contacts_info_person_name); mChatButton = (Button) findViewById(R.id.contacts_info_chat_btn); mChatButton.setOnClickListener(this); mReplyFoot = (RelativeLayout) findViewById(R.id.contacts_info_reply_foot); mReplySendBtn = (ImageView) findViewById(R.id.contacts_info_reply_send); mReplyContents = (EditText) findViewById(R.id.contacts_info_reply_contents); mReplySendBtn.setOnClickListener(mReplySendBtnClickedListener); mContactsInfoHeader = (LayoutInflater.from(this).inflate( R.layout.contacts_info_header_layout, null, false)); mHeaderLayoutBkg = (RelativeLayout) mContactsInfoHeader .findViewById(R.id.contacts_info_head_bkg); mHeaderLayoutDetail = (LinearLayout) mContactsInfoHeader .findViewById(R.id.contacts_info_head_detail); mUserPic = (RoundedImageView) mContactsInfoHeader .findViewById(R.id.contacts_info_person_pic); mFriendName = (TextView) mContactsInfoHeader .findViewById(R.id.contacts_info_friend_name); mFriendsDesc = (TextView) mContactsInfoHeader .findViewById(R.id.contacts_info_friends_description); mUserGender = (ImageView) mContactsInfoHeader .findViewById(R.id.contacts_info_gender_pic); mUserAstro = (ImageView) mContactsInfoHeader .findViewById(R.id.contacts_info_astro_pic); mUserHobby = (ImageView) mContactsInfoHeader .findViewById(R.id.contacts_info_hobby_pic); mEditUserInfo = (TextView) mContactsInfoHeader .findViewById(R.id.contacts_info_edit_info); mListView = (ListView) findViewById(R.id.contacts_info_listview); mListView.addHeaderView(mContactsInfoHeader); mListViewAdapter = new DynamicInfoListAdapter(this); mListViewAdapter.setCommentDataSource(mCommentEntrys); mListViewAdapter.setBravoDataSource(mBravoEntrys); mListViewAdapter.setReplyDataSource(mReplyEntrys); mListViewAdapter.setUserInfoDataSource(mUserInfoEntrys); mListViewAdapter.setReplyBtnClickedListener(mReplyBtnClickedListener); mListViewAdapter.setEnterInContactsInfoActivity(true); mListView.setAdapter(mListViewAdapter); mListView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mTouchDownY = event.getY(); break; case MotionEvent.ACTION_MOVE: mTouchMoveY = event.getY() - mTouchDownY; if (Math.abs(mTouchMoveY) < 50) { break; } if (mTouchMoveY < 0) { if (!mIsFingUp) { mIsFingUp = true; mHandler.sendEmptyMessageDelayed(TOUCH_FING_UP, 50); } } else { if (mIsFingUp) { mIsFingUp = false; mHandler.sendEmptyMessageDelayed(TOUCH_FING_DOWN, 50); } } break; case MotionEvent.ACTION_UP: break; default: break; } return false; } }); SharedPreferences prefs = this.getSharedPreferences( CommonDataStructure.PREFS_LAIQIAN_DEFAULT, MODE_PRIVATE); mAuthorUid = prefs.getString(CommonDataStructure.UID, ""); mAuthorName = prefs.getString(CommonDataStructure.AUTHOR_NAME, ""); mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime() .availableProcessors() * POOL_SIZE); initOriginData(); mChangeObserver = new DataSetChangeObserver(mHandler, UPLOAD_COMMENT); mHeaderPicChangeObserver = new DataSetChangeObserver(mHandler, REFRESH_HEADER_PIC); getContentResolver() .registerContentObserver(CommonDataStructure.HEADPICSURL, true, mHeaderPicChangeObserver); getContentResolver().registerContentObserver( CommonDataStructure.BRAVOURL, true, mChangeObserver); getContentResolver().registerContentObserver( CommonDataStructure.REPLYURL, true, mChangeObserver); } @Override protected void onResume() { super.onResume(); mCommentEntrys.clear(); mCommentEntrys.addAll(loadUserCommentsFromDB(mUserInfoUid)); mListViewAdapter.setCommentDataSource(mCommentEntrys); mListViewAdapter.notifyDataSetChanged(); if (mUserInfoUid.equalsIgnoreCase(mAuthorUid)) { SharedPreferences prefs = this.getSharedPreferences( CommonDataStructure.PREFS_LAIQIAN_DEFAULT, MODE_PRIVATE); String name = prefs.getString(CommonDataStructure.AUTHOR_NAME, ""); String intro = prefs.getString(CommonDataStructure.INTRODUCE, ""); if (name != null && name.length() != 0) { mFriendName.setText(name); mUserName.setText(name); } if (intro != null && intro.length() != 0) { mFriendsDesc.setText(intro); } } } // @Override // public void onWindowFocusChanged(boolean hasFocus) { // super.onWindowFocusChanged(hasFocus); // // mUserInfo = mUserInfoEntrys.get(mUserInfoUid); // // // mContactsInfoHeaderHeight = mContactsInfoHeader.getMeasuredHeight(); // // mContactsInfoHeaderWidth = mContactsInfoHeader.getMeasuredWidth(); // // if ("0".equalsIgnoreCase(mUserInfo.getHeaderBkgIndex())) { // // Bitmap thumbHeader = BitmapFactory.decodeResource(getResources(), // // R.drawable.person_default_bkg); // // Bitmap cropHeader = Utils.cropImages(thumbHeader, // // mContactsInfoHeaderWidth, mContactsInfoHeaderHeight, true); // // mHeaderLayoutBkg // // .setBackground(ImageUtils.bitmapToDrawable(cropHeader)); // mHeaderLayoutBkg // .setBackgroundResource(R.drawable.person_default_bkg); // } else { // mExecutorService.execute(new DownloadHeadBackground(mUserInfo // .getUid(), mUserInfo.getHeaderBkgIndex())); // } // // } @Override public void onDestroy() { super.onDestroy(); getContentResolver().unregisterContentObserver(mChangeObserver); getContentResolver() .unregisterContentObserver(mHeaderPicChangeObserver); } @Override public void onClick(View arg0) { switch (arg0.getId()) { case R.id.contacts_info_return: { this.finish(); break; } case R.id.contacts_info_head_bkg: { if (mUserInfoUid.equalsIgnoreCase(mAuthorUid)) { showBackgroundPicsPicker(this); } break; } case R.id.contacts_info_person_pic: { if (mUserInfoUid.equalsIgnoreCase(mAuthorUid)) { showHeaderPicsPicker(this, true); } if (mCropPhoto != null) { mCropPhoto = null; } break; } case R.id.contacts_info_chat_btn: { String chatId = mAuthorUid + "_" + mUserInfoUid; startToChat(chatId); break; } case R.id.contacts_info_edit_info: { startToEditUserInfo(); break; } default: break; } } private void initOriginData() { mHeaderLayoutBkg.setOnClickListener(this); mHeaderLayoutDetail.setOnClickListener(this); mReturnBtn.setOnClickListener(this); mUserPic.setOnClickListener(this); mEditUserInfo.setOnClickListener(this); if (mUserHeadPic != null) { mUserPic.setImageBitmap(mUserHeadPic); } mUserName.setText(mUserInfo.getNickName()); mFriendName.setText(mUserInfo.getNickName()); mFriendsDesc.setText(mUserInfo.getIntroduce()); if (mUserInfoUid.equalsIgnoreCase(mAuthorUid)) { mChatButton.setVisibility(View.INVISIBLE); mEditUserInfo.setText("编辑资料"); } else { // String friendsDesc = String.format( // this.getString(R.string.chat_msg_friends_more), // mUserInfo.getFirstDirectFriend(), // mUserInfo.getDirectFriendsCount()); // mFriendsDesc.setText(friendsDesc); showChatBtn(); mEditUserInfo.setText("查看资料"); } if (mUserInfo.getGender() == ContactsInfo.GENDER.FEMALE.ordinal()) { mUserGender.setImageResource(R.drawable.ic_female_selected); } else { mUserGender.setImageResource(R.drawable.ic_male_selected); } if (mUserInfo.getAstro() == ContactsInfo.ASTRO.ARIES.ordinal()) { mUserAstro.setImageResource(R.drawable.ic_aries_baiyang_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.TAURUS.ordinal()) { mUserAstro.setImageResource(R.drawable.ic_taurus_jinniu_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.GEMINI.ordinal()) { mUserAstro.setImageResource(R.drawable.ic_gemini_shuangzhi_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.CANCER.ordinal()) { mUserAstro.setImageResource(R.drawable.ic_cancer_juxie_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.LEO.ordinal()) { mUserAstro.setImageResource(R.drawable.ic_leo_shizhi_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.VIRGO.ordinal()) { mUserAstro.setImageResource(R.drawable.ic_virgo_chunv_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.LIBRA.ordinal()) { mUserAstro.setImageResource(R.drawable.ic_libra_tiancheng_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.SCORPIO.ordinal()) { mUserAstro.setImageResource(R.drawable.ic_scorpio_tianxie_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.SAGITTARIUS .ordinal()) { mUserAstro .setImageResource(R.drawable.ic_sagittarius_sheshou_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.CAPRICPRN .ordinal()) { mUserAstro.setImageResource(R.drawable.ic_capricprn_mejie_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.AQUARIUS .ordinal()) { mUserAstro.setImageResource(R.drawable.ic_aquarius_shuiping_green); } else if (mUserInfo.getAstro() == ContactsInfo.ASTRO.PISCES.ordinal()) { mUserAstro.setImageResource(R.drawable.ic_pisces_shuangyu_green); } if (mUserInfo.getHobby() == ContactsInfo.GENDER.FEMALE.ordinal()) { mUserHobby.setImageResource(R.drawable.ic_female_selected); } else { mUserHobby.setImageResource(R.drawable.ic_male_selected); } if ("0".equalsIgnoreCase(mUserInfo.getHeaderBkgIndex())) { mHeaderLayoutBkg .setBackgroundResource(R.drawable.person_default_bkg); } else { mExecutorService.execute(new DownloadHeadBackground(mUserInfo .getUid(), mUserInfo.getHeaderBkgIndex())); } } private Bitmap loadUserHeadPicFromDB(String uid) { Bitmap headpic = null; String whereClause = MarrySocialDBHelper.KEY_UID + " = " + uid; Cursor cursor = mDBHelper .query(MarrySocialDBHelper.DATABASE_HEAD_PICS_TABLE, HEAD_PICS_PROJECTION, whereClause, null, null, null, null, null); if (cursor == null) { Log.w(TAG, "nannan query fail!"); return null; } try { cursor.moveToNext(); byte[] in = cursor.getBlob(1); headpic = BitmapFactory.decodeByteArray(in, 0, in.length); } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } return headpic; } private void loadContactsFromDB() { MarrySocialDBHelper dbHelper = MarrySocialDBHelper.newInstance(this); Cursor cursor = dbHelper.query( MarrySocialDBHelper.DATABASE_CONTACTS_TABLE, CONTACTS_PROJECTION, null, null, null, null, null, null); if (cursor == null) { Log.w(TAG, "nannan query fail!"); return; } try { while (cursor.moveToNext()) { String uid = cursor.getString(0); String phoneNum = cursor.getString(1); String nickname = cursor.getString(2); String realname = cursor.getString(3); String firstDirectFriend = cursor.getString(4); String directFriends = cursor.getString(5); String indirectId = cursor.getString(6); int directFriendsCount = cursor.getInt(7); int avatar = Integer.valueOf(cursor.getInt(8)); int gender = Integer.valueOf(cursor.getInt(9)); int astro = Integer.valueOf(cursor.getInt(10)); int hobby = Integer.valueOf(cursor.getInt(11)); String headerBkg = cursor.getString(12); String introduce = cursor.getString(13); ContactsInfo contactItem = new ContactsInfo(); contactItem.setUid(uid); contactItem.setPhoneNum(phoneNum); contactItem.setNickName(nickname); contactItem.setRealName(realname); contactItem.setHeadPic(avatar); contactItem.setGender(gender); contactItem.setAstro(astro); contactItem.setHobby(hobby); contactItem.setIndirectId(indirectId); contactItem.setFirstDirectFriend(firstDirectFriend); contactItem.setDirectFriends(directFriends); contactItem.setDirectFriendsCount(directFriendsCount); contactItem.setHeaderBkgIndex(headerBkg); contactItem.setIntroduce(introduce); mUserInfoEntrys.put(uid, contactItem); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } return; } private ArrayList<CommentsItem> loadUserCommentsFromDB(String uid) { ArrayList<CommentsItem> commentEntrys = new ArrayList<CommentsItem>(); Cursor cursor = null; try { String whereclause = MarrySocialDBHelper.KEY_UID + " = " + uid; String orderBy = MarrySocialDBHelper.KEY_ADDED_TIME + " DESC"; cursor = mDBHelper.query( MarrySocialDBHelper.DATABASE_COMMENTS_TABLE, COMMENTS_PROJECTION, whereclause, null, null, null, orderBy, null); if (cursor == null) { Log.e(TAG, "nannan loadUserCommentsFromDB().. cursor == null"); return commentEntrys; } while (cursor.moveToNext()) { CommentsItem comment = new CommentsItem(); String uId = cursor.getString(0); String bucketId = cursor.getString(1); String contents = cursor.getString(2); String nick_name = cursor.getString(3); int photo_count = cursor.getInt(4); int bravo_status = cursor.getInt(5); String added_time = cursor.getString(6); String comment_id = cursor.getString(7); comment.setUid(uId); comment.setBucketId(bucketId); comment.setCommentId(comment_id); comment.setContents(contents); comment.setRealName(nick_name); comment.setNickName(nick_name); comment.setPhotoCount(photo_count); comment.setAddTime(Utils.getAddedTimeTitle(this, added_time)); comment.setIsBravo(bravo_status == MarrySocialDBHelper.BRAVO_CONFIRM); commentEntrys.add(comment); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } mHandler.sendEmptyMessage(START_TO_LOAD_BRAVO_REPLY); return commentEntrys; } private void startToChat(String chatId) { Intent intent = new Intent(this, ChatMsgActivity.class); intent.putExtra(MarrySocialDBHelper.KEY_CHAT_ID, chatId); startActivity(intent); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case NEED_CROP: { Uri uri = null; if (data != null) { uri = data.getData(); } else { String fileName = getSharedPreferences( CommonDataStructure.PREFS_LAIQIAN_DEFAULT, MODE_PRIVATE).getString( CommonDataStructure.HEAD_PIC_NAME, ""); uri = Uri.fromFile(new File( CommonDataStructure.HEAD_PICS_DIR_URL, fileName)); } if (uri != null) { cropImage(uri, Utils.mCropCenterThumbPhotoWidth, Utils.mCropCenterThumbPhotoWidth, CROP_PICTURE); } break; } case CROP_PICTURE: { Uri photoUri = data.getData(); if (photoUri != null) { mCropPhoto = BitmapFactory.decodeFile(photoUri.getPath()); } if (mCropPhoto == null) { Bundle extra = data.getExtras(); if (extra != null) { mCropPhoto = (Bitmap) extra.get("data"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); mCropPhoto.compress(Bitmap.CompressFormat.JPEG, 100, stream); } } mCropPhotoName = "head_pic_" + mUserInfoUid + ".jpg"; ImageUtils.savePhotoToSDCard(mCropPhoto, CommonDataStructure.HEAD_PICS_DIR_URL, mCropPhotoName); mHandler.sendEmptyMessage(START_TO_UPLOAD); // iv_image.setImageBitmap(mCropPhoto);//联网才能上传照片 break; } case CHOOSE_BACKGROUND_PICTURE: { String localPath = data.getExtras().getString( MarrySocialDBHelper.KEY_PHOTO_LOCAL_PATH); String headerBkgIndex = data.getExtras().getString( MarrySocialDBHelper.KEY_HEADER_BACKGROUND_INDEX); updateHeaderBkgIndexToContactsDB(mAuthorUid, headerBkgIndex); Bitmap thumbHeader = Utils.decodeThumbnail(localPath, null, Utils.mThumbPhotoWidth); // Bitmap cropHeader = Utils.cropImages(thumbHeader, // mContactsInfoHeaderWidth, mContactsInfoHeaderHeight, // true); // mHeaderLayoutBkg.setBackground(ImageUtils // .bitmapToDrawable(cropHeader)); mHeaderLayoutBkg.setBackground(ImageUtils .bitmapToDrawable(thumbHeader)); mExecutorService.execute(new UploadHeadBackground(mAuthorUid, headerBkgIndex)); break; } default: break; } } } private void updateHeaderBkgIndexToContactsDB(String uid, String headerebkgindex) { ContentValues values = new ContentValues(); values.put(MarrySocialDBHelper.KEY_HEADER_BACKGROUND_INDEX, headerebkgindex); try { String whereClause = MarrySocialDBHelper.KEY_UID + " = " + uid; mDBHelper.update(MarrySocialDBHelper.DATABASE_CONTACTS_TABLE, values, whereClause, null); } catch (Exception exp) { exp.printStackTrace(); } } private void showBackgroundPicsPicker(Context context) { mSelectBkgDialog = new SelectBackgroundPicDialog(context); mSelectBkgDialog .setOnSelectPicBtnClickListener(mSelectPicBtnClickListener); mSelectBkgDialog.show(); } private OnSelectPicBtnClickListener mSelectPicBtnClickListener = new OnSelectPicBtnClickListener() { @Override public void onSelectPicBtnClick() { mSelectBkgDialog.dismiss(); startToChooseBackgroundPic(); } }; private void showHeaderPicsPicker(Context context, boolean isCrop) { final boolean needCrop = isCrop; mSelectHeaderPicDialog = new SelectHeaderPicDialog(context); mSelectHeaderPicDialog .setOnSmallItemClickListener(new OnSmallItemClickListener() { // 类型码 int REQUEST_CODE; @Override public void onCameraBtnClick() { Uri imageUri = null; String fileName = null; Intent openCameraIntent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); if (needCrop) { REQUEST_CODE = NEED_CROP; // 删除上一次截图的临时文件 SharedPreferences sharedPreferences = getSharedPreferences( CommonDataStructure.PREFS_LAIQIAN_DEFAULT, MODE_PRIVATE); ImageUtils.deletePhotoAtPathAndName( CommonDataStructure.HEAD_PICS_DIR_URL, sharedPreferences.getString( CommonDataStructure.HEAD_PIC_NAME, "")); // 保存本次截图临时文件名字 fileName = "head_pic_" + mUserInfoUid + ".jpg"; Editor editor = sharedPreferences.edit(); editor.putString(CommonDataStructure.HEAD_PIC_NAME, fileName); editor.commit(); } else { REQUEST_CODE = TAKE_PICTURE_FROM_CAMERA; fileName = "image.jpg"; } imageUri = Uri .fromFile(new File( CommonDataStructure.HEAD_PICS_DIR_URL, fileName)); // 指定照片保存路径(SD卡),image.jpg为一个临时文件,每次拍照后这个图片都会被替换 openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(openCameraIntent, REQUEST_CODE); mSelectHeaderPicDialog.dismiss(); } @Override public void onGalleryBtnClick() { // Intent openGalleryIntent = new Intent( // Intent.ACTION_GET_CONTENT); Intent openGalleryIntent = new Intent( Intent.ACTION_PICK); if (needCrop) { REQUEST_CODE = NEED_CROP; } else { REQUEST_CODE = CHOOSE_PICTURE_FROM_GALLERY; } openGalleryIntent.setDataAndType( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(openGalleryIntent, REQUEST_CODE); mSelectHeaderPicDialog.dismiss(); } }); mSelectHeaderPicDialog.show(); } // 截取图片 public void cropImage(Uri uri, int outputX, int outputY, int requestCode) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", outputX); intent.putExtra("outputY", outputY); intent.putExtra("outputFormat", "JPEG"); intent.putExtra("noFaceDetection", true); intent.putExtra("return-data", true); startActivityForResult(intent, requestCode); } class UploadHeadPics implements Runnable { private String uid; public UploadHeadPics(String uid) { this.uid = uid; } @Override public void run() { CommonDataStructure.UploadHeadPicResultEntry resultEntry = Utils .uploadHeadPicBitmap( CommonDataStructure.URL_UPLOAD_HEAD_PIC, uid, mCropPhoto, mCropPhotoName); if (!isUidExistInHeadPicDB(uid)) { insertHeadPicToHeadPicsDB(resultEntry); } else { updateHeadPicToHeadPicsDB(resultEntry); } mHandler.sendEmptyMessage(UPLOAD_FINISH); } } class UploadHeadBackground implements Runnable { private String uid; private String photonum; public UploadHeadBackground(String uid, String photonum) { this.uid = uid; this.photonum = photonum; } @Override public void run() { Utils.uploadHeaderBackground( CommonDataStructure.URL_PROFILE_BACKGROUND, uid, photonum); } } class DownloadHeadBackground implements Runnable { private String uid; private String photonum; public DownloadHeadBackground(String uid, String photonum) { this.uid = uid; this.photonum = photonum; } @Override public void run() { HeaderBackgroundEntry headerBkg = queryHeaderBkgEntryFromDB(photonum); if (headerBkg.photoLocalPath != null && headerBkg.photoLocalPath.length() != 0) { mHeadBkgPath = headerBkg.photoLocalPath; } else { File imageFile = Utils.downloadImageAndCache( headerBkg.photoRemotePath, CommonDataStructure.BACKGROUND_PICS_DIR_URL); updateHeaderBkgPathToHeaderBkgDB(imageFile.getAbsolutePath(), headerBkg.photoRemotePath); mHeadBkgPath = imageFile.getAbsolutePath(); } mHandler.sendEmptyMessage(DOWNLOAD_HEADER_BKG_FINISH); } } private void updateHeaderBkgPathToHeaderBkgDB(String localpath, String remotepath) { ContentValues values = new ContentValues(); values.put(MarrySocialDBHelper.KEY_PHOTO_LOCAL_PATH, localpath); values.put(MarrySocialDBHelper.KEY_CURRENT_STATUS, MarrySocialDBHelper.DOWNLOAD_FROM_CLOUD_SUCCESS); String whereClause = MarrySocialDBHelper.KEY_PHOTO_REMOTE_ORG_PATH + " = " + '"' + remotepath + '"'; try { ContentResolver resolver = getContentResolver(); resolver.update(CommonDataStructure.HEADBACKGROUNDURL, values, whereClause, null); } catch (Exception exp) { exp.printStackTrace(); } } private void insertHeadPicToHeadPicsDB( CommonDataStructure.UploadHeadPicResultEntry headPic) { ContentValues insertValues = new ContentValues(); insertValues.put(MarrySocialDBHelper.KEY_UID, headPic.uid); insertValues.put(MarrySocialDBHelper.KEY_HEAD_PIC_BITMAP, Utils.Bitmap2Bytes(mCropPhoto)); insertValues.put(MarrySocialDBHelper.KEY_PHOTO_REMOTE_ORG_PATH, headPic.orgUrl); insertValues.put(MarrySocialDBHelper.KEY_PHOTO_REMOTE_THUMB_PATH, headPic.smallThumbUrl); insertValues.put(MarrySocialDBHelper.KEY_CURRENT_STATUS, MarrySocialDBHelper.UPLOAD_TO_CLOUD_SUCCESS); try { ContentResolver resolver = getContentResolver(); resolver.insert(CommonDataStructure.HEADPICSURL, insertValues); } catch (Exception exp) { exp.printStackTrace(); } } private void updateHeadPicToHeadPicsDB( CommonDataStructure.UploadHeadPicResultEntry headPic) { ContentValues insertValues = new ContentValues(); insertValues.put(MarrySocialDBHelper.KEY_HEAD_PIC_BITMAP, Utils.Bitmap2Bytes(mCropPhoto)); insertValues.put(MarrySocialDBHelper.KEY_PHOTO_REMOTE_ORG_PATH, headPic.orgUrl); insertValues.put(MarrySocialDBHelper.KEY_PHOTO_REMOTE_THUMB_PATH, headPic.smallThumbUrl); insertValues.put(MarrySocialDBHelper.KEY_CURRENT_STATUS, MarrySocialDBHelper.UPLOAD_TO_CLOUD_SUCCESS); String whereClause = MarrySocialDBHelper.KEY_UID + " = " + headPic.uid; try { ContentResolver resolver = getContentResolver(); resolver.update(CommonDataStructure.HEADPICSURL, insertValues, whereClause, null); } catch (Exception exp) { exp.printStackTrace(); } } public HeaderBackgroundEntry queryHeaderBkgEntryFromDB(String headerBkgIndex) { HeaderBackgroundEntry headerBkgEntry = new HeaderBackgroundEntry(); Cursor cursor = null; try { String whereclause = MarrySocialDBHelper.KEY_HEADER_BACKGROUND_INDEX + " = " + headerBkgIndex; cursor = mDBHelper.query( MarrySocialDBHelper.DATABASE_HEAD_BACKGROUND_PICS_TABLE, HEAD_BACKGROUND_PROJECTION, whereclause, null, null, null, null, null); if (cursor == null || cursor.getCount() == 0) { return headerBkgEntry; } cursor.moveToNext(); headerBkgEntry.photoName = cursor.getString(0); headerBkgEntry.photoLocalPath = cursor.getString(1); headerBkgEntry.photoRemotePath = cursor.getString(2); headerBkgEntry.headerBkgIndex = cursor.getString(3); } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } return headerBkgEntry; } public boolean isUidExistInHeadPicDB(String uid) { Cursor cursor = null; try { String whereclause = MarrySocialDBHelper.KEY_UID + " = " + uid; cursor = mDBHelper.query( MarrySocialDBHelper.DATABASE_HEAD_PICS_TABLE, HEAD_PICS_PROJECTION, whereclause, null, null, null, null, null); if (cursor == null || cursor.getCount() == 0) { return false; } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } return true; } private class DataSetChangeObserver extends ContentObserver { private Handler handler; private int status; public DataSetChangeObserver(Handler handler, int status) { super(handler); this.handler = handler; this.status = status; } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); switch (status) { case REFRESH_HEADER_PIC: { handler.sendEmptyMessage(REFRESH_HEADER_PIC); break; } case UPLOAD_COMMENT: { handler.sendEmptyMessage(UPLOAD_COMMENT); break; } default: break; } Log.e(TAG, "nannan onChange().."); } } private void startToChooseBackgroundPic() { Intent intent = new Intent(this, ChooseHeaderBackgroundActivity.class); startActivityForResult(intent, CHOOSE_BACKGROUND_PICTURE); } private void generateDBData() { int index = 1; for (String remote : CommonDataStructure.HEADER_BKG_PATH) { String name = index + ".jpg"; if (!isHeaderBkgPathExistInHeaderBkgDB(remote)) { insertHeaderBkgPathToHeaderBkgDB(name, remote, index); } index++; } } public boolean isHeaderBkgPathExistInHeaderBkgDB(String remotepath) { Cursor cursor = null; try { String whereclause = MarrySocialDBHelper.KEY_PHOTO_REMOTE_ORG_PATH + " = " + '"' + remotepath + '"'; cursor = mDBHelper.query( MarrySocialDBHelper.DATABASE_HEAD_BACKGROUND_PICS_TABLE, HEAD_BKG_PROJECTION, whereclause, null, null, null, null, null); if (cursor == null || cursor.getCount() == 0) { return false; } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } return true; } private void insertHeaderBkgPathToHeaderBkgDB(String photoname, String remotepath, int picindex) { ContentValues values = new ContentValues(); values.put(MarrySocialDBHelper.KEY_PHOTO_NAME, photoname); values.put(MarrySocialDBHelper.KEY_PHOTO_REMOTE_ORG_PATH, remotepath); values.put(MarrySocialDBHelper.KEY_CURRENT_STATUS, MarrySocialDBHelper.NEED_DOWNLOAD_FROM_CLOUD); values.put(MarrySocialDBHelper.KEY_HEADER_BACKGROUND_INDEX, String.valueOf(picindex)); try { mDBHelper.insert( MarrySocialDBHelper.DATABASE_HEAD_BACKGROUND_PICS_TABLE, values); } catch (Exception exp) { exp.printStackTrace(); } } class LoadBravoAndReplyContents implements Runnable { private String comment_id; public LoadBravoAndReplyContents(String comment_id) { this.comment_id = comment_id; } @Override public void run() { loadContactsFromDB(); loadBravosFromDB(comment_id); loadReplysFromDB(comment_id); mHandler.sendEmptyMessage(UPDATE_DYNAMIC_INFO); } } private void loadBravosFromDB(String comment_id) { StringBuffer author_names = new StringBuffer(); Cursor cursor = null; try { String whereclause = MarrySocialDBHelper.KEY_COMMENT_ID + " = " + comment_id + " AND " + MarrySocialDBHelper.KEY_CURRENT_STATUS + " != " + MarrySocialDBHelper.NEED_DELETE_FROM_CLOUD; String orderBy = MarrySocialDBHelper.KEY_ID + " ASC"; cursor = mDBHelper.query(MarrySocialDBHelper.DATABASE_BRAVOS_TABLE, BRAVOS_PROJECTION, whereclause, null, null, null, orderBy, null); if (cursor == null) { Log.e(TAG, "nannan loadBravosFromDB().. cursor == null"); return; } while (cursor.moveToNext()) { author_names.append(cursor.getString(2)).append(" "); } if (author_names.length() != 0) { mBravoEntrys.put(comment_id, author_names.toString()); } else { mBravoEntrys.put(comment_id, ""); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } } private void loadReplysFromDB(String comment_id) { ArrayList<ReplysItem> replys = new ArrayList<ReplysItem>(); Cursor cursor = null; try { String whereclause = MarrySocialDBHelper.KEY_COMMENT_ID + " = " + comment_id; String orderBy = MarrySocialDBHelper.KEY_ADDED_TIME + " ASC"; cursor = mDBHelper.query(MarrySocialDBHelper.DATABASE_REPLYS_TABLE, REPLYS_PROJECTION, whereclause, null, null, null, orderBy, null); if (cursor == null) { Log.e(TAG, "nannan loadReplysFromDB().. cursor == null"); return; } while (cursor.moveToNext()) { ReplysItem item = new ReplysItem(); item.setCommentId(comment_id); item.setNickname(cursor.getString(1)); item.setReplyContents(cursor.getString(2)); item.setUid(cursor.getString(0)); replys.add(item); } if (replys.size() != 0) { mReplyEntrys.put(comment_id, replys); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } } private onReplyBtnClickedListener mReplyBtnClickedListener = new onReplyBtnClickedListener() { @Override public void onReplyBtnClicked(int position) { mReplyCommentsPosition = position; hideChatBtn(); showReplyFootBar(); mHandler.sendEmptyMessageDelayed(SHOW_SOFT_INPUT_METHOD, 50); Message msg = mHandler.obtainMessage(); msg.what = SELECT_SPECIFIED_LIST_ITEM; msg.arg1 = position + 1; mHandler.sendMessage(msg); } }; private View.OnClickListener mReplySendBtnClickedListener = new View.OnClickListener() { @Override public void onClick(View v) { if (!Utils.isActiveNetWorkAvailable(ContactsInfoActivity.this)) { mHandler.sendEmptyMessage(NETWORK_INVALID); return; } CommentsItem comment = (CommentsItem) (mListViewAdapter .getItem(mReplyCommentsPosition)); long time = System.currentTimeMillis() / 1000; String replyTime = Long.toString(time); String bucketId = String.valueOf(replyTime.hashCode()); ReplysItem reply = new ReplysItem(); reply.setCommentId(comment.getCommentId()); reply.setReplyContents(mReplyContents.getText().toString()); reply.setReplyTime(replyTime); reply.setBucketId(bucketId); insertReplysToReplyDB(reply); uploadReplysToCloud(CommonDataStructure.KEY_REPLYS, comment.getCommentId(), bucketId); mHandler.sendEmptyMessage(SEND_REPLY_FINISH); mHandler.sendEmptyMessage(UPDATE_DYNAMIC_INFO); } }; private void insertReplysToReplyDB(ReplysItem reply) { ContentValues insertValues = new ContentValues(); insertValues.put(MarrySocialDBHelper.KEY_COMMENT_ID, reply.getCommentId()); insertValues.put(MarrySocialDBHelper.KEY_UID, mAuthorUid); insertValues .put(MarrySocialDBHelper.KEY_BUCKET_ID, reply.getBucketId()); insertValues.put(MarrySocialDBHelper.KEY_AUTHOR_NICKNAME, mAuthorName); insertValues.put(MarrySocialDBHelper.KEY_REPLY_CONTENTS, reply.getReplyContents()); insertValues.put(MarrySocialDBHelper.KEY_ADDED_TIME, reply.getReplyTime()); insertValues.put(MarrySocialDBHelper.KEY_CURRENT_STATUS, MarrySocialDBHelper.NEED_UPLOAD_TO_CLOUD); try { ContentResolver resolver = this.getContentResolver(); resolver.insert(CommonDataStructure.REPLYURL, insertValues); } catch (Exception exp) { exp.printStackTrace(); } } private void uploadReplysToCloud(int uploadType, String comment_id, String bucket_id) { Intent serviceIntent = new Intent(this, UploadCommentsAndBravosAndReplysIntentService.class); serviceIntent.putExtra(CommonDataStructure.KEY_UPLOAD_TYPE, uploadType); serviceIntent.putExtra(MarrySocialDBHelper.KEY_COMMENT_ID, comment_id); serviceIntent.putExtra(MarrySocialDBHelper.KEY_BUCKET_ID, bucket_id); startService(serviceIntent); } private void hideReplyFootBar() { mReplyFoot.setVisibility(View.GONE); } private void showReplyFootBar() { mReplyFoot.setVisibility(View.VISIBLE); mReplyFoot.requestFocus(); } private void hideChatBtn() { if (!mUserInfoUid.equalsIgnoreCase(mAuthorUid)) { mChatButton.clearAnimation(); mChatButton.startAnimation(mHideChatBtnTransAnimation); mChatButton.setVisibility(View.INVISIBLE); mChatButton.setClickable(false); } } private void showChatBtn() { if (!mUserInfoUid.equalsIgnoreCase(mAuthorUid)) { mChatButton.clearAnimation(); mChatButton.startAnimation(mShowChatBtnTransAnimation); mChatButton.setVisibility(View.VISIBLE); mChatButton.setClickable(true); mChatButton.requestFocus(); } } private void startToEditUserInfo() { Intent intent = new Intent(this, EditUserInfoActivity.class); intent.putExtra(MarrySocialDBHelper.KEY_UID, mUserInfoUid); startActivity(intent); } }
package de.shm.fangbuch; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.FileProvider; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Spinner; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link AddFish.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link AddFish#newInstance} factory method to * create an instance of this fragment. */ public class AddFish extends Fragment { static final int REQUEST_IMAGE_CAPTURE = 1; static final int REQUEST_TAKE_PHOTO = 2; public final static String ADD_FISH = "AddFish"; public final static String LON = "LON"; public final static String LAT = "LAT"; public final static String ART = "ART"; public final static String GROESSE = "groesse"; public final static String GEWICHT = "gewicht"; public final static String LOCATION = "ort"; public final static String KOEDER = "Koeder"; public final static String TEMPERATUR = "Temperatur"; public final static String LUFTDRUCK = "Luftdruck"; public final static String WETTER = "Wetter"; private double latitude; private double longtitude; private Weather mWeather; Spinner spinnerChooseFish; EditText editTextSize; EditText editTextGewicht; EditText editTextLocation; AutoCompleteTextView autoCompleteTextViewBait; private String mCurrentPhotoPath; public AddFish() { // Required empty public constructor } public static AddFish newInstance(double lon, double lat) { AddFish fragment = new AddFish(); Bundle args = new Bundle(); args.putDouble(LON,lon); args.putDouble(LAT,lat); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(getArguments()!=null){ longtitude = getArguments().getDouble(LON); latitude = getArguments().getDouble(LAT); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment FloatingActionButton floatingActionButton = (FloatingActionButton) getActivity().findViewById(R.id.fab); floatingActionButton.hide(); View view = inflater.inflate(R.layout.fragment_addfish, container, false); ImageButton imageButtonAddPicture = (ImageButton) view.findViewById(R.id.imageButtonNewFishAddPicture); imageButtonAddPicture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchTakePictureIntent(); } }); spinnerChooseFish = (Spinner) view.findViewById(R.id.spinnerChooseFish); String[] fishes = getActivity().getResources().getStringArray(R.array.fishes); ArrayAdapter<String> adapter = new ArrayAdapter<String>(view.getContext(),android.R.layout.simple_spinner_dropdown_item,fishes); spinnerChooseFish.setAdapter(adapter); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); mWeather = Weather.newInstance(longtitude,latitude); transaction.replace(R.id.addFishFragment,mWeather,Weather.WEATHER_FRAGMENT); transaction.commit(); final Button buttonFishDeclair = (Button) view.findViewById(R.id.buttonNewFishDeclair); buttonFishDeclair.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragmentManager fm = getActivity().getSupportFragmentManager(); FishDeclair fd = FishDeclair.newInstance(spinnerChooseFish.getSelectedItem().toString()); fd.show(fm,FishDeclair.FISH_DECLAIR); } }); final Button buttonSaveFish = (Button) view.findViewById(R.id.buttonNewFishSave); buttonSaveFish.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveFisch(); } }); editTextSize = (EditText) view.findViewById(R.id.editTextNewFishSize) ; editTextGewicht = (EditText) view.findViewById(R.id.editTextNewFishWeight); editTextLocation = (EditText) view.findViewById(R.id.editTextNewFishLocation); autoCompleteTextViewBait = (AutoCompleteTextView) view.findViewById(R.id.autoComTextViewNewFishBait); return view; } public void onButtonPressed(Uri uri) { } @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onDetach() { super.onDetach(); FloatingActionButton floatingActionButton = (FloatingActionButton) getActivity().findViewById(R.id.fab); floatingActionButton.show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == getActivity().RESULT_OK){ Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); final ImageView imageViewPicture = (ImageView) getView().findViewById(R.id.imageViewNewFishPicture); imageViewPicture.setImageBitmap(imageBitmap); } if(requestCode == REQUEST_TAKE_PHOTO && resultCode == getActivity().RESULT_OK){ setPic(); } } public interface OnFragmentInteractionListener { void onFragmentInteraction(Uri uri); } private void dispatchTakePictureIntent(){ Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(takePictureIntent.resolveActivity(getActivity().getPackageManager())!=null){ File photoFile = null; try { photoFile = creatImageFile(); }catch (IOException e){ e.printStackTrace(); } if(photoFile!=null) { Uri photoURI = FileProvider.getUriForFile(getActivity(),"de.shm.fangbuch",photoFile); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI); startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); } } } private File creatImageFile() throws IOException { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES); File image = File.createTempFile(imageFileName,".jpg",storageDir); mCurrentPhotoPath="file:"+image.getAbsolutePath(); return image; } private void setPic(){ ImageView imageViewNewFishPic = (ImageView) getView().findViewById(R.id.imageViewNewFishPicture); int targetW = imageViewNewFishPic.getWidth(); int targetH = imageViewNewFishPic.getHeight(); BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(mCurrentPhotoPath.replaceFirst("file:",""),bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; int scaleFactor = Math.min(photoW/targetW,photoH/targetH); bmOptions.inJustDecodeBounds=false; bmOptions.inSampleSize=scaleFactor; bmOptions.inPurgeable=true; Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath.replaceFirst("file:",""),bmOptions); imageViewNewFishPic.setImageBitmap(bitmap); } private void saveFisch(){ JSONObject store = new JSONObject(); try { store.put(LAT,latitude); store.put(LON,longtitude); String fischArt = spinnerChooseFish.getSelectedItem().toString(); store.put(ART,fischArt); store.put(GROESSE,Long.parseLong(editTextSize.getText().toString())); store.put(GEWICHT,Long.parseLong(editTextGewicht.getText().toString())); store.put(LOCATION,editTextLocation.getText().toString()); store.put(KOEDER,autoCompleteTextViewBait.getText().toString()); store.put(TEMPERATUR,mWeather.getTemperatur()); store.put(LUFTDRUCK,mWeather.getPressure()); Log.d(ADD_FISH,store.toString()); } catch (JSONException e) { e.printStackTrace(); }catch (NumberFormatException e){ e.printStackTrace(); } } }
package com.whs.shop.bgrestful.goods.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.whs.shop.baseentity.baseentity.rest.Response; import com.whs.shop.common.web.BaseController; import com.whs.shop.common.utils.ObjectUtils; import com.whs.shop.modules.goods.entity.GoodsSpec; import com.whs.shop.modules.goods.service.interf.IGoodsSpecService; /** * 商品规格Controller * @author huang * @version 2018-05-05 */ @RestController @RequestMapping(value = "${adminPath}/rest/goods/goodsSpec") public class GoodsSpecController extends BaseController { @Autowired private IGoodsSpecService goodsSpecService; /** * 添加商品标签 */ @RequestMapping("/add") public Response addgoodsSpec(HttpServletRequest request,Model model, RedirectAttributes redirectAttributes) throws Exception { GoodsSpec goodsSpec = ObjectUtils.fromJson(GoodsSpec.class, request); goodsSpecService.insert(goodsSpec); return new Response().success(); } /** * 删除商品标签 */ @RequestMapping("/delete") public Response deletegoodsSpec(HttpServletRequest request) throws Exception { GoodsSpec goodsSpec = ObjectUtils.fromJson(GoodsSpec.class, request); int status = 0; try{ goodsSpecService.delete(goodsSpec); status =200; }catch(Exception e){ status =201; } return new Response().success(status); } /** *修改商品标签 */ @RequestMapping("/update") public Response updategoodsSpec(HttpServletRequest request) throws Exception { GoodsSpec goodsSpec = ObjectUtils.fromJson(GoodsSpec.class, request); int status = 0; try{ goodsSpecService.update(goodsSpec); status =200; }catch(Exception e){ status =201; } return new Response().success(status); } /** * 查询商品标签 */ @RequestMapping("/get") public Response getgoodsSpec(HttpServletRequest request) throws Exception { GoodsSpec goodsSpec = ObjectUtils.fromJson(GoodsSpec.class, request); return new Response().success(goodsSpecService.get(goodsSpec)); } /*@RequestMapping("/list") public Response list(HttpServletRequest request) throws Exception { GoodsSpec goodsSpec = ObjectUtils.fromJson(GoodsSpec.class, request); return null; }*/ }
package com.wcy.netty.protocol.response; import com.wcy.netty.protocol.Packet; import com.wcy.zjh.model.Player; import lombok.Data; import java.util.List; import java.util.Set; import static com.wcy.netty.protocol.command.Command.ROOM_USER_RESPONSE; @Data public class RoomUserResponsePacket extends Packet { private boolean success; private String message; private List<Player> playerList; @Override public Byte getCommand() { return ROOM_USER_RESPONSE; } }
package org.apache.commons.net.nntp; import java.io.BufferedReader; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.net.io.DotTerminatedMessageReader; import org.apache.commons.net.io.Util; class ReplyIterator implements Iterator<String>, Iterable<String> { private final BufferedReader reader; private String line; private Exception savedException; ReplyIterator(BufferedReader _reader, boolean addDotReader) throws IOException { this.reader = addDotReader ? (BufferedReader)new DotTerminatedMessageReader(_reader) : _reader; this.line = this.reader.readLine(); if (this.line == null) Util.closeQuietly(this.reader); } ReplyIterator(BufferedReader _reader) throws IOException { this(_reader, true); } public boolean hasNext() { if (this.savedException != null) throw new NoSuchElementException(this.savedException.toString()); return (this.line != null); } public String next() throws NoSuchElementException { if (this.savedException != null) throw new NoSuchElementException(this.savedException.toString()); String prev = this.line; if (prev == null) throw new NoSuchElementException(); try { this.line = this.reader.readLine(); if (this.line == null) Util.closeQuietly(this.reader); } catch (IOException ex) { this.savedException = ex; Util.closeQuietly(this.reader); } return prev; } public void remove() { throw new UnsupportedOperationException(); } public Iterator<String> iterator() { return this; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\nntp\ReplyIterator.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
/* * Copyright 2008 University of California at Berkeley * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.rebioma.client.forms; import com.google.gwt.user.client.ui.PasswordTextBox; /** * A password {@link FormInput} that if required, validates input using the * following password rules: * * <pre> * Must be 6-16 characters. * Alphanumeric, hyphen(-), and underscore(_) allowed. * Must contain both numbers and letters. * </pre> * */ public class PasswordFormInput extends FormInput { /** * The regular expression that passwords must match. * */ private final static String PASSWORD_REGEX = "^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9_-]{6,24}$"; /** * Constructs a new password form input. * * @param inputTitle form title * @param validate if true, validate the input */ public PasswordFormInput(String inputTitle, boolean validate) { super(inputTitle, new PasswordTextBox(), validate); validateInput = validate; } @Override public void clear() { ((PasswordTextBox) widget).setText(""); } @Override public String getInputValue() { return ((PasswordTextBox) widget).getText(); } @Override public String validate() { if (validateInput) { return getInputValue().matches(PASSWORD_REGEX) ? null : " "; } return null; } }
import java.util.Scanner; public class RabbitsWhile { /** * @param args */ public static void main(String[] args) { int months; int something = 0; int a = 0; int b = 1; int c = 0; int PH = 1; int input; Scanner keyboard = new Scanner(System.in); months = keyboard.nextInt(); while(months != something) { c = a+b; b=a; a=c; something++; System.out.println("Month "+PH+" had: "+c+" Rabbit pairs!"); PH++; } System.out.println("Test"); } }
package com.lucy.start.mvc.spring.news.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class NewsContrller { @RequestMapping("/") public String getNews() { return "news"; } }
package net.h2.web.mob.mainpage; import java.util.List; import net.h2.web.core.base.shared.service.IBaseService; import net.h2.web.mob.file.page.MainPageFileDTO; import net.h2.web.mob.mainpage.enums.MainPageType; public interface IMainPageService extends IBaseService<MainPageFileDTO, Long> { List<MainPageFileDTO> getMainPageListByType(MainPageType type); }
package seleniummaven; import java.io.File; import java.lang.ref.PhantomReference; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Assert; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.io.FileHandler; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Reporter; import org.testng.annotations.Test; public class ChromeUpdate { public static Logger log=LogManager.getLogger(ChromeUpdate.class.getName()); public static WebDriver driver; @Test public void runner() throws Exception { System.setProperty("webdriver.chrome.driver","C:\\Sunny\\chromedriver\\chromedriver.exe"); driver=new ChromeDriver(); log.info("Starting Browser"); driver.manage().window().maximize(); driver.get("http://www.google.com"); WebElement tin=driver.findElement(By.name("q")); tin.sendKeys("Selenium"+Keys.ENTER); log.info("value Browser"); Thread.sleep(5000); driver.getTitle().contains("Selenium"); Assert.assertFalse(true); log.info("Fail Browser"); driver.close(); } public void getScreenshot(String screenshotName) { try { TakesScreenshot ts=(TakesScreenshot)driver; File src=ts.getScreenshotAs(OutputType.FILE); FileHandler.copy(src, new File("C:\\Sunny\\Screenshot\\"+screenshotName+".png")); } catch (Exception e) { System.out.println(e); } } }
package com.proyecto.pac.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import com.proyecto.pac.models.entity.Empleado; import com.proyecto.pac.models.service.ServicioUsuario; @Controller public class EmpleadoController { @Autowired ServicioUsuario servicioUsuario; @GetMapping(path = {"/empleado/validar"}) public String validar() { return "empleado/validar"; } @PostMapping("/empleado/validar") public String agregar(@RequestParam("username") String correoe, @RequestParam("password") String claveacceso, Model modelo) { return "redirect:/productos/list"; } @GetMapping("/empleado/agregar") public String agregar(Model model) { model.addAttribute("usuario", new Empleado()); return "empleado/agregar"; } @PostMapping("/empleado/agregar") public String agregar (Model modelo, @ModelAttribute Empleado user, @RequestParam("clave") String clave, HttpSession sesion) { boolean res = servicioUsuario.agregar(user, clave, sesion); if(res) { return "redirect:/empleado/validar"; } modelo.addAttribute("error", servicioUsuario.getMensaje()); return "empleado/validar"; } @GetMapping("/empleado/salir") public String salir(HttpSession sesion) { SecurityContextHolder.clearContext(); sesion.invalidate(); return "redirect:/home"; } }
package com.example.animation; import com.example.animation.widget.ShutterView; import android.animation.ObjectAnimator; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.AdapterView.OnItemSelectedListener; /** * Created by ouyangshen on 2017/11/27. */ public class ShutterActivity extends AppCompatActivity { private ShutterView sv_shutter; // 声明一个百叶窗视图对象 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shutter); // 从布局文件中获取名叫sv_shutter的百叶窗视图 sv_shutter = findViewById(R.id.sv_shutter); // 设置百叶窗视图的位图对象 sv_shutter.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.bdg03)); initShutterSpinner(); } // 初始化动画类型下拉框 private void initShutterSpinner() { ArrayAdapter<String> shutterAdapter = new ArrayAdapter<String>(this, R.layout.item_select, shutterArray); Spinner sp_shutter = findViewById(R.id.sp_shutter); sp_shutter.setPrompt("请选择百叶窗动画类型"); sp_shutter.setAdapter(shutterAdapter); sp_shutter.setOnItemSelectedListener(new ShutterSelectedListener()); sp_shutter.setSelection(0); } private String[] shutterArray = {"水平五叶", "水平十叶", "水平二十叶", "垂直五叶", "垂直十叶", "垂直二十叶"}; class ShutterSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // 设置百叶窗的方向 sv_shutter.setOriention((arg2 < 3) ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); if (arg2 == 0 || arg2 == 3) { sv_shutter.setLeafCount(5); // 设置百叶窗的叶片数量 } else if (arg2 == 1 || arg2 == 4) { sv_shutter.setLeafCount(10); // 设置百叶窗的叶片数量 } else if (arg2 == 2 || arg2 == 5) { sv_shutter.setLeafCount(20); // 设置百叶窗的叶片数量 } // 构造一个按比率逐步展开的属性动画 ObjectAnimator anim = ObjectAnimator.ofInt(sv_shutter, "ratio", 0, 100); anim.setDuration(3000); // 设置动画的播放时长 anim.start(); // 开始播放属性动画 } public void onNothingSelected(AdapterView<?> arg0) {} } }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; public class Task10 { /*Дан массив целых чисел: [15,10,0,-6,-5,3,0,-34,0,32,56,0,24,-52]. Переместить нули в конец массива. Вывести результат в консоль*/ public static void main(String[] args) { int[] data = {15, 10, 0, -6, -5, 3, 0, -34, 0, 32, 56, 0, 24, -52}; ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < data.length; i++) list.add(data[i]); moveZero(list); } public static void moveZero(ArrayList<Integer> list) { for (int i = 0; i < list.size(); i++) { if (list.get(i) == 0) { list.remove(i); list.add(list.size(), 0); } } for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } }
package com.ebay.lightning.core.beans; import java.io.Serializable; import java.util.Map; import java.util.Map.Entry; import com.ebay.lightning.core.constants.LightningCoreConstants.WorkStatus; /** * The {@code LightningResponse} class defines the interface for the task agreed by the client and core. * The class also contains {@link SuccessResponse} to define a successful task, which is identified by a * HTTP response code of '200' and {@link FailedResponse} to define a failed task. * * @author shashukla * @see LightningRequest * @see SuccessResponse * @see FailedResponse * @see BatchReport */ public class LightningResponse implements Serializable { private static final long serialVersionUID = 1L; private String sessionId; private int totalCount; private int successCount; private WorkStatus status; private Map<Integer, FailedResponse> failedResponses; private Map<Integer, SuccessResponse> successResponses; public LightningResponse(String sessionId, WorkStatus status) { this.sessionId = sessionId; this.status = status; } /** * Get the sessionId of the request. * @return the sessionId of the request */ public String getSessionId() { return this.sessionId; } /** * Set the sessionId of the request. * @param sessionId the sessionId to set */ public void setSessionId(String sessionId) { this.sessionId = sessionId; } /** * Get the total count of tasks executed. * @return the total count of tasks executed */ public int getTotalCount() { return this.totalCount; } /** * Set the total count of tasks executed. * @param totalCount the total count of tasks executed */ public void setTotalCount(int totalCount) { this.totalCount = totalCount; } /** * Get the successful count of tasks executed. * @return the successful count of tasks executed */ public int getSuccessCount() { return this.successCount; } /** * Set the successful count of tasks executed. * @param successCount the successful count of tasks executed */ public void setSuccessCount(int successCount) { this.successCount = successCount; } /** * Get the {@link WorkStatus} of the request. * * The status can be one of (IN_QUEUE, RUNNING, DONE, STOPPED, CLEANED_UP) * @return the {@link WorkStatus} of the request */ public WorkStatus getStatus() { return this.status; } /** * Set the {@link WorkStatus} of the request. * * The status can be one of (IN_QUEUE, RUNNING, DONE, STOPPED, CLEANED_UP) * @param status the {@link WorkStatus} of the request */ public void setStatus(WorkStatus status) { this.status = status; } /** * Check of the request is completed. * @return true if the all tasks in the request are completed. */ public boolean isCompleted() { return WorkStatus.DONE.equals(this.status) || WorkStatus.STOPPED.equals(this.status); } /* (non-Javadoc) * @see {@link Object#toString()} */ @Override public String toString() { return "LightningResponse [Id=" + this.sessionId + ", success/total=" + this.successCount + "/" + this.totalCount + ", status=" + this.status + "]"; } public String prettyPrint(){ final String seperator = System.getProperty("line.separator"); final StringBuilder builder = new StringBuilder(); builder.append(toString()).append(seperator); if(this.successResponses!=null && this.successResponses.size()>0){ builder.append("Successful Response").append(seperator).append("********************").append(seperator); for(final Entry<Integer, SuccessResponse> response : this.successResponses.entrySet()) { builder.append(response.getKey()+ " -> " + response.getValue()).append(seperator); } } if(this.failedResponses!=null && this.failedResponses.size()>0){ builder.append("Failed Response").append(seperator).append("****************").append(seperator); for(final Entry<Integer, FailedResponse> response : this.failedResponses.entrySet()) { builder.append(response.getKey()+ " -> " + response.getValue()).append(seperator); } } return builder.toString(); } /** * Get the list of failed response. * @return the list of failed response */ public Map<Integer, FailedResponse> getFailedResponses() { return this.failedResponses; } /** * Set the list of failed response. * @param failedResponses the list of failed response */ public void setFailedResponses(Map<Integer, FailedResponse> failedResponses) { this.failedResponses = failedResponses; } /** * Get the list of successful response. * @return the list of successful response */ public Map<Integer, SuccessResponse> getSuccessResponses() { return this.successResponses; } /** * Set the list of successful response. * @param successResponses the list of successful response */ public void setSuccessResponses(Map<Integer, SuccessResponse> successResponses) { this.successResponses = successResponses; } public static class FailedResponse implements Serializable { private static final long serialVersionUID = 1L; private final int statusCode; private final String errMsg; /** * Initialized a failed response. * @param statusCode the HTTP status code * @param errMsg the error message */ public FailedResponse(int statusCode, String errMsg) { this.statusCode = statusCode; this.errMsg = errMsg; } /** * Get the error message related to the failure. * @return the error message */ public String getErrMsg() { return this.errMsg; } /** * Get the HTTP status code. * @return the HTTP status code */ public int getStatusCode() { return this.statusCode; } /* (non-Javadoc) * @see {@link Object#toString()} */ @Override public String toString() { return String.format("Status [%d], Error Msg [%s]", this.statusCode, this.errMsg); } } public static class SuccessResponse implements Serializable { private static final long serialVersionUID = 1L; private static final int maxFormatLength = 10; private String body; /** * Initializes a successful response. * @param body the response content */ public SuccessResponse(String body) { this.body = body; } /** * Get the response body content. * @return the response body content */ public String getBody() { return this.body; } /** * Set the response body content. * @param body the response body content */ public void setBody(String body) { this.body = body; } /* (non-Javadoc) * @see {@link Object#toString()} */ @Override public String toString() { String trimBody = this.body; if(trimBody != null && trimBody.length()>maxFormatLength){ trimBody = trimBody.substring(0, maxFormatLength) + "..."; } return String.format("Status [200], Body [%s]", trimBody); } } }
package edu.bupt.cbh.testing.dao; import edu.bupt.cbh.testing.entity.Testing; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by scarlett on 2017/5/26. */ @Repository public interface TestingDao { Integer addTesting(Testing testing); Integer updateTesting(Testing testing); /** * 获得此测试下所有测试单元 * @param testId * @return */ List<Testing> getAllTestings(Integer testId); }
package com.entity; import java.sql.Date; import javax.persistence.Entity; /** * @author lyx * * 2015-8-18上午11:38:32 * *com.yr.entity.MemberUser * TODO MemberUser实体类 */ public class MemberUser { /** * 会员ID */ private int memberId; /** * 会员名称 */ private String memberName; /** * 年龄 */ private int age; /** * 性别 */ private String gender; /** * 生日 */ private Date birthday; /** * 个人标签 */ private String memberLabel; /** * 个人说明 */ private String memberIntroduction; /** * 图片 */ private String memberPicture; /** * 注册日期 */ private Date registerDate; /** * 角色ID */ private int roleId; /** * 会员密码 */ private String pwd; /** * 会员积分 */ private int memberIntegral; /** * 账号 */ private String accountNumber; /** * 用户邮箱 */ private String memberEmail; public MemberUser() { super(); } public MemberUser(int memberId, String memberName, int age, String gender, Date birthday, String memberLabel, String memberIntroduction, String memberPicture, Date registerDate, int roleId, String pwd, int memberIntegral, String accountNumber, String memberEmail) { super(); this.memberId = memberId; this.memberName = memberName; this.age = age; this.gender = gender; this.birthday = birthday; this.memberLabel = memberLabel; this.memberIntroduction = memberIntroduction; this.memberPicture = memberPicture; this.registerDate = registerDate; this.roleId = roleId; this.pwd = pwd; this.memberIntegral = memberIntegral; this.accountNumber = accountNumber; this.memberEmail = memberEmail; } public String getAccountNumber() { return accountNumber; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public String getMemberLabel() { return memberLabel; } public String getMemberEmail() { return memberEmail; } public void setMemberEmail(String memberEmail) { this.memberEmail = memberEmail; } public int getMemberId() { return memberId; } public void setMemberId(int memberId) { this.memberId = memberId; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMenberLabel() { return memberLabel; } public void setMemberLabel(String memberLabel) { this.memberLabel = memberLabel; } public String getMemberIntroduction() { return memberIntroduction; } public void setMemberIntroduction(String memberIntroduction) { this.memberIntroduction = memberIntroduction; } public String getMemberPicture() { return memberPicture; } public void setMemberPicture(String memberPicture) { this.memberPicture = memberPicture; } public Date getRegisterDate() { return registerDate; } public void setRegisterDate(Date registerDate) { this.registerDate = registerDate; } public int getRoleId() { return roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public int getMemberIntegral() { return memberIntegral; } public void setMemberIntegral(int memberIntegral) { this.memberIntegral = memberIntegral; } }
package com.fr.virtualtimeclock_client; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.renderscript.Script; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.firebase.ui.firestore.FirestoreRecyclerAdapter; import com.firebase.ui.firestore.FirestoreRecyclerOptions; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.GeoPoint; import com.google.firebase.firestore.Query; public class MissionManagerActivity extends AppCompatActivity { private FirebaseFirestore db = FirebaseFirestore.getInstance(); private CollectionReference notebookRef = db.collection("missions"); private MissionCell cell; private FirebaseAuth mAuth = FirebaseAuth.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { // Cette directive permet d'enlever la barre de notifications pour afficher l'application en plein écran getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //Hide ActionBar getSupportActionBar().setTitle(""); super.onCreate(savedInstanceState); setContentView(R.layout.activity_mission_manager); setUpRecyclerView(); } private void setUpRecyclerView() { Query query = notebookRef.orderBy("debut", Query.Direction.ASCENDING); FirestoreRecyclerOptions<Mission> options = new FirestoreRecyclerOptions.Builder<Mission>() .setQuery(query, Mission.class) .build(); cell = new MissionCell(options); RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(cell); //Détecte le clic sur la mission cell.setOnClickListener(new MissionCell.OnItemClickListener() { @Override public void onItemClick(DocumentSnapshot documentSnapshot, int position) { //String path = documentSnapshot.getReference().getPath(); //Toast.makeText(MissionManagerActivity.this, "Position: " + position+ " ID: "+id, Toast.LENGTH_SHORT).show(); Mission mission = documentSnapshot.toObject(Mission.class); Intent MissionSheetActivity = new Intent(MissionManagerActivity.this, MissionSheetActivity.class); assert mission != null; MissionSheetActivity.putExtra("Identifiant_mission", documentSnapshot.getId()); MissionSheetActivity.putExtra("Titre", mission.getTitre()); MissionSheetActivity.putExtra("Lieu", mission.getLieu()); MissionSheetActivity.putExtra("Description", mission.getDescription()); Double latitude = mission.getLocalisation().getLatitude(); Double longitude = mission.getLocalisation().getLongitude(); MissionSheetActivity.putExtra("Latitude", latitude); MissionSheetActivity.putExtra("Longitude", longitude); MissionSheetActivity.putExtra("Rayon", mission.getRayon()); startActivity(MissionSheetActivity); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.mission_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.logOut: userLogout(); return true; default: return super.onOptionsItemSelected(item); } } private void userLogout() { mAuth.getInstance().signOut(); Intent intent = new Intent(MissionManagerActivity.this, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } @Override protected void onStart() { super.onStart(); cell.startListening(); } @Override protected void onStop() { super.onStop(); cell.stopListening(); } }
package monopoly.model.field; public abstract class Field { private String name; public Field(String name) { this.name = name; } public String getName() { return name; } }
package fr.lteconsulting.servlet; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import fr.lteconsulting.model.Quizz; public class Rendu { public static void pageBienvenue( String nomUtilisateur, List<Quizz> quizzs, ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { request.setAttribute( "nomUtilisateur", nomUtilisateur ); request.setAttribute( "quizzs", quizzs ); pagePrincipale( "Bienvenue", "/WEB-INF/accueil.jsp", context, request, response ); } public static void pageLogin( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { pagePrincipale( "Bienvenue", "/WEB-INF/login.jsp", context, request, response ); } public static void pagePrincipale( String title, String contentJsp, ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { request.setAttribute( "pageTitle", title ); request.setAttribute( "contentJsp", contentJsp ); RequestDispatcher dispatcher = context.getRequestDispatcher( "/WEB-INF/body.jsp" ); dispatcher.forward( request, response ); } }
/* * 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 engine.board; /** * * @author Alois */ public class Cell { public final int row; public final int col; Cell(int _row, int _col){ if(_row < 0 || _row >= 8 || _col < 0 || _col >= 8) throw new RuntimeException("Cell not on the board, check position"); row = _row; col = _col; } }
/* * 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 telas; import apoio.Criptografia; import apoio.Mensagem; import dao.UsuarioDAO; import entidade.Usuario; import static java.awt.Color.white; import java.io.IOException; import java.net.Socket; /** * * @author renan */ public class jfrLogin extends javax.swing.JFrame { private static Usuario colab; public static Usuario getUsuarioLogado() { return colab; } public static void setUsuarioLogado(Usuario c) { colab = c; } public jfrLogin() { initComponents(); this.setLocationRelativeTo(null); this.setResizable(false); getContentPane().setBackground(white); colab = new Usuario(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jtfLogin = new javax.swing.JTextField(); jpfSenha = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); jlbMsgAutenticacao = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Trader | Acessar"); setBackground(new java.awt.Color(192, 187, 182)); jtfLogin.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtfLogin.setToolTipText("Digite seu usuário"); jtfLogin.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jtfLoginMouseClicked(evt); } }); jpfSenha.setHorizontalAlignment(javax.swing.JTextField.CENTER); jpfSenha.setToolTipText("Digite sua senha"); jpfSenha.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jpfSenhaMouseClicked(evt); } }); jButton1.setBackground(new java.awt.Color(70, 54, 54)); jButton1.setForeground(java.awt.Color.white); jButton1.setText("Acessar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jlbMsgAutenticacao.setForeground(java.awt.Color.red); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/profle.png"))); // NOI18N jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/key.png"))); // NOI18N jLabel3.setText("Usuário"); jLabel4.setText("Senha"); jButton2.setBackground(new java.awt.Color(144, 127, 127)); jButton2.setForeground(java.awt.Color.white); jButton2.setText("Se cadastrar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(39, 39, 39) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlbMsgAutenticacao, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jtfLogin, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE) .addComponent(jpfSenha) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jLabel4)) .addContainerGap(64, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(13, 13, 13) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jpfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jlbMsgAutenticacao, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed UsuarioDAO dao = new UsuarioDAO(); colab = dao.autenticarUsuario(jtfLogin.getText(), Criptografia.criptografar(jpfSenha.getText())); if (colab != null) { FrmPrincipal menu = new FrmPrincipal(); menu.setVisible(true); this.setVisible(false); } else { jlbMsgAutenticacao.setText("Usuário ou senha inválidos."); } }//GEN-LAST:event_jButton1ActionPerformed private void jtfLoginMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtfLoginMouseClicked jlbMsgAutenticacao.setText(""); }//GEN-LAST:event_jtfLoginMouseClicked private void jpfSenhaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jpfSenhaMouseClicked jlbMsgAutenticacao.setText(""); }//GEN-LAST:event_jpfSenhaMouseClicked private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed NovoUsuario cadUsuario = new NovoUsuario(); cadUsuario.setVisible(true); }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jlbMsgAutenticacao; private javax.swing.JPasswordField jpfSenha; private javax.swing.JTextField jtfLogin; // End of variables declaration//GEN-END:variables }
package uk.co.samwho.modopticon.util; import static com.google.common.truth.Truth.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import uk.co.samwho.modopticon.testutil.FakeClock; import java.time.Duration; @RunWith(JUnit4.class) public class EventTrackerTest { private final FakeClock clock = FakeClock.now(); @Test public void testSimpleEvent() { EventTracker tracker = EventTracker.builder() .duration(Duration.ofHours(1)) .build(); tracker.inc(1, clock.minutesAgo(5)); assertThat(tracker.count()).isEqualTo(1); } @Test public void testMultipleEvents() { EventTracker tracker = EventTracker.builder() .duration(Duration.ofHours(1)) .build(); tracker.inc(1, clock.minutesAgo(5)); tracker.inc(1, clock.minutesAgo(10)); assertThat(tracker.count()).isEqualTo(2); } @Test public void testAddEventNotInRange() { EventTracker tracker = EventTracker.builder() .duration(Duration.ofHours(1)) .build(); tracker.inc(1, clock.minutesAgo(61)); assertThat(tracker.count()).isEqualTo(0); } @Test public void testAddingEventsRightNow() { EventTracker tracker = EventTracker.builder() .duration(Duration.ofHours(1)) .clock(clock) .build(); tracker.inc(1, clock.instant()); assertThat(tracker.count()).isEqualTo(1); } @Test public void testEventFallingOutOfRange() { EventTracker tracker = EventTracker.builder() .duration(Duration.ofHours(1)) .clock(clock) .build(); tracker.inc(1, clock.minutesAgo(0)); clock.advance(Duration.ofMinutes(61)); assertThat(tracker.count()).isEqualTo(0); } @Test public void testReset() { EventTracker tracker = EventTracker.builder() .duration(Duration.ofHours(1)) .build(); tracker.inc(1, clock.minutesAgo(5)); assertThat(tracker.count()).isEqualTo(1); tracker.reset(); assertThat(tracker.count()).isEqualTo(0); } @Test public void testIncrementingByMoreThan1() { EventTracker tracker = EventTracker.builder() .duration(Duration.ofHours(1)) .clock(clock) .build(); tracker.inc(10, clock.instant()); assertThat(tracker.count()).isEqualTo(10); } }
package webmail.pages; import webmail.WebmailServer; import webmail.managers.Manager; import webmail.managers.otherManagers.ErrorManager; import webmail.managers.userManagers.UserManager; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Constructor; public class DispatchServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uri = request.getRequestURI(); if(uri.contains("Manager")){//run Manager Manager u = createManager(uri, request, response); if( u == null){ response.sendRedirect("files/error.html"); return; } response.setContentType("text/html"); u.run(); } else {//run Page Page p = createPage(uri, request, response); if (p == null) { response.sendRedirect("/files/error.html"); return; } response.setContentType("text/html"); p.generate(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uri = request.getRequestURI(); if(uri.contains("Manager")){ Manager u = createManager(uri, request, response); if( u == null){ response.sendRedirect("files/error.html"); return; } response.setContentType("text/html"); u.run(); } else { Page p = createPage(uri, request, response); if (p == null) { response.sendRedirect("/files/error.html"); return; } response.setContentType("text/html"); p.generate(); } } public Manager createManager(String uri, HttpServletRequest request, HttpServletResponse response) { Class managerClass = WebmailServer.mapping.get(uri); try{ Constructor<Manager> ctor =managerClass.getConstructor(HttpServletRequest.class, HttpServletResponse.class); return ctor.newInstance(request, response); } catch (Exception e){ ErrorManager.instance().error(e); } return null; } public Page createPage(String uri, HttpServletRequest request, HttpServletResponse response) { Class pageClass = WebmailServer.mapping.get(uri); try { Constructor<Page> ctor = pageClass.getConstructor(HttpServletRequest.class, HttpServletResponse.class); return ctor.newInstance(request, response); } catch (Exception e) { ErrorManager.instance().error(e); } return null; } }
package com.noringerazancutyun.retrofit_example.Adapter; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.noringerazancutyun.retrofit_example.Model.MovieModel; import com.noringerazancutyun.retrofit_example.R; import com.noringerazancutyun.retrofit_example.UI.ItemActivity; import java.util.ArrayList; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewAdapter> { private List<MovieModel> model; private Context context; public RecyclerViewAdapter(List<MovieModel> model, Context context) { this.model = model; this.context = context; } @NonNull @Override public MyViewAdapter onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view; LayoutInflater inflater = LayoutInflater.from(context); view = inflater.inflate(R.layout.recycler_layout, viewGroup, false); return new MyViewAdapter(view); } @Override public void onBindViewHolder(@NonNull MyViewAdapter myViewAdapter, int i) { myViewAdapter.itemTitle.setText(model.get(i).getTitle()); myViewAdapter.imageUrl = model.get(i).getImage(); myViewAdapter.itemReleaseTV.setText(" " + model.get(i).getReleaseYear()); myViewAdapter.itemRatingTV.setText(" " + (model.get(i).getRating())); myViewAdapter.itemRating = toString().valueOf(model.get(i).getRating()); myViewAdapter.itemReleas = toString().valueOf(model.get(i).getReleaseYear()); // List Strings to convert String Vatue for Janre TextView ArrayList<String> list = (ArrayList<String>) model.get(i).getGenre(); String listString = ""; for (String s : list) { listString += s + ", "; } myViewAdapter.itemGenre = (listString); Glide.with(context) .load(myViewAdapter.imageUrl) .centerCrop() .into(myViewAdapter.itemImage); } @Override public int getItemCount() { return model.size(); } public class MyViewAdapter extends RecyclerView.ViewHolder { TextView itemTitle; ImageView itemImage; TextView itemRatingTV; TextView itemReleaseTV; String imageUrl; String itemGenre; String itemReleas; String itemRating; public MyViewAdapter(final View itemView) { super(itemView); itemTitle = itemView.findViewById(R.id.title_recycler); itemImage = itemView.findViewById(R.id.image_recycler); itemRatingTV = itemView.findViewById(R.id.rating_recycler); itemReleaseTV = itemView.findViewById(R.id.release_recycler); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, ItemActivity.class); intent.putExtra("title", itemTitle.getText()); intent.putExtra("release", itemReleas); intent.putExtra("genre", itemGenre); intent.putExtra("rating", itemRating); intent.putExtra("imageUrl", imageUrl); context.startActivity(intent); } }); } } }
package com.lhlp.pages.action; import java.util.List; import java.util.Map; import org.apache.struts2.interceptor.SessionAware; import com.lhlp.pages.entity.Student; import com.lhlp.pages.service.StudentService; import com.lhlp.pages.service.impl.StudentServiceImpl; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ModelDriven; public class StudentAction implements ModelDriven<Student>,SessionAware{ private StudentService studentService; private Student student; private Map<String,Object> session; public StudentAction(){ studentService=new StudentServiceImpl(); } public String studentinfo(){ List<Student> student=studentService.getStuInfo(); session=ActionContext.getContext().getSession(); session.put("student", student); System.out.println("查询到的所有的学生信息=="+student); return "students"; } @Override public void setSession(Map<String, Object> session) { this.session=session; } @Override public Student getModel() { student=new Student(); return student; } }
package com.undertone.lift.request.service; import com.undertone.geo.GeoRequest; import com.undertone.geo.GeoResponse; import com.undertone.lift.request.service.service.enrich.GeoFetchService; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import reactor.core.publisher.Mono; @Slf4j public class GeoFetchServiceTest extends AbstractTest { @Autowired private GeoFetchService geoFetchService; @Test public void geoFetchServiceTest(){ final Mono<GeoResponse> geoResponseMono = geoFetchService .geo(GeoRequest.newBuilder().setClientIp("199.203.210.41").build()); final GeoResponse geoResponse = geoResponseMono.block(); log.info(geoResponse.toString()); } }
package com.yuliia.vlasenko.imagesearcher.repository.entities; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Getter @Setter @EqualsAndHashCode(of = {"id"}) @Entity @Table(name = "picture_metadata") public class PictureMetaDataEntity { @Id private String id; private String author; private String camera; private String tags; @Column(name = "cropped_picture") private String croppedPicture; @Column(name = "full_picture") private String fullPicture; @Column(name = "search_terms") private String searchTerms; }
package com.arkaces.aces_marketplace_api.account_service; import lombok.Data; import java.util.Set; @Data public class UpdateServiceRequest { private String label; private String url; private Set<Long> categoryPids; private Boolean isTestnet; private String status; }
package com.example.myapplication.model; import java.util.Date; public class PersonalSmsGateway { private long id; private String phoneNumber; private String message; private boolean isSent; private boolean isDelivered; private Date createdDate; private Date sentDate; private Date deliveredDate; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public boolean isSent() { return isSent; } public void setSent(boolean sent) { isSent = sent; } public boolean isDelivered() { return isDelivered; } public void setDelivered(boolean delivered) { isDelivered = delivered; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Date getSentDate() { return sentDate; } public void setSentDate(Date sentDate) { this.sentDate = sentDate; } public Date getDeliveredDate() { return deliveredDate; } public void setDeliveredDate(Date deliveredDate) { this.deliveredDate = deliveredDate; } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.math.BigDecimal; /** * Jobshop制造周期Id generated by hbm2java */ public class Jobshop制造周期Id implements java.io.Serializable { private String deptid; private String deptname; private String partNumber; private String partName; private BigDecimal avgcycle; public Jobshop制造周期Id() { } public Jobshop制造周期Id(String deptid, String partNumber) { this.deptid = deptid; this.partNumber = partNumber; } public Jobshop制造周期Id(String deptid, String deptname, String partNumber, String partName, BigDecimal avgcycle) { this.deptid = deptid; this.deptname = deptname; this.partNumber = partNumber; this.partName = partName; this.avgcycle = avgcycle; } public String getDeptid() { return this.deptid; } public void setDeptid(String deptid) { this.deptid = deptid; } public String getDeptname() { return this.deptname; } public void setDeptname(String deptname) { this.deptname = deptname; } public String getPartNumber() { return this.partNumber; } public void setPartNumber(String partNumber) { this.partNumber = partNumber; } public String getPartName() { return this.partName; } public void setPartName(String partName) { this.partName = partName; } public BigDecimal getAvgcycle() { return this.avgcycle; } public void setAvgcycle(BigDecimal avgcycle) { this.avgcycle = avgcycle; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof Jobshop制造周期Id)) return false; Jobshop制造周期Id castOther = (Jobshop制造周期Id) other; return ((this.getDeptid() == castOther.getDeptid()) || (this.getDeptid() != null && castOther.getDeptid() != null && this.getDeptid().equals(castOther.getDeptid()))) && ((this.getDeptname() == castOther.getDeptname()) || (this.getDeptname() != null && castOther.getDeptname() != null && this.getDeptname().equals(castOther.getDeptname()))) && ((this.getPartNumber() == castOther.getPartNumber()) || (this.getPartNumber() != null && castOther.getPartNumber() != null && this.getPartNumber().equals(castOther.getPartNumber()))) && ((this.getPartName() == castOther.getPartName()) || (this.getPartName() != null && castOther.getPartName() != null && this.getPartName().equals(castOther.getPartName()))) && ((this.getAvgcycle() == castOther.getAvgcycle()) || (this.getAvgcycle() != null && castOther.getAvgcycle() != null && this.getAvgcycle().equals(castOther.getAvgcycle()))); } public int hashCode() { int result = 17; result = 37 * result + (getDeptid() == null ? 0 : this.getDeptid().hashCode()); result = 37 * result + (getDeptname() == null ? 0 : this.getDeptname().hashCode()); result = 37 * result + (getPartNumber() == null ? 0 : this.getPartNumber().hashCode()); result = 37 * result + (getPartName() == null ? 0 : this.getPartName().hashCode()); result = 37 * result + (getAvgcycle() == null ? 0 : this.getAvgcycle().hashCode()); return result; } }
package Arrays; public class PrintanArray { public static void main(String[] args) { int [] arr= {1,3,4,6}; for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } }
/* * 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 dictionary; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; /** * * @author Muzyk */ public class MindfulDictionary { private Map<String, String> EnglishToFinnish; private Map<String, String> FinnishToEnglish; private Scanner reader; private FileWriter writer; private File file; public MindfulDictionary() { EnglishToFinnish = new HashMap<String, String>(); FinnishToEnglish = new HashMap<String, String>(); } public MindfulDictionary(String file) { this(); this.file = new File(file); } public void add(String word, String translation) { if (!EnglishToFinnish.containsKey(word)) { EnglishToFinnish.put(word, translation); } if (!FinnishToEnglish.containsKey(word)) { FinnishToEnglish.put(translation, word); } } public String translate(String word) { if (EnglishToFinnish.containsKey(word)) { return EnglishToFinnish.get(word); } else if (FinnishToEnglish.containsKey(word)) { return FinnishToEnglish.get(word); } return null; } public void remove(String word) { String finnish = EnglishToFinnish.get(word); String english = FinnishToEnglish.get(word); EnglishToFinnish.remove(english); FinnishToEnglish.remove(finnish); EnglishToFinnish.remove(word); FinnishToEnglish.remove(word); } public boolean load() { try { reader = new Scanner(file); } catch (FileNotFoundException e) { return false; } while (reader.hasNextLine()) { String wordPair = reader.nextLine(); String[] wordPairDivided = wordPair.split(":"); this.add(wordPairDivided[0], wordPairDivided[1]); } return true; } public boolean save() { try { writer = new FileWriter(file); Set<String> keySet = EnglishToFinnish.keySet(); for (String k : keySet) { writer.write(k + ":" + EnglishToFinnish.get(k) + "\n"); } writer.close(); } catch (IOException e) { return false; } return true; } }
package org.alienideology.jcord.event.client.relation; import org.alienideology.jcord.event.client.ClientEvent; import org.alienideology.jcord.handle.client.IClient; import org.alienideology.jcord.handle.client.relation.IRelationship; import org.alienideology.jcord.handle.user.IUser; /** * @author AlienIdeology */ public class RelationshipEvent extends ClientEvent { private final IRelationship relationship; public RelationshipEvent(IClient client, int sequence, IRelationship relationship) { super(client, sequence); this.relationship = relationship; } public IRelationship getRelationship() { return relationship; } public IUser getUser() { return relationship.getUser(); } }
package com.example.study.activity.start; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.example.study.R; public class TargetActivity extends AppCompatActivity { private static final String DATA_TAG = "args_data"; public static void startAction(Context context) { Intent intent = new Intent(context, TargetActivity.class); context.startActivity(intent); } public static void startAction(Context context, String args) { Intent intent = new Intent(context, TargetActivity.class); intent.putExtra(DATA_TAG, args); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_target); String data = getIntent().getStringExtra("args_data"); String text = "congratulations! welcome to this target activity"; if (data != null) { text += (", got data: " + data); } ((TextView) findViewById(R.id.text_dashboard)).setText(text); findViewById(R.id.btn_finish).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); //返回数据 intent.putExtra("data_return", "return data from target"); //返回状态 setResult(RESULT_OK, intent); finish(); } }); } }
package com.awrzosek.ski_station.tables.ski.equipment; public enum Condition { EX("Świetny"), GOOD("Dobry"), AVG("Średni"), POOR("Słaby"), BROKEN("Zniszczony"); private final String label; Condition(String label) { this.label = label; } public String toString() { return this.label; } }
package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Change owed:"); double change = input.nextDouble(); while (change <=0 || change ==(' ')) { System.out.print("Must enter a number higher than 0:"); change = input.nextDouble(); } int cents = (int) Math.round(change * 100); int coinCount= 0; while (cents >= 25) { coinCount++; cents -= 25; } while (cents >= 10) { coinCount++; cents -= 10; } while (cents >= 5) { coinCount++; cents -= 5; } while (cents >= 1) { coinCount++; cents -= 1; } System.out.println( "You get " + coinCount + " coins."); } }
package com.elepy.admin.concepts; import com.elepy.ElepyPostConfiguration; import com.elepy.admin.ElepyAdminPanel; import com.elepy.http.HttpService; import java.util.Map; import java.util.Objects; public abstract class ElepyAdminPanelPlugin implements Comparable<ElepyAdminPanelPlugin> { private final String name; private final String slug; private ElepyAdminPanel adminPanel; public ElepyAdminPanelPlugin(String name, String slug) { this.name = name; this.slug = slug; } public abstract void setup(HttpService http, ElepyPostConfiguration elepy); public abstract String renderContent(Map<String, Object> model); public String getName() { return name; } public String getSlug() { return slug; } public ElepyAdminPanel getAdminPanel() { return adminPanel; } protected void setAdminPanel(ElepyAdminPanel adminPanel) { this.adminPanel = adminPanel; } @Override public int compareTo(ElepyAdminPanelPlugin o) { return name.compareTo(o.name); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ElepyAdminPanelPlugin that = (ElepyAdminPanelPlugin) o; return Objects.equals(name, that.name) && Objects.equals(slug, that.slug); } @Override public int hashCode() { return Objects.hash(name, slug); } }
import java.io.*; import java.util.Scanner; public class PattNew{ String pName; long phoneNo; char gender; Float docFee; byte age; Double billAmount; public PattNew(){ //default constructor pName="amritha"; phoneNo=25220133; docFee=(float)2500.0; age=22; billAmount=1000.0; gender='f'; } public PattNew(String a ,Byte b,long c, char d){ //parametrized constructor pName=a; age=b; phoneNo=c; docFee=(float)2000.0; billAmount=5000.0; gender=d; } public void read() throws IOException{ BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); System.out.println("--------PATIENT INFORMATION--------"); System.out.println("Enter the patient Name"); pName=br.readLine(); System.out.println("Enter the patient phoneno"); phoneNo=Long.parseLong(br.readLine()); System.out.println("Enter the doctors fee"); docFee=Float.parseFloat(br.readLine()); System.out.println("Enter age of the patient"); age=Byte.parseByte(br.readLine()); System.out.println("Enter the billAmount"); billAmount=Double.parseDouble(br.readLine()); System.out.println("Enter gender"); gender=(char)br.read(); } public void display(){ System.out.println("Name :"+ pName); System.out.println("Phoneno:"+ phoneNo); System.out.println("Doctors fee"+ docFee); System.out.println("Age:"+ age ); System.out.println("Billamount"+ billAmount ); System.out.println("tax"+ bill( ) ); System.out.println("total amount"+ bill(billAmount , bill() , docFee ) ); System.out.println("Gender:"+ gender); } public Double bill(){ Double tax= 150.0; return tax; } public Double bill(Double a, Double b, Float c){ Double tax; billAmount=a; tax=bill(); tax=b; docFee=c; return(a+b+c); } public static void main(String args[]) throws IOException{ BufferedReader br =new BufferedReader (new InputStreamReader(System.in)); PattNew p = new PattNew("lala",(byte)22,25134141,'m'); //parameterized constructor calling p.display(); PattNew p1= new PattNew(); //default constructor calling /* p1.display(); PattNew p2= new PattNew(); p2.read(); p2.display();*/ /*BufferedReader br =new BufferedReader (new InputStreamReader(System.in));*/ boolean choice=true; byte result; PattNew pat[] = new PattNew[3]; while(choice) { System.out.println("1. Read data"); System.out.println("2. Display data"); System.out.println("3. Exit"); System.out.println("Enter your choice"); result=Byte.parseByte(br.readLine()); switch(result){ case 1: for (int i=0;i<2 ;i++ ) { pat[i] = new PattNew(); pat[i].read(); } break; case 2: for (int i=0;i<2 ;i++ ) { pat[i].display(); } break; case 3: choice=false; break; } } } }
/** * DNet eBusiness Suite * Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package net.nan21.dnet.module.bd.domain.impl.classification; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.PrePersist; import javax.persistence.Table; import net.nan21.dnet.core.domain.impl.AbstractAuditable; import net.nan21.dnet.module.bd.domain.impl.classification.ClassificationItem; import net.nan21.dnet.module.bd.domain.impl.classification.ClassificationSystem; import org.hibernate.validator.constraints.NotBlank; @Entity @Table(name = Classification.TABLE_NAME) public class Classification extends AbstractAuditable { public static final String TABLE_NAME = "BD_CLSF"; private static final long serialVersionUID = -8865917134914502125L; @NotBlank @Column(name = "TARGETREFID", nullable = false, length = 64) private String targetRefid; @NotBlank @Column(name = "TARGETALIAS", nullable = false, length = 64) private String targetAlias; @Column(name = "TARGETTYPE", length = 255) private String targetType; @ManyToOne(fetch = FetchType.LAZY, targetEntity = ClassificationSystem.class) @JoinColumn(name = "CLASSSYSTEM_ID", referencedColumnName = "ID") private ClassificationSystem classSystem; @ManyToOne(fetch = FetchType.LAZY, targetEntity = ClassificationItem.class) @JoinColumn(name = "CLASSITEM_ID", referencedColumnName = "ID") private ClassificationItem classItem; public String getTargetRefid() { return this.targetRefid; } public void setTargetRefid(String targetRefid) { this.targetRefid = targetRefid; } public String getTargetAlias() { return this.targetAlias; } public void setTargetAlias(String targetAlias) { this.targetAlias = targetAlias; } public String getTargetType() { return this.targetType; } public void setTargetType(String targetType) { this.targetType = targetType; } public ClassificationSystem getClassSystem() { return this.classSystem; } public void setClassSystem(ClassificationSystem classSystem) { if (classSystem != null) { this.__validate_client_context__(classSystem.getClientId()); } this.classSystem = classSystem; } public ClassificationItem getClassItem() { return this.classItem; } public void setClassItem(ClassificationItem classItem) { if (classItem != null) { this.__validate_client_context__(classItem.getClientId()); } this.classItem = classItem; } @PrePersist public void prePersist() { super.prePersist(); } }