text
stringlengths
10
2.72M
/* * This Class demonstrates use of Todo annotation defined in Todo.java * * @author Yashwant Golecha (ygolecha@gmail.com) * @version 1.0 * */ package annotation; public class ShardLogic { public ShardLogic() { super(); } @Shard(shardType = Shard.ShardType.NOSHARD, ignore = false) public void operation() { // No Code Written yet doit(); } @Transactional protected void doit() { } }
package kr.co.wisenut.login.dao.impl; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import kr.co.wisenut.db.DB_ENV; import kr.co.wisenut.db.SessionService; import kr.co.wisenut.editor.dao.impl.EditorDaoImpl; import kr.co.wisenut.login.dao.UserDao; import kr.co.wisenut.login.model.User; import kr.co.wisenut.util.StringUtil; @Repository("LoginMapper") public class UserDaoImpl implements UserDao { private static final Logger logger = LoggerFactory.getLogger(EditorDaoImpl.class); private final SessionService sessionService = new SessionService(DB_ENV.PROD1); @Override public boolean isValidUser(User loginInfo){ SqlSession session = sessionService.getSession(); boolean ret = false; try{ session = sessionService.getSession(); if(session.selectOne("LoginMapper.getUserInfo", loginInfo) != null){ ret = true; } }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return ret; } }
package com.adamfei.hbase.mapper; import org.apache.storm.hbase.bolt.mapper.HBaseMapper; import org.apache.storm.hbase.common.ColumnList; import backtype.storm.tuple.Tuple; /** * 自定义tuple与hbase数据行的映射 * @author adam * */ public class MyHBaseMapper implements HBaseMapper { public ColumnList columns(Tuple tuple) { ColumnList cols = new ColumnList(); cols.addColumn("c1".getBytes(), "str".getBytes(), tuple.getStringByField("str").getBytes()); cols.addColumn("c2".getBytes(), "num".getBytes(), tuple.getStringByField("num").getBytes()); return cols; } public byte[] rowKey(Tuple tuple) { return tuple.getStringByField("id").getBytes(); } }
package ch.ethz.geco.t4j.internal.json; /** * Represents a playlist JSON object. */ public class PlaylistObject { public Long id; public String name; public String description; }
public class Room { private RoomType roomType; public Room(RoomType roomType){ this.roomType = roomType; } public RoomType getRoomType() { return this.roomType; } public int getValueFromEnum() { return this.roomType.getValue(); } RoomType[] roomTypes = RoomType.values(); }
package travel.api.table.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import travel.api.dto.request.chat.ChatRequestDTO; import travel.api.dto.response.chat.PrivateMsgResponseDTO; import travel.api.table.entity.PrivateMsg; import java.util.List; /** * @Author: dd */ public interface PrivateMsgMapper extends BaseMapper<PrivateMsg> { List<PrivateMsgResponseDTO> privateMsg(ChatRequestDTO requestDTO); }
import java.util.Comparator; /** * this class implements the Comparator and compares two females by their age * * @author Carlos */ public class yComparator implements Comparator<Female> { /** * method for comparing two females * * @param f1 * @param f2 * @return 0, -1 or 1 */ public int compare(Female f1, Female f2) { if (f1.getAge() > f2.getAge()) { return 1; } else if (f1.getAge() < f2.getAge()) { return -1; } else { return 0; } } }
/* 513m - Find bottom left tree value */ public class Solution { public int value=0, maxLevel=0, level=0; public void inOrderWalk(TreeNode n, int level) { if(n==null) return; /* left most element in a new level */ if(level > maxLevel) { maxLevel = level; value = n.val; } inOrderWalk(n.left, level+1); inOrderWalk(n.right, level+1); } public int findBottomLeftValue(TreeNode root) { inOrderWalk(root, level=1); return value; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http; import java.io.Serializable; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; /** * Default implementation of {@link HttpStatusCode}. * * @author Arjen Poutsma * @since 6.0 */ final class DefaultHttpStatusCode implements HttpStatusCode, Comparable<HttpStatusCode>, Serializable { private static final long serialVersionUID = 7017664779360718111L; private final int value; public DefaultHttpStatusCode(int value) { this.value = value; } @Override public int value() { return this.value; } @Override public boolean is1xxInformational() { return hundreds() == 1; } @Override public boolean is2xxSuccessful() { return hundreds() == 2; } @Override public boolean is3xxRedirection() { return hundreds() == 3; } @Override public boolean is4xxClientError() { return hundreds() == 4; } @Override public boolean is5xxServerError() { return hundreds() == 5; } @Override public boolean isError() { int hundreds = hundreds(); return hundreds == 4 || hundreds == 5; } private int hundreds() { return this.value / 100; } @Override public int compareTo(@NonNull HttpStatusCode o) { return Integer.compare(this.value, o.value()); } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof HttpStatusCode that && this.value == that.value())); } @Override public int hashCode() { return this.value; } @Override public String toString() { return Integer.toString(this.value); } }
package com.lenovohit.elh.base.web.rest; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContextAware; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.lenovohit.bdrp.org.model.Person; import com.lenovohit.core.dao.Page; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.core.utils.JSONUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.rest.BaseRestController; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.elh.base.model.MedicalCard; import com.lenovohit.elh.base.model.Patient; import com.lenovohit.elh.base.model.UserPatient; /******************************************************常用就诊人app方法*************************************************************************/ /** * 就诊人管理 * * @author Administrator * */ @RestController @RequestMapping("/elh/userPatient") public class UserPatientRestController extends BaseRestController implements ApplicationContextAware { @Autowired private GenericManager<Patient, String> patientManager; @Autowired private GenericManager<UserPatient, String> userPatientManager; @Autowired private GenericManager<MedicalCard, String> medicalCardManager; @Autowired private GenericManager<Person, String> personManager; /** * ELH_BASE_002 保存常用就诊人信息 * * @param data * @return */ @RequestMapping(value = "/my/create", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result forCreate(@RequestBody String data) { List<String> values = new ArrayList<String>(); UserPatient userPatient = JSONUtils.deserialize(data, UserPatient.class); // 判断该常用就诊人是否存在 String hql = "from UserPatient t where t.name=? and t.idno=? and status='1' and userId=?"; values.add(userPatient.getName()); values.add(userPatient.getIdno()); values.add(userPatient.getUserId()); UserPatient oldUserPatient = this.userPatientManager.findOne(hql, values.toArray()); if (oldUserPatient != null){ return ResultUtils.renderFailureResult("常用就诊人已存在"); }else{ //判断该就诊人是否存在 String phql = "from Patient where status='1' and idno= ? "; Patient oldPatient = this.patientManager.findOne(phql, userPatient.getIdno()); //添加就诊人 Patient patient = new Patient(); if(oldPatient!=null){ if(oldPatient.getName().equals(userPatient.getName())){ userPatient.setPatientId(oldPatient.getId()); userPatient = this.userPatientManager.save(userPatient); return ResultUtils.renderSuccessResult(userPatient); }else{ patient.setUserType(userPatient.getUserType()); patient.setName(userPatient.getName()); patient.setPhoto(userPatient.getPhoto()); patient.setIdno(userPatient.getIdno()); patient.setMobile(userPatient.getMobile()); patient.setEmail(userPatient.getEmail()); patient.setGender(userPatient.getGender()); patient.setAddress(userPatient.getAddress()); patient.setStatus(userPatient.getStatus()); patient.setBirthday(userPatient.getBirthday()); patient.setHeight(userPatient.getHeight()); patient.setWeight(userPatient.getWeight()); } }else{ patient.setUserType(userPatient.getUserType()); patient.setName(userPatient.getName()); patient.setPhoto(userPatient.getPhoto()); patient.setIdno(userPatient.getIdno()); patient.setMobile(userPatient.getMobile()); patient.setEmail(userPatient.getEmail()); patient.setGender(userPatient.getGender()); patient.setAddress(userPatient.getAddress()); patient.setStatus(userPatient.getStatus()); patient.setBirthday(userPatient.getBirthday()); patient.setHeight(userPatient.getHeight()); patient.setWeight(userPatient.getWeight()); } patient = this.patientManager.save(patient); userPatient.setPatientId(patient.getId()); } userPatient = this.userPatientManager.save(userPatient); return ResultUtils.renderSuccessResult(userPatient); } /** * ELH_BASE_003 查询常用就诊人信息 * * @param id * @return */ @RequestMapping(value = "/my/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forInfo(@PathVariable("id") String id) { UserPatient userPatient = this.userPatientManager.get(id); StringBuilder sb = new StringBuilder(); List<String> cdList = new ArrayList<String>(); cdList = new ArrayList<String>(); sb.append("from MedicalCard t where t.state=1 and t.patientId=?"); cdList.add(userPatient.getId()); userPatient.setCardCount(this.userPatientManager.findByJql(sb.toString(), cdList).size()); return ResultUtils.renderSuccessResult(userPatient); } /** * ELH_BASE_002 维护常用就诊人信息 * * @param id * @param data * @return */ @SuppressWarnings("rawtypes") @RequestMapping(value = "/my/{id}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8) public Result forUpdate(@PathVariable("id") String id, @RequestBody String data) { UserPatient userPatient = this.userPatientManager.get(id); /*这里有可能需要判断修改后的就诊人是不是和某个重复 然后统一为一个就诊人,暂时不做*/ // UserPatient userPatientOld = this.userPatientManager.findOne("from UserPatient where idno = ? ", userPatient.getIdno()); // if(userPatientOld!=null){ // if(!userPatientOld.getName().equals(userPatient.getName())){ // return ResultUtils.renderFailureResult("身份证号已存在并且姓名不符"); // } // } Patient patient = this.patientManager.findOne("from Patient where id = ? and status='1'", userPatient.getPatientId()); patient.setUserType(userPatient.getUserType()); patient.setName(userPatient.getName()); patient.setPhoto(userPatient.getPhoto()); patient.setIdno(userPatient.getIdno()); patient.setMobile(userPatient.getMobile()); patient.setEmail(userPatient.getEmail()); patient.setGender(userPatient.getGender()); patient.setAddress(userPatient.getAddress()); patient.setStatus(userPatient.getStatus()); patient.setBirthday(userPatient.getBirthday()); patient.setHeight(userPatient.getHeight()); patient.setWeight(userPatient.getWeight()); Map userPatientData = JSONUtils.deserialize(data, Map.class); if (null != userPatientData.get("userId")) { userPatient.setUserId(userPatientData.get("userId").toString()); // 用户 } if (null != userPatientData.get("patientt")) { userPatient.setPatientId(userPatientData.get("Patientt").toString()); // 就诊人 } if (null != userPatientData.get("usertype")) { userPatient.setUserType(userPatientData.get("usertype").toString()); // 用户类型 } if (null != userPatientData.get("name")) { userPatient.setName(userPatientData.get("name").toString()); // 姓名 } if (null != userPatientData.get("gender")) { userPatient.setGender(userPatientData.get("gender").toString()); // 性别 } if (null != userPatientData.get("relationshi")) { userPatient.setRelationshi(userPatientData.get("relationshi").toString()); // 关系 } if (null != userPatientData.get("alias")) { userPatient.setAlias(userPatientData.get("alias").toString()); // 别名 } if (null != userPatientData.get("idno")) { userPatient.setIdno(userPatientData.get("idno").toString()); // 身份证号码 } if (null != userPatientData.get("photo")) { userPatient.setPhoto(userPatientData.get("photo").toString()); // 头像 } if (null != userPatientData.get("mobile")) { userPatient.setMobile(userPatientData.get("mobile").toString()); // 手机 } if (null != userPatientData.get("email")) { userPatient.setEmail(userPatientData.get("email").toString()); // 邮箱 } if (null != userPatientData.get("address")) { userPatient.setAddress(userPatientData.get("address").toString()); // 地址 } if (null != userPatientData.get("status")) { userPatient.setStatus(userPatientData.get("status").toString()); // 状态 } if (null != userPatientData.get("birthday")) { userPatient.setBirthday(userPatientData.get("birthday").toString()); // 出生日期 } if (null != userPatientData.get("height")) { userPatient.setHeight(Double.parseDouble(userPatientData.get("height").toString())); // 身高 } if (null != userPatientData.get("weight")) { userPatient.setWeight(Double.parseDouble(userPatientData.get("weight").toString())); // 体重 } patient = this.patientManager.save(patient); UserPatient savedUserPatient = this.userPatientManager.save(userPatient); return ResultUtils.renderSuccessResult(savedUserPatient); } /** * ELH_BASE_004 删除常用就诊人 * * @param id * @return */ @RequestMapping(value = "/my/{id}", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8) public Result forDelete(@PathVariable("id") String id) { UserPatient userPatient = this.userPatientManager.get(id); //userPatient.setUnbindedAt(DateUtils.getCurrentDateTimeStr()); if(!userPatient.getStatus().equals("0")){ userPatient.setStatus("0"); } UserPatient saveUser = this.userPatientManager.save(userPatient); return ResultUtils.renderSuccessResult(saveUser); } /** * ELH_BASE_001 查询常用就诊人列表 * * @param start * @param pageSize * @param data * @return */ @SuppressWarnings({ "unchecked" }) @RequestMapping(value = "/my/list/{start}/{pageSize}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forList(@PathVariable(value = "start") int start, @PathVariable(value = "pageSize") int pageSize, @RequestParam(value = "data", defaultValue = "") String data) { log.info("查询列表数据,输入查询条件为:【" + data + "】"); UserPatient userPatient = JSONUtils .deserialize(data, UserPatient.class); StringBuilder sb = new StringBuilder("from UserPatient t where 1=1 "); List<String> cdList = new ArrayList<String>(); if (null != userPatient) { if (userPatient.getUserId() != null && !"".equals(userPatient.getUserId().trim())) { sb.append(" and t.userId=? "); cdList.add(userPatient.getUserId()); } if (userPatient.getStatus() != null && !"".equals(userPatient.getStatus().trim())) { sb.append(" and t.status=? "); cdList.add(userPatient.getStatus()); } if (userPatient.getName() != null && !"".equals(userPatient.getName().trim())) { sb.append(" and t.name like ? "); cdList.add("%" + userPatient.getName() + "%"); } } Page page = new Page(); page.setStart(start); page.setPageSize(pageSize); page.setValues(cdList.toArray()); page.setQuery(sb.toString()); this.userPatientManager.findPage(page); List<UserPatient> list = (List<UserPatient>) page.getResult(); List<UserPatient> sortlist = new ArrayList<UserPatient>(); UserPatient _userPatient = null; String jql = "from MedicalCard t where t.state=1 and t.patientId=?"; for (int i = 0; null != list && i < list.size(); i++) { _userPatient = list.get(i); _userPatient.setCardCount(this.userPatientManager.getCount(jql, _userPatient.getPatientId())); } if (list != null) { int j = 0; for (int i = 0; i < list.size(); i++) { if (list.get(i).getCardCount() > 0) { sortlist.add(j, list.get(i)); ++j; } else { sortlist.add(i, list.get(i)); } } page.setResult(sortlist); } return ResultUtils.renderSuccessResult(page); } /** * ELH_BASE_006.5 判断人有没有实名认证 * * @return */ @RequestMapping(value = "/my/realperson/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forRealPerson(@PathVariable("id") String id) { Boolean flag = false; String patientstr = "from Patient where id = ? and status='1'"; Patient patient = this.patientManager.findOne(patientstr, id); if (patient != null && patient.getPersonId() != null) { flag = true; } return ResultUtils.renderSuccessResult(flag); } /** * ELH_BASE_006 绑定健康卡 流程未定,demo 3 TODO 注意事务完整性 * * @return */ @RequestMapping(value = "/bindcard/health", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forBindHealthCard() { return ResultUtils.renderSuccessResult(); } /** * ELH_BASE_005 绑定就诊卡 流程未定,demo 3 TODO 注意事务完整性 * * @return */ @RequestMapping(value = "/bindcard/medical", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forBindMedicalCard() { return ResultUtils.renderSuccessResult(); } /******************************************************常用就诊人app方法end*************************************************************************/ }
package org.teacake.monolith.apk; public class SubBlock { SubBlock() { xpos=0; ypos=0; } public int xpos; public int ypos; }
package com.tianwotian.mytaobao.view; import android.content.Context; import android.graphics.Color; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.tianwotian.mytaobaotest.R; /** * 自定义一个带图片的吐司 * Created by venus on 2016/9/1. */ public class ImageToast extends Toast { private static View v; public ImageToast(Context context) { super(context); } public static ImageToast makeImage(Context context, int imgId, int duration, String text){ ImageToast imageToast = new ImageToast(context); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(R.layout.image_toast, null); TextView tv = (TextView) v.findViewById(R.id.tv_image); tv.setBackgroundResource(imgId); tv.setText(text); tv.setTextSize(18); tv.setTextColor(Color.WHITE); tv.setGravity(Gravity.CENTER); imageToast.setView(v); imageToast.setDuration(duration); imageToast.setGravity(Gravity.CENTER,0,0); return imageToast; } }
package com.springmvc.service; import java.util.List; import com.springmvc.model.Activity; public interface ExerciseService { public abstract List<Activity> findAllActivities(); }
package org.opentestsystem.ap.ivproxy.filter; import javax.servlet.http.HttpServletRequest; import com.netflix.zuul.http.HttpServletRequestWrapper; /** * Duplicated from {@link org.springframework.cloud.netflix.zuul.filters.pre.Servlet30RequestWrapper} */ class Servlet30RequestWrapper extends HttpServletRequestWrapper { private final HttpServletRequest request; Servlet30RequestWrapper(final HttpServletRequest request) { super(request); this.request = request; } /** * There is a bug in zuul 1.2.2 where HttpServletRequestWrapper.getRequest returns a wrapped request rather than the raw one. * @return the original HttpServletRequest */ @Override public HttpServletRequest getRequest() { return this.request; } }
package org.sealoflove.zero.one; import org.sealoflove.Task; import org.sealoflove.ArrayUtils; public class Task011 implements Task { //String fileName = "/home/llenterak/dg/workspace/euler/src/task011.txt"; Integer[][] array = ArrayUtils.toArray(ArrayUtils.readSquareArrayFromFile("/home/llenterak/dg/workspace/euler/src/task011.txt")); private Integer getMaxProd(int factors) { int max = 0; int n = array.length; if (factors > n) throw new RuntimeException("nr of factors too large!"); //horiz for (int i = 0; i < n; i++) { for (int j = 0; j < n - factors + 1; j++) { int prod = 1; for (int k = 0; k < factors; k++) { prod *= array[i][j+k]; } if (max < prod) max = prod; } } //vertical for (int i = 0; i < n - factors + 1; i++) { for (int j = 0; j < n; j++) { int prod = 1; for (int k = 0; k < factors; k++) { prod *= array[i+k][j]; } if (max < prod) max = prod; } } //main diagonal for (int i = 0; i < n - factors + 1; i++) { for (int j = 0; j < n - factors + 1; j++) { int prod = 1; for (int k = 0; k < factors; k++) { prod *= array[i+k][j+k]; } if (max < prod) max = prod; } } //secondary diagonal for (int i = 0; i < n - factors + 1; i++) { for (int j = factors; j < n; j++) { int prod = 1; for (int k = 0; k < factors; k++) { prod *= array[i+k][j-k]; } if (max < prod) max = prod; } } return max; } private void printArray() { for (int i = 0; i < array.length; i++){ for (int j = 0; j < array.length; j++) { System.out.print(String.format("%2d ", array[i][j])); } System.out.println(); } } @Override public String getResult() { return String.format("%d", getMaxProd(4)); } }
package pp; import hlp.MyHttpClient; import pp.model.Guild; import pp.model.IModel; import pp.model.Player; import pp.service.GlRuService; import pp.service.GlRuServiceImpl; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; /** * @author alexander.sokolovsky.a@gmail.com */ public class MailAll { public static final String domain = "s2.gladiators.ru"; public static final Set<Long> excluded = new HashSet<Long>();//Arrays.asList(20040828L, 20011096L, 20002581L, 20080818L)); public static final String subject = "Идем в Сиракузы!"; public static final String message = ""; public static void main(String[] args) { MyHttpClient client = new MyHttpClient(); client.appendInitialCookie("PHPSESSID", "66bc7c257e046e05519add1b7b1382f3", domain); client.appendInitialCookie("cookie_lang_3", "rus", domain); try { Properties props = new Properties(); props.load(new FileInputStream("settings.txt")); GlRuService service = new GlRuServiceImpl(client, new GlRuParser(), props.get("SERVER").toString().trim()); service.login(props.get("USER").toString(), props.get("PASSW").toString()); Utils.sleep(1000); //service.mail("alsa", "ЧАСЫ ПРОВЕДЕНИЯ СЕНАТОВ", message); while (true) { service.visitGuild(10L); //service.visitGuild(15L); Map<Long, Guild> guilds = service.getGuilds(); System.out.println("-----------------------------------------------------"); List<Player> senators = new ArrayList<Player>(); List<Player> imperators = new ArrayList<Player>(); List<Player> all = new ArrayList<Player>(); for (Long guildId : guilds.keySet()) { Guild guild = (Guild) guilds.get(guildId); for (IModel iModel : guild.getPlayers().values()) { Player p = (Player) iModel; if (p.getOnline() && p.getVip() > 0 && !excluded.contains(p.getId())) { senators.add(p); } if (p.getOnline() && p.getLvl() > 8 && !excluded.contains(p.getId())) { imperators.add(p); } if (!excluded.contains(p.getId())) { all.add(p); } } } System.out.print("All:" + all.size()); System.out.println(Arrays.deepToString(all.toArray())); if (all.size() > 0) { System.out.println("Emailing..."); for (Player player : all) { try { //service.mail(senator.getName(), "ЧАСЫ ПРОВЕДЕНИЯ СЕНАТОВ", message); service.mail(player.getName(), subject, message); //.toArray())); } catch (IOException e) { } Utils.sleep(100); } break; } Utils.sleep(10000); } } catch (IOException e) { e.printStackTrace(); } } }
package br.com.concar.concar.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by mdamaceno on 18/04/15. */ public class DatabaseHelper extends SQLiteOpenHelper { private static DatabaseHelper sInstance; private Context ctx; private static final String BANCO_DADOS = "Concar"; private static int VERSAO = 3; /* Tabela usuarios e suas colunas */ public static final String TABLE_U = "usuarios"; public static final String COLUMN_U_ID = "_id"; public static final String COLUMN_U_NOME = "nome"; public static final String COLUMN_U_EMAIL = "email"; public static final String COLUMN_U_SENHA = "senha"; /* Tabela clientes e suas colunas */ public static final String TABLE_K = "clientes"; public static final String COLUMN_K_ID = "_id"; public static final String COLUMN_K_NOME = "nome"; public static final String COLUMN_K_EMAIL = "email"; public static final String COLUMN_K_TELEFONE = "telefone"; public static final String COLUMN_K_SENHA = "senha"; public static final String COLUMN_K_SEXO = "sexo"; /* Tabela carros e suas colunas */ public static final String TABLE_C = "carros"; public static final String COLUMN_C_ID = "_id"; public static final String COLUMN_C_MARCA = "marca"; public static final String COLUMN_C_MODELO = "modelo"; public static final String COLUMN_C_ANO = "ano"; public static final String COLUMN_C_QUILOMETRAGEM = "quilometragem"; public static final String COLUMN_C_AIRBAG = "airbag"; public static final String COLUMN_C_ARCONDICIONADO = "ar_condicionado"; public static final String COLUMN_C_COR = "cor"; public static final String COLUMN_C_PRECO = "preco"; /* Tabela propostas e suas colunas */ public static final String TABLE_P = "propostas"; public static final String COLUMN_P_ID = "_id"; public static final String COLUMN_P_TIPOPAGAMENTO = "tipo_pagamento"; public static final String COLUMN_P_NUMPARCELAS = "num_parcelas"; public static final String COLUMN_P_VALORENTRADA = "valor_entrada"; public static final String COLUMN_P_VALORCARRO = "valor_carro"; public static final String COLUMN_P_VALORPARCELA = "valor_parcela"; public static final String COLUMN_P_CONFIRMACAO = "confirmacao"; public static final String COLUMN_P_IDCARRO = "idCarro"; public static final String COLUMN_P_IDCLIENTE = "idCliente"; public DatabaseHelper(Context context) { super(context, BANCO_DADOS, null, VERSAO); this.ctx = context; } public static synchronized DatabaseHelper getInstance(Context context) { if (sInstance == null) { sInstance = new DatabaseHelper(context.getApplicationContext()); } return sInstance; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TABLE_U + " (" + COLUMN_U_ID + " INTEGER PRIMARY KEY, " + COLUMN_U_NOME + " TEXT, " + COLUMN_U_EMAIL + " TEXT, " + COLUMN_U_SENHA + " TEXT);"); db.execSQL("CREATE TABLE " + TABLE_K + " (" + COLUMN_K_ID + " INTEGER PRIMARY KEY, " + COLUMN_K_NOME + " TEXT, " + COLUMN_K_EMAIL + " TEXT, " + COLUMN_K_SENHA + " TEXT, " + COLUMN_K_TELEFONE + " TEXT, " + COLUMN_K_SEXO + " INTEGER);"); db.execSQL("CREATE TABLE " + TABLE_C + " (" + COLUMN_C_ID + " INTEGER PRIMARY KEY, " + COLUMN_C_MARCA + " TEXT, " + COLUMN_C_MODELO + " TEXT, " + COLUMN_C_ANO + " INTEGER, " + COLUMN_C_QUILOMETRAGEM + " REAL, " + COLUMN_C_AIRBAG + " INTEGER, " + COLUMN_C_ARCONDICIONADO + " INTEGER, " + COLUMN_C_COR + " TEXT, " + COLUMN_C_PRECO + " REAL);"); db.execSQL("CREATE TABLE " + TABLE_P + " (" + COLUMN_P_ID + " INTEGER PRIMARY KEY, " + COLUMN_P_IDCARRO + " INTEGER, " + COLUMN_P_IDCLIENTE + " INTEGER, " + COLUMN_P_TIPOPAGAMENTO + " INTEGER, " + COLUMN_P_NUMPARCELAS + " INTEGER, " + COLUMN_P_VALORENTRADA + " REAL " + COLUMN_P_VALORCARRO + " REAL, " + COLUMN_P_VALORPARCELA + " REAL, " + COLUMN_P_CONFIRMACAO + " INTEGER);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_U); db.execSQL("DROP TABLE IF EXISTS " + TABLE_C); db.execSQL("DROP TABLE IF EXISTS " + TABLE_P); db.execSQL("DROP TABLE IF EXISTS " + TABLE_K); this.ctx.deleteDatabase(BANCO_DADOS); onCreate(db); } }
package src.modulo6.exercicios.prog2; import java.awt.event.*; import com.sun.opengl.util.GLUT; import java.nio.FloatBuffer; import javax.media.opengl.DebugGL; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; import src.modulo6.complementos.Point3; import src.modulo6.complementos.Vector3; import src.modulo5.complementos.*; import src.modulo6.exemplos.complementos.Camera; public class Renderer extends KeyAdapter implements GLEventListener{ // Atributos private GL gl; private GLU glu; private GLUT glut; private GLAutoDrawable glDrawable; private float translacaoX, translacaoY; private Camera camera; private double visualizacao; private Point3 eye; private Vector3 u, v, n; private double viewAngle, aspect, nearDist, farDist; //view volume shape float ex=2.3f, ey=1.3f, ez=2,vx=0, vy=0.1f,vz=0.1f; double winHt = 1.0;//0.2;//1.0; /** * Método definido na interface GLEventListener e chamado pelo objeto no qual será feito o desenho * logo após a inicialização do contexto OpenGL. */ public void init(GLAutoDrawable drawable) { glDrawable = drawable; gl = drawable.getGL(); glu = new GLU(); glut = new GLUT(); visualizacao = 1.0; eye = new Point3(); u = new Vector3(); v = new Vector3(); n = new Vector3(); System.err.println("INIT GL IS: " + gl.getClass().getName()); // Enable VSync gl.setSwapInterval(1); // Setup the drawing area and shading mode gl.glClearColor(0.0f, 0.0f, 0.0f, 0); //Cor de fundo branco gl.glViewport(0, 0, 640, 480); // gl.glColor3f(0.0f, 0.0f, 0.0f); //Cor do desenho gl.glPointSize(1.0f); //um ponto eh 4 x 4 pixels gl.glLineWidth(1.0f); gl.glShadeModel(GL.GL_SMOOTH); // try setting this to GL_FLAT and see what happens. gl.glEnable(GL.GL_LIGHTING); gl.glEnable(GL.GL_LIGHT0); gl.glEnable(GL.GL_DEPTH_TEST); gl.glEnable(GL.GL_NORMALIZE); myCamera(); } /** * Método definido na interface GLEventListener e chamado pelo objeto no qual será feito o desenho * para começar a fazer o desenho OpenGL pelo cliente. */ public void display(GLAutoDrawable drawable) { gl.glMatrixMode(GL.GL_PROJECTION); // set the view volume shape gl.glLoadIdentity(); gl.glOrtho(-winHt * 64 / 48.0, winHt * 64 / 48.0, -winHt, winHt, 0.1, 100.0); gl.glMatrixMode(GL.GL_MODELVIEW); // position and aim the camera gl.glLoadIdentity(); displaySolid(); } /** * Método definido na interface GLEventListener e chamado pelo objeto no qual será feito o desenho * quando o modo de exibição ou o dispositivo de exibição associado foi alterado. */ public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { } /** * Método definido na interface GLEventListener e chamado pelo objeto no qual será feito o desenho * depois que a janela foi redimensionada. */ public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } /** * Método definido na interface KeyListener que está sendo implementado que seja * feita a saída do sistema quando for pressionada a tecla ESC. */ @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_ESCAPE: System.exit(0); break; } glDrawable.display(); //glut.glutPostRedisplay(); // draw it again } public void wall(double thickness) { gl.glPushMatrix(); gl.glTranslated(0.5, 0.5 * thickness, 0.5); gl.glScaled(1.0, thickness, 1.0); glut.glutSolidCube(1.0f); gl.glPopMatrix(); } public void tableLeg(double thick, double len) { gl.glPushMatrix(); gl.glTranslated(0, len / 2, 0); gl.glScaled(thick, len, thick); glut.glutSolidCube(1.0f); gl.glPopMatrix(); } void jackPart() { gl.glPushMatrix(); gl.glScaled(0.2, 0.2, 1.0); glut.glutSolidSphere(1, 15, 15); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslated(0, 0, 1.2); glut.glutSolidSphere(0.2, 15, 15); gl.glTranslated(0, 0, -2.4); glut.glutSolidSphere(0.2, 15, 15); gl.glPopMatrix(); } void jack() { gl.glPushMatrix(); jackPart(); gl.glRotated(90.0, 0, 1, 0); jackPart(); gl.glRotated(90.0, 1, 0, 0); jackPart(); gl.glPopMatrix(); } void table(double topWid, double topThick, double legThick, double legLen) { gl.glPushMatrix(); gl.glTranslated(0, legLen, 0); gl.glScaled(topWid, topThick, topWid); glut.glutSolidCube(1.0f); gl.glPopMatrix(); double dist = 0.95 * topWid / 2.0 - legThick / 2.0; gl.glPushMatrix(); gl.glTranslated(dist, 0, dist); tableLeg(legThick, legLen); gl.glTranslated(0, 0, -2 * dist); tableLeg(legThick, legLen); gl.glTranslated(-2 * dist, 0, 2 * dist); tableLeg(legThick, legLen); gl.glTranslated(0, 0, -2 * dist); tableLeg(legThick, legLen); gl.glPopMatrix(); } void displaySolid() { // set properties of the surface material float[] mat_ambient = {0.0f, 0.0f, 0.7f, 1.0f}; float[] mat_diffuse = {0.6f, 0.6f, 0.6f, 1.0f}; float[] mat_specular = {1.0f, 1.0f, 1.0f, 1.0f}; float[] mat_shininess = {50.0f}; gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient, 0); gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_diffuse, 0); gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular, 0); gl.glMaterialfv(GL.GL_FRONT, GL.GL_SHININESS, mat_shininess, 0); // set the light source properties float[] lightIntensity = {0.7f, 0.7f, 0.7f, 1.0f}; float[] light_position = {2.0f, 6.0f, 3.0f, 0.0f}; gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, light_position, 0); gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, lightIntensity, 0); /*/ set camera gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); // double winHt = 1.0;//0.2;//1.0; gl.glOrtho(-winHt * 64 / 48.0, winHt * 64 / 48.0, -winHt, winHt, 0.1, 100.0); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); glu.gluLookAt(ex, ey, ez, vx, vy, vz, 0.0, 1.0, 0.0); */ // start drawing gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); gl.glPushMatrix(); gl.glTranslated(0.4, 0.4, 0.6); gl.glRotated(45.0, 0, 0, 1); gl.glScaled(0.08, 0.08, 0.08); jack(); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslated(0.6, 0.38, 0.5); gl.glRotated(30, 0, 1, 0); glut.glutSolidTeapot(0.08); gl.glPopMatrix(); gl.glPushMatrix(); // glTranslated(0.25,0.42,0.35); gl.glTranslated(1.25, 0.42, 0.35); glut.glutSolidSphere(0.1, 15, 15); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslated(0.4, 0, 0.4); table(0.6, 0.02, 0.02, 0.3); gl.glPopMatrix(); wall(0.02); gl.glPushMatrix(); gl.glRotated(90.0, 0.0, 0.0, 1.0); wall(0.02); gl.glPopMatrix(); gl.glPushMatrix(); gl.glRotated(-90.0, 1.0, 0.0, 0.0); wall(0.02); gl.glPopMatrix(); gl.glFlush(); } void myCamera(){ Point3 e = new Point3(4.0f,4.0f,4.0f); Point3 lo = new Point3(0.0f,0.0f,0.0f); Vector3 up = new Vector3(0.0f,1.0f,0.0f); set(e,lo,up); gl.glClear(GL.GL_COLOR_BUFFER_BIT|GL.GL_DEPTH_BUFFER_BIT); setShape(30.0f, 64.0f/48.0f, 0.5f, 50.0f); // glutMainLoop(); // cam.slide(0.2,0,0); } public void set(Point3 Eye, Point3 look, Vector3 up){ // make u, v, n vectors eye.setPoint3(Eye); // store the given eye position n.setVector(eye.getX() - look.getX(), eye.getY() - look.getY(),eye.getZ() - look.getZ()); // make n u.setVector(up.cross(n).getX(), up.cross(n).getY(), up.cross(n).getZ()); // make u = up X n n.normalize(); // make them unit length u.normalize(); v.setVector(n.cross(u).getX(), n.cross(u).getY(), n.cross(u).getZ()); // make v = n X u setModelViewMatrix(); // tell OpenGL }; public void setModelViewMatrix(){ // load modelview matrix with existing camera values Vector3 eVec = new Vector3(eye.getX(), eye.getY(), eye.getZ()); // float m[] = // { u.getX(), u.getY(), u.getZ(), -eVec.dot(u),// // v.getX(), v.getY(), v.getZ(), -eVec.dot(v),// // n.getX(), n.getY(), n.getZ(), -eVec.dot(n),// // 0.0f, 0.0f, 0.0f, 1.0f }; float m[] = { 0.0f, 1.0f, 0.0f, 0.0f,// 0.0f, 0.0f, 1.0f, 0.0f,// 1.0f, 0.0f, 0.0f, 0.0f,// 0.0f, 0.0f, 0.0f, 1.0f }; gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadMatrixf(m, 0); }; public void setShape(float vAngle, float asp, float nr, float fr) { viewAngle = vAngle; aspect = asp; nearDist = nr; farDist = fr; gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); glu.gluPerspective(viewAngle, aspect, nearDist, farDist); gl.glMatrixMode(GL.GL_MODELVIEW); // set its mode back again //glu.gluLookAt(ex, ey, ez, vx, vy, vz, 0.0, 1.0, 0.0); }; public void roll(float angle) { float PI = 3.1416f; float cs = (float) (Math.cos(PI/180.0 * angle)); float sn = (float) (Math.sin(PI / 180.0 * angle)); Vector3 t = u; u.setVector(cs * t.getX() - sn * v.getX(), cs * t.getY() - sn * v.getY(), cs * t.getZ() - sn * v.getZ()); v.setVector(sn * t.getX() + cs * v.getX(), sn * t.getY() + cs * v.getY(), sn * t.getZ() + cs * v.getZ()); setModelViewMatrix(); }; public void pitch(float angle) { float PI = 3.1416f; float cs = (float) (Math.cos(PI / 180 * angle)); float sn = (float) (Math.sin(PI / 180 * angle)); Vector3 t = v; // remember old v v.setVector(cs * t.getX() - sn * n.getX(), cs * t.getY() - sn * n.getY(), cs * t.getZ() - sn * n.getZ()); n.setVector(sn * t.getX() + cs * n.getX(), sn * t.getY() + cs * n.getY(), sn * t.getZ() + cs * n.getZ()); setModelViewMatrix(); }; public void yaw(float angle) { float PI = 3.1416f; float cs = (float) (Math.cos(PI / 180 * angle)); float sn = (float) (Math.sin(PI / 180 * angle)); Vector3 t = n; // remember old v n.setVector(cs * t.getX() - sn * u.getX(), cs * t.getY() - sn * u.getY(), cs * t.getZ() - sn * u.getZ()); u.setVector(sn * t.getX() + cs * u.getX(), sn * t.getY() + cs * u.getY(), sn * t.getZ() + cs * u.getZ()); setModelViewMatrix(); }; public void slide(double du, double dv, double dn) { eye.setX((float) (eye.getX() + (du * u.getX()) + (dv * v.getX()) + (dn * n.getX()))); eye.setY((float) (eye.getY() + (du * u.getY()) + (dv * v.getY()) + (dn * n.getY()))); eye.setZ((float) (eye.getZ() + (du * u.getZ()) + (dv * v.getZ()) + (dn * n.getZ()))); setModelViewMatrix(); }; public void setAspect(float asp){ aspect = asp; }; public void rotAxes(Vector3 a, Vector3 b, float angle) { // rotate orthogonal vectors a (like x axis) and b(like y axia) through angle degrees float ang = (float) (3.14159265 / 180 * angle); float C = (float) Math.cos(angle); float S = (float) Math.sin(angle); Vector3 t = new Vector3(C * a.getX() + S * b.getX(), C * a.getY() + S * b.getY(), C * a.getZ() + S * b.getZ()); b.setVector(-S * a.getX() + C * b.getX(), -S * a.getY() + C * b.getY(), -S * a.getZ() + C * b.getZ()); a.setVector(t.getX(), t.getY(), t.getZ()); // put tmp into a' }; }
package ch.alika.cukes.shopping.domain; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; class PriceListTest { private static final String BANANA = "banana"; private static final String ORANGE = "orange"; private static final Money BANANA_PRICE = new Money(1, 25); private static final Money ORANGE_PRICE = new Money(1, 45); private PriceList priceList; @BeforeEach void setup() { this.priceList = new PriceList(); priceList.putPrice(BANANA, BANANA_PRICE); priceList.putPrice(ORANGE, ORANGE_PRICE); } @Test void wherePriceRetrievedForKnownProducts() { assertThat(priceList.getPrice(BANANA),is(BANANA_PRICE)); assertThat(priceList.getPrice(ORANGE),is(ORANGE_PRICE)); } @Test void wherePriceRetreivedForUnknownProduct() { assertThrows(PriceUnknownException.class, () -> priceList.getPrice("Nonexistent_product")); } }
package com.zxt.compplatform.formengine.service; import com.zxt.framework.dictionary.entity.DataDictionary; /** * 组件树控制操作接口 * @author 007 */ public interface ComponentsTreeService { /** * 获取树数据 * @param dataDictionary * @param defalutValue * @return */ public String[] treeData(DataDictionary dataDictionary,String defalutValue); /** * 获取树展示数据 * @param dataDictionary * @param defalutValue * @param parentId * @return */ public String[] treeData(DataDictionary dataDictionary,String defalutValue,String parentId); /** * 获取组织机构数据 * @param dataDictionary * @param defaultValue * @param oid * @return */ public String[] treeOrgData(DataDictionary dataDictionary,String defaultValue,String oid); /** * 获取人员树 * @param dataDictionary * @param defaultValue * @param oid * @return */ public String[] treeHumanData(DataDictionary dataDictionary,String defaultValue,String oid); }
package com.mindstatus.bean.vo; import java.util.Date; import org.apache.commons.lang.builder.ReflectionToStringBuilder; /** * MsUser entity. * * @author MyEclipse Persistence Tools */ public class MsUser implements java.io.Serializable { private static final long serialVersionUID = -485998319443006902L; private Integer id; private String userName; private String realName; private Integer sex; private String password; private Date regTime; private Integer loginTimes; // Constructors /** default constructor */ public MsUser() { } /** minimal constructor */ public MsUser(Integer id) { this.id = id; } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getSex() { return this.sex; } public void setSex(Integer sex) { this.sex = sex; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public Date getRegTime() { return this.regTime; } public void setRegTime(Date regTime) { this.regTime = regTime; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public Integer getLoginTimes() { return this.loginTimes; } public void setLoginTimes(Integer loginTimes) { this.loginTimes = loginTimes; } public String toString() { return ReflectionToStringBuilder.toString(this); } }
package com.salesfloors.photouploader; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleScheduleBuilder; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; public class PhotoUploader { /** * @param args */ public static void main(String[] args) { try { JobDetail job = JobBuilder.newJob(UploadFacePicsJob.class) .withIdentity("batchJob", "batchGroup") .build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("batchTrigger", "batchGroup") .startNow() .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(10)) .build(); Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.scheduleJob(job, trigger); scheduler.start(); } catch (SchedulerException e) { e.printStackTrace(); } } public PhotoUploader() {} }
public class DriverOrderPC { public static void main(String[] args) { FactoryComputer factory = new FactoryComputer(); Computer computer = factory.assemblePC("Macbook"); if (computer != null) { computer.manufacture(); } Computer suface= factory.assemblePC("Surface"); if (suface != null) { suface.manufacture(); } Computer somePC= factory.assemblePC("RandomName"); if (somePC != null) { somePC.manufacture(); } } }
package com.hello.suripu.service.cli; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.model.CreateTableResult; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.hello.suripu.core.configuration.DynamoDBTableName; import com.hello.suripu.core.db.RingTimeHistoryDAODynamoDB; import com.hello.suripu.core.firmware.FirmwareFile; import com.hello.suripu.core.firmware.HardwareVersion; import com.hello.suripu.core.firmware.db.OTAFileSettingsDynamoDB; import com.hello.suripu.coredropwizard.configuration.NewDynamoDBConfiguration; import com.hello.suripu.service.configuration.SuripuConfiguration; import io.dropwizard.cli.ConfiguredCommand; import io.dropwizard.setup.Bootstrap; import net.sourceforge.argparse4j.inf.Namespace; import java.util.Map; public class CreateDynamoDBTables extends ConfiguredCommand<SuripuConfiguration> { public CreateDynamoDBTables() { super("create_dynamodb_tables_service", "Create service specific dynamoDB tables"); } @Override protected void run(Bootstrap<SuripuConfiguration> bootstrap, Namespace namespace, SuripuConfiguration configuration) throws Exception { final AWSCredentialsProvider awsCredentialsProvider = new DefaultAWSCredentialsProviderChain(); createRingTimeHistoryTable(configuration, awsCredentialsProvider); createOtaFileSettingsTable(configuration, awsCredentialsProvider); } private void createOtaFileSettingsTable(final SuripuConfiguration configuration, final AWSCredentialsProvider awsCredentialsProvider) throws InterruptedException { final AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsCredentialsProvider); final ImmutableMap<DynamoDBTableName, String> tableNames = configuration.dynamoDBConfiguration().tables(); final ImmutableMap<DynamoDBTableName, String> endpoints = configuration.dynamoDBConfiguration().endpoints(); final String tableName = tableNames.get(DynamoDBTableName.OTA_FILE_SETTINGS); final String endpoint = endpoints.get(DynamoDBTableName.OTA_FILE_SETTINGS); client.setEndpoint(endpoint); try { client.describeTable(tableName); System.out.println(String.format("%s already exists.", tableName)); } catch (AmazonServiceException exception) { final TableDescription description = OTAFileSettingsDynamoDB.createTable(client, tableName); System.out.println(tableName + ": " + description.getTableStatus()); } // TODO: remove this // Adds a few files to db for hardware version final OTAFileSettingsDynamoDB ddb = OTAFileSettingsDynamoDB.create(client, tableName, new ObjectMapper()); final FirmwareFile kitsune = FirmwareFile.create(true, false, true, "mcuimgx.bin", "/sys/", "mcuimgx.bin", "/"); final FirmwareFile top = FirmwareFile.create(true, false, false, "top.bin", "/top/", "update.bin", "/"); final FirmwareFile sp = FirmwareFile.create(true, false, false, "servicepack.ucf", "/sys/", "servicepack.ucf", "/"); final Map<String, FirmwareFile> map = Maps.newHashMap(); map.put("kitsune.bin", kitsune); map.put("top.bin", top); map.put("servicepack.ucf", sp); ddb.put(HardwareVersion.SENSE_ONE, map); } private void createRingTimeHistoryTable(final SuripuConfiguration configuration, final AWSCredentialsProvider awsCredentialsProvider){ final NewDynamoDBConfiguration config = configuration.dynamoDBConfiguration(); final AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsCredentialsProvider); final ImmutableMap<DynamoDBTableName, String> tableNames = configuration.dynamoDBConfiguration().tables(); final ImmutableMap<DynamoDBTableName, String> endpoints = configuration.dynamoDBConfiguration().endpoints(); final String tableName = tableNames.get(DynamoDBTableName.RING_TIME_HISTORY); final String endpoint = endpoints.get(DynamoDBTableName.RING_TIME_HISTORY); client.setEndpoint(endpoint); try { client.describeTable(tableName); System.out.println(String.format("%s already exists.", tableName)); } catch (AmazonServiceException exception) { final CreateTableResult result = RingTimeHistoryDAODynamoDB.createTable(tableName, client); final TableDescription description = result.getTableDescription(); System.out.println(tableName + ": " + description.getTableStatus()); } } }
import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.*; /** * The test class ArrayPriorityQueueTest. * * @author Kody Dangtongdee * @version 2/10/2015 */ public class ArrayPriorityQueueTest { /** * Default constructor for test class ArrayPriorityQueueTest */ public ArrayPriorityQueueTest() { } /** * Sets up the test fixture. * * Called before every test case method. */ @Before public void setUp() { } /** * Tears down the test fixture. * * Called after every test case method. */ @After public void tearDown() { } @Test @SuppressWarnings({"unchecked"}) public void testClear() { ArrayPriorityQueue<Integer> priority1 = new ArrayPriorityQueue<Integer>(); priority1.enqueue(new Integer(1)); priority1.enqueue(new Integer(2)); assertEquals(2, priority1.size()); priority1.clear(); assertEquals(0, priority1.size()); } @Test @SuppressWarnings({"unchecked"}) public void testDequeue() { ArrayPriorityQueue<Integer> priority1 = new ArrayPriorityQueue<Integer>(); assertEquals(null, priority1.dequeue()); priority1.enqueue(new Integer(3)); priority1.enqueue(new Integer(1)); priority1.enqueue(new Integer(6)); priority1.enqueue(new Integer(7)); priority1.enqueue(new Integer(4)); assertEquals(new Integer(1), priority1.dequeue()); assertEquals(new Integer(3), priority1.dequeue()); assertEquals(new Integer(4), priority1.dequeue()); assertEquals(new Integer(6), priority1.dequeue()); assertEquals(new Integer(7), priority1.dequeue()); assertEquals(0, priority1.size()); } @Test @SuppressWarnings({"unchecked"}) public void testIsEmpty() { ArrayPriorityQueue<Integer> priority1 = new ArrayPriorityQueue<Integer>(); assertTrue(priority1.isEmpty()); priority1.enqueue(new Integer(3)); priority1.enqueue(new Integer(2)); assertFalse(priority1.isEmpty()); } @Test @SuppressWarnings({"unchecked"}) public void testPeek() { ArrayPriorityQueue priority1 = new ArrayPriorityQueue(); assertEquals(null, priority1.peek()); priority1.enqueue(new Integer(3)); priority1.enqueue(new Integer(1)); priority1.enqueue(new Integer(6)); priority1.enqueue(new Integer(7)); priority1.enqueue(new Integer(4)); assertEquals(1, priority1.peek()); priority1.dequeue(); assertEquals(3, priority1.peek()); } @Test @SuppressWarnings({"unchecked"}) public void testIterator() { ArrayPriorityQueue<Integer> priority1 = new ArrayPriorityQueue<Integer>(); priority1.enqueue(new Integer(3)); priority1.enqueue(new Integer(1)); priority1.enqueue(new Integer(6)); priority1.enqueue(new Integer(7)); priority1.enqueue(new Integer(4)); ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(3); list.add(4); list.add(6); list.add(7); Iterator listIterator = list.iterator(); Iterator prioIterator = priority1.iterator(); assertEquals(listIterator.next(), prioIterator.next()); assertTrue(prioIterator.hasNext()); assertEquals(listIterator.next(), prioIterator.next()); assertTrue(prioIterator.hasNext()); assertEquals(listIterator.next(), prioIterator.next()); assertTrue(prioIterator.hasNext()); assertEquals(listIterator.next(), prioIterator.next()); assertTrue(prioIterator.hasNext()); assertEquals(listIterator.next(), prioIterator.next()); assertFalse(prioIterator.hasNext()); try { prioIterator.remove(); fail(); } catch(UnsupportedOperationException e) { assertTrue(true); } try { prioIterator.next(); fail(); } catch(NoSuchElementException e) { assertTrue(true); } } }
//package com.lenovohit.ssm.treat.web.rest; // //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.web.bind.annotation.RequestBody; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.RequestMethod; //import org.springframework.web.bind.annotation.RestController; // //import com.lenovohit.core.manager.GenericManager; //import com.lenovohit.core.utils.DateUtils; //import com.lenovohit.core.utils.JSONUtils; //import com.lenovohit.core.utils.StringUtils; //import com.lenovohit.core.web.MediaTypes; //import com.lenovohit.core.web.rest.BaseRestController; //import com.lenovohit.core.web.utils.Result; //import com.lenovohit.core.web.utils.ResultUtils; //import com.lenovohit.ssm.SSMConstants; //import com.lenovohit.ssm.base.model.Machine; //import com.lenovohit.ssm.payment.model.Order; //import com.lenovohit.ssm.payment.model.Settlement; //import com.lenovohit.ssm.payment.utils.OrderSeqCalculator; // ///** // * 预存 // */ //@RestController //@RequestMapping("/ssm/treat/prepaid") //public class PrepaidRestController extends BaseRestController { // @Autowired // private GenericManager<Order, String> orderManager; // @Autowired // private GenericManager<Settlement, String> settlementManager; // /** // * 生成订单、结算单 // * @param data // * @return // */ // @RequestMapping(value="/createOrder",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) // public Result forCreateOrder(@RequestBody String data){ // Order order = JSONUtils.deserialize(data, Order.class); // validOrder(order); // buildOrder(order); // // this.orderManager.save(order); // /*List<PayChannel> channels= this.payChannelManager.find("from PayChannel where code = ? ", order.getPayChannel()); // if(null ==channels || channels.size() == 0 ){ // return ResultUtils.renderFailureResult("不支持的支付渠道"); // }else if(channels.size() > 1){ // return ResultUtils.renderFailureResult("多个符合条件的支付渠道"); // } // Settlement settle = this.creatSettle(order, channels.get(0)); // // this.settlementManager.save(settle); // order.getSettlements().add(settle);*/ // return ResultUtils.renderSuccessResult(order); // } // // // private void buildOrder(Order order) { // if (null == order) { // throw new NullPointerException("order should not be NULL!"); // } // Machine machine = (Machine) this.getSession().getAttribute(SSMConstants.SSM_MACHINE_KEY); // if (null == machine){ // throw new NullPointerException("machine should not be NULL!"); // } // order.setOrderNo(OrderSeqCalculator.calculateCode(Order.ORDER_TYPE_PAY)); // order.setOrderType(Order.ORDER_TYPE_PAY); // order.setOrderTitle("昆华医院自助机预存: " + order.getAmt() + " 元!"); // order.setOrderDesc("昆华医院自助机预存: " + order.getAmt() + " 元!"); // order.setBizType("00"); // order.setBizNo(""); // order.setBizUrl(""); // order.setBizBean("hisPrePaidManager"); // order.setStatus(Order.ORDER_STAT_INITIAL); // order.setSelfAmt(order.getAmt()); // order.setAmt(order.getAmt()); // order.setHisNo(machine.getHospitalNo()); // order.setTerminalId(machine.getId()); // order.setTerminalCode(machine.getCode()); // order.setTerminalName(machine.getName()); // order.setCreateTime(DateUtils.getCurrentDate()); // } // // private void validOrder(Order order) { // if (StringUtils.isEmpty(order.getPatientNo())) { // throw new NullPointerException("patientNo should not be NULL!"); // } // if (StringUtils.isEmpty(order.getPatientName())) { // throw new NullPointerException("patientName should not be NULL!"); // } // /* if (StringUtils.isEmpty(order.getPatientIdNo())) { // throw new NullPointerException("patientIdNo should not be NULL!"); // } // if (StringUtils.isEmpty(order.getPatientCardNo())) { // throw new NullPointerException("patientCardNo should not be NULL!"); // } // if (StringUtils.isEmpty(order.getPatientCardType())) { // throw new NullPointerException("patientCardType should not be NULL!"); // }*/ // } // /*private Settlement creatSettle(Order order,PayChannel channel){ // Settlement settle = new Settlement(); // settle.setOrderId(order.getId()); // settle.setAmt(order.getAmt()); // settle.setOrderNo(order.getOrderNo()); // settle.setPayChannelCode(channel.getCode()); // settle.setPayChannelId(channel.getId()); // settle.setPayChannelName(channel.getName()); // // return settle; // }*/ //}
package org.didierdominguez.view.transaction; import com.jfoenix.controls.JFXAlert; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXDialogLayout; import com.jfoenix.controls.JFXTextField; import com.jfoenix.validation.RequiredFieldValidator; import javafx.geometry.Insets; import javafx.scene.control.Label; import javafx.scene.control.Spinner; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import org.didierdominguez.bean.CreditCard; import org.didierdominguez.controller.ControllerCreditCard; import org.didierdominguez.controller.ControllerPurchase; import org.didierdominguez.util.ScreenSize; import org.didierdominguez.util.Verifications; import org.didierdominguez.view.Alert; public class ViewPurchase { private static ViewPurchase instance; private ViewPurchase() { } public static ViewPurchase getInstance() { if (instance == null) { instance = new ViewPurchase(); } return instance; } public void showAlertProduct(HBox hBox, String title) { JFXAlert<String> alert = new JFXAlert<>((Stage) hBox.getScene().getWindow()); alert.initModality(Modality.APPLICATION_MODAL); alert.setOverlayClose(false); RequiredFieldValidator validator = new RequiredFieldValidator(); double x = ScreenSize.getInstance().getX(); GridPane gridfields = new GridPane(); gridfields.setVgap(25); gridfields.setPadding(new Insets(20)); JFXTextField fieldCreditCard = new JFXTextField(); fieldCreditCard.setPromptText("NO. DE TARJETA DE CREDITO"); fieldCreditCard.setLabelFloat(true); fieldCreditCard.setPrefWidth(x); fieldCreditCard.getValidators().add(validator); fieldCreditCard.focusedProperty().addListener((observable, oldValue, newValue) -> { if (!newValue) { fieldCreditCard.validate(); } }); gridfields.add(fieldCreditCard, 0, 0, 2, 1); Label labelAmount = new Label("MONTO:"); labelAmount.setPrefWidth(x); gridfields.add(labelAmount, 0, 1); Spinner<Double> spinnerAmount = new Spinner<>(0.00, 100000.00, 0, 1); spinnerAmount.setEditable(true); spinnerAmount.setPrefWidth(x); gridfields.add(spinnerAmount, 1, 1); JFXDialogLayout layout = new JFXDialogLayout(); layout.setHeading(new Label(title)); layout.setBody(new VBox(gridfields)); JFXButton cancelButton = new JFXButton("Cerrar"); cancelButton.setCancelButton(true); cancelButton.getStyleClass().addAll("customButton", "primaryButton"); cancelButton.setButtonType(JFXButton.ButtonType.FLAT); cancelButton.setOnAction(closeEvent -> alert.hideWithAnimation()); JFXButton buttonAdd = new JFXButton("Aceptar"); buttonAdd.getStyleClass().addAll("customButton", "primaryButton"); buttonAdd.setButtonType(JFXButton.ButtonType.FLAT); buttonAdd.setOnAction(event -> { CreditCard creditCard = ControllerCreditCard.getInstance().searchCreditCard(fieldCreditCard.getText()); if (fieldCreditCard.getText().length() == 0 || !Verifications.getInstance().isNumeric(spinnerAmount.getEditor().getText()) || Double.parseDouble(spinnerAmount.getEditor().getText()) <= 0) { Alert.getInstance().showAlert(gridfields, "ERROR", "UNO O MÁS DATOS SON INCORRECTOS"); } else if (creditCard == null || creditCard.getAuthorization() == null || creditCard.getCustomer() != TransactionPanel.getInstance().getCustomer()) { Alert.getInstance().showAlert(gridfields, "ERROR", "LA TARJETA NO FUE ENCONTRADA"); } else { if ((Double.parseDouble(spinnerAmount.getEditor().getText()) + creditCard.getAmountOwed()) <= creditCard .getCreditLimit()) { ControllerCreditCard.getInstance().updateCreditCard(creditCard.getId(), (Double.parseDouble(spinnerAmount.getEditor().getText()))); ControllerPurchase.getInstance().createPurchase(TransactionPanel.getInstance().getCustomer(), creditCard, Double.parseDouble(spinnerAmount.getEditor().getText())); Alert.getInstance().showAlert(gridfields, "ÉXITO", "COMPRA REALIZADA"); } else { Alert.getInstance().showAlert(gridfields, "ERROR", "LA TARJETA NO POSEE FONDOS"); } } }); layout.setActions(buttonAdd, cancelButton); alert.setContent(layout); alert.show(); } }
package com.rednovo.ace.ui.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.rednovo.ace.AceApplication; public class BaseFragment extends Fragment { protected boolean isOnCreateView = false; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { isOnCreateView = true; return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onDestroyView() { super.onDestroyView(); isOnCreateView = false; } @Override public void onDestroy() { super.onDestroy(); // RefWatcher refWatcher = AceApplication.getRefWatcher(getActivity()); // refWatcher.watch(this); } }
package phonebook; import static org.junit.Assert.*; import org.junit.Test; /** * Unit tests for phonebook.PhoneNumber. * @author jherwitz */ public class PhoneNumberTests { //TODO: generate random phone numbers for these tests @Test public void testHashCodeLegality(){ PhoneNumber number1 = new PhoneNumber(999,999,9999); PhoneNumber number2 = new PhoneNumber(999,999,9999); assertTrue(number1.hashCode() == number2.hashCode()); } @Test public void testHashCodeSparseness(){ PhoneNumber number1 = new PhoneNumber(999,999,9998); PhoneNumber number2 = new PhoneNumber(999,999,9999); assertFalse(number1.hashCode() == number2.hashCode()); } @Test (expected = IllegalArgumentException.class) public void testOutOfRangeNumberException(){ PhoneNumber number = new PhoneNumber(110,1101,1100); } @Test (expected = IllegalArgumentException.class) public void testOutOfRangeNumberExceptionAgain(){ PhoneNumber number = new PhoneNumber(110,-10,1100); } @Test public void testGenericHashCode(){ PhoneNumber number1 = new PhoneNumber(101,202,3303); assertTrue(number1.hashCode() == number1.genericHashCode()); } @Test public void testGenericHashCodeAgain(){ PhoneNumber number1 = new PhoneNumber(000,000,0000); assertTrue(number1.hashCode() == number1.genericHashCode()); } @Test public void testPhoneNumberComparisonLineNumber(){ PhoneNumber number1 = new PhoneNumber(999,999,9998); PhoneNumber number2 = new PhoneNumber(999,999,9999); assertTrue(number1.compareTo(number2) < 0); } @Test public void testPhoneNumberComparisonAreaCode(){ PhoneNumber number1 = new PhoneNumber(998,999,9998); PhoneNumber number2 = new PhoneNumber(999,999,9999); assertTrue(number1.compareTo(number2) < 0); } @Test public void testPhoneNumberComparisonPrefix(){ PhoneNumber number1 = new PhoneNumber(999,998,9998); PhoneNumber number2 = new PhoneNumber(999,999,9999); assertTrue(number1.compareTo(number2) < 0); } @Test public void testToStringNotBroken(){ PhoneNumber number1 = new PhoneNumber(000,000,0000); String str = number1.toString(); assertTrue(str != null && str != ""); } @Test public void testPhoneNumberNotEqualToDifferentObject(){ PhoneNumber number = new PhoneNumber(101,110,1101); assertFalse(number.equals(new Object())); } @Test public void testPhoneNumberEquals(){ PhoneNumber number1 = new PhoneNumber(999,999,9999); PhoneNumber number2 = new PhoneNumber(999,999,9999); assertTrue(number1.equals(number2)); } @Test public void testPhoneNumberNotEquals(){ PhoneNumber number1 = new PhoneNumber(998,999,9999); PhoneNumber number2 = new PhoneNumber(999,999,9999); assertFalse(number1.equals(number2)); } @Test public void testPhoneNumberEqualsNull(){ PhoneNumber number1 = new PhoneNumber(998,999,9999); assertFalse(number1.equals(null)); } @Test public void testPhoneNumberEqualsReflexivity(){ PhoneNumber number1 = new PhoneNumber(998,999,9999); assertTrue(number1.equals(number1)); } @Test public void testPhoneNumberEqualsSymmetry(){ PhoneNumber number1 = new PhoneNumber(998,999,9999); PhoneNumber number2 = new PhoneNumber(999,999,9999); assertFalse(number1.equals(number2) && number2.equals(number1)); } @Test public void testPhoneNumberEqualsTransitivity(){ PhoneNumber number1 = new PhoneNumber(999,999,9999); PhoneNumber number2 = new PhoneNumber(999,999,9999); PhoneNumber number3 = new PhoneNumber(999,999,9999); assertTrue(number1.equals(number2) && number2.equals(number3) && number1.equals(number3)); } @Test public void testPhoneNumberEqualsConsistency() throws InterruptedException{ PhoneNumber number1 = new PhoneNumber(998,999,9999); PhoneNumber number2 = new PhoneNumber(999,999,9999); boolean try1 = number1.equals(number2); Thread.sleep(1000); boolean try2 = number1.equals(number2); assertTrue(try1==try2); } @Test (expected = IllegalArgumentException.class) public void testPhoneNumberComparisonWithNull(){ PhoneNumber number1 = new PhoneNumber(101,111,1101); number1.compareTo(null); } }
package cn.android.support.v7.lib.sin.crown.utils; import android.util.Log; import org.json.JSONArray; import org.json.JSONObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * JSON数据转实体类工具,一般都是读取json数据。而转化为json数据的,比较少用。 * 1,必须有空构造函数,2,必须有get,set方法【get,set后面的那个字母必须是大写】。 * 3,必须实现Serializable接口(implements)。这个没有必要,如果要对这个实体类进行数据缓存的话,就必须实现序列化。单纯的json数据转换,不需要实现Serializable。只有对数据进行保存的时候才需要。 * 4,只对当前类属性有效,父类属性访问不到。 * <p> * 日期格式,也是String类型。一定要使用Integer,Boolean类型,而不是基本类型int,boolean。不要使用基本类型,也不要使用Object * 5,属性支持String,Double,Float,Integer,Boolean,Long类型【Integer能转int,Boolean能转boolean,基本类型能够转换成所对应的类型】,不支持Byte,char类型 * <p> * 对Object也不支持,只是保存了Object的引用地址而已,无法真正保存一个Object对象。 * 虽然支持基本类型(Object强制转换的),不推荐使用基本类型。尽量使用Strign,Integer等类型,而不是int,long。尽量不要使用基本类型。 * <p> * <p> * JSONObjiect对象,自带url解密。即"\u6731\u4e8c" 这个格式,谷歌自带的json对象是可以解析出来的。 * <p> * Created by 彭治铭 on 2017/5/26. */ public class JSONObjectUtils<T> { private static JSONObjectUtils utilJSONObject; private JSONObjectUtils() { } public static JSONObjectUtils getInstance() { if (utilJSONObject == null) { utilJSONObject = new JSONObjectUtils(); } return utilJSONObject; } /** * JSONObject对象转实体类【通过反射实现,亲测可行,实体类只要不混淆即可,签名打包都没问题。效果杠杠的】 * * @param jsonObject org.json.JSONObject 安卓自带的json对象,非第三方 * @param clazz 泛型,Class类型。实体类的所有属性都必须是String类型。且必须具体空构造函数和set方法。【get方法里面没有用到,所以不需要】 * @return 返回实体类 */ public T getBean(JSONObject jsonObject, Class<T> clazz) { T t = null; try { t = clazz.newInstance();//泛型实例化,注意啦,这一步,必须具备空构造函数,不然无法实例化 //遍历类 成员属性【只对当前类有效,父类无效,即只获取本类的属性】 Field[] fields = t.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { // 获取属性的名字 String name = fields[i].getName(); String jName = name; // 将属性的首字符大写,方便构造get,set方法 name = name.substring(0, 1).toUpperCase() + name.substring(1); // 获取属性的类型 String type = fields[i].getGenericType().toString(); //Method m = t.getClass().getMethod("get" + name); // 调用getter方法获取属性值 //String value = (String) m.invoke(t); //调用set方法 ///Log.e("test","name:\t"+name); if (!jsonObject.has(jName)) {//判斷json數據是否存在該字段 continue; } Class[] parameterTypes = new Class[1]; parameterTypes[0] = fields[i].getType(); Method m = t.getClass().getMethod("set" + name, parameterTypes);//set方法 Object[] objects = new Object[1]; Object obj = jsonObject.get(jName); //判断值是否为空 if (obj == null || obj.toString().equals("null") || obj.toString().equals("")) { continue;//不允许值为空 } //Log.e("test","type:\t"+type); // 如果type是类类型,则前面包含"class ",后面跟类名【一般都是String,Double,Object,所以这三个写前面】 if (type.equals("class java.lang.String")) { objects[0] = jsonObject.getString(jName);//String类型 } else if (type.equals("class java.lang.Double")) { objects[0] = jsonObject.getDouble(jName);//Double类型 } else if (type.equals("class java.lang.Object")) { objects[0] = jsonObject.get(jName);//Object类型 } else if (type.equals("class java.lang.Float")) { objects[0] = Float.valueOf(jsonObject.get(jName).toString());//Float类型 } else if (type.equals("class java.lang.Integer")) { objects[0] = jsonObject.getInt(jName);//Integer类型 } else if (type.equals("class java.lang.Boolean")) { objects[0] = jsonObject.getBoolean(jName);//Boolean类型 //Log.e("test","波尔:\t"+objects[0]); } else if (type.equals("class java.lang.Long")) { objects[0] = jsonObject.getLong(jName);//Long类型 } else { objects[0] = jsonObject.get(jName);//Object类型,兼容基本类型 } //Log.e("test","objects[0]:\t"+objects[0]+"\tjName:\t"+jName+"\t等于空:\t"+(objects[0]!=null)+"\t"+(!objects[0].toString().equals("null"))+"\t"+(!objects[0].toString().equals(""))); if (objects[0] != null && !objects[0].toString().equals("null") && !objects[0].toString().equals("")) { try { //Log.e("test","type:\t"+type+"\tjName:\t"+jName+"\t值:\t"+objects[0]); m.invoke(t, objects);//方法调用 } catch (Exception e) { Log.e("test", "UtilJSONObject赋值异常:\t" + e.getMessage()); } } } } catch (Exception e) { Log.e("test", "UtilJSONObject反射异常:\t" + e.getMessage()); } return t; } /** * JSONObject转ArrayList * * @param jsonArray org.json.JSONArray安卓自带json数组 * @param clazz 泛型,Class类型。 * @return 返回 ArrayList 数组 */ public List<T> getArrayList(JSONArray jsonArray, Class<T> clazz) { List<T> list = new ArrayList<>(); try { for (int i = 0; i < jsonArray.length(); i++) { list.add(getBean(jsonArray.getJSONObject(i), clazz)); } } catch (Exception e) { Log.e("test", "UtilJSONObject反射List异常:\t" + e.getMessage()); } return list; } //实体类转化成json数据,参数直接传实体类对象即可 public JSONObject BeanToJSON(T t) { JSONObject jsonObject = new JSONObject(); try { //遍历类 成员属性【只对当前类有效,父类无效,即只获取本类的属性】 Field[] fields = t.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { // 获取属性的名字 String name = fields[i].getName(); if (name.trim().equals("$change") || name.trim().equals("serialVersionUID")) { continue; } String jName = name; // 将属性的首字符大写,方便构造get,set方法 name = name.substring(0, 1).toUpperCase() + name.substring(1); // 获取属性的类型 String type = fields[i].getGenericType().toString(); //Log.e("test","type:\t"+type+"\tjName:\t"+jName); Method m = null; try { // 调用getter方法获取属性值 m = t.getClass().getMethod("get" + name); Object obj = m.invoke(t); //Log.e("test","obj:\t"+obj); if (obj == null) { continue; } } catch (Exception e) { Log.e("test", "get()异常:\t" + e.getMessage()); } // 如果type是类类型,则前面包含"class ",后面跟类名 if (type.equals("class java.lang.String")) { String value = (String) m.invoke(t); jsonObject.put(jName, value); } else if (type.equals("class java.lang.Double")) { double value = (Double) m.invoke(t); jsonObject.put(jName, value); } else if (type.equals("class java.lang.Object")) { Object value = m.invoke(t); jsonObject.put(jName, value); } else if (type.equals("class java.lang.Float")) { float value = (float) m.invoke(t); jsonObject.put(jName, value); } else if (type.equals("class java.lang.Integer")) { int value = (int) m.invoke(t); jsonObject.put(jName, value); } else if (type.equals("class java.lang.Boolean")) { boolean value = (boolean) m.invoke(t); jsonObject.put(jName, value); } else if (type.equals("class java.lang.Long")) { long value = (long) m.invoke(t); jsonObject.put(jName, value); } else { Object value = m.invoke(t); if (value != null && !value.equals("null") && !value.equals("")) { jsonObject.put(jName, value);//Object类型,兼容基本类型 } } } } catch (Exception e) { Log.e("test", "UtilJSONObject实体类转JSON数据异常:\t" + e.getMessage()); } return jsonObject; } //ArrayList转化为JSON public JSONArray ArrayListToJSONArray(List<T> list) { JSONArray jsonArray = new JSONArray(); try { for (int i = 0; i < list.size(); i++) { JSONObject jsonObject = BeanToJSON(list.get(i)); jsonArray.put(i, jsonObject); } } catch (Exception e) { Log.e("test", "UtilJSONObject List转换JSON异常:\t" + e.getMessage()); } return jsonArray; } //兼容之前的。 public JSONArray ArrayListToJSON(List<T> list) { return ArrayListToJSONArray(list); } }
import java.awt.BorderLayout; import java.awt.Component; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.Statement; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.awt.event.ActionEvent; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.SystemColor; import java.awt.Font; import javax.swing.border.SoftBevelBorder; import javax.swing.border.BevelBorder; public class Mainpage extends JFrame { private JPanel contentPane; private JTextField textField; private JTextField textField_1; private JTextField textField_2; private JLabel lblBalance; private JLabel lblNewLabel; private JLabel lblEnterYourAccount; private JLabel lblNewLabel_1; private JLabel lblNewLabel_2; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Mainpage frame = new Mainpage(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Mainpage() { setTitle("OMG Bank "); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBackground(SystemColor.controlShadow); contentPane.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null)); setContentPane(contentPane); contentPane.setLayout(null); Login Lg = new Login(); String User=Lg.lbl_username.getText(); System.out.println("This is the session "+User); Connection conn; String balance = null; try { conn = (Connection) DriverManager .getConnection("jdbc:mysql://192.168.16.171:3306/bank","monty", "monty1234"); Statement stmt = (Statement) conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM account WHERE account_number = "+ User); while (rs.next()) { balance= rs.getString("balance"); lblNewLabel.setText(balance); System.out.println("This is the Balance "+balance); } } catch(SQLException e) { } textField = new JTextField(); textField.setToolTipText("Enter your account number"); textField.setBounds(10, 53, 204, 20); contentPane.add(textField); textField.setColumns(10); textField.setText(User); textField_1 = new JTextField(); textField_1.setToolTipText("Enter Value"); textField_1.setBounds(10, 84, 204, 20); contentPane.add(textField_1); textField_1.setColumns(10); textField_2 = new JTextField(); textField_2.setToolTipText("Enter the account you want to send to"); textField_2.setBounds(10, 130, 204, 20); contentPane.add(textField_2); textField_2.setColumns(10); JButton btnSend = new JButton("Send"); btnSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String AN =textField.getText(); String MTS=textField_1.getText(); String SAN=textField_2.getText(); String balance2= null; String balance = null; try { Connection conn = (Connection) DriverManager .getConnection("jdbc:mysql://192.168.16.171:3306/bank","monty", "monty1234"); Statement stmt = (Statement) conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM account WHERE account_number = "+AN); while (rs.next()) { balance= rs.getString("balance"); lblNewLabel.setText(balance); } Date date = new Date(); String insert= "INSERT INTO transaction_log (account_number, t_time_date, receiver_number,amount_sent)" + "VALUES (?, ?, ?,?)"; PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(insert); preparedStatement.setString(1,AN ); preparedStatement.setString(2,date.toString()); preparedStatement.setString(3, SAN); preparedStatement.setString(4, MTS); preparedStatement.executeUpdate(); int mts =Integer.parseInt(MTS); int bal =Integer.parseInt(balance); int rb=bal - mts ; String RB = String.valueOf(rb); Statement stmt2 = (Statement) conn.createStatement(); rs = stmt2.executeQuery("SELECT * FROM account WHERE account_number = "+SAN); while (rs.next()) { balance2 = rs.getString("balance"); } int bal2 =Integer.parseInt(balance2); int mtbs=mts+bal2; String MBS= String.valueOf(mtbs); // create the java mysql update preparedstatement String query = "update account set balance = ? where account_number = ?"; PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(query); preparedStmt.setString (1, RB); preparedStmt.setString(2, AN); // execute the java preparedstatement preparedStmt.executeUpdate(); // create the java mysql update preparedstatement String sql= "update account set balance = ? where account_number = ?"; preparedStmt = (PreparedStatement) conn.prepareStatement(sql); preparedStmt.setString (1, MBS); preparedStmt.setString(2, SAN); // execute the java preparedstatement preparedStmt.executeUpdate(); Component frame = null; JOptionPane.showMessageDialog(frame, "Successfully sent."); lblNewLabel_2.setText("Sent !") ; } catch (SQLException e) { System.out.println("Connection Failed! Check output console"); e.printStackTrace(); return; } } }); btnSend.setBounds(10, 174, 91, 23); contentPane.add(btnSend); lblBalance = new JLabel("Balance:"); lblBalance.setBounds(10, 0, 60, 14); contentPane.add(lblBalance); lblNewLabel = new JLabel(""); lblNewLabel.setBounds(309, 0, 123, 14); contentPane.add(lblNewLabel); lblEnterYourAccount = new JLabel("Enter your Account Number"); lblEnterYourAccount.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11)); lblEnterYourAccount.setBounds(10, 37, 173, 14); contentPane.add(lblEnterYourAccount); lblNewLabel_1 = new JLabel(""); lblNewLabel_1.setBounds(224, 161, 149, 14); contentPane.add(lblNewLabel_1); JLabel lblEnterAmountTo = new JLabel("Enter Amount to be sent"); lblEnterAmountTo.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11)); lblEnterAmountTo.setBounds(10, 72, 149, 14); contentPane.add(lblEnterAmountTo); JLabel lblReceiversAccount = new JLabel("Receivers Account"); lblReceiversAccount.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11)); lblReceiversAccount.setBounds(10, 115, 149, 14); contentPane.add(lblReceiversAccount); lblNewLabel_2 = new JLabel(""); lblNewLabel_2.setBounds(10, 246, 212, 14); contentPane.add(lblNewLabel_2); } }
package be.chuk; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.ScreenHelper; import be.openclinic.finance.Insurar; import be.openclinic.finance.InsuranceCategory; import be.openclinic.finance.Prestation; import be.openclinic.common.ObjectReference; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.ResultSet; import java.util.Date; import java.util.Vector; import java.text.SimpleDateFormat; public class Sage { public static void synchronizeInsurars(){ try { System.out.println("Synchronising insurars"); Date lastSync= new SimpleDateFormat("yyyyMMddHHmmss").parse("19000101000000"); try{ lastSync = new SimpleDateFormat("yyyyMMddHHmmss").parse(MedwanQuery.getInstance().getConfigString("lastSageInsurarSync","19000101000000")); } catch(Exception e4){ } Date maxDate=lastSync; Connection oc_conn=MedwanQuery.getInstance().getLongOpenclinicConnection(); Connection loc_conn=MedwanQuery.getInstance().getLongOpenclinicConnection(); PreparedStatement ps = loc_conn.prepareStatement("select * from SageInsurars where cbModification>?"); ps.setTimestamp(1,new Timestamp(lastSync.getTime())); ResultSet rs = ps.executeQuery(); while(rs.next()){ String insuranceCode=rs.getString("CT_Num"); String insuranceName=rs.getString("CT_Intitule"); String insurarContact= ScreenHelper.checkString(rs.getString("CT_Adresse"))+"\n"+ ScreenHelper.checkString(rs.getString("CT_CodePostal"))+" "+ScreenHelper.checkString(rs.getString("CT_Ville"))+"\n"+ ScreenHelper.checkString(rs.getString("CT_Pays")); String insurarCatTariff=ScreenHelper.checkString(rs.getString("N_CatTarif")); //We zoeken nu deze verzekeraar op boolean bexists=false; System.out.println("Checking SAGE insurar "+insuranceCode); Vector insurars = Insurar.getInsurarsByName("%#"+insuranceCode); if(insurars.size()>0){ Insurar insurar=null; for(int i=0;i<insurars.size();i++){ Insurar ins = (Insurar)insurars.elementAt(i); if(ins.getName().endsWith("#"+insuranceCode)){ insurar=ins; } } if(insurar!=null){ System.out.println("Updating"); bexists=true; //De verzekeraar bestaat reeds, we gaan de gegevens updaten insurar.setName(insuranceName+" #"+insuranceCode); insurar.setOfficialName(insuranceName); insurar.setContact(insurarContact.trim()); insurar.setContactPerson((ScreenHelper.checkString(rs.getString("CT_Contact"))+" "+ScreenHelper.checkString(rs.getString("CT_Email"))).trim()); insurar.setLanguage("FR"); int reimbursement=rs.getInt("CT_Taux01"); if(reimbursement==0){ //Let's checkout if there is no default reimbursement to be found in the SageFamilyReimbursements String sQuery2="select count(*),FC_Remise from SageFamilyReimbursements where CT_Num=? group by FC_Remise order by count(*) desc"; PreparedStatement ps2=oc_conn.prepareStatement(sQuery2); try{ ps2.setString(1,insuranceCode); ResultSet rs2=ps2.executeQuery(); if(rs2.next()){ reimbursement=rs2.getInt("FC_Remise"); } rs2.close(); ps2.close(); } catch (Exception e){ e.printStackTrace(); } } String patientShare=reimbursement+""; if (insurarCatTariff.equalsIgnoreCase("1")){ insurarCatTariff="A"; insurar.setInsuraceCategories(new Vector()); insurar.addInsuranceCategory("1.-1","A","Default",MedwanQuery.getInstance().getConfigString("defaultInsuranceCategoryPatientShare"+insurarCatTariff.toUpperCase(),patientShare)); } else if(insurarCatTariff.equalsIgnoreCase("2")){ insurarCatTariff="B"; insurar.setInsuraceCategories(new Vector()); insurar.addInsuranceCategory("1.-1","B","Default",MedwanQuery.getInstance().getConfigString("defaultInsuranceCategoryPatientShare"+insurarCatTariff.toUpperCase(),patientShare)); } else { insurarCatTariff="C"; insurar.setInsuraceCategories(new Vector()); insurar.addInsuranceCategory("1.-1","C","Default",MedwanQuery.getInstance().getConfigString("defaultInsuranceCategoryPatientShare"+insurarCatTariff.toUpperCase(),patientShare)); } insurar.setType(insurarCatTariff); insurar.setUpdateDateTime(rs.getTimestamp("cbModification")); if(insurar.getUpdateDateTime().after(maxDate)){ maxDate=insurar.getUpdateDateTime(); } insurar.setUpdateUser("4"); insurar.store(); } } if(!bexists) { System.out.println("Creating"); //De verzekeraar bestaat nog niet, we gaan hem toevoegen Insurar insurar = new Insurar(); insurar.setUid("1.-1"); insurar.setName(insuranceName+" #"+insuranceCode); insurar.setCreateDateTime(new Date()); insurar.setOfficialName(insuranceName); insurar.setContact(insurarContact.trim()); insurar.setContactPerson((ScreenHelper.checkString(rs.getString("CT_Contact"))+" "+ScreenHelper.checkString(rs.getString("CT_Email"))).trim()); insurar.setLanguage("FR"); int reimbursement=rs.getInt("CT_Taux01"); if(reimbursement==0){ //Let's checkout if there is no default reimbursement to be found in the SageFamilyReimbursements String sQuery2="select count(*),FC_Remise from SageFamilyReimbursements where CT_Num=? group by FC_Remise order by count(*) desc"; PreparedStatement ps2=oc_conn.prepareStatement(sQuery2); try{ ps2.setString(1,insuranceCode); ResultSet rs2=ps2.executeQuery(); if(rs2.next()){ reimbursement=rs2.getInt("FC_Remise"); } rs2.close(); ps2.close(); } catch (Exception e){ e.printStackTrace(); } } String patientShare=reimbursement+""; if (insurarCatTariff.equalsIgnoreCase("1")){ insurarCatTariff="A"; insurar.setInsuraceCategories(new Vector()); insurar.addInsuranceCategory("1.-1","A","Default",MedwanQuery.getInstance().getConfigString("defaultInsuranceCategoryPatientShare"+insurarCatTariff.toUpperCase(),patientShare)); } else if(insurarCatTariff.equalsIgnoreCase("2")){ insurarCatTariff="B"; insurar.setInsuraceCategories(new Vector()); insurar.addInsuranceCategory("1.-1","B","Default",MedwanQuery.getInstance().getConfigString("defaultInsuranceCategoryPatientShare"+insurarCatTariff.toUpperCase(),patientShare)); } else { insurarCatTariff="C"; insurar.setInsuraceCategories(new Vector()); insurar.addInsuranceCategory("1.-1","C","Default",MedwanQuery.getInstance().getConfigString("defaultInsuranceCategoryPatientShare"+insurarCatTariff.toUpperCase(),patientShare)); } insurar.setType(insurarCatTariff); insurar.setUpdateDateTime(rs.getDate("cbModification")); insurar.setUpdateUser("4"); insurar.store(); } } rs.close(); ps.close(); oc_conn.close(); loc_conn.close(); MedwanQuery.getInstance().setConfigString("lastSageInsurarSync",new SimpleDateFormat("yyyyMMddHHmmss").format(maxDate)); } catch (Exception e) { e.printStackTrace(); } } public static void synchronizeReimbursements(){ try { System.out.println("Synchronizing reimbursements"); Date lastSync= new SimpleDateFormat("yyyyMMddHHmmss").parse("19000101000000"); try{ lastSync = new SimpleDateFormat("yyyyMMddHHmmss").parse(MedwanQuery.getInstance().getConfigString("lastSageReimbursementSync","19000101000000")); } catch(Exception e4){ } Date maxDate = lastSync; Connection loc_conn=MedwanQuery.getInstance().getLongOpenclinicConnection(); PreparedStatement ps = loc_conn.prepareStatement("select * from SageReimbursements where cbModification>? order by ar_ref"); ps.setTimestamp(1,new Timestamp(lastSync.getTime())); ResultSet rs = ps.executeQuery(); while(rs.next()){ String prestationCode=ScreenHelper.checkString(rs.getString("AR_Ref")).replaceAll("'",""); System.out.println("Checking prestation code "+prestationCode); int patientshare=rs.getInt("AC_Remise"); String insurarCode=ScreenHelper.checkString(rs.getString("CT_Num")); Vector insurars = Insurar.getInsurarsByName("%#"+insurarCode); Prestation prestation=Prestation.getByCode(prestationCode); if(insurars.size()>0 && prestation!=null){ System.out.println("Updating"); Date d = rs.getTimestamp("cbModification"); if(d.after(maxDate)){ maxDate=d; } Insurar insurar = (Insurar)insurars.elementAt(0); PreparedStatement ps2 =loc_conn.prepareStatement("delete from OC_PRESTATION_REIMBURSEMENTS where OC_PR_PRESTATIONUID=? and OC_PR_INSURARUID=?"); ps2.setString(1,prestation.getUid()); ps2.setString(2,insurar.getUid()); ps2.executeUpdate(); ps2.close(); ps2=loc_conn.prepareStatement("insert into OC_PRESTATION_REIMBURSEMENTS(" + "OC_PR_PRESTATIONUID," + "OC_PR_PRESTATIONCODE," + "OC_PR_INSURARUID," + "OC_PR_INSURARCODE," + "OC_PR_PATIENTSHARE) values (?,?,?,?,?)"); ps2.setString(1,prestation.getUid()); ps2.setString(2,prestation.getCode()); ps2.setString(3,insurar.getUid()); ps2.setString(4,insurarCode); ps2.setInt(5,patientshare); ps2.executeUpdate(); ps2.close(); } } rs.close(); ps.close(); ps=loc_conn.prepareStatement("delete from OC_PRESTATION_REIMBURSEMENTS where not exists (" + "select * from SageReimbursements where AR_Ref COLLATE DATABASE_DEFAULT=OC_PR_PRESTATIONCODE COLLATE DATABASE_DEFAULT and " + "CT_Num COLLATE DATABASE_DEFAULT=OC_PR_INSURARCODE COLLATE DATABASE_DEFAULT)"); ps.executeUpdate(); ps.close(); MedwanQuery.getInstance().setConfigString("lastSageReimbursementSync",new SimpleDateFormat("yyyyMMddHHmmss").format(maxDate)); loc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } public static void synchronizeFamilyReimbursements(){ try { System.out.println("Synchronizing familyreimbursements"); Date lastSync= new SimpleDateFormat("yyyyMMddHHmmss").parse("19000101000000"); try{ lastSync = new SimpleDateFormat("yyyyMMddHHmmss").parse(MedwanQuery.getInstance().getConfigString("lastSageFamilyReimbursementSync","19000101000000")); } catch(Exception e4){ } Date maxDate = lastSync; Connection loc_conn=MedwanQuery.getInstance().getLongOpenclinicConnection(); PreparedStatement ps = loc_conn.prepareStatement("select * from SageFamilyReimbursements where cbModification>? order by FA_CodeFamille"); ps.setTimestamp(1,new Timestamp(lastSync.getTime())); ResultSet rs = ps.executeQuery(); System.out.println("Launching query"); while(rs.next()){ String familyCode=ScreenHelper.checkString(rs.getString("FA_CodeFamille")).replaceAll("'",""); System.out.println("Checking family code "+familyCode); int patientshare=rs.getInt("FC_Remise"); String insurarCode=ScreenHelper.checkString(rs.getString("CT_Num")); Vector insurars = Insurar.getInsurarsByName("%#"+insurarCode); if(insurars.size()>0){ System.out.println("Updating"); Date d = rs.getTimestamp("cbModification"); if(d.after(maxDate)){ maxDate=d; } Insurar insurar = (Insurar)insurars.elementAt(0); PreparedStatement ps2 =loc_conn.prepareStatement("delete from OC_PRESTATIONFAMILY_REIMBURSEMENTS where OC_PR_PRESTATIONTYPE=? and OC_PR_INSURARUID=?"); ps2.setString(1,familyCode); ps2.setString(2,insurar.getUid()); ps2.executeUpdate(); ps2.close(); ps2=loc_conn.prepareStatement("insert into OC_PRESTATIONFAMILY_REIMBURSEMENTS(" + "OC_PR_PRESTATIONTYPE," + "OC_PR_INSURARUID," + "OC_PR_INSURARCODE," + "OC_PR_PATIENTSHARE) values (?,?,?,?)"); ps2.setString(1,familyCode); ps2.setString(2,insurar.getUid()); ps2.setString(3,insurarCode); ps2.setInt(4,patientshare); ps2.executeUpdate(); ps2.close(); } } rs.close(); ps.close(); System.out.println("Deleting removed reimbursements"); ps=loc_conn.prepareStatement("delete from OC_PRESTATIONFAMILY_REIMBURSEMENTS where not exists (" + "select * from SageFamilyReimbursements where FA_CodeFamille COLLATE DATABASE_DEFAULT=OC_PR_PRESTATIONTYPE COLLATE DATABASE_DEFAULT and " + "CT_Num COLLATE DATABASE_DEFAULT=OC_PR_INSURARCODE COLLATE DATABASE_DEFAULT)"); ps.executeUpdate(); ps.close(); MedwanQuery.getInstance().setConfigString("lastSageFamilyReimbursementSync",new SimpleDateFormat("yyyyMMddHHmmss").format(maxDate)); loc_conn.close(); } catch(Exception e){ e.printStackTrace(); } System.out.println("End of synchronizing familyreimbursements"); } public static void synchronizePrestations(){ try{ System.out.println("Synchronising prestations"); Date lastSync= new SimpleDateFormat("yyyyMMddHHmmss").parse("19000101000000"); try{ lastSync = new SimpleDateFormat("yyyyMMddHHmmss").parse(MedwanQuery.getInstance().getConfigString("lastSagePrestationSync","19000101000000")); } catch(Exception e4){ } Date maxDate=lastSync; Connection loc_conn=MedwanQuery.getInstance().getLongOpenclinicConnection(); PreparedStatement ps = loc_conn.prepareStatement("select * from SagePrestations where cbModification>? order by ar_ref"); ps.setTimestamp(1,new Timestamp(lastSync.getTime())); ResultSet rs = ps.executeQuery(); while(rs.next()){ String prestationCode=ScreenHelper.checkString(rs.getString("AR_Ref")).replaceAll("'",""); System.out.println("Checking prestationcode "+prestationCode); double prestationPrice=0; try{ prestationPrice=new Double(ScreenHelper.checkString(rs.getString("AR_PrixVen"))).intValue(); } catch(Exception e2){ } String prestationTypeName=ScreenHelper.checkString(rs.getString("FA_Intitule")).replaceAll("'",""); String prestationCatTariff=ScreenHelper.checkString(rs.getString("AC_Categorie")); if (prestationCatTariff.equalsIgnoreCase("1")){ prestationCatTariff="A"; } else if(prestationCatTariff.equalsIgnoreCase("2")){ prestationCatTariff="B"; } else if(prestationCatTariff.equalsIgnoreCase("3")){ prestationCatTariff="C"; } else { prestationCatTariff="D"; } String prestationCategoryPrice=ScreenHelper.checkString(rs.getString("AC_PrixVen")); try{ prestationCategoryPrice=new Double(prestationCategoryPrice).intValue()+""; } catch(Exception e3){ } Prestation prestation=Prestation.getByCode(prestationCode); if(prestation.getCode()!=null && prestation.getCode().equalsIgnoreCase(prestationCode)){ System.out.println("Updating"); //De prestatie bestaat reeds, we gaan ze updaten prestation.setDescription(ScreenHelper.checkString(rs.getString("AR_Design")).replaceAll("'","")); prestation.setPrice(prestationPrice); /* prestation.setType(ScreenHelper.checkString(rs.getString("FA_CodeFamille"))); ObjectReference objectReference = new ObjectReference(ScreenHelper.checkString(rs.getString("FA_RacineRef")),"0"); prestation.setReferenceObject(objectReference); if(MedwanQuery.getInstance().getLabel("prestation.type",prestation.getType(),"fr").equalsIgnoreCase(prestation.getType())){ MedwanQuery.getInstance().storeLabel("prestation.type",prestation.getType(),"fr",prestationTypeName,4); MedwanQuery.getInstance().storeLabel("prestation.type",prestation.getType(),"en",prestationTypeName,4); MedwanQuery.getInstance().storeLabel("prestation.type",prestation.getType(),"nl",prestationTypeName,4); } */ prestation.setUpdateDateTime(rs.getTimestamp("cbModification")); if(prestation.getUpdateDateTime().after(maxDate)){ maxDate=prestation.getUpdateDateTime(); } prestation.setUpdateUser("4"); prestation.setCategoryPrice(prestationCatTariff,prestationCategoryPrice); prestation.store(); } else { System.out.println("Creating"); //De prestatie bestaat nog niet, toevoegen prestation=new Prestation(); prestation.setCode(prestationCode); prestation.setDescription(ScreenHelper.checkString(rs.getString("AR_Design")).replaceAll("'","")); prestation.setPrice(prestationPrice); ObjectReference objectReference = new ObjectReference(ScreenHelper.checkString(rs.getString("FA_RacineRef")),"0"); prestation.setReferenceObject(objectReference); prestation.setType(ScreenHelper.checkString(rs.getString("FA_CodeFamille"))); if(MedwanQuery.getInstance().getLabel("prestation.type",prestation.getType(),"fr").equalsIgnoreCase(prestation.getType())){ MedwanQuery.getInstance().storeLabel("prestation.type",prestation.getType(),"fr",prestationTypeName,4); MedwanQuery.getInstance().storeLabel("prestation.type",prestation.getType(),"en",prestationTypeName,4); MedwanQuery.getInstance().storeLabel("prestation.type",prestation.getType(),"nl",prestationTypeName,4); } prestation.setUpdateDateTime(rs.getTimestamp("cbModification")); if(prestation.getUpdateDateTime().after(maxDate)){ maxDate=prestation.getUpdateDateTime(); } prestation.setUpdateUser("4"); prestation.setCategories(prestationCatTariff+"="+prestationCategoryPrice+";"); prestation.setReferenceObject(new ObjectReference()); prestation.store(); } } rs.close(); ps.close(); loc_conn.close(); MedwanQuery.getInstance().setConfigString("lastSagePrestationSync",new SimpleDateFormat("yyyyMMddHHmmss").format(maxDate)); } catch(Exception e){ e.printStackTrace(); } } }
package com.example.hemil.papa_johns.AbstractFactory; /** * Created by hemil on 12/5/2015. */ public class Stix implements Desserts { @Override public String getName() { return "Cinna Stix"; } @Override public double getCost(int quantity) { return quantity*4.49; } }
public class Hollow_Mirrored_Right_Triangle { public static void main(String[] args) { int row,column,space; for (row=5;row>=1;row--) { for(space=1;space<=row;space++) { System.out.print(" "); } for(column=5;column>=row;column--) { if((row==3&&column==4||row==2&&column==3||row==2&&column==4)) { System.out.print(" "); } else {System.out.print("*"); }} System.out.println(); } } }
package br.com.argentum.model; import java.time.LocalDateTime; public final class Negociacao { private double preco; private int quantidade; private LocalDateTime data; public Negociacao(double preco, int quantidade, LocalDateTime data) { this.preco = preco; this.quantidade = quantidade; this.data = data; } public double getPreco() { return preco; } public int getQuantidade() { return quantidade; } public LocalDateTime getData() { return data; } public double getVolume(){ return this.getPreco() * this.getQuantidade(); } }
/* * login.java * * Created on __DATE__, __TIME__ */ package view; import java.sql.Connection; import java.util.ArrayList; import javax.swing.JOptionPane; import model.View_Teacher; import util.TeacherAccess; import util.jdutil; import util.login_access; /** *view类 * @author __USER__ */ public class login extends javax.swing.JFrame { /** Creates new form login */ public login() { initComponents(); setResizable(false); setLocationRelativeTo(null); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ //GEN-BEGIN:initComponents // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { label1 = new java.awt.Label(); label2 = new java.awt.Label(); textField1 = new java.awt.TextField(); button1 = new java.awt.Button(); button2 = new java.awt.Button(); jPasswordField1 = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); label1.setText("\u7528\u6237"); label2.setName("\u5bc6\u7801"); label2.setText("\u5bc6\u7801"); button1.setLabel("\u767b\u9646"); button1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button1ActionPerformed(evt); } }); button2.setLabel("\u9000\u51fa"); button2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button2ActionPerformed(evt); } }); jPasswordField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jPasswordField1KeyPressed(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() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGap(82, 82, 82) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent( textField1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( jPasswordField1, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))) .addGroup( layout.createSequentialGroup() .addGap(100, 100, 100) .addComponent( button1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(76, 76, 76) .addComponent( button2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(127, Short.MAX_VALUE))); layout.setVerticalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGap(99, 99, 99) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(33, 33, 33) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.TRAILING) .addComponent( label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(31, 31, 31) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( button1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( button2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(67, Short.MAX_VALUE))); pack(); }// </editor-fold> //GEN-END:initComponents private void jPasswordField1KeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: if (evt.getKeyChar()==evt.VK_ENTER) { String tname = textField1.getText();//取账号框内容 String tpasswd = String.valueOf(jPasswordField1.getPassword());//取密码框内容 try { Connection con = jdutil.getCon();//获得连接数据库 if (con == null) {//如果数据库连接失败则退出 return; } int re = login_access.T_login(con, tname, tpasswd); if (re == 1) { ArrayList<View_Teacher> teachers = TeacherAccess .getView_teacher(tname);//调用方法在view_teacher表查询该用户全部内容 View_Teacher teacher = teachers.get(0);//将该用户内容存储到teacher里 new main(teacher).setVisible(true);//将teacher传到main窗体里并使其显示 this.dispose();//关闭当前窗口 } else if (re == 2) { JOptionPane.showMessageDialog(this, "密码错误"); jPasswordField1.requestFocus(); jPasswordField1.selectAll(); } else if (re == -1) { JOptionPane.showMessageDialog(this, "账号错误"); textField1.requestFocus(); textField1.selectAll(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }} } private void button2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: this.dispose(); } private void button1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String tname = textField1.getText();//取账号框内容 String tpasswd = String.valueOf(jPasswordField1.getPassword());//取密码框内容 try { Connection con = jdutil.getCon();//获得连接数据库 if (con == null) {//如果数据库连接失败则退出 return; } int re = login_access.T_login(con, tname, tpasswd); if (re == 1) { ArrayList<View_Teacher> teachers = TeacherAccess .getView_teacher(tname);//调用方法在view_teacher表查询该用户全部内容 View_Teacher teacher = teachers.get(0);//将该用户内容存储到teacher里 new main(teacher).setVisible(true);//将teacher传到main窗体里并使其显示 this.dispose();//关闭当前窗口 } else if (re == 2) { JOptionPane.showMessageDialog(this, "密码错误"); jPasswordField1.requestFocus(); jPasswordField1.selectAll(); } else if (re == -1) { JOptionPane.showMessageDialog(this, "账号错误"); textField1.requestFocus(); textField1.selectAll(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new login().setVisible(true); } }); } //GEN-BEGIN:variables // Variables declaration - do not modify private java.awt.Button button1; private java.awt.Button button2; private javax.swing.JPasswordField jPasswordField1; private java.awt.Label label1; private java.awt.Label label2; private java.awt.TextField textField1; // End of variables declaration//GEN-END:variables }
package com.robin.springbootlearn.common.enums; /** * @author silkNets * @description 响应码枚举,参考HTTP状态码的语义 * @createDate 2020-03-03 08:14 */ public enum ResponseCodeEnum { // === 通用 http 返回码 === // 2xx (成功)表示成功处理了请求的状态代码 code_200(200, "OK", "请求成功"), code_201(201, "Created", "已创建, 请求成功且服务器创建了新的资源"), code_202(202, "Accepted", "已接受, 服务器已接受请求,但尚未处理"), code_203(203, "Non-Authoritative Information", "非授权信息, 服务器已成功处理了请求,但返回的信息可能来自另一来源"), code_204(204, "No Content", "无内容, 服务器成功处理了请求,但不需要返回任何实体内容"), code_205(205, "Reset Content", "重置内容, 服务器成功处理了请求,但没有返回任何内容"), code_206(206, "Partial Content", "部分内容, 服务器成功处理了部分 GET 请求"), // 3xx (重定向)表示要完成请求,需要进一步操作。 通常,这些状态代码用来重定向 code_300(300, "Multiple Choices", "多种选择, 针对请求,服务器可执行多种操作"), code_301(301, "Moved Permanently", "永久移动, 请求的网页已永久移动到新位置"), code_302(302, "Move Temporarily", "临时移动, 服务器目前从不同位置的网页响应请求,但请求者应继续使用原有位置来进行以后的请求"), code_303(303, "See Other", "查看其他位置, 请求者应当对不同的位置使用单独的 GET 请求来检索响应时,服务器返回此代码"), code_304(304, "Not Modified", "未修改, 自从上次请求后,请求的网页未修改过。 服务器返回此响应时,不会返回网页内容"), code_305(305, "Use Proxy", "使用代理, 请求者只能使用代理访问请求的网页。 如果服务器返回此响应,还表示请求者应使用代理"), code_307(307, "Temporary Redirect", "临时重定向, 服务器目前从不同位置的网页响应请求,但请求者应继续使用原有位置来进行以后的请求"), // 4xx(请求错误)表示请求可能出错,妨碍了服务器的处理 code_400(400, "Bad Request", "错误请求, 服务器不理解请求的语法"), code_401(401, "Unauthorized", "未授权, 请求要求身份验证"), code_403(403, "Forbidden", "禁止, 服务器拒绝请求"), code_404(404, "Not Found", "未找到, 服务器找不到请求的网页"), code_405(405, "Method Not Allowed", "方法禁用, 禁用请求中指定的方法"), code_406(406, "Not Acceptable", "不接受, 无法使用请求的内容特性响应请求的网页"), code_407(407, "Proxy Authentication Required", "需要代理授权, 指定请求者应当授权使用代理"), code_408(408, "Request Timeout", "请求超时, 服务器等候请求时发生超时"), code_409(409, "Conflict", "冲突, 服务器在完成请求时发生冲突。 服务器必须在响应中包含有关冲突的信息"), code_410(410, "Gone", "已删除, 如果请求的资源已永久删除,服务器就会返回此响应"), code_411(411, "Length Required", "需要有效长度, 服务器不接受不含有效内容长度标头字段的请求"), code_412(412, "Precondition Failed", "未满足前提条件, 服务器未满足请求者在请求中设置的其中一个前提条件"), code_413(413, "Request Entity Too Large", "请求实体过大, 服务器无法处理请求,因为请求实体过大,超出服务器的处理能力"), code_414(414, "Request-URI Too Long", "请求的 URI 过长, 请求的 URI(通常为网址)过长,服务器无法处理"), code_415(415, "Unsupported Media Type", "不支持的媒体类型, 请求的格式不受请求页面的支持"), code_416(416, "Requested Range Not Satisfiable", "请求范围不符合要求, 如果页面无法提供请求的范围,则服务器会返回此状态代码"), code_417(417, "Expectation Failed", "未满足期望值, 服务器未满足“期望”请求标头字段的要求"), code_421(421, "Too Many Connections", "连接数过多, 从当前客户端所在的IP地址到服务器的连接数超过了服务器许可的最大范围"), code_422(422, "Unprocessable Entity", "错误请求实体, 请求格式正确,但是由于含有语义错误,无法响应"), code_423(423, "Locked", "锁定, 当前资源被锁定"), code_424(424, "Failed Dependency", "依赖错误, 由于之前的某个请求发生的错误,导致当前请求失败"), code_425(425, "Too Early", "超前的请求, 处理该请求可能会被“重放”,从而造成潜在的重放攻击"), code_426(426, "Upgrade Required", "需要更新, 客户端应当切换到TLS/1.0"), code_449(449, "Retry With", "重试, 由微软扩展代表请求应当在执行完适当的操作后进行重试"), code_451(451, "Unavailable For Legal Reasons", "法律不可用, 该请求因法律原因不可用"), // 5xx(服务器错误)表示服务器在尝试处理请求时发生内部错误。 这些错误可能是服务器本身的错误,而不是请求出错 code_500(500, "Internal Server Error", "服务器内部错误, 服务器遇到错误,无法完成请求"), code_501(501, "Not Implemented", "尚未实施, 服务器不具备完成请求的功能"), code_502(502, "Bad Gateway", "错误网关, 服务器作为网关或代理,从上游服务器收到无效响应"), code_503(503, "Service Unavailable", "服务不可用, 服务器目前无法使用(由于超载或停机维护)"), code_504(504, "Gateway Timeout", "网关超时, 服务器作为网关或代理,但是没有及时从上游服务器收到请求"), code_505(505, "HTTP Version Not Supported", "HTTP 版本不受支持, 服务器不支持请求中所用的 HTTP 协议版本"), code_506(506, "Variant Also Negotiates", "内部配置错误, 被请求的协商变元资源被配置为在透明内容协商中使用自己"), code_507(507, "Insufficient Storage", "存储不足, 服务器无法存储完成请求所必须的内容"), code_509(509, "Bandwidth Limit Exceeded", "宽带超限, 服务器达到带宽限制"), code_510(510, "Not Extended", "不可扩展, 获取资源所需要的策略并没有被满足"), code_600(600, "Unparseable Response Headers", "响应头无法解析, 源站没有返回响应头部,只返回实体内容"), // === 业务自定义 http 返回码 === code_402(402, "Token Expired", "token 已过期, token 存在但已过期"), // 10xx(业务校验)业务中需要校验的地方,如请求参数 code_1001(1001, "Param Error", "参数错误"), code_1002(1002, "Phone Number Error", "手机号错误"), // 11xx(活动校验)活动相关的校验失败,如活动下线、关闭等 code_1101(1101, "Activity Offline", "活动已下线"), code_1102(1102, "Activity Online", "活动已在线"), code_1103(1103, "Activity Not Found", "活动不存在"), code_1104(1104, "Activity Existed", "活动已存在"), code_1105(1105, "Activity Closed", "活动已结束"), code_1106(1106, "Activity Suspended", "活动已暂停"), code_1107(1107, "Activity Violated", "活动已违规"), code_1108(1108, "Activity Forbidden", "拒绝创建活动"), code_1109(1109, "Activity Under Review", "拒绝创建活动"), code_1110(1110, "Activity Not Self", "活动不是自己发起的"), code_1111(1111, "Activity Had Joined", "活动已经发起过参与过"), code_1112(1112, "Activity Times Upper Limit", "活动创建的上限"), code_1121(1121, "Vote Existed", "已帮TA助力过"), code_1122(1122, "Vote Not Self", "自己不能给自己投票"), code_1123(1123, "Vote Times Upper Limit", "砍价次数限制"), code_1131(1131, "Source Not Enough", "资源不足"); // 20xx(业务风控)如黑名单,活动被限制参与、现金券限制使用等 // 30xx(对外交互场景)如 api 请求频次限制等 public int code; public String enCode; public String remark; ResponseCodeEnum(int code, String enCode, String remark) { this.code = code; this.enCode = enCode; this.remark = remark; } public static ResponseCodeEnum getByCode(int code) { ResponseCodeEnum[] enumTypes = values(); for (ResponseCodeEnum enumType : enumTypes) { if (enumType.getCode() == code) { return enumType; } } return null; } public int getCode() { return code; } public String getRemark() { return remark; } public String getEnCode() { return enCode; } }
package entity; import java.util.ArrayList; import java.util.List; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.World; import box2dLight.RayHandler; import component.CJBox2D; import message.Message; public class EntityContainer { // 30 pixels = 1 metre private static List<Entity> entities = new ArrayList<Entity>(); private static List<Entity> entitiesToAdd = new ArrayList<Entity>(); private static List<Entity> entitiesToDestroy = new ArrayList<Entity>(); private static List<Entity> entitiesRender = new ArrayList<Entity>(); private static List<Entity> entitiesCollide = new ArrayList<Entity>(); private static List<Body> bodiesCollide = new ArrayList<Body>(); private static Player player; private static World world = new World(new Vec2(0f, 0f), false); // Initial view public static float ViewX = 0; public static float ViewY = 0; // Map size public static float BoundX = 1600; public static float BoundY = 1200; // Unit conversion public static float SlickToJBox2D = 1f/30f; public static float JBox2DToSlick = 30f; // Box2DLight // public static RayHandler rayhandler = new RayHandler(world) public static void addEntity(Entity e){ entitiesToAdd.add(e); if (e.getComponent("Colidable") != null) entitiesCollide.add(e); if (e.getComponent("JBox2D") != null) { bodiesCollide.add(((CJBox2D) e.getComponent("JBox2D")).getBody()); ((CJBox2D) e.getComponent("JBox2D")).setDimensions(); ((CJBox2D) e.getComponent("JBox2D")).setPosition(); } } public static void moveEntitiesToAdd(){ for (Entity e : entitiesToAdd){ entities.add(e); } // sort the render list every time new entity is added if (!entitiesToAdd.isEmpty()) entitiesRender = sortRender(); entitiesToAdd.clear(); } public static void destroyEntity(Entity e){ entitiesToDestroy.add(e); if (e.getComponent("Colidable") != null) entitiesCollide.remove(e); if (e.getComponent("JBox2D") != null) { bodiesCollide.remove(((CJBox2D) e.getComponent("JBox2D")).getBody()); world.destroyBody(((CJBox2D) e.getComponent("JBox2D")).getBody()); } } public static void removeEntities(){ for (Entity e : entitiesToDestroy){ entities.remove(e); } if (!entitiesToDestroy.isEmpty()) entitiesRender = sortRender(); entitiesToDestroy.clear(); } // sort the render list according to layers public static List<Entity> sortRender(){ List<Entity> list_old = new ArrayList<Entity>(); for (Entity e : getEntities()) list_old.add(e) ; List<Entity> to_remove = new ArrayList<Entity>(); List<Entity> list_new = new ArrayList<Entity>(); int i = 0; while (!list_old.isEmpty()){ for (Entity e : list_old){ if (e.getLayer() == i) { list_new.add(e); to_remove.add(e); } } for (Entity e : to_remove){ list_old.remove(e); } to_remove.clear(); i++; } return list_new; } public static List<Entity> getEntities(){ return entities; } public static void sendMessage(Message message){ for (Entity e : getEntities()){ e.sendMessage(message); } } public static Player getPlayer() { return player; } public static List<Entity> getEntitiesRender() { return entitiesRender; } public static float getBoundX() { return BoundX; } public static void setBoundX(float boundX) { BoundX = boundX; } public static float getBoundY() { return BoundY; } public static void setBoundY(float boundY) { BoundY = boundY; } public static List<Entity> getEntitiesCollide() { return entitiesCollide; } public static World getWorld() { return world; } public static List<Body> getBodiesCollide() { return bodiesCollide; } public static void setPlayer(Player player) { EntityContainer.player = player; } }
package com.lukas.lists; public class Main { public static void main(String[] args) { MyList list = new MyList(); // ręczne dodawanie elementólisty // // pierwszy element // Element e1 = new Element(); // e1.data = "element pierwszy"; // list.head = e1; // list.tail = e1; // list.count = 1; // // // drugi element // Element e2 = new Element(); // e2.data = "element drugi"; // e2.prev = list.tail; // list.tail.next = e2; // list.tail = e2; // list.count++; // // // trzeci element // Element e3 = new Element(); // e3.data = "element trzeci"; // e3.prev = list.tail; // list.tail.next = e3; // list.tail = e3; // list.count++; list.append("element drugi"); list.append("element trzeci"); list.append("element czwarty"); list.insert("element pierwszy"); list.insertBefore(list.head.next, "intruz"); // list.printElements(); // System.out.println(); // list.printElementsRev(); // System.out.println(); System.out.println(list); list.delete(list.head.next); System.out.println(list); } }
package com.datagraph.common.exception; /** * Created by Denny Joseph on 6/1/16. */ public class TaskException extends Exception { public TaskException(String msg) { super(msg); } }
package com.legaoyi.protocol.util; /** * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2015-01-30 */ public class MessageBuilder { private int capacity = 20; private int length = 0; private byte[] array = new byte[this.capacity]; private int index = 0; public MessageBuilder() { } public MessageBuilder(int capacity) { setCapacity(capacity); } public void setCapacity(int capacity) { if (capacity > 0) { this.capacity = capacity; } } public MessageBuilder append(byte b) { if (this.index >= this.array.length) { byte[] newArray = new byte[this.array.length + this.capacity]; System.arraycopy(this.array, 0, newArray, 0, this.array.length); this.array = newArray; } this.array[this.index] = b; this.index += 1; return this; } public MessageBuilder append(byte[] array) { for (byte b : array) { append(b); } return this; } public MessageBuilder append(String string) { return append(string.getBytes()); } public void addByte(int i) { append(ByteUtils.int2byte(i)); } public void addDword(int i) { append(ByteUtils.int2dword(i)); } public void addWord(int i) { append(ByteUtils.int2word(i)); } public void append(int paramId, String string) { append(paramId, string, true); } public void append(int paramId, String string, boolean fillLength) { this.length += 1; addWord(paramId); if (string == null || "".equals(string)) { if (fillLength) { addByte(0); } return; } addByte(string.getBytes().length); append(string); } public void insertFirst(byte b) { byte[] arr = getBytes(); byte[] newArray = new byte[arr.length + this.capacity]; System.arraycopy(arr, 0, newArray, 1, arr.length); newArray[0] = b; this.array = newArray; this.index += 1; } public byte[] getBytes() { byte[] newArray = new byte[this.index]; System.arraycopy(this.array, 0, newArray, 0, this.index); return newArray; } public byte[] getNewBytes(byte[] by) { byte[] oldArray = getBytes(); byte[] newArray = new byte[oldArray.length - by.length]; System.arraycopy(oldArray, 0, newArray, 0, newArray.length); return newArray; } public int getLength() { return this.length; } }
public class GogoXBallsAndBinsEasy { public int solve (int[] t) { int count = 0; for(int i = 0; i < t.length / 2; i++) { count += t[t.length - 1 - i] - t[i]; } return count; } }
package main.java.pane.base; public class BaseTabPane extends StyledPane { private StyledPane[] tabArray; private String[] name; public BaseTabPane(String name[], StyledPane[] tabArray) { super(); this.name = name; this.tabArray = tabArray; } @Override public void InitPane() { CreateTabPane(); } /** * Create the tabpane */ protected void CreateTabPane() { StyledTabPane tabPane = new StyledTabPane(); for (int i = 0; i < tabArray.length; i++) { StyledTab tab = new StyledTab(name[i]); tab.setContent(tabArray[i]); tabPane.getTabs().add(tab); } getChildren().add(tabPane); } }
package com.ss.test.dao; import com.ss.test.model.TransactionData; public class TransactionDataDAO extends DAO<TransactionData> { protected TransactionDataDAO() { super(TransactionData.class); } private static TransactionDataDAO instance; public static TransactionDataDAO get() { if (instance == null) { instance = new TransactionDataDAO(); } return instance; } }
package arraysnstrings; public class EncodeArrayInts { private static boolean isValidCode(int i, int j) { return !(i * 10 + j > 26); } public static int combinations(int[] message) { return calculateCombinations(message, message.length - 1); } private static int calculateCombinations(int[] message, int i) { if (i < 0) { return 0; } if (i < 2) { return i + 1; } int combinations = calculateCombinations(message, i - 1); if (isValidCode(message[i - 1], message[i])) combinations += calculateCombinations(message, i - 2); return combinations; } }
package DemoRest.WebApp.resource; import DemoRest.WebApp.model.Bill; import DemoRest.WebApp.model.File; import DemoRest.WebApp.model.Users; import DemoRest.WebApp.repository.BillRepo; import DemoRest.WebApp.repository.FileRepository; import DemoRest.WebApp.repository.UserRepository; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.system.ApplicationHome; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.xml.bind.DatatypeConverter; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.util.*; @RestController @RequestMapping("/v1/bill") public class FileResource { private static final String UPLOAD_FOLDER = System.getProperty("user.dir")+"/src/main/resources/static/images/"; @Autowired BillRepo billRepo; @Autowired UserRepository userRepository; @Autowired FileRepository fileRepository; @RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, value = "/{id}/file") public ResponseEntity addAttachment(HttpServletRequest request, @PathVariable String id, @RequestParam("attachment") MultipartFile attachment) throws ParseException, IOException { try { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Bill billById = billRepo.findBillById(id); Users users = userRepository.findByEmailAddress(authentication.getName()); if (billById == null) { return new ResponseEntity(HttpStatus.NOT_FOUND); } else if (!users.getId().equals(billById.getOwnerId())) { return new ResponseEntity(HttpStatus.UNAUTHORIZED); } if(!attachment.getContentType().equals("image/jpg") && !attachment.getContentType().equals("image/jpeg") && !attachment.getContentType().equals("application/pdf") && !attachment.getContentType().equals("image/png")){ return new ResponseEntity(HttpStatus.BAD_REQUEST); } File fileExists = fileRepository.findFileByBill(billById.getId()); if(fileExists != null){ // fileRepository.delete(fileExists); // String filePath = UPLOAD_FOLDER + fileExists.getFile_name_dir(); // Path fileToDelete = Paths.get(filePath); // Files.delete(fileToDelete); return new ResponseEntity("File already exists", HttpStatus.BAD_REQUEST); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(attachment.getBytes()); byte[] digest = md.digest(); String myHash = DatatypeConverter .printHexBinary(digest).toUpperCase(); File file = new File(); file.setFile_name(attachment.getOriginalFilename()); file.setUpload_date(new Date()); file.setBill(id); file.setFile_owner(users.getId()); file.setMimetype(attachment.getContentType()); file.setSize(String.valueOf(attachment.getSize())); file.setHash(myHash); file.setCreated_date(new Date()); if (!attachment.isEmpty()) { byte[] bytes = attachment.getBytes(); double x = Math.random(); Path path = Paths.get(UPLOAD_FOLDER + x + attachment.getOriginalFilename()); Files.write(path, bytes); file.setFile_name_dir(x + attachment.getOriginalFilename()); file.setUrl(UPLOAD_FOLDER + x + attachment.getOriginalFilename()); } fileRepository.save(file); fileRepository.flush(); ObjectMapper mapperObj = new ObjectMapper(); Map<String, Object> displayFile = new HashMap<>(); displayFile.put("file_name", file.getFile_name()); displayFile.put("id", file.getId()); displayFile.put("url", file.getUrl()); displayFile.put("upload_date", file.getUpload_date()); mapperObj.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS , false); String jsonResp = mapperObj.writeValueAsString(displayFile); billById.setAttachment(jsonResp); billRepo.save(billById); return new ResponseEntity(displayFile, HttpStatus.CREATED); } catch(Exception e){ System.out.println(e); return new ResponseEntity(HttpStatus.BAD_REQUEST); } } @GetMapping(value = "/{billId}/file/{fileId}") public ResponseEntity getCorrespondingBill(@PathVariable String billId , @PathVariable String fileId) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Users users = userRepository.findByEmailAddress(authentication.getName()); Bill billById = billRepo.findBillById(billId); File file = fileRepository.findFileById(fileId); if(billById == null){ return new ResponseEntity( HttpStatus.NOT_FOUND); } else if (!users.getId().equals(billById.getOwnerId())) { return new ResponseEntity( HttpStatus.UNAUTHORIZED); } else if(file == null){ return new ResponseEntity( HttpStatus.NOT_FOUND); } else if(!file.getBill().equals(billId)){ return new ResponseEntity( HttpStatus.BAD_REQUEST); } if(file.getBill().equals(billId)){ Map<String, Object> displayFile = new HashMap<>(); displayFile.put("file_name", file.getFile_name()); displayFile.put("id", file.getId()); displayFile.put("url", file.getUrl()); displayFile.put("upload_date", file.getUpload_date()); return new ResponseEntity( displayFile , HttpStatus.OK); } else return new ResponseEntity( HttpStatus.NOT_FOUND); } @DeleteMapping("/{billId}/file/{fileId}") public ResponseEntity deleteFileById(@PathVariable String billId, @PathVariable String fileId) throws IOException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Users users = userRepository.findByEmailAddress(authentication.getName()); Bill billById = billRepo.findBillById(billId); File file = fileRepository.findFileById(fileId); if(billById == null){ return new ResponseEntity( HttpStatus.NOT_FOUND); } else if (!users.getId().equals(billById.getOwnerId())) { return new ResponseEntity( HttpStatus.UNAUTHORIZED); } else if(file == null){ return new ResponseEntity( HttpStatus.NOT_FOUND); } else if(!file.getBill().equals(billId)){ return new ResponseEntity( HttpStatus.UNAUTHORIZED); } if(file.getBill().equals(billId)){ fileRepository.delete(file); String filePath = UPLOAD_FOLDER + file.getFile_name_dir(); Path fileToDelete = Paths.get(filePath); Files.delete(fileToDelete); billById.setAttachment(null); billRepo.save(billById); return new ResponseEntity(HttpStatus.NO_CONTENT); } else return new ResponseEntity( HttpStatus.BAD_REQUEST); } @RequestMapping(method = RequestMethod.PUT, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, value = "/{id}/file/") public ResponseEntity updateAttachment(HttpServletRequest request, @PathVariable String id, @RequestParam("attachment") MultipartFile attachment) throws ParseException, IOException { try { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Bill billById = billRepo.findBillById(id); Users users = userRepository.findByEmailAddress(authentication.getName()); if (billById == null) { return new ResponseEntity(HttpStatus.NOT_FOUND); } else if (!users.getId().equals(billById.getOwnerId())) { return new ResponseEntity(HttpStatus.UNAUTHORIZED); } if(!attachment.getContentType().equals("image/jpg") && !attachment.getContentType().equals("image/jpeg") && !attachment.getContentType().equals("application/pdf") && !attachment.getContentType().equals("image/png")){ return new ResponseEntity(HttpStatus.BAD_REQUEST); } File fileExists = fileRepository.findFileByBill(billById.getId()); if(fileExists != null){ String filePath = UPLOAD_FOLDER + fileExists.getFile_name_dir(); Path fileToDelete = Paths.get(filePath); Files.delete(fileToDelete); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(attachment.getBytes()); byte[] digest = md.digest(); String myHash = DatatypeConverter .printHexBinary(digest).toUpperCase(); fileExists.setFile_name(attachment.getOriginalFilename()); fileExists.setUpload_date(new Date()); fileExists.setMimetype(attachment.getContentType()); fileExists.setSize(String.valueOf(attachment.getSize())); fileExists.setHash(myHash); if (!attachment.isEmpty()) { byte[] bytes = attachment.getBytes(); double x = Math.random(); Path path = Paths.get(UPLOAD_FOLDER + x + attachment.getOriginalFilename()); Files.write(path, bytes); fileExists.setFile_name_dir(x + attachment.getOriginalFilename()); fileExists.setUrl(UPLOAD_FOLDER + x + attachment.getOriginalFilename()); } fileRepository.save(fileExists); fileRepository.flush(); ObjectMapper mapperObj = new ObjectMapper(); Map<String, Object> displayFile = new HashMap<>(); displayFile.put("file_name", fileExists.getFile_name()); displayFile.put("id", fileExists.getId()); displayFile.put("url", fileExists.getUrl()); displayFile.put("upload_date", fileExists.getUpload_date()); mapperObj.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS , false); String jsonResp = mapperObj.writeValueAsString(displayFile); billById.setAttachment(jsonResp); billRepo.save(billById); return new ResponseEntity(displayFile, HttpStatus.CREATED); } catch(Exception e){ System.out.println(e); return new ResponseEntity(HttpStatus.BAD_REQUEST); } } }
package com.example.xgramajo.tabbedproject.Adapters; import android.app.Activity; import android.content.Context; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.TextView; import com.example.xgramajo.tabbedproject.MenuFragment; import com.example.xgramajo.tabbedproject.ProductClass; import com.example.xgramajo.tabbedproject.R; import java.util.ArrayList; public class SelectedListAdapter extends ArrayAdapter<ProductClass> { private ArrayList<ProductClass> products; private Context context; private int layoutResourceId; private SparseBooleanArray mSelectedItemsIds; /** Adapter con Holder */ public SelectedListAdapter(Context context, int layoutResourceId, ArrayList<ProductClass> products) { super(context, layoutResourceId, products); this.layoutResourceId = layoutResourceId; this.context = context; this.products = products; mSelectedItemsIds = new SparseBooleanArray(); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; SelectedListAdapter.PaymentHolder holder = null; LayoutInflater inflater = ((Activity) context).getLayoutInflater(); view = inflater.inflate(layoutResourceId, parent, false); holder = new SelectedListAdapter.PaymentHolder(); holder.Product = products.get(position); holder.button = (Button) view.findViewById(R.id.product_button); holder.name = (TextView) view.findViewById(R.id.product_name); holder.price = (TextView) view.findViewById(R.id.product_price); view.setTag(holder); holder.name.setText(holder.Product.getName()); holder.price.setText("$" + String.valueOf(holder.Product.getPrice())); holder.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MenuFragment.removeFromSelected(products.get(position)); } }); return view; } public static class PaymentHolder { ProductClass Product; TextView name; Button button; TextView price; } @Override public int getCount() { return products.size(); } }
package org.zhq.impl; import org.zhq.core.IoProvider; import org.zhq.core.NamedThreadFactory; import lombok.extern.slf4j.Slf4j; import org.zhq.utils.CloseUtil; import java.io.IOException; import java.nio.channels.*; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; @Slf4j public class IoSelectorProvider implements IoProvider { private final AtomicBoolean closed = new AtomicBoolean(false); private final AtomicBoolean inRegInput = new AtomicBoolean(false); private final AtomicBoolean inRegOutput = new AtomicBoolean(false); private final Selector readSelector; private final Selector writeSelector; private final Map<SelectionKey, Runnable> inputCallbackMap = new HashMap<>(); private final Map<SelectionKey, Runnable> outputCallbackMap = new HashMap<>(); private final ExecutorService inputHandlePool; private final ExecutorService outputHandlePool; public IoSelectorProvider() throws IOException { this.readSelector = Selector.open(); this.writeSelector = Selector.open(); this.inputHandlePool = Executors.newFixedThreadPool(4, new NamedThreadFactory("IoSelectorProvider-Input")); this.outputHandlePool = Executors.newFixedThreadPool(4, new NamedThreadFactory("IoSelectorProvider-Output")); startRead(); startWrite(); } private void startWrite() { Thread writeThread = new SelectorThread("Write Thread Listener", closed, inRegOutput, writeSelector, outputCallbackMap, outputHandlePool, SelectionKey.OP_WRITE); writeThread.start(); } private void startRead() { Thread readThread = new SelectorThread("Read Thread Listener", closed, inRegInput, readSelector, inputCallbackMap, inputHandlePool, SelectionKey.OP_READ); readThread.start(); } public boolean registerInput(SocketChannel channel, HandleProviderTask callback) { return registerSelection(channel, readSelector, SelectionKey.OP_READ, inRegInput, inputCallbackMap, callback) != null; } public boolean registerOutput(SocketChannel channel, HandleProviderTask callback) { return registerSelection(channel, writeSelector, SelectionKey.OP_WRITE, inRegOutput, outputCallbackMap, callback) != null; } public void unRegisterInput(SocketChannel channel) { unRegisterSelection(channel, readSelector, inputCallbackMap, inRegInput); } public void unRegisterOutput(SocketChannel channel) { unRegisterSelection(channel, writeSelector, outputCallbackMap, inRegOutput); } private static void waitSelection(final AtomicBoolean locker) { synchronized (locker) { if (locker.get()) { try { locker.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } private static void unRegisterSelection(SocketChannel channel, Selector selector, Map<SelectionKey, Runnable> map, AtomicBoolean locker) { synchronized (locker) { locker.set(true); selector.wakeup(); try { if (channel.isRegistered()) { SelectionKey key = channel.keyFor(selector); if (key != null) { //erase all interest key.cancel(); map.remove(key); } } } finally { locker.set(false); try { locker.notify(); } catch (Exception ignored) { } } } } private static SelectionKey registerSelection(SocketChannel channel, Selector selector, int registerOps, AtomicBoolean locker, Map<SelectionKey, Runnable> callBackMap, Runnable runnable) { synchronized (locker) { locker.set(true); try { //make selector.select() don't block selector.wakeup(); SelectionKey key = null; if (channel.isRegistered()) { key = channel.keyFor(selector); if (key != null) { // add interest key.interestOps(key.interestOps() | registerOps); } } //key isn't exist. channel not registered yet if (key == null) { //channel registerSelector selector ops key = channel.register(selector, registerOps); //save task of key callBackMap.put(key, runnable); } return key; } catch (ClosedChannelException|CancelledKeyException|ClosedSelectorException e) { return null; } finally { locker.set(false); locker.notify(); } } } private static void handleSelection(SelectionKey key, int keyOps, Map<SelectionKey, Runnable> inputCallbackMap, ExecutorService inputHandlePool, AtomicBoolean locker) { synchronized (locker) { try { key.interestOps(key.interestOps() & ~keyOps); } catch (CancelledKeyException e) { return; } } Runnable runnable = inputCallbackMap.get(key); if (runnable != null && !inputHandlePool.isShutdown()) { //sync execute inputHandlePool.execute(runnable); } } @Override public void close() { if (closed.compareAndSet(false, true)) { inputHandlePool.shutdown(); outputHandlePool.shutdown(); inputCallbackMap.clear(); outputCallbackMap.clear(); CloseUtil.close(readSelector, writeSelector); } } class SelectorThread extends Thread { private final AtomicBoolean closed; private final AtomicBoolean locker; private final Selector selector; private final Map<SelectionKey, Runnable> callMap; private final ExecutorService threadPool; private final int keyOps; public SelectorThread(String name, AtomicBoolean closed, AtomicBoolean locker, Selector selector, Map<SelectionKey, Runnable> callMap, ExecutorService threadPool, int keyOps) { super(name); this.setPriority(Thread.MAX_PRIORITY); this.keyOps = keyOps; this.closed = closed; this.locker = locker; this.selector = selector; this.callMap = callMap; this.threadPool = threadPool; } @Override public void run() { super.run(); AtomicBoolean closed = this.closed; AtomicBoolean locker = this.locker; Selector selector = this.selector; Map<SelectionKey, Runnable> callMap = this.callMap; ExecutorService threadPool = this.threadPool; int keyOps = this.keyOps; while (!closed.get()) { try { int select = selector.select(); waitSelection(locker); if (select == 0) continue; Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); if (selectionKey.isValid()) { handleSelection(selectionKey, keyOps, callMap, threadPool, locker); } iterator.remove(); } } catch (IOException e) { e.printStackTrace(); } catch (ClosedSelectorException ignored) { break; } } } } }
package com.dynamicprog; class A{ int a=5; String doA() {return "a1";} protected static String doA2() {return "a2";} } class B extends A{ int a=7; String doA() {return "b1";} protected static String doA2() {return "b2";} void go() { A myA = new B(); System.out.println(myA.doA() + myA.doA2()+myA.a); } public static void main(String[] args) { // TODO Auto-generated method stub new B().go(); } }
package com.atlassian.bitbucket.jenkins.internal.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import static java.util.Objects.requireNonNull; @JsonIgnoreProperties(ignoreUnknown = true) public class BitbucketProject { private final String key; private final String name; @JsonCreator public BitbucketProject( @JsonProperty(value = "key", required = true) String key, @JsonProperty(value = "name", required = true) String name) { this.key = requireNonNull(key, "key"); this.name = requireNonNull(name, "name"); } public String getKey() { return key; } public String getName() { return name; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.inbio.commons.dublincore.eao.ara; import javax.ejb.Local; import org.inbio.commons.dublincore.dao.DublinCoreDescriptionDAO; /** * * @author gsulca */ @Local public interface DublinCoreDescriptionEAOLocal extends DublinCoreDescriptionDAO { }
package pv260.customeranalysis.exceptions; public class CantUnderstandException extends GeneralException {}
package com.cg.go.greatoutdoor; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.cg.go.greatoutdoor.dao.IOrderRepository; import com.cg.go.greatoutdoor.entity.OrderEntity; import com.cg.go.greatoutdoor.exception.OrderException; import com.cg.go.greatoutdoor.service.OrderServiceImpl; @ExtendWith(MockitoExtension.class) public class OrderServiceTest { @Mock IOrderRepository OrderRepository; @InjectMocks OrderServiceImpl service; @Test public void addOrderTest() throws Exception { OrderEntity order = mock(OrderEntity.class); service.addOrder(order); verify(OrderRepository).save(order); } @Test public void findallOrdersTest() throws OrderException { List<OrderEntity> list = new ArrayList<>(); OrderEntity s1 = mock(OrderEntity.class); OrderEntity s2 = mock(OrderEntity.class); OrderEntity s3 = mock(OrderEntity.class); list.add(s1); list.add(s2); list.add(s3); when(OrderRepository.findAll()).thenReturn(list); List<OrderEntity> actual = service.findAllOrders(); Assertions.assertEquals(list.size(), actual.size()); verify(OrderRepository).findAll(); } }
package subarraySum560; import java.util.*; public class Solution { /** * Hash法,扫描一遍数组, 使用map记录出现同样的和的次数, 对每个i计算累计和sum并判断map内是否有sum-k * @param nums * @param k * @return */ public int subarraySum(int[] nums, int k) { if (nums.length == 0) return 0; int ans = 0; int sum = 0; Map<Integer, Integer> map = new HashMap<>(); map.put(0, 1); for (int i = 0; i < nums.length; ++i) { sum += nums[i]; if (map.containsKey(sum - k)) { ans += map.get(sum - k); } map.put(sum, map.getOrDefault(sum, 0) + 1); } return ans; } /** * 暴力O(n^2) * @param nums * @param k * @return */ public int subarraySum2(int[] nums, int k) { if (nums.length == 0) return 0; int i, j; int ans = 0; int[] sum = new int[nums.length]; sum[0] = nums[0]; for (i = 1; i < nums.length; ++i) { sum[i] = sum[i - 1] + nums[i]; } for (i = 0; i < nums.length; ++i) { if (sum[i] == k) ++ans; for (j = 0; j < i; ++j) { if (sum[i] - sum[j] == k) ++ans; } } return ans; } }
package com.wencheng.web.controller; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.wencheng.domain.Journal; import com.wencheng.service.JournalService; import com.wencheng.service.impl.JournalServiceImpl; public class JournalListAction extends HttpServlet { /** * Constructor of the object. */ public JournalListAction() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Content-Type", "application/json"); SimpleDateFormat sf = new SimpleDateFormat("YY-MM-dd"); JournalService js = new JournalServiceImpl(); List<Journal> list = js.list(request); JSONArray ja = new JSONArray(); Iterator<Journal> it = list.iterator(); while(it.hasNext()){ Journal jou = it.next(); jou.setProject(null); JSONObject jo1 = new JSONObject(); jo1.put("title", jou.getTitle()); jo1.put("type", jou.getType().getName()); jo1.put("id", jou.getId()); jo1.put("status", jou.getStatus()); jo1.put("time", sf.format(jou.getTime())); ja.add(jo1); } response.getWriter().print(ja.toString()); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //doGet doGet(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
package it.unipi.p2p.tinycoin.protocols; import java.util.ArrayList; import java.util.List; import java.util.Map; import it.unipi.p2p.tinycoin.Block; import it.unipi.p2p.tinycoin.TinyCoinNode; import it.unipi.p2p.tinycoin.Transaction; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.config.FastConfig; import peersim.core.Linkable; import peersim.core.Network; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.transport.Transport; public class NodeProtocol implements CDProtocol, EDProtocol{ private static final String PAR_P_TRANS = "transaction_prob"; private static final String PAR_SMINER = "self_miner_prot"; private double transProb; private int numTrans; private int smpid; private boolean fork; private Block forked; private int numForks; private List<Block> missedBlocks; private int limit; public NodeProtocol(String prefix) { transProb = Configuration.getDouble(prefix + "." + PAR_P_TRANS); numTrans = 0; smpid = Configuration.getPid(prefix + "." + PAR_SMINER); fork = false; forked = null; numForks = 0; missedBlocks = new ArrayList<>(); limit = 20; } @Override public Object clone() { NodeProtocol np = null; try { np = (NodeProtocol)super.clone(); np.setTransProb(transProb); np.setNumTrans(0); np.setSmpid(smpid); np.setFork(false); np.setForked(null); np.setNumForks(0); np.setMissedBlocks(new ArrayList<>()); np.setLimit(limit); } catch(CloneNotSupportedException e) { System.err.println(e); } return np; } @Override public void nextCycle(Node node, int pid) { TinyCoinNode tnode = (TinyCoinNode) node; double balance = tnode.getBalance(); // I assume that if a node has less than 1 coin cannot make a transaction // (Substitutes the test for empty balance, and allows to avoid very small, fractional transactions) if (balance < 1) { return; } double r = Math.random(); // At each cycle, each node generates a transaction with a given probability if (r < transProb) { String tid = node.getID() + "@" + numTrans; numTrans++; // Randomly choose one recipient Network.shuffle(); TinyCoinNode recipient = (TinyCoinNode) Network.get(0); double totalSpent = Math.random() * balance; double amount = totalSpent * (9.0/10.0); double fee = totalSpent - amount; Transaction t = new Transaction(tid, tnode, recipient, amount, fee); System.out.println(t.toString()); // Transaction has been created, so update balance and insert into local pool of unconfirmed transactions tnode.getTransPool().put(tid, t); balance -= totalSpent; // Send the transaction to all neighbor nodes sendTransactionToNeighbors(node, pid, t); } } @Override public void processEvent(Node node, int pid, Object event) { if (event instanceof Transaction) { Transaction t = (Transaction) event; Map<String, Transaction> transPool = ((TinyCoinNode) node).getTransPool(); String tid = t.getTid(); // If never received the transaction, broadcast it to the neighbors if (!transPool.containsKey(tid)) { transPool.put(tid, t); sendTransactionToNeighbors(node, pid, t); } } else if (event instanceof Block) { TinyCoinNode tnode = (TinyCoinNode)node; List<Block> blockchain = tnode.getBlockchain(); Block b = (Block)event; String last = blockchain.size()==0 ? null : blockchain.get(blockchain.size()-1).getBid(); if (tnode.isSelfishMiner()) { //Selfish miner receives a new block from a honest node SelfishMinerProtocol smp = (SelfishMinerProtocol)node.getProtocol(smpid); List<Block> privateBlockchain = smp.getPrivateBlockchain(); int privateBranchLength = smp.getPrivateBranchLength(); int prevDiff = privateBlockchain.size() - blockchain.size(); if ( last == b.getParent()) { blockchain.add(b); if (!missedBlocks.isEmpty()) attachMissedBlocksToBlockchain(tnode); tnode.increaseBalance(b.getTransactionsAmountIfRecipient(tnode)); if (b.getMiner() == tnode) // Added this check, should be redundant tnode.increaseBalance(b.getRevenueForBlock()); switch (prevDiff) { case(0): if (onlyAddTheBlock(privateBlockchain, blockchain)) privateBlockchain.add(b); //simply add one block else smp.copyPublicBlockchain(tnode); // also delete last block of private blockchain to make the two exactly equal smp.setPrivateBranchLength(0); sendBlockToNeighbors(node, pid, b); break; case(1): Block sb = privateBlockchain.get(privateBlockchain.size() - 1); sendBlockToNeighbors(node, pid, sb); break; case(2): for (int i = privateBranchLength; i > 0; i--) { sb = privateBlockchain.get(privateBlockchain.size() - i); sendBlockToNeighbors(node, pid, sb); } smp.copyPrivateBlockchain(tnode); smp.setPrivateBranchLength(0); break; default: if (prevDiff > 2 && privateBranchLength > 0) { sb = privateBlockchain.get(privateBlockchain.size() - privateBranchLength); sendBlockToNeighbors(node, pid, sb); smp.setPrivateBranchLength(privateBranchLength - 1); } } } else addMissedBlockToPool(b); } else { // If the parent field of the block is valid, then the honest node adds the block // to its blockchain and removes the transactions inside the block from the pool. if ( last == b.getParent() || (fork == true && forked.getBid() == b.getParent())) { if (fork == true) { if (forked.getBid() == b.getParent()) { Block lastb = blockchain.get(blockchain.size()-1); blockchain.remove(lastb); addTransactionsToPool(tnode, lastb); tnode.decreaseBalance(lastb.getTransactionsAmountIfRecipient(tnode)); if (tnode == lastb.getMiner()) tnode.decreaseBalance(lastb.getRevenueForBlock()); blockchain.add(forked); // No need to add the revenue for mining the block, because a honest miner always // takes the revenue as soon as it mines the block tnode.increaseBalance(forked.getTransactionsAmountIfRecipient(tnode)); } fork = false; // Fork is resolved, regardless of which is the extended branch forked = null; } blockchain.add(b); if (!missedBlocks.isEmpty()) attachMissedBlocksToBlockchain(tnode); tnode.increaseBalance(b.getTransactionsAmountIfRecipient(tnode)); removeTransactionsFromPool(tnode, b); // Finally (if block is valid) send the block to all the neighbor nodes sendBlockToNeighbors(node, pid, b); } else if (blockchain.size() >= 2 && blockchain.get(blockchain.size()-2).getBid() == b.getParent() && blockchain.get(blockchain.size()-1).getBid() != b.getBid() && fork == false) { fork = true; forked = b; numForks++; sendBlockToNeighbors(node, pid, b); solveForkWithMissedBlocks(tnode); } else if (last != b.getParent()) addMissedBlockToPool(b); } } } public void removeTransactionsFromPool(TinyCoinNode tn, Block b) { Map<String, Transaction> transPool = tn.getTransPool(); for (Transaction t : b.getTransactions()) { transPool.remove(t.getTid()); } } public void addTransactionsToPool(TinyCoinNode tn, Block b) { Map<String, Transaction> transPool = tn.getTransPool(); for (Transaction t : b.getTransactions()) { transPool.putIfAbsent(t.getTid(), t); } } public void setNumForks(int numForks) { this.numForks = numForks; } /** Sends a transaction t to the protocol pid of all the neighbor nodes * * @param sender The sender node * @param pid The id of the protocol the message is directed to * @param t The transaction to be sent */ public void sendTransactionToNeighbors(Node sender, int pid, Transaction t) { int linkableID = FastConfig.getLinkable(pid); Linkable linkable = (Linkable) sender.getProtocol(linkableID); for (int i =0; i<linkable.degree(); i++) { Node peer = linkable.getNeighbor(i); ((Transport)sender.getProtocol(FastConfig.getTransport(pid))) .send(sender, peer, t, pid); } } /** Sends a block b to the protocol pid of all the neighbor nodes * * @param sender The sender node * @param pid The id of the protocol the message is directed to * @param b The block to be sent */ public void sendBlockToNeighbors(Node sender, int pid, Block b) { int linkableID = FastConfig.getLinkable(pid); Linkable linkable = (Linkable) sender.getProtocol(linkableID); for (int i =0; i<linkable.degree(); i++) { Node peer = linkable.getNeighbor(i); ((Transport)sender.getProtocol(FastConfig.getTransport(pid))) .send(sender, peer, b, pid); } } public boolean solveForkWithMissedBlocks(TinyCoinNode tn) { List <Block> blockchain = tn.getBlockchain(); for (int i=0; i< missedBlocks.size(); i++) { if (missedBlocks.get(i).getParent() == forked.getBid()) { Block lastb = blockchain.get(blockchain.size()-1); blockchain.remove(lastb); tn.decreaseBalance(lastb.getTransactionsAmountIfRecipient(tn)); addTransactionsToPool(tn, lastb); blockchain.add(forked); Block head = missedBlocks.remove(i); blockchain.add(head); removeTransactionsFromPool(tn, head); tn.increaseBalance(head.getTransactionsAmountIfRecipient(tn)); fork = false; forked = null; attachMissedBlocksToBlockchain(tn); return true; } } return false; } /** Scans the list of missed blocks trying to find some blocks that can be attached to the head of the blockchain */ public void attachMissedBlocksToBlockchain(TinyCoinNode tn) { List <Block> blockchain = tn.getBlockchain(); Block head = blockchain.get(blockchain.size()-1); int i=0; while ( i < missedBlocks.size()) { if (missedBlocks.get(i).getParent() == head.getBid()) { head = missedBlocks.remove(i); blockchain.add(head); removeTransactionsFromPool(tn, head); tn.increaseBalance(head.getTransactionsAmountIfRecipient(tn)); i = 0; // The head of the blockchain changed, so we restart scanning the missed blocks } else i++; } } public void addMissedBlockToPool(Block missed) { if (missedBlocks.size() == limit) // If reached the limit, empty it missedBlocks.removeAll(missedBlocks); if (!missedBlocks.contains(missed)) missedBlocks.add(missed); } public int getNumForks() { return numForks; } public void setSmpid(int smpid) { this.smpid = smpid; } public void setNumTrans(int numTrans) { this.numTrans = numTrans; } public void setFork(boolean fork) { this.fork = fork; } public void setForked(Block forked) { this.forked = forked; } public double getTransProb() { return transProb; } public void setTransProb(double transProb) { this.transProb = transProb; } public void setMissedBlocks(List<Block> missedBlocks) { this.missedBlocks = missedBlocks; } public void setLimit(int limit) { this.limit = limit; } private boolean onlyAddTheBlock(List<Block> privateBlockchain , List<Block> blockchain ) { if (privateBlockchain.size() == 0 || blockchain.get(blockchain.size() -1).getParent() == privateBlockchain.get(privateBlockchain.size()-1).getBid()) return true; else return false; } }
package com.citibank.ods.modules.client.ipdocprvt.functionality; import java.lang.reflect.Array; import java.math.BigInteger; import org.apache.struts.action.ActionForm; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.functionality.BaseFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.modules.client.ipdocprvt.form.BaseIpDocPrvtListForm; import com.citibank.ods.modules.client.ipdocprvt.functionality.valueobject.BaseIpDocPrvtListFncVO; // //©2002-2007 Accenture. All rights reserved. // /** * [Class description] * * @see package com.citibank.ods.modules.client.ipdocprvt.functionality; * @version 1.0 * @author gerson.a.rodrigues,Apr 12, 2007 * */ public abstract class BaseIpDocPrvtListFnc extends BaseFnc { public void updateFncVOFromForm( ActionForm form_, BaseFncVO fncVO_ ) { BaseIpDocPrvtListForm baseIpDocPrvtListForm = ( BaseIpDocPrvtListForm ) form_; BaseIpDocPrvtListFncVO baseIpDocPrvtListFncVO = ( BaseIpDocPrvtListFncVO ) fncVO_; BigInteger custNbrSrc = baseIpDocPrvtListForm.getCustNbrSrc() != null && baseIpDocPrvtListForm.getCustNbrSrc().length() > 0 ? new BigInteger( baseIpDocPrvtListForm.getCustNbrSrc() ) : null; BigInteger ipDocCodeSrc = baseIpDocPrvtListForm.getIpDocCodeSrc() != null && baseIpDocPrvtListForm.getIpDocCodeSrc().length() > 0 ? new BigInteger( baseIpDocPrvtListForm.getIpDocCodeSrc() ) : null; String ipDocTextSrc = baseIpDocPrvtListForm.getIpDocTextSrc() != null && baseIpDocPrvtListForm.getIpDocTextSrc().length() > 0 ? baseIpDocPrvtListForm.getIpDocTextSrc() : null; DataSet results = baseIpDocPrvtListForm.getResults() != null ? baseIpDocPrvtListForm.getResults() : null; String ipInvstCurAcctInd = baseIpDocPrvtListForm.getIpInvstCurAcctIndSrc() != null && baseIpDocPrvtListForm.getIpInvstCurAcctIndSrc().length() > 0 ? baseIpDocPrvtListForm.getIpInvstCurAcctIndSrc() : null; DataSet ipInvstCurAcctIndDomain = baseIpDocPrvtListForm.getIpInvstCurAcctIndDomain() != null ? baseIpDocPrvtListForm.getIpInvstCurAcctIndDomain() : null; String selectedCustNbr = baseIpDocPrvtListForm.getSelectedCustNbr() != null && baseIpDocPrvtListForm.getSelectedCustNbr().length() > 0 ? baseIpDocPrvtListForm.getSelectedCustNbr() : null; String selectedIpDocCode = baseIpDocPrvtListForm.getSelectedIpDocCode() != null && baseIpDocPrvtListForm.getSelectedIpDocCode().length() > 0 ? baseIpDocPrvtListForm.getSelectedIpDocCode() : null; String custFullNameText = ( baseIpDocPrvtListForm.getCustFullNameText() != null ? new String( baseIpDocPrvtListForm.getCustFullNameText() ) : null ); String fromCurAcct = ( baseIpDocPrvtListForm.getFromCurAcct() != null && !baseIpDocPrvtListForm.getFromCurAcct().equals( "" ) ? baseIpDocPrvtListForm.getFromCurAcct() : "" ); baseIpDocPrvtListFncVO.setCustNbrSrc( custNbrSrc ); baseIpDocPrvtListFncVO.setIpDocCodeSrc( ipDocCodeSrc ); baseIpDocPrvtListFncVO.setIpDocTextSrc( ipDocTextSrc ); baseIpDocPrvtListFncVO.setResults( results ); baseIpDocPrvtListFncVO.setIpInvstCurAcctInd( ipInvstCurAcctInd ); baseIpDocPrvtListFncVO.setIpInvstCurAcctIndDomain( ipInvstCurAcctIndDomain ); baseIpDocPrvtListFncVO.setSelectedCustNbr( selectedCustNbr ); baseIpDocPrvtListFncVO.setSelectedIpDocCode( selectedIpDocCode ); baseIpDocPrvtListFncVO.setCustFullNameText( custFullNameText ); baseIpDocPrvtListFncVO.setFromCurAcct( fromCurAcct ); baseIpDocPrvtListFncVO.setClickedSearch( "" ); } public void updateFormFromFncVO( ActionForm form_, BaseFncVO fncVO_ ) { BaseIpDocPrvtListForm baseIpDocPrvtListForm = ( BaseIpDocPrvtListForm ) form_; BaseIpDocPrvtListFncVO baseIpDocPrvtListFncVO = ( BaseIpDocPrvtListFncVO ) fncVO_; String custNbrSrc = baseIpDocPrvtListFncVO.getCustNbrSrc() != null ? baseIpDocPrvtListFncVO.getCustNbrSrc().toString() : ""; String ipDocCodeSrc = baseIpDocPrvtListFncVO.getIpDocCodeSrc() != null ? baseIpDocPrvtListFncVO.getIpDocCodeSrc().toString() : ""; String ipDocTextSrc = baseIpDocPrvtListFncVO.getIpDocTextSrc() != null ? baseIpDocPrvtListFncVO.getIpDocTextSrc().toString() : ""; DataSet results = baseIpDocPrvtListFncVO.getResults() != null ? baseIpDocPrvtListFncVO.getResults() : null; String ipInvstCurAcctInd = baseIpDocPrvtListFncVO.getIpInvstCurAcctInd() != null ? baseIpDocPrvtListFncVO.getIpInvstCurAcctInd().toString() : ""; DataSet ipInvstCurAcctIndDomain = baseIpDocPrvtListFncVO.getIpInvstCurAcctIndDomain() != null ? baseIpDocPrvtListFncVO.getIpInvstCurAcctIndDomain() : null; String selectedCustNbr = baseIpDocPrvtListFncVO.getSelectedCustNbr() != null ? baseIpDocPrvtListFncVO.getSelectedCustNbr().toString() : ""; String selectedIpDocCode = baseIpDocPrvtListFncVO.getSelectedIpDocCode() != null ? baseIpDocPrvtListFncVO.getSelectedIpDocCode().toString() : ""; String custFullNameText = ( baseIpDocPrvtListFncVO.getCustFullNameText() != null && baseIpDocPrvtListFncVO.getCustFullNameText().length() > 0 ? baseIpDocPrvtListFncVO.getCustFullNameText() : "" ); String fromCurAcct = ( baseIpDocPrvtListFncVO.getFromCurAcct() != null && !baseIpDocPrvtListFncVO.getFromCurAcct().equals( "" ) ? baseIpDocPrvtListFncVO.getFromCurAcct() : "" ); baseIpDocPrvtListForm.setCustNbrSrc( custNbrSrc ); baseIpDocPrvtListForm.setIpDocCodeSrc( ipDocCodeSrc ); baseIpDocPrvtListForm.setIpDocTextSrc( ipDocTextSrc ); baseIpDocPrvtListForm.setResults( results ); baseIpDocPrvtListForm.setCustFullNameText( custFullNameText ); baseIpDocPrvtListForm.setIpInvstCurAcctIndSrc( ipInvstCurAcctInd ); baseIpDocPrvtListForm.setIpInvstCurAcctIndDomain( ipInvstCurAcctIndDomain ); baseIpDocPrvtListForm.setSelectedCustNbr( selectedCustNbr ); baseIpDocPrvtListForm.setSelectedIpDocCode( selectedIpDocCode ); baseIpDocPrvtListForm.setFromCurAcct( fromCurAcct ); baseIpDocPrvtListForm.setClickedSearch( baseIpDocPrvtListFncVO.getClickedSearch() ); } }
package flow; // https://java.keicode.com/lang/flow.php // javac -encoding utf-8 ControlFlow4.java public class ControlFlow4 { public static void main(String[] args) { int i = 0; do { System.out.println( i ); i++; } while( i < 3 ); } }
package rs.ac.bg.etf.pmu.sv100502.monopoly; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import rs.ac.bg.etf.pmu.sv100502.monopoly.db.DBContract.*; import rs.ac.bg.etf.pmu.sv100502.monopoly.db.DBHelper; import rs.ac.bg.etf.pmu.sv100502.monopoly.dialogs.SettingsDialogFragment; import rs.ac.bg.etf.pmu.sv100502.monopoly.dialogs.PlayerNamesDialogFragment; public class MainActivity extends AppCompatActivity { public static final String SETTINGS = "rs.ac.bg.etf.pmu.sv100502.monopoly.SETTINGS"; public static final int DEFAULT_MOVE_TIME = 300; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void newGame(View view) { PlayerNamesDialogFragment names = new PlayerNamesDialogFragment(); names.setCancelable(false); names.show(getFragmentManager(), "Player names"); } public void results(View view) { // Check if results table is empty DBHelper dbHelper = new DBHelper(view.getContext()); SQLiteDatabase db = dbHelper.getReadableDatabase(); String selection = ResultEntry.COLUMN_NAME_WINNER + " != ?"; String[] selectionArgs = { "" }; Cursor cursor = db.query(ResultEntry.TABLE_NAME, null, selection, selectionArgs, null, null, null); if (cursor.moveToFirst() && (cursor.getInt(0) > 0)) { Intent intent = new Intent(this, ResultsActivity.class); startActivity(intent); } else { Toast.makeText(MainActivity.this, R.string.no_results, Toast.LENGTH_SHORT).show(); } cursor.close(); } public void settings(View view) { SettingsDialogFragment settings = new SettingsDialogFragment(); Bundle args = new Bundle(); args.putBoolean("shaking", true); settings.setArguments(args); settings.setCancelable(false); settings.show(getFragmentManager(), "Settings"); } }
package excepciones; public class FueraDeTableroException extends Exception { public void getMessage(String string) { System.out.println(string); } }
package com.zhouqi.schedule.task.cfg; import java.io.File; import java.sql.Timestamp; public interface ITaskConfig { public String getAsString(String codeValue); public boolean contains(String codeValue); public int getAsInt(String key); public float getAsFloat(String key); public long getAsLong(String key); public byte getAsByte(String key); public char getAsChar(String key); public short getAsShort(String key); public double getAsDouble(String key); public boolean getAsBoolean(String key); public Timestamp getAsDate(String key); public File getAsFile(String key); public String getAsString(String key, String defaultValue); public int getAsInt(String key, int defaultValue); public float getAsFloat(String key, float defaultValue); public long getAsLong(String key, long defaultValue); public byte getAsByte(String key, byte defaultValue); public char getAsChar(String key, char defaultValue); public short getAsShort(String key, short defaultValue); public double getAsDouble(String key, double defaultValue); public boolean getAsBoolean(String key, boolean defaultValue); public String taskName(); }
package org.jphototagger.userdefinedfiletypes; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.jphototagger.domain.filetypes.UserDefinedFileType; import org.jphototagger.domain.repository.UserDefinedFileTypesRepository; import org.jphototagger.lib.swing.MessageDisplayer; import org.jphototagger.lib.swing.MouseEventUtil; import org.jphototagger.lib.swing.util.MnemonicUtil; import org.jphototagger.lib.util.Bundle; import org.openide.util.Lookup; /** * @author Elmar Baumann */ public class UserDefinedFileTypesPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; public UserDefinedFileTypesPanel() { initComponents(); postInitComponents(); } private void postInitComponents() { MnemonicUtil.setMnemonics(this); list.addListSelectionListener(new ButtonEnabler()); } private void addUserDefinedFileType() { EditUserDefinedFileTypeDialog dlg = new EditUserDefinedFileTypeDialog(); dlg.setVisible(true); } private void editUserDefinedFileType() { List<UserDefinedFileType> fileTypes = getSelectedUserDefinedFileTypes(); for (UserDefinedFileType fileType : fileTypes) { EditUserDefinedFileTypeDialog dlg = new EditUserDefinedFileTypeDialog(); dlg.setUserDefinedFileType(fileType); dlg.setVisible(true); } } private void deleteUserDefinedFileType() { String message = Bundle.getString(UserDefinedFileTypesPanel.class, "UserDefinedFileTypesPanel.Confirm.Delete"); if (MessageDisplayer.confirmYesNo(this, message)) { List<UserDefinedFileType> fileTypes = getSelectedUserDefinedFileTypes(); UserDefinedFileTypesRepository repo = Lookup.getDefault().lookup(UserDefinedFileTypesRepository.class); for (UserDefinedFileType fileType : fileTypes) { repo.deleteUserDefinedFileType(fileType); } } } private void editClickedUserDefinedFileType(MouseEvent evt) { if (MouseEventUtil.isDoubleClick(evt)) { editUserDefinedFileType(); } } private List<UserDefinedFileType> getSelectedUserDefinedFileTypes() { List<UserDefinedFileType> fileTypes = new ArrayList<>(); for (Object selectedValue : list.getSelectedValues()) { if (selectedValue instanceof UserDefinedFileType) { fileTypes.add((UserDefinedFileType) selectedValue); } } return fileTypes; } private boolean isListItemSelected() { int selectedIndex = list.getSelectedIndex(); return selectedIndex >= 0; } private void checkDelete(KeyEvent evt) { if (evt.getKeyCode() == KeyEvent.VK_DELETE && isListItemSelected()) { deleteUserDefinedFileType(); } } private class ButtonEnabler implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { boolean itemSelected = isListItemSelected(); buttonDelete.setEnabled(itemSelected); buttonEdit.setEnabled(itemSelected); } } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") private void initComponents() {//GEN-BEGIN:initComponents java.awt.GridBagConstraints gridBagConstraints; scrollPane = new javax.swing.JScrollPane(); list = new org.jdesktop.swingx.JXList(); panelButtons = new javax.swing.JPanel(); buttonAdd = new javax.swing.JButton(); buttonEdit = new javax.swing.JButton(); buttonDelete = new javax.swing.JButton(); setLayout(new java.awt.GridBagLayout()); list.setModel(new org.jphototagger.userdefinedfiletypes.UserDefinedFileTypesListModel()); list.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { listMouseClicked(evt); } }); list.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { listKeyPressed(evt); } }); scrollPane.setViewportView(list); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(scrollPane, gridBagConstraints); panelButtons.setLayout(new java.awt.GridLayout(1, 0, 3, 0)); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jphototagger/userdefinedfiletypes/Bundle"); // NOI18N buttonAdd.setText(bundle.getString("UserDefinedFileTypesPanel.buttonAdd.text")); // NOI18N buttonAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonAddActionPerformed(evt); } }); panelButtons.add(buttonAdd); buttonEdit.setText(bundle.getString("UserDefinedFileTypesPanel.buttonEdit.text")); // NOI18N buttonEdit.setEnabled(false); buttonEdit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonEditActionPerformed(evt); } }); panelButtons.add(buttonEdit); buttonDelete.setText(bundle.getString("UserDefinedFileTypesPanel.buttonDelete.text")); // NOI18N buttonDelete.setEnabled(false); buttonDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonDeleteActionPerformed(evt); } }); panelButtons.add(buttonDelete); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0); add(panelButtons, gridBagConstraints); }//GEN-END:initComponents private void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddActionPerformed addUserDefinedFileType(); }//GEN-LAST:event_buttonAddActionPerformed private void buttonEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEditActionPerformed editUserDefinedFileType(); }//GEN-LAST:event_buttonEditActionPerformed private void buttonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDeleteActionPerformed deleteUserDefinedFileType(); }//GEN-LAST:event_buttonDeleteActionPerformed private void listKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_listKeyPressed checkDelete(evt); }//GEN-LAST:event_listKeyPressed private void listMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listMouseClicked editClickedUserDefinedFileType(evt); }//GEN-LAST:event_listMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buttonAdd; private javax.swing.JButton buttonDelete; private javax.swing.JButton buttonEdit; private org.jdesktop.swingx.JXList list; private javax.swing.JPanel panelButtons; private javax.swing.JScrollPane scrollPane; // End of variables declaration//GEN-END:variables }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.inbio.ara.eao.gathering.impl; import org.inbio.ara.eao.gathering.*; import javax.ejb.Stateless; import org.inbio.ara.eao.BaseEAOImpl; import org.inbio.ara.persistence.gathering.MorphologicalDescription; /** * * @author esmata */ @Stateless public class MorphologicalDescriptionEAOImpl extends BaseEAOImpl<MorphologicalDescription,Long> implements MorphologicalDescriptionEAOLocal { // Add business logic below. (Right-click in editor and choose // "Insert Code > Add Business Method" or "Web Service > Add Operation") }
import java.util.Arrays; public class Ferramentas { public Ferramentas() { } public Integer pesquisaSequencial(Integer num[], Integer numEscolhido) { for(int i = 0;i < 10;i++) { if(num[i] == numEscolhido){ return i; } } return -1; } public Integer bubbleSort(Integer num[], Integer numEscolhido) { Integer metade = num.length / 2; for(int i = 0;i < 10;i++) { if(num[metade] == numEscolhido) { return metade; } else if(num[metade] < numEscolhido) { metade += 1; } else { metade -= 1; } } return -1; } public Integer[] InsertionSort(Integer num[]) { int key; int j,i; for (i = 1; i < num.length-1; i++) { key = num[i]; for (j= i - 1; (j >= 0) && (num[j] > key); j--){ num[j + 1] = num[j]; } num[j + 1] = key; } return num; } public Integer[] insertionSortBinarySearch(Integer num[]) { for (int i = 1; i < num.length; i++) { Integer x = num[i]; Integer j = Math.abs(Arrays.binarySearch(num, 0, i, x) + 1); System.arraycopy(num, j, num, j+1, i-j); num[j] = x; } return num; } }
package com.ainory.kafka.streams.timestamp.extractor; import com.ainory.kafka.streams.util.JsonUtil; import com.ainory.kafka.streams.entity.CollectdKafkaVO; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.streams.processor.TimestampExtractor; /** * @author ainory on 2018. 3. 29.. */ public class CollectdTimestampExtractor implements TimestampExtractor { @Override public long extract(ConsumerRecord<Object, Object> consumerRecord, long l) { try { CollectdKafkaVO[] arrCollectdKafkaVO = (CollectdKafkaVO[]) JsonUtil.jsonStringToObject(consumerRecord.value().toString(), CollectdKafkaVO[].class); CollectdKafkaVO collectdKafkaVO = arrCollectdKafkaVO[0]; try { return Long.parseLong(StringUtils.replace(collectdKafkaVO.getTime(), ".", "")); } catch (Exception e) { e.printStackTrace(); return System.currentTimeMillis(); } } catch (Exception e) { e.printStackTrace(); return System.currentTimeMillis(); } } }
package com.developworks.jvmcode; /** * <p>Title: i2f</p> * <p>Description: int数值转换为float类型</p> * <p>Author: ouyp </p> * <p>Date: 2018-05-19 20:53</p> */ public class i2f { public void i2f(int i) { float f = i; } } /** * public void i2f(int); * Code: * 0: iload_1 * 1: i2f * 2: fstore_2 * 3: return */
package io.breen.socrates.criteria; /** * Created by abreen on 2015-09-03. */ public class InvalidCriteriaException extends Exception { public InvalidCriteriaException(String msg) { super(msg); } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.enhancers; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import net.datacrow.core.db.DatabaseManager; import net.datacrow.core.modules.DcModule; import net.datacrow.core.modules.DcModules; import net.datacrow.core.objects.DcField; import net.datacrow.core.resources.DcResources; import net.datacrow.util.DcSwingUtilities; import org.apache.log4j.Logger; /** * Auto numbering functionality. Applies a new number to the indicated number * field. * * @see IValueEnhancer * @author Robert Jan van der Waals */ public class AutoIncrementer implements IValueEnhancer { private static Logger logger = Logger.getLogger(AutoIncrementer.class.getName()); private boolean enabled = false; private boolean fillGaps = false; private int step = 1; private int field; /** * Creates a new instance. * @param field The field to which enhancements will be made. */ public AutoIncrementer(int field) { this.field = field; } /** * Creates a new instance. * @param field The field to which enhancements will be made. * @param enabled Indicates if this enhancer is enabled. * @param fillGaps Indicates if gaps in the numbering should be filled. * @param step The step size (amount to increase per number). */ public AutoIncrementer(int field, boolean enabled, boolean fillGaps, int step) { this.field = field; this.enabled = enabled; this.fillGaps = fillGaps; this.step = step; } @Override public String toSaveString() { return enabled + "/&/" + fillGaps + "/&/" + step; } @Override public boolean isEnabled() { return enabled; } public boolean isFillGaps() { return fillGaps; } public int getStep() { return step; } @Override public boolean isRunOnUpdating() { return false; } @Override public boolean isRunOnInsert() { return true; } @Override @SuppressWarnings("resource") public Object apply(DcField field, Object value) { Object result = value; DcModule module = DcModules.get(field.getModule()); int counter = 0; ResultSet rs = null; try { if (!fillGaps) { String query = "SELECT MAX(" + field.getDatabaseFieldName() + ") AS COUNTMAXIMUM FROM " + module.getTableName(); rs = DatabaseManager.executeSQL(query); int maximum = 0; while (rs.next()) { maximum = rs.getInt("COUNTMAXIMUM"); } result = Long.valueOf(maximum + getStep()); rs.close(); } else { counter = counter + getStep(); String qryCurrent = "SELECT " + field.getDatabaseFieldName() + " FROM " + module.getTableName() + " WHERE " + field.getDatabaseFieldName() + " IS NOT NULL AND " + field.getDatabaseFieldName() + " > 0 " + "ORDER BY 1"; Collection<Integer> currentValues = new ArrayList<Integer>(); rs = DatabaseManager.executeSQL(qryCurrent); while (rs.next()) currentValues.add(rs.getInt(field.getDatabaseFieldName())); if (currentValues.contains(counter)) { boolean currentfound = false; for (int x : currentValues) { while (!currentfound && x == counter) counter += getStep(); } } result = Long.valueOf(counter); } } catch (Exception e) { String msg = DcResources.getText("msgAutoNumberError", new String[] {field.getLabel(), e.getMessage()}); logger.error(msg, e); DcSwingUtilities.displayErrorMessage(msg); } try { if (rs != null) rs.close(); } catch (SQLException se) { logger.debug("Failed to close the database resources", se); } return result; } public int getField() { return field; } @Override public void parse(String s) { String tmp = s; String s1 = tmp.substring(0, tmp.indexOf("/&/")); tmp = tmp.substring(tmp.indexOf("/&/") + 3, tmp.length()); String s2 = tmp.substring(0, tmp.indexOf("/&/")); tmp = tmp.substring(tmp.indexOf("/&/") + 3, tmp.length()); String s3 = tmp; enabled = Boolean.valueOf(s1); fillGaps = Boolean.valueOf(s2); step = Integer.valueOf(s3); } @Override public int getIndex() { return ValueEnhancers._AUTOINCREMENT; } }
/* * Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.jet.contrib.connect; import com.hazelcast.jet.Job; import com.hazelcast.jet.config.JobConfig; import com.hazelcast.jet.core.JetTestSupport; import com.hazelcast.jet.pipeline.Pipeline; import com.hazelcast.jet.pipeline.test.AssertionCompletedException; import com.hazelcast.jet.pipeline.test.AssertionSinks; import org.apache.kafka.connect.data.Values; import org.junit.Ignore; import org.junit.Test; import java.util.Objects; import java.util.Properties; import java.util.concurrent.CompletionException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class KafkaConnectRandomIntIntegrationTest extends JetTestSupport { public static final int ITEM_COUNT = 10_000; @Ignore("This test fails because of resource upload permissions. Fix this test " + "after the default resource upload permissions are decided.") @Test public void readFromRandomSource() throws Exception { System.setProperty("hazelcast.logging.type", "log4j"); Properties randomProperties = new Properties(); randomProperties.setProperty("name", "random-source-connector"); randomProperties.setProperty("connector.class", "sasakitoa.kafka.connect.random.RandomSourceConnector"); randomProperties.setProperty("generator.class", "sasakitoa.kafka.connect.random.generator.RandomInt"); randomProperties.setProperty("tasks.max", "1"); randomProperties.setProperty("messages.per.second", "1000"); randomProperties.setProperty("topic", "test"); randomProperties.setProperty("task.summary.enable", "true"); Pipeline pipeline = Pipeline.create(); pipeline.readFrom(KafkaConnectSources.connect(randomProperties)) .withoutTimestamps() .map(record -> Values.convertToString(record.valueSchema(), record.value())) .writeTo(AssertionSinks.assertCollectedEventually(60, list -> assertEquals(ITEM_COUNT, list.size()))); JobConfig jobConfig = new JobConfig(); jobConfig.addJar(Objects.requireNonNull(this.getClass() .getClassLoader() .getResource("random-connector-1.0-SNAPSHOT.jar")) .getPath() ); Job job = createHazelcastInstance().getJet().newJob(pipeline, jobConfig); sleepAtLeastSeconds(5); try { job.join(); fail("Job should have completed with an AssertionCompletedException, but completed normally"); } catch (CompletionException e) { String errorMsg = e.getCause().getMessage(); assertTrue("Job was expected to complete with AssertionCompletedException, but completed with: " + e.getCause(), errorMsg.contains(AssertionCompletedException.class.getName())); } } }
package utils.tileboard; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Hashtable; import javax.imageio.ImageIO; /** * A BufferedImage-Based Tileboard * * This class contains all the tools needed to easily create a tiled base image * for use in graphics, or interactive games. The constructor allows the user * to either just set the image dimensions. Or optionally specify the tile dimensions * and/or amount of tiles to place. Note: tiles can be non-square. * * In order to draw tiles, the user should first call loadTile, which allows the user * to specify an ID for the tile as well as the file path. The ID is a string that * is paired with the image, so that the user can easily recall images to draw. * @author Nick Cheng * TODO: interface the tileboard for use with the movie clip/displaylist model * I think the best way to do this would be to extend MovieClip */ public class ImageTileboard extends BufferedImage implements Tileboard { private int WIDTH; private int HEIGHT; private int numRows = -1; private int numCols = -1; private int tileWidth = -1; private int tileHeight = -1; private Hashtable<String,BufferedImage> tileset; private Graphics2D graphics; private Boolean active; /** * Creates a tileboard. You must call setTileSize before you * can draw tiles. * @param width How wide in pixels the image should be * @param height How tall in pixels the image should be */ public ImageTileboard(int width, int height) { super(width, height, TYPE_INT_ARGB); WIDTH = width; HEIGHT = height; tileset = new Hashtable<String,BufferedImage>(10); graphics = this.createGraphics(); active = true; } /** * Creates a tileboard. * @param i_width How wide in pixels the image should be * @param i_height How tall in pixels the image should be * @param t_width How wide in pixels each tile is * @param t_height How tall in pixels each tile is */ public ImageTileboard(int i_width, int i_height, int t_width, int t_height) { super(i_width, i_height, TYPE_INT_ARGB); WIDTH = i_width; HEIGHT = i_height; tileset = new Hashtable<String,BufferedImage>(10); graphics = this.createGraphics(); active = true; setTileSize(t_width,t_height); } /** * Creates a tileboard. * Note: the constructor will fail if the user specifies more tiles than the * image dimensions can fit. * @param i_width How wide in pixels the image should be * @param i_height How tall in pixels the image should be * @param t_width How wide in pixels each tile is * @param t_height How tall in pixels each tile is * @param tilesX How many tiles there should be horizontally * @param tilesY How many tiles there should be vertically */ public ImageTileboard(int i_width, int i_height, int t_width, int t_height, int tilesX, int tilesY) { super(i_width, i_height, TYPE_INT_ARGB); if (t_width*tilesX > i_width || t_height*tilesY > i_height){ System.out.println("You cannot fit that many tiles."); return; } WIDTH = i_width; HEIGHT = i_height; tileset = new Hashtable<String,BufferedImage>(10); graphics = this.createGraphics(); active = true; tileWidth = t_width; tileHeight = t_height; numCols = tilesX; numRows = tilesY; } /** * This sets the dimensions of a tile in pixels * @param width The width of the tile in pixels * @param height The height of a tile in pixels */ @Override public void setTileSize(int width, int height) { tileWidth = width; tileHeight = height; numCols = WIDTH/width; numRows = HEIGHT/height; } /** * This will pair an ID with an image and load that image * into memory. This must be done before calling drawTile. * @param name The ID the user desires to use for easy recall * of the tile during drawTile * @param filepath A string representation of the path of an image the user * desires to load */ @Override public void loadTile(String name, String filepath) { if (active){ try { BufferedImage newBufferedImage = ImageIO.read(new File(filepath)); tileset.put(name, newBufferedImage); } catch (IOException e) { e.printStackTrace(); System.out.println("Could not load "+filepath); } }else{ System.out.println("Tileboard has been finalized."); } } /** * This will draw a tile onto the image at a given position * @param name The ID for the tile (specified in loadTile) * @param x The horizontal position to place the tile (in columns, not pixels) * @param y The vertical position to place the tile (in rows, not pixels) */ @Override public void drawTile(String name, int x, int y) { if (active){ if (x<0 || x>= numCols || y<0 || y>= numRows){ System.out.println("("+Integer.toString(x)+","+Integer.toString(y)+") is out of bounds"); return; } if (numRows == -1 || numCols == -1 || tileWidth == -1 || tileHeight == -1){ System.out.println("Board not initiliazed correctly. Check for setting of tilesize."); return; } if(tileset.containsKey(name)){ BufferedImage img = tileset.get(name); graphics.drawImage(img, x*tileWidth, y*tileHeight, null); }else{ System.out.println(name+" is not a loaded tile."); } }else{ System.out.println("Tileboard has been finalized."); } } /** * This will draw a tile onto the image at a given position * @param name The ID for the tile (specified in loadTile) * @param p The position to place the tile (column,row) */ @Override public void drawTile(String name, Point p) { drawTile(name,p.x,p.y); } /** * This will fill the entire board with a given tile * @param name The ID for the tile (specified in loadTile) */ @Override public void fillBoard(String name) { for(int i=0;i<numRows;i++){ for(int j=0;j<numCols;j++){ drawTile(name,j,i); } } } /** * If the board has been finalized it is no longer active and can no longer * be changed. This function lets the user know if the board is active. * @return Whether the board is active */ public boolean isAcive () { return active; } public void clearEverything() { graphics.setBackground(new Color(255,255,255,0)); graphics.clearRect(0, 0, WIDTH, HEIGHT); } /** * Free memory associated with updating graphics, while retaining the image * for future use. The image will no longer be active and can no longer be changed. */ public void finalizeImage(){ active = false; graphics.dispose(); } /** * Yields the width and height of the the board in columns and rows respectively * @return A point (number of columns, number of rows) */ @Override public Point getDimensions() { return new Point(numCols,numRows); } }
package guc.supermarket.tests; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import org.junit.Test; import static org.junit.Assert.*; import guc.supermarket.cart.Cart; import guc.supermarket.products.*; public class Lab3AllTests { String gPath = "guc.supermarket.products.GroceryProduct"; String bPath = "guc.supermarket.products.Beverage"; String dPath = "guc.supermarket.products.DairyProduct"; String cPath = "guc.supermarket.cart.Cart"; @Test(timeout = 1000) public void testClassIsAbstractGroceryProduct() throws NoSuchMethodException { assertTrue( "No object should be instantiated from class groceryProducts", Modifier.isAbstract(GroceryProduct.class.getModifiers())); } @Test public void testConstructorCart() throws Exception { Class.forName(cPath).getConstructor(); } @SuppressWarnings("unchecked") @Test public void testConstructorCartInitialization() throws Exception { Cart c = new Cart(); Field f = Cart.class.getDeclaredField("products"); f.setAccessible(true); ArrayList<GroceryProduct> products = (ArrayList<GroceryProduct>) f .get(c); assertNotNull( "The Cart constructor should initiallize the instance variables correctly.", products); } @Test public void testInstanceVariableCartProducts() throws Exception { testInstanceVariablesArePresent(Cart.class, "products", true); testInstanceVariableIsPrivate(Cart.class, "products"); } @Test public void testInstanceVariableCartProductsGetter() { testGetterMethodExistsInClass(Cart.class, "getProducts", ArrayList.class); } @Test public void testInstanceVariableCartProductsSetter() { testSetterMethodExistsInClass(Cart.class, "setProducts", ArrayList.class, false); } @Test(timeout = 1000) public void testMethodBeverageGetActualPrice2() { try { Beverage.class.getDeclaredMethod("getActualPrice", double.class); } catch (NoSuchMethodException e) { fail("The overloaded method getTotal(double extra) should be implemented in the Beverage class."); } } @Test (timeout = 1000) public void testMethodBeverageGetActualPrice2Logic() { Beverage b = new Beverage("Schweppes Pomegranate", 10, 5, SugarLevel.ADDED_SUGAR); assertEquals( "The overloaded method getTotal(double extra) should calculate the price after adding the voucher's extra discount to the original dicount.", 9, b.getActualPrice(5.0), 0.01); b = new Beverage("Schweppes Pomegranate", 20, 10, SugarLevel.ADDED_SUGAR); assertEquals( "The overloaded method getTotal(double extra) should calculate the price after adding the voucher's extra discount to the original dicount.", 18, b.getActualPrice(0.0), 0.01); } @Test public void testMethodBeverageRefrigerate() throws Exception { Beverage.class.getDeclaredMethod("refrigerate"); } @Test public void testMethodBeverageRefrigerateLogic() throws Exception { Beverage p = new Beverage("Schweppes Pomegranate", 10, 5, SugarLevel.ADDED_SUGAR); assertEquals("Beverages does not need to be kept in a refrigerator", false, p.refrigerate()); } @Test public void testMethodCartAddProduct() throws Exception { Cart.class.getDeclaredMethod("addProduct", GroceryProduct.class); } @SuppressWarnings("unchecked") @Test public void testMethodCartAddProductLogic() throws Exception { Cart c = new Cart(); Field f = Cart.class.getDeclaredField("products"); f.setAccessible(true); ArrayList<GroceryProduct> products = (ArrayList<GroceryProduct>) f .get(c); assertNotNull( "The Cart constructor should initiallize the instance variables correctly.", products); Beverage b = new Beverage("Schweppes Pomegranate", 10, 5, SugarLevel.ADDED_SUGAR); c.addProduct(b); products = (ArrayList<GroceryProduct>) f.get(c); assertEquals( "The method addProduct should add a product to the products of the cart.", 1, products.size()); assertEquals( "The method addProduct should add the passed product to the products of the cart.", b, products.get(0)); } @Test public void testMethodCartGetTotal1() throws Exception { Cart.class.getDeclaredMethod("getTotal"); } @Test public void testMethodCartGetTotal1Logic() throws Exception { Cart c = new Cart(); Beverage beverage = new Beverage("Schweppes Pomegranate", 10, 10, SugarLevel.ADDED_SUGAR); DairyProduct dairyProduct = new DairyProduct("Juhayna", 20, 5, Fat.FULLCREAM); ArrayList<GroceryProduct> products = new ArrayList<>(Arrays.asList( dairyProduct, beverage)); Field f = Cart.class.getDeclaredField("products"); f.setAccessible(true); f.set(c, products); assertEquals( "The getTotal method should return the total of summing up the actual price of the products in the cart.", 28, c.getTotal(), 0.001); } @Test(timeout = 1000) public void testMethodCartToStringLogic() throws Exception { Cart c = new Cart(); Beverage beverage = new Beverage("Schweppes Pomegranate", 10, 10, SugarLevel.ADDED_SUGAR); DairyProduct dairyProduct = new DairyProduct("Juhayna", 20, 5, Fat.FULLCREAM); ArrayList<GroceryProduct> products = new ArrayList<>(Arrays.asList( dairyProduct, beverage)); Field f = Cart.class.getDeclaredField("products"); f.setAccessible(true); f.set(c, products); String s = c.toString(); String t = s.toLowerCase(); String[] sa = t.split("\n"); assertTrue( "The \"Cart\" toString() method should return all infromation about the products seperated by 1 line.\nHint: you can use \"\\n\" in order to insert a line break in a String.\n" + s , sa.length==9 || sa.length == 10); assertTrue( "The \"Cart\" toString() method should return all infromation about the first product; the \"Name\" information is missing or incorrect.\n" + s, sa[0].contains("name") && sa[0].contains("juhayna")); assertTrue( "The \"Cart\" toString() method should return all infromation about the first product; the \"Price\" information is missing or incorrect.\n" + s, sa[1].contains("price") && sa[1].contains("" + 20)); assertTrue( "The \"Cart\" toString() method should return all infromation about the first product; the \"Discount\" information is missing or incorrect.\n" + s, sa[2].contains("discount") && sa[2].contains("" + 5)); assertTrue( "The \"Cart\" toString() method should return all infromation about the first product; the \"Fat Level\" information is missing or incorrect.\n" + s, sa[3].contains("fat") && sa[3].contains("level") && sa[3].contains("fullcream")); assertTrue( "The \"Beverage\" toString() method should return all infromation about the product; the \"Name\" information is missing or incorrect.\n" + s, sa[5].contains("name") && sa[5].contains("schweppes pomegranate")); assertTrue( "The \"Beverage\" toString() method should return all infromation about the product; the \"Price\" information is missing or incorrect.\n" + s, sa[6].contains("price") && sa[6].contains("" + 10)); assertTrue( "The \"Beverage\" toString() method should return all infromation about the product; the \"Discount\" information is missing or incorrect.\n" + s, sa[7].contains("discount") && sa[7].contains("" + 10)); assertTrue( "The \"Beverage\" toString() method should return all infromation about the product; the \"Sugar Level\" information is missing or incorrect.\n" + s, sa[8].contains("sugar") && sa[8].contains("level") && sa[8].contains("added_sugar")); } @Test public void testMethodDairyProductRefrigerate() throws Exception { DairyProduct.class.getDeclaredMethod("refrigerate"); } @Test public void testMethodDairyProductRefrigerateLogic() throws Exception { DairyProduct p = new DairyProduct("Juhayna", 20, 5, Fat.FULLCREAM); assertEquals("Dairy products need to be kept in a refrigerator", true, p.refrigerate()); } @Test public void testMethodGroceryProductRefrigerate() throws Exception { assertTrue( "A method that behaves completely differently in each subclass should be declared as abstract in the super class and implemented in each subclass.", Modifier.isAbstract(GroceryProduct.class.getMethod( "refrigerate", new Class[0]).getModifiers())); } @Test(timeout = 1000) public void testOverloading(){ assertTrue("The method \"getActualPrice(int extra)\" should be declared in the Beverage class", containsMethod(Beverage.class, "getActualPrice",new Class[]{double.class})); } @Test//(timeout = 1000) public void testEqualsDairyProductPolymorphism() { DairyProduct milk1= new DairyProduct("Juhayna Milk", 10, 5, Fat.FULLCREAM); DairyProduct milk2= new DairyProduct("Juhayna Milk", 10, 5, Fat.FULLCREAM); DairyProduct milk3= new DairyProduct("Labanita", 10, 5, Fat.FULLCREAM); DairyProduct milk4= new DairyProduct("Juhayna Milk", 9, 5, Fat.FULLCREAM); DairyProduct milk5= new DairyProduct("Juhayna Milk", 9, 25, Fat.FULLCREAM); DairyProduct milk6= new DairyProduct("Juhayna Milk", 9, 25, Fat.SKIMMED); assertTrue("The two instances are equal", milk1.equals(milk2)); assertFalse("The two instances are not equal, they have different names", milk1.equals(milk3)); assertFalse("The two instances are not equal, they have different prices", milk1.equals(milk4)); assertFalse("The two instances are not equal, they have different discounts", milk1.equals(milk5)); assertFalse("The two instances are not equal, they have different fat levels", milk1.equals(milk6)); } //equals -> Beverage //equals -> Dairy //private @Test(timeout = 1000) public void testEqualsBeveragePolymorphism() { assertTrue("The method \"equals\" should be declared in the GroceryProduct class", containsMethod(GroceryProduct.class, "equals", new Class[]{Object.class})); assertTrue("The method \"equals\" should be declared in the DairyProduct class", containsMethod(DairyProduct.class, "equals", new Class[]{Object.class})); assertTrue("The method \"equals\" should be declared in the Beverage class", containsMethod(Beverage.class, "equals", new Class[]{Object.class})); Beverage beverage1= new Beverage("Schweppes Pomegranate", 10, 5, SugarLevel.ADDED_SUGAR); Beverage beverage2= new Beverage("Schweppes Pomegranate", 10, 5, SugarLevel.ADDED_SUGAR); Beverage beverage3= new Beverage("Sprite", 10, 5, SugarLevel.ADDED_SUGAR); Beverage beverage4= new Beverage("Schweppes Pomegranate", 9, 5, SugarLevel.ADDED_SUGAR); Beverage beverage5= new Beverage("Schweppes Pomegranate", 9, 25, SugarLevel.ADDED_SUGAR); Beverage beverage6= new Beverage("Schweppes Pomegranate", 9, 25, SugarLevel.ADDED_SUGAR); assertTrue("The two instances are equal", beverage1.equals(beverage2)); assertFalse("The two instances are not equal, they have different names", beverage1.equals(beverage3)); assertFalse("The two instances are not equal, they have different prices", beverage1.equals(beverage4)); assertFalse("The two instances are not equal, they have different discounts", beverage1.equals(beverage5)); assertFalse("The two instances are not equal, they have different fat levels", beverage1.equals(beverage6)); } //equals -> diff types //private @Test(timeout = 1000) public void testEqualsPolymorphism() { DairyProduct milk= new DairyProduct("Juhayna Milk", 10, 5, Fat.FULLCREAM); Beverage beverage= new Beverage("Schweppes Pomegranate", 10, 5, SugarLevel.ADDED_SUGAR); assertFalse("When comparing different types of grocery products, the method should return false with no exception", milk.equals(beverage)); assertFalse("When comparing different types of grocery products, the method should return false with no exception", beverage.equals(milk)); } // ===============================================Helpers @SuppressWarnings("rawtypes") private void testInstanceVariablesArePresent(Class aClass, String varName, boolean implementedVar) throws SecurityException { boolean thrown = false; try { aClass.getDeclaredField(varName); } catch (NoSuchFieldException e) { thrown = true; } if (implementedVar) { assertFalse("There should be " + varName + " instance variable in class " + aClass.getName(), thrown); } else { assertTrue("There should not be " + varName + " instance variable in class " + aClass.getName() + ", it should be inherited from the super class", thrown); } } @SuppressWarnings("rawtypes") private void testInstanceVariableIsPrivate(Class aClass, String varName) throws NoSuchFieldException, SecurityException { Field f = aClass.getDeclaredField(varName); assertEquals( varName + " instance variable in class " + aClass.getName() + " should not be accessed outside that class", 2, f.getModifiers()); } @SuppressWarnings({ "unchecked", "rawtypes" }) private void testGetterMethodExistsInClass(Class aClass, String methodName, Class returnedType) { Method m = null; boolean found = true; try { m = aClass.getDeclaredMethod(methodName); } catch (NoSuchMethodException e) { found = false; } String varName = methodName.substring(3).toLowerCase(); assertTrue( "The " + varName + " instance variable in class " + aClass.getName() + " is a READ variable.", found); assertTrue("incorrect return type for " + methodName + " method in " + aClass.getName() + " class.", m.getReturnType() .isAssignableFrom(returnedType)); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void testSetterMethodExistsInClass(Class aClass, String methodName, Class inputType, boolean writeVariable) { Method[] methods = aClass.getDeclaredMethods(); String varName = methodName.substring(3).toLowerCase(); if (writeVariable) { assertTrue("The " + varName + " instance variable in class " + aClass.getName() + " is a WRITE variable.", containsMethodName(methods, methodName)); } else { assertFalse("The " + varName + " instance variable in class " + aClass.getName() + " is a READ ONLY variable.", containsMethodName(methods, methodName)); return; } Method m = null; boolean found = true; try { m = aClass.getDeclaredMethod(methodName, inputType); } catch (NoSuchMethodException e) { found = false; } assertTrue(aClass.getName() + " class should have " + methodName + " method that takes one " + inputType.getSimpleName() + " parameter", found); assertTrue("incorrect return type for " + methodName + " method in " + aClass.getName() + ".", m.getReturnType().equals(Void.TYPE)); } private static boolean containsMethodName(Method[] methods, String name) { for (Method method : methods) { if (method.getName().equals(name)) return true; } return false; } public static boolean containsMethod(Class c, String name, Class[] parameters){ try{ c.getDeclaredMethod(name, parameters); return true; } catch(NoSuchMethodException e){ return false; } } }
package automationFramework; import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import pageObjects.HomePage; import pageObjects.LoginPage; public class POM_TC { private static WebDriver driver=null; public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\Jeevakumar\\eclipse-workspace\\Selenium_Dependencies\\chromedriver.exe"); driver=new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("http://www.store.demoqa.com"); HomePage.lnk_MyAccount(driver).click(); LoginPage.txtbx_UserName(driver).sendKeys("testuser_1"); LoginPage.txtbx_Password(driver).sendKeys("Test@123"); LoginPage.btn_LogIn(driver).click(); System.out.println("Login Successful, Time to Log off"); HomePage.lnk_Account(driver).click(); driver.quit(); } }
package us.gibb.dev.gwt.demo.server; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import us.gibb.dev.gwt.command.results.StringResult; import us.gibb.dev.gwt.demo.client.command.GetHelloCommand; import us.gibb.dev.gwt.demo.client.command.HelloResult; import us.gibb.dev.gwt.demo.client.command.SayHelloCommand; import us.gibb.dev.gwt.demo.model.Hello; import us.gibb.dev.gwt.server.command.handler.Context; import us.gibb.dev.gwt.server.command.handler.MultiCommandHandler; @Service("helloCommandHandler") //@Component("helloCommandHandler") //@Scope("request") public class HelloCommandHandlerImpl extends MultiCommandHandler implements HelloCommandHandler { @PersistenceContext private EntityManager em; public HelloCommandHandlerImpl() { } @Transactional public StringResult sayHello(SayHelloCommand command, Context context) { try { EntityTransaction tx = em.getTransaction(); tx.begin(); Hello hello = new Hello(); hello.setName(command.getName()); hello.setCreatedDate(new Date()); em.persist(hello); tx.commit(); em.close(); return new StringResult(hello.toString()); } catch (Exception e) { e.printStackTrace(); } return null; } @SuppressWarnings("unchecked") public HelloResult getHello(GetHelloCommand command, Context context) { Query query = em.createQuery("select q from Hello q where q.name = :name order by q.createdDate desc"); query.setMaxResults(1); //only get the latest query.setParameter("name", command.getName()); List<Hello> results = query.getResultList(); if (results == null || results.isEmpty()) { return new HelloResult(null); } return new HelloResult(results.get(0)); } }
package edu.erlm.epi.repository.exercise; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import edu.erlm.epi.domain.exercise.File; public interface FileRepository extends JpaRepository<File, Long> { @Query("select file from File file where file.teachingExerciseId = :teachingExerciseId") List<File> findByTeachingExerciseId(@Param("teachingExerciseId")Long teachingExerciseId); }
package com.example.simpledashcam; import android.app.Service; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Process; import android.util.Log; import android.webkit.MimeTypeMap; import com.google.api.client.auth.oauth.OAuthHmacSigner; import com.google.api.client.auth.oauth.OAuthParameters; import com.google.api.client.http.FileContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpMediaType; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.MultipartContent; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.common.io.CharStreams; import java.io.File; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Files; public class UploadFileService extends Service { private ServiceHandler serviceHandler; static final String LOG_TYPE = "UploadFileService"; protected String apiKey; protected String apiSecret; protected String accessToken; protected String tokenSecret; // Handler that receives messages from the thread private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(final Message msg) { if (apiKey == null) { Log.e(LOG_TYPE, "User not logged in, service exiting!"); stopSelf(); } else { final File fileToUpload = (File)msg.obj; Log.i(LOG_TYPE, "Service received file: " + fileToUpload.getPath() + " size: " + fileToUpload.length() + " to upload."); if (uploadFile(fileToUpload)) { deleteFile(fileToUpload); } // Stop the service using the startId, so that we don't stop // the service in the middle of handling another job stopSelf(msg.arg1); } } } @Override public void onCreate() { String url = FlickrLoginProvider.URL; Uri flickrLogin = Uri.parse(url); Cursor c = getContentResolver().query( flickrLogin, null, null, null ); if (c.getCount() > 0) { if (c.moveToFirst()) { apiKey = c.getString(c.getColumnIndex(FlickrLoginProvider.API_KEY)); apiSecret = c.getString(c.getColumnIndex(FlickrLoginProvider.API_KEY_SECRET)); accessToken = c.getString(c.getColumnIndex(FlickrLoginProvider.ACCESS_TOKEN)); tokenSecret = c.getString(c.getColumnIndex(FlickrLoginProvider.TOKEN_SECRET)); } } HandlerThread thread = new HandlerThread("UploadFileServiceThread", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); // Get the HandlerThread's Looper and use it for our Handler Looper serviceLooper = thread.getLooper(); serviceHandler = new ServiceHandler(serviceLooper); Log.i(LOG_TYPE, "Service created."); c.close(); } public UploadFileService() { } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { Log.i(LOG_TYPE, "My watch has ended!"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // For each start request, send a message to start a job and deliver the // start ID so we know which request we're stopping when we finish the job Message msg = serviceHandler.obtainMessage(); msg.arg1 = startId; if (null != intent.getStringExtra(PrepareFileService.UPLOAD_FILE_URI)) { msg.obj = new File(intent.getStringExtra(PrepareFileService.UPLOAD_FILE_URI)); } serviceHandler.sendMessage(msg); // If we get killed, after returning from here, restart return START_STICKY; } private boolean uploadFile(File file) { try { OAuthParameters parameters = new OAuthParameters(); parameters.consumerKey = apiKey; OAuthHmacSigner hmacSigner = new OAuthHmacSigner(); hmacSigner.clientSharedSecret = apiSecret; hmacSigner.tokenSharedSecret = tokenSecret; parameters.signer = hmacSigner; parameters.token = accessToken; parameters.computeNonce(); parameters.computeTimestamp(); NetHttpTransport transport = new NetHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(parameters); GenericUrl genericUrl = new GenericUrl(StartPage.FLICKR_UPLOAD_ENDPOINT); genericUrl.set("format", "json") .set("nojsoncallback", 1); FileContent fileContent = new FileContent(getMimeType(file.getPath()), file); MultipartContent multipartContent = new MultipartContent() .setMediaType( new HttpMediaType("multipart/form-data") .setParameter("boundary", "__END_OF_PART__")); MultipartContent.Part part = new MultipartContent.Part(fileContent); part.setHeaders(new HttpHeaders().set( "Content-Disposition", String.format("form-data; name=\"photo\"; filename=\"%s\"", file.getAbsolutePath()))); Log.i(StartPage.LOG_TYPE_FLICKR, "Upload mimetype: " + getMimeType(file.getPath())); Log.i(StartPage.LOG_TYPE_FLICKR, "Upload absfilepath: " + file.getAbsolutePath()); multipartContent.addPart(part); HttpRequest request = requestFactory.buildPostRequest(genericUrl, multipartContent); Log.i(StartPage.LOG_TYPE_FLICKR, "HTTP Request: " + request.getHeaders().toString()); HttpResponse response = request.execute(); String textResponse = null; try (Reader reader = new InputStreamReader(response.getContent())) { textResponse = CharStreams.toString(reader); } Log.i(StartPage.LOG_TYPE_FLICKR, "Upload response: " + textResponse); return response.getStatusCode() == 200; } catch (Exception e) { Log.e(StartPage.LOG_TYPE_FLICKR, "Failed upload to Flickr: " + e.toString()); return false; } } /** * * @param file */ private void deleteFile(File file) { Log.i(StartPage.LOG_TYPE_FLICKR, "Deleting file post upload: " + file.getPath()); boolean deleted = file.delete(); File parentDir = file.getParentFile(); try { if (Files.isDirectory(parentDir.toPath())) { if (!Files.list(parentDir.toPath()).findAny().isPresent()) { Log.i(StartPage.LOG_TYPE_FLICKR, "Deleting empty dir post upload: " + parentDir.getPath()); boolean deletedDir = parentDir.delete(); } } } catch (Exception e) { Log.e(StartPage.LOG_TYPE_FLICKR, "Failed to delete dir: " + parentDir.getPath()); } } public static String getMimeType(String url) { String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(url); if (extension != null) { type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } return type; } }
/* * 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. */ /** * * @author mati */ public class Ej1 { public static void main (String args[]) { System.out.println("Pablo Torrecillas"); System.out.println("14/08/87"); } }
package com.qqq.stormy.model; import com.qqq.stormy.R; import java.util.HashMap; import java.util.Map; public class IconManager { private static String[] mIconsNames = {"clear-day", "clear-night", "rain", "snow", "sleet", "wind", "fog", "cloudy", "partly-cloudy-day", "partly-cloudy-night"}; private static int[] mIconsId = {R.drawable.clear_day, R.drawable.clear_night, R.drawable.rain, R.drawable.snow, R.drawable.fog, R.drawable.sleet, R.drawable.wind, R.drawable.fog, R.drawable.cloudy, R.drawable.partly_cloudy, R.drawable.cloudy_night}; public static int getIconId(String iconName) { for (int i = 0; i < mIconsNames.length; i++) { if (iconName.equals(mIconsNames[i])) { return mIconsId[i]; } } return R.drawable.partly_cloudy; } }
/** * $Id: AddMusicianFrame.java,v 1.2 2005/09/08 15:37:40 nicks Exp $ * * Based on AddConstituentFrame, this one's for adding Musicians * (i.e. orchestra members) to the roster. (Did you honestly * need me to tell you that?) * * Originally part of the AMATO application. * * @author Nick Seidenman <nick@seidenman.net> * @version $Revision: 1.2 $ * * $Log: AddMusicianFrame.java,v $ * Revision 1.2 2005/09/08 15:37:40 nicks * Seasons, Productions, Performances, Constituents, and Operas are now * all editable! * * Revision 1.1 2005/08/02 21:39:59 nicks * Initial revision * * */ import java.util.*; import java.io.*; import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class AddMusicianFrame extends AddConstituentFrame { private static final long serialVersionUID = 20050802143000L; private static ListEditorTextField instruments; public AddMusicianFrame () { super ("Add Musician"); JPanel vp = new JPanel (new FlowLayout ()); instruments = new ListEditorTextField (); vp.setBorder (BorderFactory.createTitledBorder ("Instrument(s)")); vp.add (instruments); injectPanel (vp); realize (); } public Constituent addMap (HashMap<String,String> h) { h.put ("instrument", instruments.toString ()); return (Constituent) new Musician (h); } /** * After creating the frame, use this method to populate it * with values from an existing Musician instance. This way * we can edit the entries. */ public void populate (Musician s) { super.populate ((Constituent) s); instruments.add (s.getInstrumentsArray()); } static public void main (String[] args) { AddMusicianFrame asf = new AddMusicianFrame (); } }
package bms; public class Persona { private double altezza; private double peso; private int anni; private String attivitaFisica; private char sesso; public Persona(double altezza, double peso, int anni, String attivitaFisica, char sesso) { this.altezza = altezza; this.peso = peso; this.anni = anni; this.attivitaFisica = attivitaFisica; this.sesso = sesso; } public double getAltezza() { return this.altezza; } public double getPeso() { return this.peso; } public int getAnni(){ return this.anni; } public String getAttivitaFisica() { return this.attivitaFisica; } public char getSesso() { return this.sesso; } public String stampaDettagli() { return "Altezza: " + this.getAltezza() + "|| peso: " + this.getPeso() + "|| anni: " + this.getAnni() + "|| attivitą fisica: " + this.getAttivitaFisica() + "|| sesso: " + this.getSesso(); } }
package com.dian.diabetes.activity.indicator; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Calendar; import java.util.List; import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import org.achartengine.chart.PointStyle; import org.achartengine.model.XYMultipleSeriesDataset; import org.achartengine.model.XYSeries; import org.achartengine.renderer.XYMultipleSeriesRenderer; import org.achartengine.renderer.XYSeriesRenderer; import android.graphics.Color; import android.graphics.Paint.Align; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.LinearLayout.LayoutParams; import com.dian.diabetes.R; import com.dian.diabetes.activity.eat.TotalBaseFragment; import com.dian.diabetes.db.dao.IndicateValue; import com.dian.diabetes.tool.Config; import com.dian.diabetes.utils.DateUtil; import com.dian.diabetes.widget.MutiProgress; import com.dian.diabetes.widget.anotation.ViewInject; public class PressChartFragment extends TotalBaseFragment implements OnClickListener { @ViewInject(id = R.id.weight_target_label) private TextView targetLabel; @ViewInject(id = R.id.trend_label) private TextView trendLabel; @ViewInject(id = R.id.trend_suggest) private TextView trendSuggest; @ViewInject(id = R.id.trend_suggest) private TextView unionView; @ViewInject(id = R.id.chart) private RelativeLayout chart; @ViewInject(id = R.id.target) private TextView targetValue; @ViewInject(id = R.id.avg_progress) private MutiProgress avgProgress; @ViewInject(id = R.id.close_press) private TextView closePressView; @ViewInject(id = R.id.open_press) private TextView openPressView; @ViewInject(id = R.id.trend_img) private ImageView trendImg; @ViewInject(id = R.id.trend_value) private TextView trendValue; @ViewInject(id = R.id.sugar_effect) private ImageView sugarEffect; // chart private XYMultipleSeriesDataset dataSet; private XYMultipleSeriesRenderer mRenderer; private IndicatorActivity activity; private GraphicalView lineChart; private DecimalFormat format; private boolean isCreate = false; private DetailFragment parentFragment; private float[] alignmentOpen, alignmentClose; private int size = 0, level = 0, level1 = 0; private float total = 0, total1 = 0, increse = 1; public static PressChartFragment getInstance() { PressChartFragment fragment = new PressChartFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activity = (IndicatorActivity) getActivity(); parentFragment = (DetailFragment) getParentFragment(); dataSet = new XYMultipleSeriesDataset(); format = new DecimalFormat("0"); getRender(); XYSeries series = new XYSeries("舒张压线"); dataSet.addSeries(series); XYSeries series1 = new XYSeries("收缩压线"); dataSet.addSeries(series1); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_press_chart, container, false); fieldView(view); initView(view); return view; } private void initView(View view) { targetValue.setOnClickListener(this); alignmentOpen = new float[] { 90, Config.getFloatPro("highOpenPress") }; alignmentClose = new float[] { 60, Config.getFloatPro("highClosePress") }; if (!isCreate) { new DataTask().execute(); } loadChart(); } @SuppressWarnings("deprecation") private void loadChart() { lineChart = ChartFactory.getLineChartView(context, dataSet, mRenderer); chart.addView(lineChart, 0, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); } private void loadChartData() { int[] levelColor = { getResources().getColor(R.color.trend_down_bad), getResources().getColor(R.color.trend_down_normal), getResources().getColor(R.color.trend_up_bad) }; float[] temp = new float[]{alignmentOpen[1],alignmentClose[1]}; mRenderer.setAlign(temp); mRenderer.setAlignColors(levelColor); targetValue.setText(format.format(alignmentClose[1]) + "/" + format.format(alignmentOpen[1])); mRenderer.setAlignLineColor(Color.rgb(120, 253, 100)); // 数值写入 int[] levelColor1 = { getResources().getColor(R.color.trend_down_normal), getResources().getColor(R.color.trend_down_bad), getResources().getColor(R.color.trend_up_bad) }; if (size == 0) { avgProgress.setValue(0, 0, alignmentOpen[1], levelColor1[level1], levelColor1[level]); closePressView.setText("0"); openPressView.setText("0"); } else { avgProgress.setValue(total1, total, alignmentOpen[1], levelColor1[level], levelColor1[level1]); openPressView.setText(format.format(total1)); openPressView.setTextColor(levelColor1[level1]); closePressView.setText(format.format(total)); closePressView.setTextColor(levelColor1[level]); } lineChart.repaint(); if (increse < -0.25) { trendValue.setTextColor(getResources().getColor( R.color.trend_down_bad)); trendImg.setImageResource(R.drawable.trend_down_normal); sugarEffect.setImageResource(R.drawable.icon_sugar_bad); } else if (increse < 0) { trendValue.setTextColor(getResources().getColor( R.color.trend_down_normal)); trendImg.setImageResource(R.drawable.trend_down_good); sugarEffect.setImageResource(R.drawable.icon_sugar_normal); } else if (increse < 0.25) { trendValue.setTextColor(getResources().getColor( R.color.trend_up_normal)); trendImg.setImageResource(R.drawable.trend_up_normal); sugarEffect.setImageResource(R.drawable.icon_sugar_good); } else if (increse < 0.5) { trendValue.setTextColor(getResources().getColor( R.color.trend_up_more)); trendImg.setImageResource(R.drawable.trend_up_more); sugarEffect.setImageResource(R.drawable.icon_sugar_normal); } else { trendValue.setTextColor(getResources().getColor( R.color.trend_up_bad)); trendImg.setImageResource(R.drawable.trend_up_bad); sugarEffect.setImageResource(R.drawable.icon_sugar_bad); } trendValue.setText(((int) (increse * 100)) * 1.0f + "%"); } public boolean onBackKeyPressed() { activity.startIndicateList(); return true; } private class DataTask extends AsyncTask<Object, Object, Object> { private List<IndicateValue> listData; @Override protected Object doInBackground(Object... arg0) { listData = parentFragment.getData(); size = listData.size(); return null; } @Override protected void onPostExecute(Object result) { mRenderer.clearXTextLabels(); dataSet.clear(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, parentFragment.getDay()); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); float value1 = 0, value2 = 0, max = 0, itemValue = 0, itemValue1 = 0; XYSeries series = new XYSeries("舒张压线"); XYSeries series1 = new XYSeries("收缩压线"); String day = ""; int index = 0, delta = -parentFragment.getDelta(), indicateIndex = 0, temp = 0; int preMonth = -1; for (int i = 0; i > parentFragment.getDay(); i--) { index++; calendar.add(Calendar.DATE, 1); int tempMonth = calendar.get(Calendar.MONTH); day = DateUtil.parseToString(calendar.getTime(), DateUtil.yyyyMMdd); for (int j = indicateIndex; j < listData.size(); j++) { IndicateValue value = listData.get(j); String itemDay = DateUtil.parseToString( value.getUpdate_time(), DateUtil.yyyyMMdd); if (day.equals(itemDay)) { if (itemValue != 0) { itemValue = (itemValue + value.getValue()) / 2; itemValue1 = (itemValue1 + value.getValue1()) / 2; } else { itemValue = value.getValue(); itemValue1 = value.getValue1(); } indicateIndex++; } else { break; } if (j < listData.size() / 2) { value1 = (value1 + value.getValue()) / 2; } else { value2 = (value2 + value.getValue()) / 2; } } if (index == delta || i == (parentFragment.getDay() + 1)) { String dayout; if(tempMonth == preMonth){ dayout = DateUtil.parseToString(calendar.getTime(), DateUtil.dd); }else{ dayout = DateUtil.parseToString(calendar.getTime(), DateUtil.MMdd); } preMonth = tempMonth; series.add(temp, itemValue); series1.add(temp, itemValue1); max = Math.max(itemValue, max); max = Math.max(itemValue1, max); mRenderer.addXTextLabel(temp, dayout); index = 0; itemValue = 0; itemValue1 = 0; temp++; } } max = Math.max(max, alignmentOpen[1]); mRenderer.setXAxisMin(0); mRenderer.setXAxisMax(temp - 1); mRenderer.setYAxisMax(max + max / 2); dataSet.addSeries(series); dataSet.addSeries(series1); increse = value1 == 0 ? 0 : (value2 - value1) / value1; if (size == 0) { total = 0; } else { IndicateValue value = listData.get(listData.size() - 1); total = value.getValue(); level = value.getLevel(); total1 = value.getValue1(); level1 = value.getLevel1(); } loadChartData(); } } @Override public void notifyData() { new DataTask().execute(); } private XYMultipleSeriesRenderer getRender() { if (mRenderer != null) { return mRenderer; } float size = getResources().getDimension(R.dimen.text_size_12); mRenderer = new XYMultipleSeriesRenderer(); mRenderer .setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL); mRenderer.setYAxisMin(0);// 设置y轴最小值是0 mRenderer.setYAxisMax(30); mRenderer.setZoomEnabled(false, false); mRenderer.setPanEnabled(false, false); mRenderer.setShowGrid(true); mRenderer.setYLabelsPadding(10); mRenderer.setLabelsTextSize(size); mRenderer.setAxisTitleTextSize(size); mRenderer.setLegendTextSize(size); mRenderer.setXLabelsAlign(Align.CENTER); mRenderer.setYLabelsAlign(Align.LEFT); mRenderer.setLabelsColor(Color.BLACK); mRenderer.setShowAxes(false); mRenderer.setShowLegend(false); mRenderer.setShowLabels(true); mRenderer.setApplyBackgroundColor(true); mRenderer.setBackgroundColor(Color.WHITE); mRenderer.setMarginsColor(Color.WHITE); mRenderer.setXLabelsPadding(getResources().getDimension( R.dimen.text_size_14)); // 画一条线 XYSeriesRenderer r = new XYSeriesRenderer();// (类似于一条线对象) r.setColor(Color.rgb(136, 204, 153));// 设置颜色 r.setPointStyle(PointStyle.POINT);// 设置点的样式 r.setDisplayChartValues(true); r.setDisplayChartValuesDistance(1); r.setChartValuesTextSize(size); r.setChartValuesFormat(NumberFormat.getInstance()); r.setFillBelowLine(true);// 是否填充折线图的下方 r.setFillBelowLineColor(Color.argb(40, 136, 204, 153));// 填充的颜色,如果不设置就默认与线的颜色一致 r.setLineWidth(2);// 设置线宽 mRenderer.addSeriesRenderer(r); mRenderer.addSeriesRenderer(r); return mRenderer; } @Override public void onClick(View view) { switch (view.getId()) { case R.id.target: toTargetSet(); break; } } private void toTargetSet() { String tag = "press_target_set"; FragmentManager manager = context.getSupportFragmentManager(); PressSetFragment tempFragment = (PressSetFragment) context .getSupportFragmentManager().findFragmentByTag(tag); if (tempFragment == null) { tempFragment = PressSetFragment.getInstance(); tempFragment.setCallBack(new PressSetFragment.CallBack() { @Override public void callBack(float lowValue, float highValue) { targetValue.setText(lowValue + "/" + highValue); alignmentClose[1] = lowValue; alignmentOpen[1] = highValue; loadChartData(); } }); } tempFragment.show(manager, tag); } }
package com.java.log; import com.java.log.impl.ILoggerImpl; public class LogFactory { public static ILogger getLogger(Class<?> invokeClass){ return new ILoggerImpl(invokeClass); } }
package cn.jpush.impl.applist; public class UidPackageVO { public String uid; public String packageStr; public void setUid(String uid) { this.uid = uid; } public void setPackageStr(String packageStr) { this.packageStr = packageStr; } public String getUid() { return uid; } public String getPackageStr() { return packageStr; } public UidPackageVO(String uid, String packageStr) { this.uid = uid; this.packageStr = packageStr; } }
package data_manager; import java.io.Serializable; /** * container for system device */ public class Device implements Serializable{ private static final long serialVersionUID = 1L; // user friendly name private String name; // system identifier private String systemIdName; /** * constructor for a device * @param name user friendly name (i.e functionality in the system) * @param systemIdName Id of the device (e.g "COM1") */ public Device(String name, String systemIdName) { this.name = name; this.systemIdName = systemIdName; } /** * @return user friendly name of the device */ public String getName() { return name; } /** * set name * @param name user friendly name */ public void setName(String name) { this.name = name; } /** * * @return system identifier for the device */ public String getSystemIdName() { return systemIdName; } /** * set system identifier * @param systemIdName system identifier */ public void setSystemIdName(String systemIdName) { this.systemIdName = systemIdName; } }
package co.id.datascrip.mo_sam_div4_dts1.littlefluffy; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.util.Date; import java.util.concurrent.TimeUnit; import co.id.datascrip.mo_sam_div4_dts1.Function; import co.id.datascrip.mo_sam_div4_dts1.Global; import co.id.datascrip.mo_sam_div4_dts1.SessionManager; import co.id.datascrip.mo_sam_div4_dts1.object.BEX; import co.id.datascrip.mo_sam_div4_dts1.process.interfaces.IC_Kegiatan; import co.id.datascrip.mo_sam_div4_dts1.sqlite.KegiatanSQLite; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class LocationReceiver extends BroadcastReceiver { private static boolean isRegistered; @Override public void onReceive(Context context, Intent intent) { Log.d("LocBroadcastReceiver", "onReceive: received location update"); final LocationInfo locationInfo = (LocationInfo) intent.getSerializableExtra(LocationLibraryConstants.LOCATION_BROADCAST_EXTRA_LOCATIONINFO); SessionManager sessionManager = new SessionManager(context); KegiatanSQLite kegiatanSQLite = new KegiatanSQLite(context); BEX bex = sessionManager.getUserLogin(); locationInfo.refresh(context); int id_kegiatan = kegiatanSQLite.getCurrentCheckIn(); if (!((id_kegiatan == 0) || bex.getEmpNo() == null)) Send_Position(context, makeJSON(String.valueOf(id_kegiatan), bex.getInitial(), bex.getEmpNo(), String.valueOf(locationInfo.lastLat), String.valueOf(locationInfo.lastLong))); sessionManager.setLastLocation(new Date(), locationInfo.lastLat, locationInfo.lastLong); } public void Send_Position(Context context, String json) { IC_Kegiatan IC = Global.CreateRetrofit(context).create(IC_Kegiatan.class); IC.SendPosition(json).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function().writeToText("LocationReceive->SendPosition", throwable.getMessage()); } }); } private String makeJSON(String id_kegiatan, String bex_initial, String bex_no, String latitude, String longitude) { JSONObject json = new JSONObject(); try { json.put("id", id_kegiatan); json.put("lat", latitude); json.put("lang", longitude); json.put("bex", bex_initial); json.put("bex_no", bex_no); } catch (JSONException e) { new Function().writeToText("position_json", e.toString()); } return json.toString(); } public Intent register(Context context, IntentFilter intentFilter) { if (isRegistered) { unregister(context); } isRegistered = true; return context.registerReceiver(this, intentFilter); } public boolean unregister(Context context) { if (isRegistered) { context.unregisterReceiver(this); isRegistered = false; return true; } return false; } private boolean sendEnable(Context context, LocationInfo locationInfo) { SessionManager sm = new SessionManager(context); double lastLat = sm.getLastLocation().latitude; double lastLong = sm.getLastLocation().longitude; Date dateNow = new Date(); Date dateLast = new Date(sm.getLastLocationTime()); int diffMinute = (int) TimeUnit.MINUTES.toMinutes(dateNow.getTime() - dateLast.getTime()); if (locationInfo.lastLat != 0 && locationInfo.lastLong != 0) { if (lastLat != locationInfo.lastLat && lastLong != locationInfo.lastLong) { return true; } else if (diffMinute >= 0) { return true; } } return false; } }
package com.fods.psp_bt; import java.util.Random; /** * Created by User on 2017-12-17. */ public class Generator { public static int[] generateRandom(int array_size){ int[] sk = new int[array_size]; Random rand = new Random(); for(int i = 0;i < sk.length;i++){ //sk[i] = rand.nextInt(65535); //sk[i] = rand.nextInt(35535); sk[i] = RandomInteger(35535,65535, rand); } int pick = 35535; for(int i = 0;i < sk.length/265;i++){ if( i > (sk.length/265)/2 ) { //pick = pick - (i*2); }else{ pick = pick - (i*2); } sk[array_size/2+i] = pick; } return sk; } private static int RandomInteger(int aStart, int aEnd, Random aRandom){ if (aStart > aEnd) { throw new IllegalArgumentException("Start cannot exceed End."); } //get the range, casting to long to avoid overflow problems long range = (long)aEnd - (long)aStart + 1; // compute a fraction of the range, 0 <= frac < range long fraction = (long)(range * aRandom.nextDouble()); return (int)(fraction + aStart); } public static int[] generateStrait(int array_size){ int[] sk = new int[array_size]; for(int i = 0;i<array_size;i++){ if(i >= 65535){ sk[i] = 65535; } else{ sk[i] = i; } } return sk; } public static int[] generateLog(int array_size){ int[] sk = new int[100000]; int check = 0; for(int i = 0;i<array_size;i++){ if(i != 0){ check = 2/i; if(check >= 65535){ sk[i] = 65535; } else { sk[i] = 2/i; } } else{ sk[i] = 0; } } return sk; } public static int[] generateSin(int array_size){ int[] sk = new int[array_size]; int check = 0; for(int i = 0;i<array_size;i++){ check = (int) ((Math.sin(i) + 2) * 2); if(check < 0){ sk[i] = 0; } else{ if(check >= 65535){ sk[i] = 65535; } else{ sk[i] = check; } } } return sk; } }
package com.example.dagger2mvpdemo.utils; import android.text.TextUtils; import com.example.dagger2mvpdemo.base.ResultCallback; import com.example.dagger2mvpdemo.common.APIService; import com.example.dagger2mvpdemo.common.Api; import com.google.gson.Gson; import java.util.Map; import java.util.concurrent.TimeUnit; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.http.Url; /** * @author 时志邦 * @CreateDate 2017/11/16 15:16 * @Description: ${TODO}(用一句话描述该文件做什么) */ public class RetrofitManager { private volatile static RetrofitManager retrofitManager; private final Retrofit retrofit; private Gson gson; private RetrofitManager() { gson = new Gson(); OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(8000, TimeUnit.SECONDS) //设置连接超时时间 .readTimeout(5000, TimeUnit.SECONDS) //设置读取超时时间 .writeTimeout(5000, TimeUnit.SECONDS) //设置写入超时时间 //.addInterceptor(new ParamInterceptor())//添加其他拦截器 .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build(); retrofit = new Retrofit.Builder().baseUrl(Api.baseUrl).client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } public static RetrofitManager getInstance() { if (retrofitManager==null) { synchronized (RetrofitManager.class){ if (retrofitManager==null) { retrofitManager=new RetrofitManager(); return retrofitManager; } } } return retrofitManager; } public void request(final String path, final Map<String,String> map, final ResultCallback callback) { execute(path,map).subscribe(new Consumer<ResponseBody>() { @Override public void accept(ResponseBody responseBody) throws Exception { if (responseBody!=null) { String string = responseBody.string(); if (!TextUtils.isEmpty(string)) callback.onResponse(gson.fromJson(string, callback.mType), string); } } }); } public void upload(final String path, RequestBody body, final ResultCallback callback) { APIService apiService = retrofit.create(APIService.class); apiService.upLoad(path,body).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<ResponseBody>() { @Override public void accept(ResponseBody responseBody) throws Exception { if (responseBody!=null) { String string = responseBody.string(); if (!TextUtils.isEmpty(string)) callback.onResponse(gson.fromJson(string, callback.mType), string); } } }); } public void request(final String path, final Map<String,String> map,Consumer<ResponseBody> observer) { execute(path,map).subscribe(observer); } private Observable<ResponseBody> execute(String path, Map<String,String> map) { APIService apiService = retrofit.create(APIService.class); Observable<ResponseBody> request; if (map!=null&&map.size()>0) { request = apiService.request(path, map); }else { request = apiService.request(path); } return request.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } public void request(final String path, final Map<String,String> map,Observer<ResponseBody> observer) { execute(path,map).subscribe(observer); } }
package com.example.fiorella.gastoapp.Controllers; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.example.fiorella.gastoapp.Database.AdminSQLiteOpenHelper; import com.example.fiorella.gastoapp.Model.Expense; import com.example.fiorella.gastoapp.R; import java.util.ArrayList; public class ActivityGeneralReport extends AppCompatActivity { ListView listView_general; TextView txt_total_general; ArrayList<String> list_expense_string; ArrayList<Expense> expense_list_expense; Double total_expense; AdminSQLiteOpenHelper admin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_activity_general_report); consultExpenseList(); listView_general = (ListView)findViewById(R.id.listView_general); txt_total_general = (TextView)findViewById(R.id.txt_total_classification); total_expense = getTotal(); ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, list_expense_string); listView_general.setAdapter(adapter); txt_total_general.setText(String.valueOf(total_expense)); } private void consultExpenseList() { //Abrimos base de datos en modo lectura y escritura admin= new AdminSQLiteOpenHelper(this, "gastoApp", null, 1); SQLiteDatabase dataBase = admin.getReadableDatabase(); Expense expense = null; expense_list_expense = new ArrayList<Expense>(); Cursor cursor = dataBase.rawQuery("select * from expense", null); while(cursor.moveToNext()){ expense = new Expense(); expense.set_id(cursor.getInt(0)); expense.set_concept(cursor.getString(1)); expense.set_amount(cursor.getDouble(2)); expense.set_date(cursor.getString(3)); expense_list_expense.add(expense); // Log.i("id", String.valueOf(expense.get_id())); // Log.i("Nombre",expense.get_concept()); // Log.i("Monto", String.valueOf(expense.get_amount())); // Log.i("Fecha", expense.get_date()); } getList(); dataBase.close(); } private void getList(){ list_expense_string = new ArrayList<String>(); for(int i = 0; i< expense_list_expense.size(); i++){ list_expense_string.add( " " + expense_list_expense.get(i).get_concept() + " " + expense_list_expense.get(i).get_amount() ); } } /** * Metodo para obtener el total general gastado * @return double gasto total */ public double getTotal(){ double amount; admin= new AdminSQLiteOpenHelper(this, "gastoApp", null, 1); SQLiteDatabase db = admin.getReadableDatabase(); Cursor c ; c = db.rawQuery("select sum(amount) from expense", null); if(c.moveToFirst()) amount = c.getInt(0); else amount = -1; c.close(); return amount; } }
package com.example.hello; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button btn1; Button btn2; TextView text; CheckBox check; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn1 = findViewById(R.id.btn1); btn2 = findViewById(R.id.btn2); text = findViewById(R.id.text); check = findViewById(R.id.check); btn1.setOnClickListener(this); btn2.setOnClickListener(this); check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { text.setText("чекед"); } else { text.setText("анчекед"); } } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn1: check.setChecked(true); text.setBackgroundColor(Color.parseColor("#FFDDFF")); break; case R.id.btn2: check.setChecked(false); text.setBackgroundColor(Color.parseColor("#DDDDFF")); break; } } }
package person.lgc.myexperiencecode.listViewSeries;/* package a.baozouptu.chosePicture; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import com.readystatesoftware.systembartint.SystemBarTintManager; import java.util.ArrayList; import java.util.List; import a.baozouptu.R; import a.baozouptu.base.dataAndLogic.AllData; import a.baozouptu.base.dataAndLogic.AsyncImageLoader3; import a.baozouptu.base.util.FileTool; import a.baozouptu.base.util.Util; import a.baozouptu.ptu.PtuActivity; */ /* * 显示所选的最近的或某个文件夹下面的所有图片 * 并且有选择文件夹,相机,空白图画图的功能 *//* public class ChosePictureActivityBackupBackup extends AppCompatActivity { private String TAG = "ChosePictureActivityBackup"; */ /* * 进度条 *//* private ProgressDialog m_ProgressDialog = null; */ /* * 保存最近图片的路径 *//* public static List<String> usualyPicPathList = new ArrayList<>(); */ /* * 获取和保存某个文件下面所有图片的路径 *//* private List<String> picPathInFile = new ArrayList<>(); */ /* * 当前要现实的所有图片的路径 *//* private List<String> currentPicPathList = new ArrayList<>(); */ /* * 文件列表的几个相关list *//* private List<String> dirInfoList, dirPathList, dirRepresentPathList; private DrawerLayout fileListDrawer; private GridViewAdapter picAdpter; private GridView pictureGridview; private ProcessUsuallyPicPath usuPicProcess; private ListView pictureFileListView; private MyFileListAdapter fileAdapter; boolean isFirst = true; */ /* * Called when the activity is first created. * 过程描述:启动一个线程获取所有图片的路径,再启动一个子线程设置好GridView,而且要求这个子线程必须在ui线程之前启动 *//* @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chose_picture); //test(); Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.obj.equals("change_pic")) { if (isFirst) { pictureGridview.setAdapter(picAdpter); m_ProgressDialog.dismiss();// 表示此处开始就解除这个进度条Dialog,应该是在相对起始线程的另一个中使用 isFirst = false; } else { picAdpter.notifyDataSetChanged(); } Util.P.le(TAG, "finish update picture"); } else if (msg.obj.equals("change_file")) { Util.P.le(TAG, "finish update file"); fileAdapter.notifyDataSetChanged(); } } }; usuPicProcess = new ProcessUsuallyPicPath(this, handler); getScreenWidth(); initView(); initToolbar(); m_ProgressDialog = ProgressDialog.show(ChosePictureActivityBackup.this, "请稍后", "数据读取中...", true); initPicInfo(); } private void test() { if (getIntent().getStringExtra("test") == null) return; Intent intent1 = new Intent(this, PtuActivity.class); intent1.putExtras(getIntent()); intent1.putExtra("pic_path", "/storage/sdcard1/中大图.jpg"); startActivityForResult(intent1, 0); } */ /* * 获取所有图片的文件信息,最近的图片, * <p>并且为图片grid,文件列表加载数据 *//* private void initPicInfo() { usualyPicPathList = usuPicProcess.getUsuallyPathFromDB(); currentPicPathList = usualyPicPathList; Util.P.le(TAG, "获取了上次数据库中的图片"); disposeShowPicture(); Util.P.le(TAG, "初始化显示图片完成"); disposeDrawer(); Util.P.le(TAG, "初始化显示Drawer完成"); } */ /* * 获取屏幕的宽度 *//* void getScreenWidth() { DisplayMetrics metric = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metric); AllData.screenWidth = metric.widthPixels; // 屏幕宽度(像素) } Toolbar toolbar; private void initView() { fileListDrawer = (DrawerLayout) findViewById(R.id.drawer_layout_show_picture); pictureGridview = (GridView) findViewById(R.id.gv_photolist); toolbar = (Toolbar) findViewById(R.id.toolbar_show_picture); setSupportActionBar(toolbar); final ImageButton showFile = (ImageButton) findViewById(R.id.show_pic_file); showFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (fileListDrawer.isDrawerOpen(GravityCompat.END)) fileListDrawer.closeDrawer(GravityCompat.END); else fileListDrawer.openDrawer(GravityCompat.END); } }); } @TargetApi(19) private void initToolbar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); SystemBarTintManager tintManager = new SystemBarTintManager(this); tintManager.setStatusBarTintColor(Util.getColor(this, R.color.base_toolbar_background)); tintManager.setStatusBarTintEnabled(true); } } */ /* * 为显示图片的gridView加载数据 *//* private void disposeShowPicture() { picAdpter = new GridViewAdapter( ChosePictureActivityBackup.this, currentPicPathList); pictureGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent sourceIntent = getIntent(); if (sourceIntent != null) { String s = sourceIntent.getAction(); if (s != null && s.equals("tietu")) {//是来自选择贴图,不是选择的贴图 Intent intent1 = new Intent(); Util.P.le(TAG, currentPicPathList.get(position)); intent1.putExtra("pic_path", currentPicPathList.get(position)); setResult(3, intent1); ChosePictureActivityBackup.this.finish(); } else {//正常的选择 Intent intent = new Intent(ChosePictureActivityBackup.this, PtuActivity.class); intent.putExtra("pic_path", currentPicPathList.get(position)); startActivityForResult(intent, 0); } } } }); pictureGridview.setOnScrollListener(new AbsListView.OnScrollListener() { AsyncImageLoader3 imageLoader = AsyncImageLoader3.getInstatnce(); @Override public void onScrollStateChanged(AbsListView view, int scrollState) { switch (scrollState) { case AbsListView.OnScrollListener.SCROLL_STATE_IDLE: showAdjacentPic(); break; case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: imageLoader.cancelLoad();//取消解析,提交的任务还没有执行的就不执行了 break; } } AsyncImageLoader3.ImageCallback imageCallback = new AsyncImageLoader3.ImageCallback() { public void imageLoaded(Bitmap imageBitmap, ImageView image, int position, String imageUrl) { if (image != null && position == (int) image.getTag()) { if (imageBitmap == null) { image.setImageResource(R.mipmap.decode_failed_icon); } else image.setImageBitmap(imageBitmap); } } }; private void showAdjacentPic() { int first = pictureGridview.getFirstVisiblePosition(); int last = pictureGridview.getLastVisiblePosition(); for (int position = first; position <= last; position++) { if (position > currentPicPathList.size()) break; String path = currentPicPathList.get(position); final ImageView ivImage = (ImageView) pictureGridview.findViewWithTag(position); imageLoader.loadBitmap(path, ivImage, position, imageCallback, AllData.screenWidth / 3); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); pictureGridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { final PopupWindow popWindowFile = new PopupWindow(ChosePictureActivityBackup.this); LinearLayout linearLayout = new LinearLayout(ChosePictureActivityBackup.this); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.setGravity(Gravity.CENTER); linearLayout.setDividerPadding(10); linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE); linearLayout.setDividerDrawable(Util.getDrawable(R.drawable.divider_picture_opration)); linearLayout.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT)); linearLayout.setPadding(Util.dp2Px(2), Util.dp2Px(2), Util.dp2Px(2), Util.dp2Px(2)); TextView frequentlyTextView = new TextView(ChosePictureActivityBackup.this); frequentlyTextView.setGravity(Gravity.CENTER); frequentlyTextView.setWidth(view.getWidth() / 2); frequentlyTextView.setGravity(Gravity.CENTER_HORIZONTAL); final String path = currentPicPathList.get(position); if (usualyPicPathList.lastIndexOf(path) >= usuPicProcess.getPreferStart()) { frequentlyTextView.setText("取消"); frequentlyTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { usuPicProcess.deletePreferPath(path, position); dirInfoList.remove(0); dirInfoList.add(0, " " + "常用图片(" + usualyPicPathList.size() + ")"); if (currentPicPathList == usualyPicPathList) picAdpter.notifyDataSetChanged(); popWindowFile.dismiss(); } }); } else { frequentlyTextView.setText("常用"); frequentlyTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popWindowFile.dismiss(); boolean change = usuPicProcess.addPreferPath(path); dirInfoList.remove(0); dirInfoList.add(0, " " + "常用图片(" + usualyPicPathList.size() + ")"); if (change && currentPicPathList == usualyPicPathList) picAdpter.notifyDataSetChanged(); } }); } frequentlyTextView.setTextSize(22); frequentlyTextView.setTextColor(Util.getColor(R.color.text_deep_black)); linearLayout.addView(frequentlyTextView); TextView deleteTextView = new TextView(ChosePictureActivityBackup.this); deleteTextView.setGravity(Gravity.CENTER); deleteTextView.setWidth(view.getWidth() / 2); deleteTextView.setGravity(Gravity.CENTER_HORIZONTAL); deleteTextView.setText("删除"); deleteTextView.setTextSize(22); deleteTextView.setTextColor(Util.getColor(R.color.text_deep_black)); deleteTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popWindowFile.dismiss(); deletePicture(currentPicPathList.get(position)); } }); linearLayout.addView(deleteTextView); int[] popWH = new int[2]; Util.getMesureWH(linearLayout, popWH); popWindowFile.setContentView(linearLayout); popWindowFile.setWidth(view.getWidth()); popWindowFile.setHeight(popWH[1]); popWindowFile.setFocusable(true); popWindowFile.setBackgroundDrawable(Util.getDrawable( R.drawable.background_pic_operation)); popWindowFile.showAsDropDown(view, 0, -view.getHeight()); return true; } }); } private void deletePicture(final String path) { AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog alertDialog = builder.setTitle("删除此图片(包括SD卡中)") .setPositiveButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setNegativeButton("删除", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 先从文件中删除,不能删除则不行 if (!usuPicProcess.onDeleteOnePicInfile(path))//删除图片文件并更新目录列表信息 { AlertDialog alertDialog1 = new AlertDialog.Builder(ChosePictureActivityBackup.this) .setTitle("删除失败,此图片无法删除") .setPositiveButton("确定", new AlertDialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .create(); alertDialog1.show(); return; } if (usualyPicPathList.contains(path)) {//包含才常用列表里面,删除常用列表中的信息 } picAdpter.notifyDataSetChanged(); fileAdapter.notifyDataSetChanged(); } }) .create(); alertDialog.show(); } @Override protected void onResume() { usuPicProcess.getAllPicInfoAndRecent(); super.onResume(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Util.P.le(TAG, "onActivityResult:开始处理其它activity的返回"); if (resultCode == 0 && data != null) { String action = data.getAction(); if (action != null && action.equals("finish")) { setResult(0, new Intent(action)); finish(); overridePendingTransition(0, R.anim.go_send_exit); } else { String path = data.getStringExtra("pic_path"); if (path != null) { usuPicProcess.addUsedPath(path); } if (path != null && currentPicPathList == usualyPicPathList) { picAdpter.notifyDataSetChanged(); } } } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onPause() { AsyncImageLoader3.getInstatnce().evitAll(); super.onPause(); } @Override public void onBackPressed() { if (currentPicPathList == usualyPicPathList) { super.onBackPressed(); } else { currentPicPathList = usualyPicPathList; picAdpter.setList(usualyPicPathList); pictureGridview.setAdapter(picAdpter); } } @Override protected void onDestroy() { AllData.lastScanTime = 0; super.onDestroy(); } } */
package com.yanovski.load_balancer.controllers; import com.yanovski.load_balancer.services.ClusterRegistrationService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Controller to register a Service Node into a cluster. * * @author SV */ @RestController public class RegisterController { private final Logger logger = LogManager.getLogger(RegisterController.class); private final ClusterRegistrationService clusterRegistrationService; @Autowired public RegisterController(ClusterRegistrationService clusterRegistrationService) { this.clusterRegistrationService = clusterRegistrationService; } @GetMapping("/register") public void setKVPair(@RequestParam(required = true) String url, @RequestParam(required = true) String port) { logger.info("Trying to register KV Server Node with URL: {}:{}", url, port); clusterRegistrationService.registerServiceNode(url,port); } @GetMapping("/getServerNode") public String getNode() { return clusterRegistrationService.getAvailableNode(); } @GetMapping("/getAllServerNodes") public List<String> getAllNodes() { return clusterRegistrationService.getAllRegisteredNodes(); } }
package com.example.thelimitbreaker.keyboardsamples; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText=findViewById(R.id.editText); } public void showToast(View view) { Toast.makeText(this,editText.getText().toString(),Toast.LENGTH_SHORT).show(); } }
package game; import java.util.ArrayList; import java.util.List; import java.util.Observable; /** * Reuse a villager. * @author Pimwalun Witchawanitchanun * */ public class ObjectPool extends Observable { private List<Villager> villagers; private Thread mainLoop; private boolean alive; private int stop = 750; /** * Initialize new ObjectPool to reuse. */ public ObjectPool() { alive = true; villagers = new ArrayList<Villager>(); mainLoop = new Thread() { @Override public void run() { while (alive) { moveVillager(); cleanupVillagers(); setChanged(); notifyObservers(villagers); try { Thread.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); } } } }; mainLoop.start(); } /** * Move villager. */ private void moveVillager() { for (Villager villager : villagers) { villager.move(); } } /** * Remove when villager at a specified distance. */ private void cleanupVillagers() { List<Villager> toRemove = new ArrayList<Villager>(); for (Villager villager : villagers) { if (villager.getX() <= (-900 + getStop())) { toRemove.add(villager); } } for (Villager villager : toRemove) { villager.setProperties(0, 0, false); villagers.remove(villager); } } /** * Return list of a villager to release. * @return */ public List<Villager> getVillager() { return villagers; } /** * Release villager if user answered correctly. * @param x */ public void burstVillagers(int x) { List<Villager> villagerList = VillagerPool.getInstance().getVillagerList(); Villager villager = villagerList.get(0); villager.setProperties(x, -1, true); villagers.add(villager); } /** * Return distance to stop. * @return distance to stop. */ public int getStop() { return stop; } /** * Set distance to stop. * @param stop */ public void setStop(int stop) { this.stop = stop; } }
package homeED; public class AirConditioning extends ChangeTempDevice implements Rotate { public boolean on() { System.out.println(" AirConditioning is on"); return true; } public boolean off() { System.out.println(" AirConditioning is off"); return false; } }
package by.epam.aliaksei.litvin.services; import by.epam.aliaksei.litvin.domain.Event; import by.epam.aliaksei.litvin.service.EventService; import by.epam.aliaksei.litvin.service.impl.EventServiceImpl; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.NavigableSet; import java.util.Set; import java.util.TreeSet; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/spring.xml") public class EventServiceImplTest { private static final String EVENT_NAME = "name"; @Autowired private EventServiceImpl eventService; @Before public void setup() { Event event1 = new Event(); Event event2 = new Event(); Event event3 = new Event(); event1.setName(EVENT_NAME); NavigableSet<LocalDateTime> airDates1 = new TreeSet<>(); airDates1.add(LocalDateTime.now().plusHours(1)); airDates1.add(LocalDateTime.now().plusDays(1)); airDates1.add(LocalDateTime.now().plusDays(7)); event1.setAirDates(airDates1); NavigableSet<LocalDateTime> airDates2 = new TreeSet<>(); airDates2.add(LocalDateTime.now().plusDays(1)); event2.setAirDates(airDates2); eventService.save(event1); eventService.save(event2); eventService.save(event3); } @After public void tearDown() { eventService.removeAll(); } @Test public void test_getForDateRange() { Set<Event> events = eventService.getForDateRange(LocalDate.now().minusDays(1), LocalDate.now().plusDays(2)); assertEquals(events.size(), 2); } @Test public void test_getByName() { Event eventByName = eventService.getByName(EVENT_NAME); assertEquals(eventByName.getName(), EVENT_NAME); } @Test public void test_getNextEvents() { Set<Event> nextEvents = eventService.getNextEvents(LocalDateTime.now().plusDays(2)); assertEquals(nextEvents.size(), 3); } }
package jd.http; import java.net.URL; import org.appwork.utils.net.httpconnection.HTTPProxy; public class HTTPConnectionFactory { public static URLConnectionAdapter createHTTPConnection(final URL url, final HTTPProxy proxy) { if (proxy == null) { return new URLConnectionAdapterDirectImpl(url); } if (proxy.isNone()) { return new URLConnectionAdapterDirectImpl(url, proxy); } if (proxy.isDirect()) { return new URLConnectionAdapterDirectImpl(url, proxy); } if (proxy.getType().equals(HTTPProxy.TYPE.SOCKS5)) { return new URLConnectionAdapterSocks5Impl(url, proxy); } if (proxy.getType().equals(HTTPProxy.TYPE.SOCKS4)) { return new URLConnectionAdapterSocks4Impl(url, proxy); } if (proxy.getType().equals(HTTPProxy.TYPE.HTTP)) { URLConnectionAdapterHTTPProxyImpl ret = new URLConnectionAdapterHTTPProxyImpl(url, proxy); ret.setPreferConnectMethod(proxy.isConnectMethodPrefered()); return ret; } throw new RuntimeException("unsupported proxy type: " + proxy.getType().name()); } }
package delfi.com.vn.newsample.ui.gridview; import android.content.Context; import android.widget.LinearLayout; import android.widget.TextView; import delfi.com.vn.tpcreative.common.presenter.BaseView; /** * Created by PC on 8/3/2017. */ public interface GridViewView extends BaseView { TextView tvName(); LinearLayout llName(); }
package string; public class CustomsortString { public static String customSortString(String S, String T) { if(S==null || T==null || S.length()==0 || T.length()==0) return null; int[] tDict = new int[26]; for(int i=0;i<T.length(); i++){ tDict[T.charAt(i)-'a']++; } StringBuilder sb = new StringBuilder(); for(int i=0; i<S.length();i++){ int x=tDict[S.charAt(i)-'a']; if(tDict[S.charAt(i)-'a']>0){ for(int j=0;j<tDict[S.charAt(i)-'a'];j++){ sb.append(S.charAt(i)); } tDict[S.charAt(i)-'a'] = 0; } } for(int i=0; i<26;i++){ if(tDict[i]>0){ for(int j=0; j<tDict[i];j++){ sb.append((char)('a'+i)); } } } return sb.toString(); } public static void main(String args[]) { //int maxLetters = 2, minSize = 3, maxSize = 4; String S = "cba"; String T = "abcd"; customSortString(S,T); System.out.print(customSortString(S,T)); } }
package com.imooc.o2o.service.impl; import com.imooc.o2o.dao.ProductCategoryDao; import com.imooc.o2o.dao.ProductDao; import com.imooc.o2o.dto.ProductCategoryExecution; import com.imooc.o2o.entity.ProductCategory; import com.imooc.o2o.enums.ProductCategoryStateEnum; import com.imooc.o2o.exceptions.ProductCategoryOperationException; import com.imooc.o2o.service.ProductCategoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author: LieutenantChen * @create: 2018-09-07 21:32 **/ @Service public class ProductCategoryServiceImpl implements ProductCategoryService { @Autowired private ProductCategoryDao productCategoryDao; @Autowired private ProductDao productDao; /** * 根据店铺Id获得该店铺下商品列表 * @param shopId * @return */ @Override public List<ProductCategory> getProductCategoryList(long shopId) { return productCategoryDao.queryProductCategoryList(shopId); } /** * 批量插入商品的商品分类 * @param productCategoryList * @return * @throws ProductCategoryOperationException */ @Override @Transactional public ProductCategoryExecution batchAddProductCategory( List<ProductCategory> productCategoryList) throws ProductCategoryOperationException { // 商品分类列表不空,还能获取到 if (productCategoryList != null && productCategoryList.size() > 0) { try { // 获取一下,返回影响行数 int effectedNumber = productCategoryDao.batchInsertProductCategory(productCategoryList); if (effectedNumber <= 0) { throw new ProductCategoryOperationException("商品类别创建失败,合法行数小于0"); } else { // 影响行数合法,返回成功提示 return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS); } } catch (Exception e) { throw new ProductCategoryOperationException("商品类别创建错误:" + e.getMessage()); } } else { // 商品分类列表为空,获取不到,返回空 return new ProductCategoryExecution(ProductCategoryStateEnum.EMPTY_LIST); } } /** * 删除商品分类 * @param productCategoryId * @param shopId * @return * @throws ProductCategoryOperationException */ @Override @Transactional public ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopId) throws ProductCategoryOperationException { // 将此商品类别下的商品的类别id设置为空(解耦),再删除 try { int effectedNumber = productDao.updateProductCategoryToNull(productCategoryId); if (effectedNumber < 0) { throw new RuntimeException("商品类别id删除失败"); } } catch (Exception e) { throw new RuntimeException("删除商品类别错误:" + e.getMessage()); } try { int effectedNumber = productCategoryDao.deleteProductCategory(productCategoryId, shopId); if(effectedNumber <= 0) { throw new ProductCategoryOperationException("删除失败"); } else { return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS); } } catch (Exception e) { throw new ProductCategoryOperationException("删除发生错误:" + e.getMessage()); } } }
package basics.java.core.inheritance.polymorph; public class Teacher { void Subject() { System.out.println("Generic Subject"); } }
import exercise3.InvocationHandlerCalculator; import java.lang.reflect.Proxy; import java.util.Date; public class Main { public static void main(String[] args) { Service service = new ServiceImpl(); Service serviceProxy = (Service) Proxy.newProxyInstance( ServiceImpl.class.getClassLoader(), ServiceImpl.class.getInterfaces(), new CacheProxy(service, "123.ser")); serviceProxy.run("sada", 4.6D, new Date()); // CacheProxy cacheProxy = new CacheProxy(""); // Service service = cacheProxy.cache(new ServiceImpl()); } }