text stringlengths 10 2.72M |
|---|
package data;
import java.awt.Point;
public class ThreePointLine
{
private Point leftP;
private Point midP;
private Point rightP;
public ThreePointLine() {}
public ThreePointLine(Point leftP, Point rightP)
{
this.leftP = leftP;
this.rightP = rightP;
calMidP();
}
ThreePointLine(int x1, int y1, int x2, int y2, int x3, int y3)
{
this.leftP = new Point(x1, y1);
this.rightP = new Point(x3, y3);
this.midP = new Point(x2, y2);
}
private void calMidP()
{
this.midP = new Point((leftP.x+rightP.x)/2, (leftP.y+rightP.y)/2);
}
public Point getLeftP()
{
return leftP;
}
public void setLeftP(Point leftP)
{
this.leftP = leftP;
if (this.rightP != null)
calMidP();
}
public Point getMidP()
{
return midP;
}
public void setMidP(Point midP)
{
this.midP = midP;
}
public Point getRightP()
{
return rightP;
}
public void setRightP(Point rightP)
{
this.rightP = rightP;
if (this.leftP != null)
calMidP();
}
}
|
package com.myou.appclient.util;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.util.Log;
import com.google.gson.stream.JsonReader;
/**
* @description: 解析json<br>
* @author: jiujiya
* @update: 2013-4
* @version: 1.0
* @email:136336790@qq.com
*/
public class JsonUtils {
/**
* 统一处理异常
* @param e
*/
public static void hiddleException(Exception e){
e.printStackTrace();
Log.e(ExceptionHandle.LOGNAME, e.getMessage(), e);
}
/**
* 把 json 转换成 list
* @param jsonData
* @return
*/
public static List<Map<String, Object>> getList(String jsonData){
//如果需要解析JSON数据,首要要生成一个JsonReader对象
JsonReader reader = getJsonReader((jsonData));
// try {
// reader.beginObject();
// reader.nextName();
// } catch (IOException e) {
// hiddleException(e);
// }
return getList(reader);
}
/**
* 把 json 转换成 map
*
* @param jsonData
* @return
*/
public static Map<String, List<Map<String, Object>>> getMapList(String jsonData, int size) {
Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String,Object>>>();
//如果需要解析JSON数据,首要要生成一个JsonReader对象
JsonReader reader = getJsonReader((jsonData));
try {
reader.beginObject();
} catch (IOException e) {
hiddleException(e);
}
for (int i = 0; i < size; i++) {
try {
String name = reader.nextName();
map.put(name, getList(reader));
} catch (IOException e) {
hiddleException(e);
}
}
return map;
}
/**
* 把 json 转换成 list
* @param reader
* @return
*/
public static List<Map<String, Object>> getList(JsonReader reader){
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
try{
reader.beginArray();
while(reader.hasNext()){
list.add(getMap(reader));
}
reader.endArray();
}
catch(Exception e){
hiddleException(e);
}
return list;
}
/**
* 获得JsonReader
* @param jsonData
* @return
*/
public static JsonReader getJsonReader(String jsonData){
// 如果需要解析JSON数据,首要要生成一个JsonReader对象
JsonReader reader = new JsonReader(new StringReader(jsonData));
return reader;
}
/**
* 把 json 转换成 map
*
* @param jsonData
* @return
*/
public static Map<String, Object> getMap(String jsonData) {
// 如果需要解析JSON数据,首要要生成一个JsonReader对象
JsonReader reader = getJsonReader(jsonData);
return getMap(reader);
}
/**
* 把 json 转换成 map
* @param reader
* @return
*/
public static Map<String, Object> getMap(JsonReader reader) {
Map<String, Object> map = new HashMap<String, Object>();
String tagName = "";
try {
// 如果需要解析JSON数据,首要要生成一个JsonReader对象
reader.beginObject();
while (reader.hasNext()) {
tagName = reader.nextName();
map.put(tagName, EscapeUnescape.unescape(reader.nextString()));
}
reader.endObject();
} catch (Exception e) {
hiddleException(e);
}
return map;
}
}
|
package com.alibaba.druid.bvt.sql.eval;
import org.junit.Assert;
import junit.framework.TestCase;
import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils;
import com.alibaba.druid.util.JdbcConstants;
public class EvalMethodRightTest extends TestCase {
public void test_ascii() throws Exception {
Assert.assertEquals("rbar", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "right('foobarbar', 4)"));
}
}
|
/*
* Copyright 2008-2018 shopxx.net. All rights reserved.
* Support: localhost
* License: localhost/license
* FileId: MsLp3bW8EwSmOyfaLczNUp+xJ/Kg5sBa
*/
package net.bdsc.service;
/**
* Service - 配置
*
* @author 好源++ Team
* @version 6.1
*/
public interface ConfigService {
/**
* 初始化
*/
void init();
} |
/*
* Copyright (C) 2012 www.amsoft.cn
*
* 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.bnrc.global;
// TODO: Auto-generated Javadoc
/**
* 漏 2012 amsoft.cn
* 鍚嶇О锛欰bAppConfig.java
* 鎻忚堪锛氬垵濮嬭缃被.
*
* @author 杩樺涓�姊︿腑
* @version v1.0
* @date锛�2014-07-03 涓嬪崍1:33:39
*/
public class AbAppConfig {
/** UI璁捐鐨勫熀鍑嗗搴�. */
public static int UI_WIDTH = 720;
/** UI璁捐鐨勫熀鍑嗛珮搴�. */
public static int UI_HEIGHT = 1280;
/** UI璁捐鐨勫瘑搴�. */
public static int UI_DENSITY = 2;
/** 榛樿 SharePreferences鏂囦欢鍚�. */
public static String SHARED_PATH = "app_share";
/** 榛樿涓嬭浇鏂囦欢鍦板潃. */
public static String DOWNLOAD_ROOT_DIR = "download";
/** 榛樿涓嬭浇鍥剧墖鏂囦欢鍦板潃. */
public static String DOWNLOAD_IMAGE_DIR = "images";
/** 榛樿涓嬭浇鏂囦欢鍦板潃. */
public static String DOWNLOAD_FILE_DIR = "files";
/** APP缂撳瓨鐩綍. */
public static String CACHE_DIR = "cache";
/** DB鐩綍. */
public static String DB_DIR = "db";
/** 榛樿缂撳瓨瓒呮椂鏃堕棿璁剧疆. */
public static int IMAGE_CACHE_EXPIRES_TIME = 3600*24*3;
/** 缂撳瓨澶у皬 鍗曚綅10M. */
public static int MAX_CACHE_SIZE_INBYTES = 10*1024*1024;
/** The Constant CONNECTEXCEPTION. */
public static String CONNECT_EXCEPTION = "鏃犳硶杩炴帴鍒扮綉缁�";
/** The Constant UNKNOWNHOSTEXCEPTION. */
public static String UNKNOWN_HOST_EXCEPTION = "杩炴帴杩滅▼鍦板潃澶辫触";
/** The Constant SOCKETEXCEPTION. */
public static String SOCKET_EXCEPTION = "缃戠粶杩炴帴鍑洪敊锛岃閲嶈瘯";
/** The Constant SOCKETTIMEOUTEXCEPTION. */
public static String SOCKET_TIMEOUT_EXCEPTION = "杩炴帴瓒呮椂锛岃閲嶈瘯";
/** The Constant NULLPOINTEREXCEPTION. */
public static String NULL_POINTER_EXCEPTION = "鎶辨瓑锛岃繙绋嬫湇鍔″嚭閿欎簡";
/** The Constant NULLMESSAGEEXCEPTION. */
public static String NULL_MESSAGE_EXCEPTION = "鎶辨瓑锛岀▼搴忓嚭閿欎簡";
/** The Constant CLIENTPROTOCOLEXCEPTION. */
public static String CLIENT_PROTOCOL_EXCEPTION = "Http璇锋眰鍙傛暟閿欒";
/** 鍙傛暟涓暟涓嶅. */
public static String MISSING_PARAMETERS = "鍙傛暟娌℃湁鍖呭惈瓒冲鐨勫��";
/** The Constant REMOTESERVICEEXCEPTION. */
public static String REMOTE_SERVICE_EXCEPTION = "鎶辨瓑锛岃繙绋嬫湇鍔″嚭閿欎簡";
/** 椤甸潰鏈壘鍒�. */
public static String NOT_FOUND_EXCEPTION = "椤甸潰鏈壘鍒�";
/** 鍏朵粬寮傚父. */
public static String UNTREATED_EXCEPTION = "鏈鐞嗙殑寮傚父";
}
|
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
public class Player {
private int kolona;
private int red;
public Player(int kolona, int red) {
this.kolona = kolona;
this.red = red;
}
public int getKolona() {
return this.kolona;
}
public void setKolona(int kolona) {
this.kolona = kolona;
}
public int getRed() {
return this.red;
}
public void setRed(int red) {
this.red = red;
}
}
|
package com.jtexplorer.entity.enums;
/**
* RequestEnum class
*
* @author 苏友朋
* @date 2019/06/15 17:28
*/
public enum RequestEnum {
/**
* 用于接口返回错误标识
*/
REQUEST_ERROR_NO_LOGIN("用户未登录或者登录信息已失效。", "10001"),
REQUEST_ERROR_LOGIN_INFO("登录信息有误。", "100011"),
REQUEST_ERROR_LOGIN_ACCOUNT_EMPTY("登录账号不可为空。", "100012"),
REQUEST_ERROR_LOGIN_PASSWORD_EMPTY("登录密码不可为空。", "100013"),
REQUEST_ERROR_LOGIN_NO_ROLE("无权限。", "100014"),
REQUEST_ERROR_DATABASE_INSERT_ERROR("数据库插入错误,插入数据库时数据格式错误。", "10002"),
REQUEST_ERROR_DATABASE_UPDATE_ERROR("数据库更新错误,执行数据库更新操作时数据格式错误。", "10003"),
REQUEST_ERROR_DATABASE_DELETE_ERROR("数据库删除错误,执行数据库删除操作时发生的错误。", "10004"),
REQUEST_ERROR_PARAMETER_ERROR("参数错误,参数未传值,或者参数格式错误。", "10005"),
REQUEST_ERROR_DATABASE_SELECT_ERROR("数据库查询错误,为根据条件查询出数据,或查询条件错误。", "10006"),
REQUEST_ERROR_DATABASE_QUERY_NO_DATA("无数据。", "10007"),
REQUEST_ERROR_DATABASE_UPDATE_NO_KEY("更新时缺失主键条件。", "10008"),
REQUEST_ERROR_DATABASE_DELETE_NO_KEY("删除时缺失主键条件。", "10009"),
REQUEST_ERROR_DATABASE_INSERT_HAVE_NULL("新增时有必填项为空。", "10010"),
REQUEST_ERROR_DATABASE_QUERY_ERROR_PARAM("查询参数错误。", "10011"),
// REQUEST_ERROR_ACTIVITI_START_ERROR("activiti任务开启失败。", "10012"),
REQUEST_ERROR_IMPORT_EXCEL("excel导入错误,excel格式不对。", "10013"),
REQUEST_ERROR_EXCEPTION_DATE("程序异常。时间格式化错误。", "10014"),
REQUEST_ERROR_VIRTUAL_KEY_ADD("虚拟按键中间信息插入失败,请重试。", "10015"),
REQUEST_ERROR_VIRTUAL_KEY("虚拟按键操作失败,请重试。", "10016"),
REQUEST_ERROR_EXCEL_IMPORT("excel导入失败。", "10017"),
REQUEST_ERROR_EXCEL_EXPORT("excel导出失败。", "10018"),
// REQUEST_ERROR_ACTIVITI_UPDATE_DB("activiti生成成功,但是修改数据库出错,请重试。", "10019"),
REQUEST_ERROR_HAVE_DATA("该数据已存在。", "10020"),
REQUEST_ERROR_SYSTEM_TIME_ERROR("系统错误-时间错误。", "10021"),
REQUEST_ERROR_SYSTEM_ERROR("系统错误。", "10022"),
REQUEST_ERROR_SUBORDER_OPERATION_ERROR("分单操作失败。", "10023"),
REQUEST_ERROR_VERIFY_ERROR("验证失败。", "10024"),
REQUEST_ERROR_SUBORDER_CANT_UPDATE("分单不可更新。", "10025"),
REQUEST_ERROR_WE_CHAT_ERROR("微信错误。", "10026"),
// REQUEST_ERROR_K3("K3接口请求失败,请重试。", "10026"),
;
/**
* 说明
*/
private String meaning;
/**
* 代码
*/
private String code;
public String getMeaning() {
return meaning;
}
public String getCode() {
return code;
}
RequestEnum(String meaning, String code) {
this.meaning = meaning;
this.code = code;
}
}
|
package com.lzm.KnittingHelp.db.dao;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import com.lzm.KnittingHelp.db.entity.StepEntity;
import java.util.List;
@Dao
public interface StepDao {
@Query("SELECT * FROM steps")
LiveData<List<StepEntity>> loadAllSteps();
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<StepEntity> steps);
@Query("select * from steps where id = :stepId")
LiveData<StepEntity> loadStep(int stepId);
@Query("select * from steps where id = :stepId")
StepEntity loadStepSync(int stepId);
}
|
package entity;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Column {
/**
* 所有单元格
*/
private List<Cell> cells;
/**
* 列名
*/
private String colName;
/**
* 名称与行索引
*/
private Map<String, Integer> rowNamesMap = new LinkedHashMap<>();
/**
* 名称与列索引
*/
private Map<String, Integer> colNamesMap = new LinkedHashMap<>();
}
|
package matthbo.mods.darkworld.biome;
import java.util.Random;
import matthbo.mods.darkworld.init.ModBlocks;
import matthbo.mods.darkworld.world.DarkWorldGenerator;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenDesertWells;
public class BiomeDarkDesert extends DarkBiomeGenBase{
public BiomeDarkDesert(int id) {
super(id); // add to configs
this.setBiomeName("Dark Desert");
this.setColor(16421912);
this.setDisableRain();
this.setTemperatureRainfall(2.0F, 0.0F);
this.setHeight(height_LowPlains);
this.spawnableCreatureList.clear();
this.topBlock = ModBlocks.darkSand.getDefaultState();
this.fillerBlock = ModBlocks.darkSand.getDefaultState();
this.theDecorationHandler.treesPerChunk = -999;
this.theBiomeDecorator.deadBushPerChunk = 2;
this.theBiomeDecorator.reedsPerChunk = 50;
//this.theBiomeDecorator.cactiPerChunk = 10; FIXED!
this.spawnableCreatureList.clear();
}
public void decorate(World world, Random rand, BlockPos pos)
{
super.decorate(world, rand, pos);
if (rand.nextInt(1000) == 0)
{
int i = rand.nextInt(16) + 8;
int j = rand.nextInt(16) + 8;
BlockPos blockpos1 = world.getHorizon(pos.add(i, 0, j)).up();
(new WorldGenDesertWells()).generate(world, rand, blockpos1);//uh okay TODO: make DarkWorldGenDesertWells xD
}
}
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.InstanceName;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.TenantName;
import com.yahoo.path.Path;
import com.yahoo.vespa.hosted.provision.node.Agent;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* tests basic operation of the node repository
*
* @author bratseth
*/
public class NodeRepositoryTest {
@Test
public void nodeRepositoryTest() {
NodeRepositoryTester tester = new NodeRepositoryTester();
assertEquals(0, tester.getNodes(NodeType.tenant).size());
tester.addNode("id1", "host1", "default", NodeType.tenant);
tester.addNode("id2", "host2", "default", NodeType.tenant);
tester.addNode("id3", "host3", "default", NodeType.tenant);
assertEquals(3, tester.getNodes(NodeType.tenant).size());
tester.nodeRepository().park("host2", Agent.system, "Parking to unit test");
assertTrue(tester.nodeRepository().remove("host2"));
assertEquals(2, tester.getNodes(NodeType.tenant).size());
}
@Test
public void applicationDefaultFlavor() {
NodeRepositoryTester tester = new NodeRepositoryTester();
ApplicationId application = ApplicationId.from(TenantName.from("a"), ApplicationName.from("b"), InstanceName.from("c"));
Path path = Path.fromString("/provision/v1/defaultFlavor").append(application.serializedForm());
String flavor = "example-flavor";
tester.curator().create(path);
tester.curator().set(path, flavor.getBytes(StandardCharsets.UTF_8));
assertEquals(Optional.of(flavor), tester.nodeRepository().getDefaultFlavorOverride(application));
ApplicationId applicationWithoutDefaultFlavor =
ApplicationId.from(TenantName.from("does"), ApplicationName.from("not"), InstanceName.from("exist"));
assertFalse(tester.nodeRepository().getDefaultFlavorOverride(applicationWithoutDefaultFlavor).isPresent());
}
@Test
public void featureToggleDynamicAllocationTest() {
NodeRepositoryTester tester = new NodeRepositoryTester();
assertFalse(tester.nodeRepository().dynamicAllocationEnabled());
tester.curator().set(Path.fromString("/provision/v1/dynamicDockerAllocation"), new byte[0]);
assertTrue(tester.nodeRepository().dynamicAllocationEnabled());
}
@Test
public void only_allow_to_delete_dirty_nodes_when_dynamic_allocation_feature_enabled() {
NodeRepositoryTester tester = new NodeRepositoryTester();
try {
tester.addNode("id1", "host1", "default", NodeType.host);
tester.addNode("id2", "host2", "docker", NodeType.tenant);
tester.nodeRepository().setDirty("host2");
assertFalse(tester.nodeRepository().remove("host2"));
tester.curator().set(Path.fromString("/provision/v1/dynamicDockerAllocation"), new byte[0]);
assertTrue(tester.nodeRepository().remove("host2"));
} finally {
tester.curator().delete(Path.fromString("/provision/v1/dynamicDockerAllocation"));
}
}
}
|
package com.sample1.dao.impl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.sample1.dao.SampleRepository;
import com.sample1.model.User;
@Repository
public interface SampleUserRepositoryImpl extends SampleRepository<User, Long> {
@Query("select u from User u where u.id = ?1")
public User getWhereIdIs(@Param(value = "id") Long id);
//auto generated querry
public User findByLnameAndFname(String lname, String fname);
@Query("select u from User u")
public Page<User> findUsersById(Pageable pageable);
@Query("select u from User u where u.id in (select p.owner_id from Phone p where p.number = ?1)")
public User getUserWhosPhoneNumber(@Param(value = "num") long num);
/*works great
* http://localhost:8080/sample1/getUserWhosPhoneNumber/123
* as an example
* returns :
* {"id":21,"fname":"fname21","lname":"lname21","address":"adress21","phones":[{"number":123,"owner_id":21}],"cars":[]}
*
* but not sure if it is worse than join
* */
/*######### ATTENTION #########
* return repo.findAll(request);
* will not be found here , this function is "implemented" inside of the jpa repository
* so stop looking for it here !
*
*
*
* */
}
|
package rpcrobin_.net_common;
/**
* Created by robin on 2017/8/9.
*/
public class NetConstant {
public static final int PORT=8088;
}
|
package com.ssi.cinema.backend.data.entity;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
@Entity
public class RoomStatus extends AbstractEntity {
@NotNull
@OneToOne
private Room room;
@NotNull
private Date date;
private String lockedSeats;
public RoomStatus() {
// An empty constructor is needed for all beans
}
public RoomStatus(Room room, Date date) {
Objects.requireNonNull(room);
Objects.requireNonNull(date);
this.room = room;
this.date = date;
}
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getLockedSeats() {
return lockedSeats;
}
public void setLockedSeats(String lockedSeats) {
this.lockedSeats = lockedSeats;
}
}
|
package com.cinema.sys.model.base;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="sys_area")
public class TArea {
@Id
@Column(name="area_id")
private String id;
private Integer nid;
private String parentId;
private String name;
private BigDecimal longitude;
private BigDecimal latitude;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public Integer getNid() {
return nid;
}
public void setNid(Integer nid) {
this.nid = nid;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId == null ? null : parentId.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public BigDecimal getLongitude() {
return longitude;
}
public void setLongitude(BigDecimal longitude) {
this.longitude = longitude;
}
public BigDecimal getLatitude() {
return latitude;
}
public void setLatitude(BigDecimal latitude) {
this.latitude = latitude;
}
} |
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class Appointment {
// A common method to connect to the DB
private Connection connect() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Provide the correct details: DBServer/DBName, username, password
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/hospital?useTimezone=true&serverTimezone=UTC",
"root", "");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public String insertAppointment(String no, String type, String Date, String desc) {
String output = "";
try {
Connection con = connect();
if (con == null) {
return "Error while connecting to the database for inserting.";
}
// create a prepared statement
String query = " insert into appointments " + "(`appID`,`appNo`,`appType`,`appDate`,`appDescription`)"
+ " values (?, ?, ?, ?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
// binding values
preparedStmt.setInt(1, 0);
preparedStmt.setString(2, no);
preparedStmt.setString(3, type);
preparedStmt.setString(4, Date);
preparedStmt.setString(5, desc);
// execute the statement
preparedStmt.execute();
con.close();
output = "Inserted successfully";
} catch (Exception e) {
output = "Error while inserting the item.";
System.err.println(e.getMessage());
}
return output;
}
public String readAppointments() {
String output = "";
try {
Connection con = connect();
if (con == null)
{
return "Error while connecting to the database for reading.";
}
// Prepare the html table to be displayed
output = "<table border=\"1\"><tr><th>Appointment No</th><th>Appointment Type</th><th>Appointment Date</th>"
+ "<th>Appointment Description</th><th>Update</th><th>Remove</th></tr>";
String query = "select * from appointments";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
// iterate through the rows in the result set
while (rs.next()) {
String appID = Integer.toString(rs.getInt("appID"));
String appNo = rs.getString("appNo");
String appType = rs.getString("appType");
String appDate = rs.getString("appDate");
String appDescription = rs.getString("appDescription");
// Add into the html table
output += "<tr><td>" + appNo + "</td>";
output += "<td>" + appType + "</td>";
output += "<td>" + appDate + "</td>";
output += "<td>" + appDescription + "</td>";
// buttons
output += "<td><input name=\"btnUpdate\" type=\"button\" value=\"Update\" class=\"btn btn-secondary\"></td>"
+ "<td><form method=\"post\" action=\"appointments.jsp\">"
+ "<input name=\"btnRemove\" type=\"submit\" value=\"Remove\" class=\"btn btn-danger\">"
+ "<input name=\"itemID\" type=\"hidden\" value=\"" + appID + "\">" + "</form></td></tr>";
}
con.close();
// Complete the html table
output += "</table>";
}
catch (Exception e) {
output = "Error while reading the appointments.";
System.err.println(e.getMessage());
}
return output;
}
public String updateAppointment(String appID, String appNo, String appType, String appDate, String appDescription) {
String output = "";
try {
Connection con = connect();
if (con == null) {
return "Error while connecting to the database for updating.";
}
// create a prepared statement
String query = "UPDATE appointments SET appNo=?,appType=?,appDate=?,appDescription=? WHERE appID=?";
PreparedStatement preparedStmt = con.prepareStatement(query);
// binding values
preparedStmt.setString(1, appNo);
preparedStmt.setString(2, appType);
preparedStmt.setString(3, appDate);
preparedStmt.setString(4, appDescription);
preparedStmt.setInt(5, Integer.parseInt(appID));
// execute the statement
preparedStmt.execute();
con.close();
output = "Updated successfully";
} catch (Exception e) {
output = "Error while updating the item.";
System.err.println(e.getMessage());
}
return output;
}
public String deleteAppointment(String appID) {
String output = "";
try {
Connection con = connect();
if (con == null) {
return "Error while connecting to the database for deleting.";
}
// create a prepared statement
String query = "delete from appointments where appID=?";
PreparedStatement preparedStmt = con.prepareStatement(query);
// binding values
preparedStmt.setInt(1, Integer.parseInt(appID));
// execute the statement
preparedStmt.execute();
con.close();
output = "Deleted successfully";
}
catch (Exception e) {
output = "Error while deleting the Appointment.";
System.err.println(e.getMessage());
}
return output;
}
}
|
import java.net.*;
import java.io.*;
/*
Server
socket()
bind()
listen()
accept()
read()
write()
Client
socket()
connect()
write()
read()
*/
/*
Socket()
Creates an unconnected socket, with the system-default type of SocketImpl.
Socket(InetAddress address, int port)
Creates a stream socket and connects it to the specified port number at the specified IP address.
*/
public class MyClient
{
public static void main(String[] args) throws IOException
{
Socket sock = new Socket("localhost", 9996);
// connect called implicitly
// Each Socket object has an input stream and an output stream
InputStream sockets_input_stream = sock.getInputStream();
BufferedReader sin = new BufferedReader(new InputStreamReader(sockets_input_stream));
OutputStream sockets_output_stream = sock.getOutputStream();
PrintWriter sout = new PrintWriter(sockets_output_stream, true); // autoflush set to true
// Take the filename as input from user
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String given_file_name = cin.readLine();
System.out.println("received input" + given_file_name);
// Send the filename to server
sout.println(given_file_name);
// Read the content that server sends and print to console
while (true)
{
String msg = sin.readLine();
if (msg == null)
{
break;
}
else
{
System.out.println(msg + "$");
}
}
}
}
|
package com.accolite.au.mappers;
import com.accolite.au.dto.BusinessUnitDTO;
import com.accolite.au.models.BusinessUnit;
import org.mapstruct.Mapper;
import java.util.List;
@Mapper(componentModel = "spring")
public interface BusinessUnitMapper {
BusinessUnit toBusinessUnit(BusinessUnitDTO businessUnitDTO);
BusinessUnitDTO toBusinessUnitDTO(BusinessUnit businessUnit);
List<BusinessUnitDTO> toBusinessUnitDTOs(List<BusinessUnit> businessUnits);
} |
/*
* File: TempSensor.java
* Author: David Green DGreen@uab.edu
* Assignment: Fall2018P1toP3 - EE333 Fall 2018
* Vers: 1.0.1 10/11/2018 alf - added default constructor
* Vers: 1.0.0 08/18/2018 dgg - initial coding
*/
/**
* TempSensors are unique and consist of a unique ID assigned at creation
* (starting at 10000 and incremented by 1 for each creation),
* and sense a temperature. A temperature sensor will initially indicate
* a temperature of <code>NaN</code>.
* @author David Green DGreen@uab.edu
*/
public class TempSensor implements Saveable {
private static long UIDSource = 10000;
private long UID; // Unique ID
private double temp; // Temperature of sensor
private Logger logger; // Logger object
// Constructors
/**
* Create an temperature sensor
*/
TempSensor() {
UID = UIDSource++;
temp = Double.NaN;
this.logger = new NullLogger();
}
/**
*
* @param logger logger to use
*/
TempSensor(Logger logger) {
UID = UIDSource++;
temp = Double.NaN;
this.logger = (logger != null) ? logger : new NullLogger();
}
// Queries
/**
* Get the UID for the sensor
*
* @return sensor UID
*/
public long getUID() {
return UID;
}
/**
* get sensor's temperature
*
* @return temperature in degrees F
*/
public double getTemp() {
return temp;
}
/**
* returns the string “TS:{UID} = {temperature}” example:
* <code>TS:10000 = 75.0</code>
*
* @return formatted string
*/
@Override
public String toString() {
return "TS:" + UID + " = " + temp;
}
// Commands
/**
* Set the temperature of the sensor
*
* @param temperature new value to be considered the sensed temperature in
* degrees F
*/
public void setTemp(double temperature) {
temp = temperature;
logger.log(Logger.INFO, this + " (set)");
}
}
|
package com.zym.blog.dto;
import com.zym.blog.model.Admin;
import com.zym.blog.model.Right;
import java.io.Serializable;
import java.util.Date;
/**
* 登录用户菜单权限信息dto
* @author Gavin
* @date 2016-10-18
*/
public class AdminMenuRightDto implements Serializable {
private Integer rightId;
private Integer rightType;
private String rightTypeDesc;
private String rightName;
private Integer menuId;
private String menuName;
private String menuUrl;
private Integer parentMenuId;
public Integer getRightId() {
return rightId;
}
public void setRightId(Integer rightId) {
this.rightId = rightId;
}
public Integer getRightType() {
return rightType;
}
public void setRightType(Integer rightType) {
this.rightType = rightType;
}
public String getRightTypeDesc() {
return rightTypeDesc;
}
public void setRightTypeDesc(String rightTypeDesc) {
this.rightTypeDesc = rightTypeDesc;
}
public String getRightName() {
return rightName;
}
public void setRightName(String rightName) {
this.rightName = rightName;
}
public Integer getMenuId() {
return menuId;
}
public void setMenuId(Integer menuId) {
this.menuId = menuId;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public String getMenuUrl() {
return menuUrl;
}
public void setMenuUrl(String menuUrl) {
this.menuUrl = menuUrl;
}
public Integer getParentMenuId() {
return parentMenuId;
}
public void setParentMenuId(Integer parentMenuId) {
this.parentMenuId = parentMenuId;
}
}
|
package com.redhat.service.bridge.manager.models;
import java.time.ZonedDateTime;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Version;
import com.redhat.service.bridge.infra.api.APIConstants;
import com.redhat.service.bridge.infra.models.dto.BridgeStatus;
import com.redhat.service.bridge.infra.models.dto.ProcessorDTO;
import com.redhat.service.bridge.infra.models.filters.BaseFilter;
import com.redhat.service.bridge.infra.models.filters.FilterFactory;
import com.redhat.service.bridge.manager.api.models.responses.ProcessorResponse;
@NamedQueries({
@NamedQuery(name = "PROCESSOR.findByBridgeIdAndName",
query = "from Processor p where p.name=:name and p.bridge.id=:bridgeId"),
@NamedQuery(name = "PROCESSOR.findByStatus",
query = "from Processor p join fetch p.bridge left join fetch p.filters join fetch p.action join fetch p.action.parameters where p.status in (:statuses) and p.bridge.status='AVAILABLE'"),
@NamedQuery(name = "PROCESSOR.findByIdBridgeIdAndCustomerId",
query = "from Processor p join fetch p.bridge left join fetch p.filters join fetch p.action join fetch p.action.parameters where p.id=:id and (p.bridge.id=:bridgeId and p.bridge.customerId=:customerId)"),
@NamedQuery(name = "PROCESSOR.findByBridgeIdAndCustomerId",
query = "from Processor p join fetch p.bridge left join fetch p.filters join fetch p.action join fetch p.action.parameters where p.bridge.id=:bridgeId and p.bridge.customerId=:customerId"),
@NamedQuery(name = "PROCESSOR.countByBridgeIdAndCustomerId",
query = "select count(p.id) from Processor p where p.bridge.id=:bridgeId and p.bridge.customerId=:customerId"),
@NamedQuery(name = "PROCESSOR.idsByBridgeIdAndCustomerId",
query = "select p.id from Processor p where p.bridge.id=:bridgeId and p.bridge.customerId=:customerId order by p.submittedAt asc"),
@NamedQuery(name = "PROCESSOR.findByIds",
query = "select p, p.action from Processor p join fetch p.bridge left join fetch p.filters join fetch p.action join fetch p.action.parameters where p.id in (:ids)")
})
@Entity
public class Processor {
public static final String ID_PARAM = "id";
public static final String NAME_PARAM = "name";
public static final String BRIDGE_ID_PARAM = "bridgeId";
@Id
private String id = UUID.randomUUID().toString();
@Column(nullable = false, name = "name")
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "bridge_id")
private Bridge bridge;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Action action;
@Version
private long version;
@Column(name = "submitted_at", updatable = false, nullable = false, columnDefinition = "TIMESTAMP")
private ZonedDateTime submittedAt;
@Column(name = "published_at", columnDefinition = "TIMESTAMP")
private ZonedDateTime publishedAt;
@Column(name = "status")
@Enumerated(EnumType.STRING)
private BridgeStatus status;
@OneToMany(mappedBy = "processor", fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
private Set<Filter> filters;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Bridge getBridge() {
return bridge;
}
public void setBridge(Bridge bridge) {
this.bridge = bridge;
}
public long getVersion() {
return version;
}
public ZonedDateTime getSubmittedAt() {
return submittedAt;
}
public void setSubmittedAt(ZonedDateTime submittedAt) {
this.submittedAt = submittedAt;
}
public ZonedDateTime getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(ZonedDateTime publishedAt) {
this.publishedAt = publishedAt;
}
public BridgeStatus getStatus() {
return status;
}
public void setStatus(BridgeStatus status) {
this.status = status;
}
public Action getAction() {
return action;
}
public void setAction(Action action) {
this.action = action;
}
public void setFilters(Set<Filter> filters) {
this.filters = filters;
}
public ProcessorResponse toResponse() {
ProcessorResponse processorResponse = new ProcessorResponse();
processorResponse.setId(id);
processorResponse.setName(name);
processorResponse.setStatus(status);
processorResponse.setPublishedAt(publishedAt);
processorResponse.setSubmittedAt(submittedAt);
if (this.bridge != null) {
processorResponse.setHref(APIConstants.USER_API_BASE_PATH + bridge.getId() + "/processors/" + id);
processorResponse.setBridge(this.bridge.toResponse());
}
processorResponse.setFilters(buildFilters());
processorResponse.setAction(action.toActionRequest());
return processorResponse;
}
public ProcessorDTO toDTO() {
ProcessorDTO dto = new ProcessorDTO();
dto.setStatus(this.status);
dto.setName(this.name);
dto.setId(this.id);
dto.setFilters(buildFilters());
if (this.bridge != null) {
dto.setBridge(this.bridge.toDTO());
}
dto.setAction(this.action.toActionRequest());
return dto;
}
/*
* See: https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
* In the context of JPA equality, our id is our unique business key as we generate it via UUID.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Processor processor = (Processor) o;
return id.equals(processor.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
private Set<BaseFilter> buildFilters() {
if (this.filters == null) {
return null;
}
return this.filters
.stream()
.map(x -> FilterFactory.buildFilter(x.getType(), x.getKey(), x.getValue()))
.collect(Collectors.toSet());
}
}
|
package IO;
/**
* Created by Netai Benaim
* for G-Lab, Hebrew University of Jerusalem
* contact at: netai.benaim@mail.huji.ac.il
* version:
* <p>
* this is Protocol in IO
* created on 9/12/2016
*/
public enum Protocol {
DELIMITER ("#"), REWARD ("REW");
private final String str;
Protocol(String str){
this.str = str;
}
public String str(){
return str;
}
@Override
public String toString() {
return str;
}
}
|
package com.example.demo.security;
import com.example.demo.model.AppUser;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserDetailServiceImpl implements UserDetailsService {
private final UserService userService;
@Autowired
public UserDetailServiceImpl(UserService userService) {
this.userService = userService;
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
/*
todo
Optional<AppUser> user = userRepository.findByUsername(s);
user.orElseThrow(() -> new UsernameNotFoundException(s + " not found."));
return user.map(UserDetailServiceImpl::new).get();
/**/
return userService.findByUsername(s);
}
}
|
package model.dto.shop;
public class couponDTO {
String cCode;
public String getcCode() {
return cCode;
}
public void setcCode(String cCode) {
this.cCode = cCode;
}
public couponDTO(String cCode) {
super();
this.cCode = cCode;
}
public couponDTO() {}
}
|
package ioreadstring.transaction;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class TransactionManager {
List<BankAccount> accounts = new ArrayList<>();
public void uploadListFromFile(String path) {
try {
List<String> lines = Files.readAllLines(Path.of(path));
for (String line : lines) {
accounts.add(getBankAccountFromString(line));
}
} catch (IOException ex) {
throw new IllegalStateException("File not found", ex);
}
}
public void makeTransactions(String path) {
try {
List<String> lines = Files.readAllLines(Path.of(path));
for (String line : lines) {
doTransaction(line);
}
} catch (IOException ex) {
throw new IllegalStateException("File not found", ex);
} catch (
NumberFormatException e) {
throw new IllegalStateException("Invalid format", e);
}
}
private void doTransaction(String transStr) {
String[] splittedStr = transStr.split(";");
BankAccount foundedAccount = findBankAccount(splittedStr[0]);
if (foundedAccount != null) {
foundedAccount.setBalance(Long.parseLong(splittedStr[1]));
}
}
private BankAccount findBankAccount(String accountNumber) {
for (BankAccount item : accounts) {
if (item.getAccountNumber().equals(accountNumber)) {
return item;
}
}
return null;
}
private BankAccount getBankAccountFromString(String str) {
String[] splittedStr = str.split(";");
return new BankAccount(splittedStr[0], splittedStr[1], Long.parseLong(splittedStr[2]));
}
public List<BankAccount> getAccountList() {
return accounts;
}
}
|
package com.trump.auction.back.configue.datasource;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.miemiedev.mybatis.paginator.OffsetLimitInterceptor;
import com.github.miemiedev.mybatis.paginator.dialect.MySQLDialect;
import com.github.pagehelper.PageHelper;
@Configuration
public class DataSourceHelp {
@Value("${mybatis.mapperLocations}")
protected String mapperLocations;
@Value("${mybatis.typeAliasesPackage}")
protected String typeAliasesPackage;
@Value("${auction.bid.detail.table.range}")
protected String auctionBidetailTableRange;
@Value("${datasource.driver-class-name}")
protected String driverClassName;
@Value("${datasource.filters}")
protected String filters;
@Value("${datasource.maxActive}")
protected int maxActive;
@Value("${datasource.initialSize}")
protected int initialSize;
@Value("${datasource.maxWait}")
protected int maxWait;
@Value("${datasource.minIdle}")
protected int minIdle;
@Value("${datasource.timeBetweenEvictionRunsMillis}")
protected int timeBetweenEvictionRunsMillis;
@Value("${datasource.minEvictableIdleTimeMillis}")
protected int minEvictableIdleTimeMillis;
@Value("${datasource.validationQuery}")
protected String validationQuery;
@Value("${datasource.testWhileIdle}")
protected boolean testWhileIdle;
@Value("${datasource.testOnBorrow}")
protected boolean testOnBorrow;
@Value("${datasource.testOnReturn}")
protected boolean testOnReturn;
@Value("${datasource.poolPreparedStatements}")
protected boolean poolPreparedStatements;
@Value("${datasource.maxOpenPreparedStatements}")
protected int maxPoolPreparedStatementPerConnectionSize;
public DruidDataSource buildDruidDataSource() {
DruidDataSource baseDataSource = new DruidDataSource();
baseDataSource.setMaxActive(maxActive);
baseDataSource.setInitialSize(initialSize);
baseDataSource.setMaxWait(maxWait);
baseDataSource.setMinIdle(minIdle);
baseDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
baseDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
baseDataSource.setValidationQuery(validationQuery);
baseDataSource.setTestWhileIdle(testWhileIdle);
baseDataSource.setTestOnBorrow(testOnBorrow);
baseDataSource.setTestOnReturn(testOnReturn);
baseDataSource.setPoolPreparedStatements(poolPreparedStatements);
baseDataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
return baseDataSource;
}
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws ClassNotFoundException {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setTypeAliasesPackage(typeAliasesPackage);
Class<?>[] typeAliases = {
Class.forName("com.trump.auction.back.sys.model.Module"),
Class.forName("com.trump.auction.back.sys.model.Role"),
Class.forName("com.trump.auction.back.sys.model.RoleModule"),
Class.forName("com.trump.auction.back.sys.model.SysUser"),
Class.forName("com.trump.auction.back.sys.model.UserRole"),
Class.forName("com.trump.auction.back.sys.model.ZTree"),
Class.forName("com.trump.auction.back.sys.model.SysLog"),
Class.forName("com.trump.auction.back.sys.model.Config")};
bean.setTypeAliases(typeAliases);
Properties props = new Properties();
props.setProperty("reasonable", "true");
props.setProperty("supportMethodsArguments", "true");
props.setProperty("returnPageInfo", "check");
props.setProperty("params", "count=countSql");
props.setProperty("dialect", "mysql");
props.setProperty("offsetAsPageNum", "true");
props.setProperty("rowBoundsWithCount", "true");
try {
bean.setDataSource(dataSource);
PageHelper pageHelper = new PageHelper();
pageHelper.setProperties(props);
bean.setPlugins(new Interceptor[]{pageHelper});
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setMapperLocations(resolver.getResources(mapperLocations));
return bean.getObject();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
|
package com.zantong.mobilecttx.interf;
import android.view.View;
public interface IBaseFragment {
public void initView(View view);
public void initData();
}
|
package cn.run;
import java.io.FileNotFoundException;
import java.io.IOException;
import cn.domain.Config;
import cn.net.Service;
public class Run {
/**
* @param args
*/
public static void main(String[] args) {
Config scon = new Config("Service.properties");
System.out.println(scon.getInt("ServerPort"));
Service ser = new Service(scon.getInt("ServerPort"));
try {
ser.OpenService();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package template;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
* A class to store simple information about a template statement.
*/
public class Template {
int templateID;
String statement;
public Template(ResultSet rs){
try {
templateID = rs.getInt("templateID");
statement = rs.getString("statement");
}catch(SQLException e){
System.out.println(e+" Error creating Template");
}
}
public Template(int id, String text){
templateID = id;
statement = text;
}
public int getTemplateID(){
return templateID;
}
public String getStatement(){
return statement;
}
public String toString(){
return statement;
}
}
|
package it.univr.domain;
public interface AbstractValue {
public AbstractValue leastUpperBound(AbstractValue other);
public AbstractValue widening(AbstractValue other);
public String toString();
public AbstractValue greatestLowerBound(AbstractValue value);
public AbstractValue narrowing(AbstractValue value);
public default int distanceFromBottom() {
return 0;
}
public default String distanceFrom(AbstractValue other) {
return "-";
}
}
|
package Replica3.resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.Date;
public class Log {
private File file;
private BufferedWriter writer;
public Log (String[] path) {
String fileSeparator = System.getProperty("file.separator");
String fileName = "";
for (int i = 0; i < path.length - 1; i++) {
fileName += path[i];
fileName += fileSeparator;
}
File file = new File(fileName);
if (!file.exists()) {
file.mkdirs();
}
fileName += path[path.length - 1];
initLog(fileName);
}
public Log(String fileName) {
initLog(fileName);
}
private void initLog(String fileName) {
file = new File(fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
writer = new BufferedWriter(new FileWriter(file.getAbsolutePath(), true));
}
catch (FileNotFoundException e) {
System.out.println("Warning: \"" + fileName + "\" cannot be found.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Warning: \"" + fileName + "\" cannot be opened.");
e.printStackTrace();
}
}
private String timeStamp() {
return new Timestamp(new Date().getTime()).toString();
}
public void write(String msg) {
try {
writer.append("[" + timeStamp() + "]: " + msg);
writer.newLine();
writer.flush();
} catch (IOException e) {
System.out.println("Warning: \"" + file.getName() + "\" cannot be written.");
e.printStackTrace();
}
}
public void close() {
try {
writer.close();
}
catch (IOException e) {
System.out.println("Warning: \"" + file.getName() + "\" cannot be closed." );
e.printStackTrace();
}
}
public static void main(String[] args) {
Log log = new Log(new String[] {(Paths.get("").toAbsolutePath().toString()), "src", "server", "logs", "log.txt"});
log.write("first message.");
}
}
|
package com.jstf.selenium;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Point;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.jstf.accessibility.JAXE;
import com.jstf.accessibility.JAXE.AxeReportLevel;
import com.jstf.accessibility.JAXE.AxeTag;
import com.jstf.config.JConfig;
import lombok.Cleanup;
public class JElement {
private static final int retryInterval = 100;
private List<JSelector> byList = new ArrayList<>();
private JDriver jDriver;
private WebDriver driver;
private Exception resultException = null;
public JElement(JDriver qDriver, By... bys) {
this(qDriver, ElementSelectionType.ALL, bys);
}
public JElement(JElement jElement, String cssSelector) {
this(jElement, By.cssSelector(cssSelector));
}
public JElement(JElement jElement, ElementSelectionType elementSelectionType, String cssSelector) {
this(jElement, elementSelectionType, By.cssSelector(cssSelector));
}
public JElement(JElement jElement, By... bys) {
this(jElement, ElementSelectionType.ALL, bys);
}
public JElement(JDriver jDriver, ElementSelectionType elementSelectionType, By... bys) {
this.jDriver = jDriver;
this.driver = jDriver.getDriver();
for(int i=0;i<bys.length;i++) {
if(i==bys.length-1) {
byList.add(new JSelector(bys[i], elementSelectionType));
}else {
byList.add(new JSelector(bys[i], ElementSelectionType.ALL));
}
}
}
public JElement(JElement jElement, ElementSelectionType elementSelectionType, By... bys) {
this.byList = new ArrayList<>(jElement.byList);
this.jDriver = jElement.getJDriver();
this.driver = jDriver.getDriver();
for(int i=0;i<bys.length;i++) {
if(i==bys.length-1) {
byList.add(new JSelector(bys[i], elementSelectionType));
}else {
byList.add(new JSelector(bys[i], ElementSelectionType.ALL));
}
}
}
public JDriver getJDriver() {
return this.jDriver;
}
public JElement find(By... bys) {
return find(ElementSelectionType.ALL, bys);
}
public JElement find(ElementSelectionType elementSelectionType, By... bys) {
return new JElement(this, elementSelectionType, bys);
}
public JElement find(String cssSelector) {
return find(ElementSelectionType.ALL, cssSelector);
}
public JElement find(ElementSelectionType elementSelectionType, String cssSelector) {
return new JElement(this, cssSelector);
}
public List<WebElement> getWebElements() throws Exception {
@Cleanup JDriverWait jDriverWait = new JDriverWait(jDriver, 1);
List<WebElement> elements = null;
for (JSelector jBy : byList) {
if(elements==null) {
elements = driver.findElements(jBy.getBy());
elements = filterElementSelection(elements, jBy.getElementSelectionType());
}else {
if(elements.size()==0) {
return elements;
}
elements = getSubElements(elements, jBy);
}
}
return elements;
}
public List<WebElement> filterElementSelection(List<WebElement> elements, ElementSelectionType elementSelectionType){
List<WebElement> filteredElements = new ArrayList<>();
switch(elementSelectionType) {
case FIRST:
filteredElements.add(elements.get(0));
break;
case LAST:
filteredElements.add(elements.get(elements.size()-1));
break;
case RANDOM:
int randomIndex = (int) (Math.random() * elements.size());
filteredElements.add(elements.get(randomIndex));
break;
default:
filteredElements = new ArrayList<>(elements);
}
return filteredElements;
}
public WebElement getWebElement() throws Exception {
List<WebElement> webElements = getWebElements();
int size = webElements.size();
if(size==0) {
throw new Exception("This element is not found. By List:" + this.byList);
}
if(size>1) {
throw new Exception(size + " elements are found. By List:" + this.byList);
}
return webElements.get(0);
}
public WebElement getRandomElement() throws Exception {
List<WebElement> elements = getWebElements();
if(elements.size()==0) {
throw new Exception("No element found.");
}
int randomIndex = (int) (Math.random() * elements.size());
return elements.get(randomIndex);
}
private List<WebElement> getSubElements(List<WebElement> elements, JSelector jBy){
List<WebElement> results = new ArrayList<>();
for (WebElement element : elements) {
results.addAll(element.findElements(jBy.getBy()));
}
results = filterElementSelection(results, jBy.getElementSelectionType());
return results;
}
public JElement getParentElement() throws Exception{
return find(By.xpath("./.."));
}
public JElement clear() throws Exception{
isDisplayed();
Exception resultException = null;
for(int i = 0; i< JConfig.ELEMENT_RETRYTIMES; i++) {
try{
focus();
getWebElement().clear();
return this;
}catch(Exception e) {
resultException = e;
Thread.sleep(retryInterval);
}
}
throw resultException;
}
public JElement click() throws Exception {
assertDisplayed();
Exception resultException = null;
for(int i = 0; i< JConfig.ELEMENT_RETRYTIMES; i++) {
try{
focus();
getWebElement().click();
return this;
}catch(Exception e) {
resultException = e;
Thread.sleep(retryInterval);
}
}
throw resultException;
}
public JElement hover() throws Exception {
return hover(null);
}
public JElement hover(ExpectedCondition<Boolean> expectedCondition) throws Exception {
focus();
Exception resultException = null;
for(int i = 0; i< JConfig.ELEMENT_RETRYTIMES; i++) {
try{
new Actions(driver).moveToElement(this.getWebElement()).perform();
if(expectedCondition!=null) {
new WebDriverWait(driver, 1).until(expectedCondition);
}
return this;
}catch(Exception e) {
resultException = e;
Thread.sleep(retryInterval);
}
}
throw resultException;
}
public String getAttribute(String name) throws Exception{
assertExists();
Exception resultException = null;
for(int i = 0; i< JConfig.ELEMENT_RETRYTIMES; i++) {
try{
return getWebElement().getAttribute(name);
}catch(Exception e) {
resultException = e;
Thread.sleep(retryInterval);
}
}
throw resultException;
}
public String getTagName() throws Exception {
assertExists();
Exception resultException = null;
for(int i = 0; i< JConfig.ELEMENT_RETRYTIMES; i++) {
try{
return getWebElement().getTagName();
}catch(Exception e) {
resultException = e;
Thread.sleep(retryInterval);
}
}
throw resultException;
}
public String getText() throws Exception{
assertExists();
Exception resultException = null;
for(int i = 0; i< JConfig.ELEMENT_RETRYTIMES; i++) {
try{
return getWebElement().getText();
}catch(Exception e) {
resultException = e;
Thread.sleep(retryInterval);
}
}
throw resultException;
}
public String getValue() throws Exception{
assertExists();
Exception resultException = null;
for(int i = 0; i< JConfig.ELEMENT_RETRYTIMES; i++) {
try{
return getWebElement().getAttribute("value");
}catch(Exception e) {
resultException = e;
Thread.sleep(retryInterval);
}
}
throw resultException;
}
public boolean isDisplayed() throws Exception {
return isDisplayed(JConfig.ELEMENT_TIMEOUT);
}
public boolean isDisplayed(int timeoutInSeconds) throws Exception{
try {
return new WebDriverWait(driver, timeoutInSeconds).until(JExpectedConditions.isDisplayed(this));
}catch (TimeoutException e) {
return false;
}
}
public boolean exists() throws Exception {
return exists(JConfig.ELEMENT_TIMEOUT);
}
public boolean exists(int timeoutInSeconds) throws Exception{
try {
return new WebDriverWait(driver, timeoutInSeconds).until(JExpectedConditions.exists(this));
}catch (TimeoutException e) {
return false;
}
}
public boolean isVisibleInViewport()throws Exception{
return (Boolean)((JavascriptExecutor)driver).executeScript(
"var elem = arguments[0], " +
" box = elem.getBoundingClientRect(), " +
" cx = box.left + box.width / 2, " +
" cy = box.top + box.height / 2, " +
" e = document.elementFromPoint(cx, cy); " +
"for (; e; e = e.parentElement) { " +
" if (e === elem) " +
" return true; " +
"} " +
"return false; "
, getWebElement());
}
public boolean isEnabled() throws Exception {
return isEnabled(JConfig.ASSERTION_TIMEOUT);
}
public boolean isEnabled(int timeoutInSeconds) throws Exception{
try {
return new WebDriverWait(driver, timeoutInSeconds).until(JExpectedConditions.isEnabled(this));
}catch (TimeoutException e) {
return false;
}
}
public boolean textEquals(String text) throws Exception {
return textEquals(text, JConfig.ASSERTION_TIMEOUT);
}
public boolean textEquals(String text, int timeoutInSeconds) throws Exception {
return new WebDriverWait(driver, timeoutInSeconds).until(JExpectedConditions.textEquals(this, text));
}
public boolean textNotEquals(String text) throws Exception {
return textNotEquals(text, JConfig.ASSERTION_TIMEOUT);
}
public boolean textNotEquals(String text, int timeoutInSeconds) throws Exception {
return new WebDriverWait(driver, timeoutInSeconds).until(JExpectedConditions.textNotEquals(this, text));
}
public boolean valueEquals(String value) throws Exception {
return valueEquals(value, JConfig.ASSERTION_TIMEOUT);
}
public boolean valueEquals(String value, int timeoutInSeconds) throws Exception {
return new WebDriverWait(driver, timeoutInSeconds).until(JExpectedConditions.valueEquals(this, value));
}
public boolean valueNotEquals(String value) throws Exception {
return valueNotEquals(value, JConfig.ASSERTION_TIMEOUT);
}
public boolean valueNotEquals(String value, int timeoutInSeconds) throws Exception {
return new WebDriverWait(driver, timeoutInSeconds).until(JExpectedConditions.valueNotEquals(this, value));
}
public boolean isNotDisplayed() throws Exception {
return isNotDisplayed(JConfig.ASSERTION_TIMEOUT);
}
public boolean isNotDisplayed(int timeoutInSeconds) throws Exception{
try {
return new WebDriverWait(driver, timeoutInSeconds).until(JExpectedConditions.isNotDisplayed(this));
}catch (TimeoutException e) {
return false;
}
}
public boolean isSelected() throws Exception {
int timeOut = 3;
return isSelected(timeOut);
}
public boolean isSelected(int timeOutInSeconds) throws Exception {
assertDisplayed();
try {
return new WebDriverWait(driver, timeOutInSeconds).until(JExpectedConditions.isSelected(this));
}catch (Exception e) {
return false;
}
}
public JElement input(String inputStr) throws Exception {
return input(inputStr, inputStr);
}
public JElement input(String inputStr, String expectedValue) throws Exception {
assertDisplayed();
for(int i = 0; i< JConfig.ELEMENT_RETRYTIMES; i++) {
try{
WebElement element = getWebElement();
this.clear();
element.sendKeys(inputStr);
if(valueEquals(expectedValue)) {
return this;
}else {
throw new Exception("Send keys failed. Input str: " + inputStr + ", expectedValue:" + expectedValue + ", Actual value:" + getValue());
}
}catch(Exception e) {
resultException = e;
Thread.sleep(retryInterval);
}
}
throw resultException;
}
public int size() throws Exception{
return getWebElements().size();
}
public void focus() throws Exception{
assertDisplayed();
for(int i = 0; i< JConfig.ELEMENT_RETRYTIMES; i++) {
try{
if(!isVisibleInViewport() && getWebElement().getSize().height<200) {
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("arguments[0].scrollIntoView({block: \"center\"});",getWebElement());
if(!isPositioned()) {
throw new Exception("Element is still moving.");
}
}
return;
}catch(Exception e) {
resultException = e;
Thread.sleep(retryInterval);
}
}
throw resultException;
}
/**
* Check element is at a fixed position. This function is to avoid to click on a moving element.
* @return
*/
public boolean isPositioned() {
return isPositioned(JConfig.ELEMENT_TIMEOUT);
}
/**
* Check element is at a fixed position. This function is to avoid to click on a moving element.
* @param timeOutInSeconds
* @return
*/
public boolean isPositioned(int timeOutInSeconds) {
return new WebDriverWait(driver, timeOutInSeconds).until(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
Point elementPosition = getWebElement().getLocation();
Thread.sleep(500);
return getWebElement().getLocation().equals(elementPosition);
}catch (Exception e) {
return false;
}
}
});
}
public void validateAccessibility() throws Exception {
new JAXE(jDriver).validate(this);
}
public void validateAccessibility(AxeReportLevel reportLevel, AxeTag...tags) throws Exception {
new JAXE(jDriver, reportLevel, tags).validate(this);
}
private void assertDisplayed() throws Exception {
if(!isDisplayed()) {
throw new Exception("Element not found either not displayed. By List:" + this.byList);
}
}
private void assertExists() throws Exception {
if(!exists()) {
throw new Exception("Element does not exist. By List:" + this.byList);
}
}
}
|
/*
* Created on 2005-2-5
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.aof.component.helpdesk;
import java.io.Serializable;
/**
* @author Daniel Liao
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class ProblemType implements Serializable{
/** The cached hash code value for this instance. Settting to 0 triggers re-calculation. */
private int hashValue = 0;
/** The composite primary key value. */
private Integer id;
/** The composite description*/
private String desc;
// /**
// * Implementation of the equals comparison on the basis of equality of the primary key values.
// * @param rhs
// * @return boolean
// */
// public boolean equals(Object rhs)
// {
// if (rhs == null)
// return false;
// if (! (rhs instanceof CallType))
// return false;
// CallType that = (CallType) rhs;
// if (this.getID() != null && that.getType() != null)
// {
// if (! this.getID().equals(that.getType()))
// {
// return false;
// }
// }
// return true;
// }
//
// /**
// * Implementation of the hashCode method conforming to the Bloch pattern with
// * the exception of array properties (these are very unlikely primary key types).
// * @return int
// */
// public int hashCode()
// {
// if (this.hashValue == 0)
// {
// int result = 17;
// int typeValue = this.getID() == null ? 0 : this.getID().hashCode();
// result = result * 37 + typeValue;
// this.hashValue = result;
// }
// return this.hashValue;
// }
/**
* @return
*/
public String getDesc() {
return desc;
}
/**
* @return
*/
public Integer getId() {
return id;
}
/**
* @param string
*/
public void setDesc(String string) {
desc = string;
}
/**
* @param integer
*/
public void setId(Integer integer) {
id = integer;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Fruit;
/**
*
* @author Go Eun Sung
*/
public abstract class Fruit {
private int price, weight;
//constructor
public Fruit(int price, int weight) {
this.price = price;
this.weight = weight;
}
//getter & setter
public int getPrice() {
return price;
}
public void setPrice(int price) {
if (price > 0) {
this.price = price;
}
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
if (weight > 0) {
this.weight = weight;
}
}
//method
public abstract String origin();
public abstract String distribution();
}
|
import java.util.ArrayList;
public class ConvertBSTtoGreaterTree {
/**
* Given a Binary Search Tree (BST), convert it to a Greater Tree such that
* every key of the original BST is changed to the original key plus sum of
* all keys greater than the original key in BST.
* Input: The root of a Binary Search Tree like this:
5
/ \
2 13
Output: The root of a Greater Tree like this:
18
/ \
20 13
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
ArrayList<Integer> db = new ArrayList<Integer>();
public TreeNode convertBST(TreeNode root) {
store(root);
System.out.println(db);
return convert(root);
}
public void store(TreeNode root) {
if (root == null)
return;
db.add(root.val);
store(root.left);
store(root.right);
}
public TreeNode convert(TreeNode root) {
if (root == null)
return null;
int nval = root.val;
root.left = convert(root.left);
root.right = convert(root.right);
for (int i = 0; i < db.size(); i++) {
if (db.get(i) > root.val)
nval += db.get(i);
}
root.val = nval;
return root;
}
int sum = 0;
public TreeNode convertBST2(TreeNode root) {
if (root == null)
return null;
convertBST(root.right);
root.val += sum;
sum = root.val;
convertBST(root.left);
return root;
}
/**
* Method 1: Using an arraylist to store verything and check each node to
* add, which is O(n^2)
* Method 2: Logic behind this is that first check iz
* rightnode, then itself, and left one. The whole process is cumulative, so
* we just keep track of the adding value.
*/
}
|
package dev.demo.spring5webfluxrest.coverters;
import dev.demo.spring5webfluxrest.commands.CategoryCommand;
import dev.demo.spring5webfluxrest.domain.Category;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CategoryCommandToCategoryConverterTest {
private static final String ID_VALUE = "testId";
private static final String DESCRIPTION = "test";
private CategoryCommandToCategoryConverter converter;
@BeforeEach
void setUp() {
converter = new CategoryCommandToCategoryConverter();
}
@Test
void testNull() {
assertNull(converter.convert(null));
}
@Test
void testNotNull() {
assertNotNull(converter.convert(new CategoryCommand()));
}
@Test
void convert() {
CategoryCommand categoryCommand = CategoryCommand.builder().id(ID_VALUE).description(DESCRIPTION).build();
final Category convert = converter.convert(categoryCommand);
assertEquals(ID_VALUE, convert.getId());
assertEquals(DESCRIPTION, convert.getDescription());
}
} |
package com.assignment.nalin.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@Entity
@Table(name = "departments")
public class Department {
@EmbeddedId
private DepartmentId departmentId;
// @NotBlank(message = "name is mandatory")
// @Size(max = 255)
// private String name;
// @NotBlank(message = "location is mandatory")
// @Size(max = 255)
// private String location;
@OneToMany(mappedBy = "department",fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private Set<Course> courses = new HashSet<>();
@OneToMany(mappedBy = "department",fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private Set<Instructor> instructors = new HashSet<>();
public Department() {
}
public Department(DepartmentId departmentId, String name, String location, Set<Course> courses,Set<Instructor> instructors) {
this.departmentId = departmentId;
//this.name = name;
//this.location = location;
this.courses = courses;
this.instructors = instructors;
}
public DepartmentId getDepartmentId() {
return departmentId;
}
public void setDepartmentId(DepartmentId departmentId) {
this.departmentId = departmentId;
}
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public String getLocation() {
// return location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
public Set<Instructor> getInstructors() {
return instructors;
}
public void setInstructors(Set<Instructor> instructors) {
this.instructors = instructors;
}
}
|
/*
* Name: Luis Gustavo Grubert Valensuela Z#:23351882 lvalensuela2015@fau.edu
* Course: JavaProgramming
* Professor: Dr. Mehrdad Nojoumian
* Due Date:04/12/2018 Due Time: 11:30PM
* Assignment Number: lab 08
* Last Changed: 03/29/2018
*
* Description:
* Program to show the creation of an interface
*/
package lab10.q2;
/**
* Mustang class that implements the Car Interface
* @author valen
*/
public class Mustang implements Car{
private int gear = 0;
private int speed = 0;
boolean applyBrakes;
/**
* Default Constructor
*/
public Mustang()
{
}
/**
* Mutator method to change the gear value
* @param newGear
*/
@Override
public void changeGear(int newGear)
{
gear =newGear;
}
/**
* Mutator method to increment the speed value
* @param increment
*/
@Override
public void speedUp(int increment)
{
speed+= increment;
}
/**
* Mutator method to decrement the speed value
* @param decrement
*/
@Override
public void applyBrakes(int decrement)
{
speed-=decrement;
}
/**
* Method to print the states of the object of type Mustang
*/
void printStates(){
System.out.println("Speed: " + speed);
System.out.println("gear: " + gear);
}
}
|
package com.example.proyectogrupal;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.bumptech.glide.Glide;
import com.example.proyectogrupal.entidades.IncidenciaDto;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
public class DetallesActivity extends AppCompatActivity {
String id;
String nombre;
String descripcion;
int ubicacion;
boolean estado;
ToggleButton toggleButton;
EditText editTextComentario;
String comentario;
DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detalles);
databaseReference = FirebaseDatabase.getInstance().getReference("Incidencias");
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReference = firebaseStorage.getReference();
//Obtener el id del equipo seleccionado en la anterior actividad.
Intent intent = getIntent();
id = intent.getData().toString();
Log.d("infoApp", id);
StorageReference imagenesRef = storageReference.child("3178.png");
//Cargar la imagen del equipo sin descargarla
ImageView imageViewFoto = findViewById(R.id.imageViewFoto);
Glide.with(this).load(imagenesRef).into(imageViewFoto);
databaseReference.child("1").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null){
IncidenciaDto incidenciaDto = dataSnapshot.getValue(IncidenciaDto.class);
Log.d("infoApp", incidenciaDto.getNombre()+"hola");
TextView textViewTituloNombre = findViewById(R.id.textViewTituloNombre);
nombre = incidenciaDto.getNombre();
textViewTituloNombre.setText("Detalles de incidencia: "+nombre);
TextView textViewDescripcion = findViewById(R.id.textViewDescripcion);
descripcion = incidenciaDto.getDescripcion();
textViewDescripcion.setText(descripcion);
/*
TextView textViewUbicacion = findViewById(R.id.textViewUbicacion);
ubicacion = incidenciaDto.getUbicacion();
textViewUbicacion.setText(String.valueOf(ubicacion));
*/
toggleButton = findViewById(R.id.toggleButton);
toggleButton.setChecked(incidenciaDto.isEstado());
editTextComentario = findViewById(R.id.editTextComentario);
editTextComentario.setText(incidenciaDto.getComentario());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public void btnGuardar(View view){
IncidenciaDto incidenciaDto = new IncidenciaDto();
//Poner los valores antiguos
incidenciaDto.setId(id);
incidenciaDto.setNombre(nombre);
incidenciaDto.setDescripcion(descripcion);
// incidenciaDto.setUbicacion(ubicacion);
//Valor del switch
estado = toggleButton.isChecked();
incidenciaDto.setEstado(estado);
Log.d("infoApp", String.valueOf(estado));
//Valor del comentario
comentario = String.valueOf(editTextComentario.getText());
incidenciaDto.setComentario(comentario);
databaseReference.child(String.valueOf(id)).setValue(incidenciaDto);
finish();
}
} |
/* Ara - capture species and specimen data
*
* Copyright (C) 2009 INBio ( Instituto Nacional de Biodiversidad )
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.inbio.ara.dto.agent;
import org.inbio.ara.dto.BaseEntityOrDTOFactory;
import org.inbio.ara.persistence.audiences.Audience;
/**
*
* @author esmata
*/
public class AudienceDTOFactory
extends BaseEntityOrDTOFactory<Audience, AudienceDTO> {
@Override
public Audience getEntityWithPlainValues(AudienceDTO dto) {
if(dto == null) return null;
Audience result = new Audience();
result.setAudienceId(dto.getAudienceId());
result.setDescription(dto.getDescription());
result.setName(dto.getName());
return result;
}
@Override
public Audience updateEntityWithPlainValues(AudienceDTO dto, Audience e) {
if(dto == null || e == null) return null;
e.setAudienceId(dto.getAudienceId());
e.setDescription(dto.getDescription());
e.setName(dto.getName());
return e;
}
public AudienceDTO createDTO(Audience entity) {
if(entity == null) return null;
AudienceDTO result = new AudienceDTO();
result.setAudienceId(entity.getAudienceId());
result.setDescription(entity.getDescription());
result.setName(entity.getName());
result.setSelected(false); //Inicialmente debe ser falso
return result;
}
}
|
package com.bnrc.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.impl.cookie.BrowserCompatSpecFactory;
import u.aly.br;
import u.aly.cu;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.bnrc.busapp.R;
import com.bnrc.ui.rtBus.Child;
import com.bnrc.ui.rtBus.Group;
import com.bnrc.ui.rtBus.historyItem;
import com.bnrc.util.collectwifi.Constants;
import android.R.integer;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.util.Log;
@SuppressLint("SdCardPath")
public class PCUserDataDBHelper extends SQLiteOpenHelper {
private static final String TAG = PCUserDataDBHelper.class.getSimpleName();
// The Android's default system path of your application database.
private static PCUserDataDBHelper instance;
public static String DB_PATH = "/data/data/com.bnrc.busapp/databases/";
public static String DB_NAME = "userdata.db";
public SQLiteDatabase myDataBase;
public Context myContext;
public ArrayList<ArrayList<String>> alertStations = null;
public ArrayList<ArrayList<String>> favStations = null;
public ArrayList<ArrayList<String>> favBuslines = null;
private static PCDataBaseHelper mPcDataBaseHelper;
private static SharePrefrenceUtil mSharePrefrenceUtil;
public static PCUserDataDBHelper getInstance(Context context) {
if (instance == null) {
try {
DB_PATH = context.getFilesDir().getAbsolutePath();
DB_PATH = DB_PATH.replace("files", "databases/");
instance = new PCUserDataDBHelper(context);
mPcDataBaseHelper = PCDataBaseHelper.getInstance(context);
mSharePrefrenceUtil = SharePrefrenceUtil.getInstance(context);
instance.myContext = context;
instance.openDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
}
return instance;
}
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
* @throws IOException
*/
public PCUserDataDBHelper(Context context) throws IOException {
super(context, DB_NAME, null, 1);
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
try {
// ����ļ��ľ���·��
String databaseFilename = myPath;
File dir = new File(DB_PATH);
if (!dir.exists()) {
dir.mkdir();
}
;
if (!(new File(databaseFilename)).exists()) {
InputStream is = myContext.getResources().openRawResource(
R.raw.pcuserdata);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte[] buffer = new byte[8192];
int count = 0;
// ��ʼ�����ļ�
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
myDataBase = SQLiteDatabase.openOrCreateDatabase(databaseFilename,
null);
} catch (Exception e) {
Log.i("open error", e.getMessage());
}
}
@Override
public synchronized void close() {
if (getMyDataBase() != null)
getMyDataBase().close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public SQLiteDatabase getMyDataBase() {
return myDataBase;
}
public void setMyDataBase(SQLiteDatabase myDataBase) {
this.myDataBase = myDataBase;
}
public void addSearchRecord(historyItem newRecord) {
String sql = "";
switch (newRecord.getType()) {
case Constants.STATION:// station 0:stationName,1:lat,2:lon,3:AZ
sql = "delete from LatestSearch where StationID = \'"
+ newRecord.getStationID() + "\'";
myDataBase.execSQL(sql);
sql = "insert into LatestSearch (StationID,StationName,Latitude,Longitude,LineNum,AZ,Type) values (\'"
+ newRecord.getStationID()
+ "\',\'"
+ newRecord.getStationName()
+ "\',\'"
+ newRecord.getLatitude()
+ "\',\'"
+ newRecord.getLongitude()
+ "\',\'"
+ newRecord.getLineNum()
+ "\',\'"
+ newRecord.getAzimuth()
+ "\',\'" + newRecord.getType() + "\')";
myDataBase.execSQL(sql);
break;
case Constants.BUSLINE:// busline 0:ID,1:FullName,2:KeyName
sql = "delete from LatestSearch where LineID = \'"
+ newRecord.getLineID() + "\'";
myDataBase.execSQL(sql);
sql = "insert into LatestSearch (LineID,LineName,StationNum,StartStation,EndStation,StartTime,EndTime,Type) values (\'"
+ newRecord.getLineID()
+ "\',\'"
+ newRecord.getLineName()
+ "\',\'"
+ newRecord.getStationsNum()
+ "\',\'"
+ newRecord.getStartStation()
+ "\',\'"
+ newRecord.getEndStation()
+ "\',\'"
+ newRecord.getStartTime()
+ "\',\'"
+ newRecord.getEndTime()
+ "\',\'"
+ newRecord.getType()
+ "\')";
myDataBase.execSQL(sql);
break;
default:
break;
}
}
public void delAllSearchRecord() {
String sql = "delete from LatestSearch ";
myDataBase.execSQL(sql);
}
public void delOneSearchRecordByType(historyItem item) {
String sql = "";
int type = item.getType();
switch (type) {
case Constants.STATION:// station 0:stationName,1:lat,2:lon,3:AZ
sql = "delete from LatestSearch where StationID = \'"
+ item.getStationID() + "\'";
myDataBase.execSQL(sql);
break;
case Constants.BUSLINE:// busline 0:ID,1:FullName,2:KeyName
sql = "delete from LatestSearch where LineID = \'"
+ item.getLineID() + "\'";
myDataBase.execSQL(sql);
break;
default:
break;
}
}
public List<historyItem> acquireLatestSearchHistory() {
List<historyItem> history = new ArrayList<historyItem>();
// openDataBase();
String sql = "select * from LatestSearch order by _id desc";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
while (cursor.moveToNext() && history.size() <= 20) {
historyItem item = new historyItem();
item.setType(cursor.getInt(cursor.getColumnIndex("Type")));
item.setStationID(cursor.getInt(cursor.getColumnIndex("StationID")));
item.setStationName(cursor.getString(cursor
.getColumnIndex("StationName")));
item.setLineNum(cursor.getInt(cursor.getColumnIndex("LineNum")));
item.setLongitude(cursor.getDouble(cursor
.getColumnIndex("Longitude")));
item.setLatitude(cursor.getDouble(cursor
.getColumnIndex("Longitude")));
item.setAzimuth(cursor.getInt(cursor.getColumnIndex("AZ")));
item.setLineID(cursor.getInt(cursor.getColumnIndex("LineID")));
item.setLineName(cursor.getString(cursor.getColumnIndex("LineName")));
item.setStationsNum(cursor.getInt(cursor
.getColumnIndex("StationNum")));
item.setStartStation(cursor.getString(cursor
.getColumnIndex("StartStation")));
item.setEndStation(cursor.getString(cursor
.getColumnIndex("EndStation")));
item.setStartTime(cursor.getString(cursor
.getColumnIndex("StartTime")));
item.setEndTime(cursor.getString(cursor.getColumnIndex("EndTime")));
item.setDelete(true);
history.add(item);
}
cursor.close();
// close();
return history;
}
public List<Group> acquireFavInfoWithLocation(LatLng location, int type) {
String updateFav = mSharePrefrenceUtil.getValue("UPDATEFAV", "no");
if (updateFav.equalsIgnoreCase("no")) {
Log.i(TAG, "acquireFavInfoWithLocation update");
updateFavorite();
mSharePrefrenceUtil.setKey("UPDATEFAV", "yes");
}
List<Group> mGroups = new ArrayList();
Set<String> keySet = new HashSet<String>();
String sql = "";
if (type == Constants.TYPE_ALL)
sql = "select * from Favorite order by _id desc";
else
sql = "select * from Favorite where Type=\'" + type
+ "\' order by _id desc";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
while (cursor.moveToNext()) {
double stationLat = cursor.getDouble(cursor
.getColumnIndex("Latitude"));
double stationLng = cursor.getDouble(cursor
.getColumnIndex("Longitude"));
LatLng stationPoint = new LatLng(stationLat, stationLng);
double distance = 0.0;
if (location != null)
distance = DistanceUtil.getDistance(location, stationPoint);
String StationName = cursor.getString(cursor
.getColumnIndex("StationName"));
String LineName = cursor.getString(cursor
.getColumnIndex("LineName"));
String StartStation = cursor.getString(cursor
.getColumnIndex("StartStation"));
String EndStation = cursor.getString(cursor
.getColumnIndex("EndStation"));
int LineID = cursor.getInt(cursor.getColumnIndex("LineID"));
int StationID = cursor.getInt(cursor.getColumnIndex("StationID"));
int Azimuth = cursor.getInt(cursor.getColumnIndex("Azimuth"));
int Type = cursor.getInt(cursor.getColumnIndex("Type"));
int Sequence = cursor.getInt(cursor.getColumnIndex("Sequence"));
int OfflineID = cursor.getInt(cursor.getColumnIndex("OfflineID"));
String FullName = LineName + "(" + StartStation + "-" + EndStation
+ ")";
Child child = new Child(LineID, StationID, LineName, FullName,
StationName, stationLat, stationLng);
child.setLineID(LineID);
child.setStartStation(StartStation);
child.setEndStation(EndStation);
child.setAZ(Azimuth);
child.setType(Type);
child.setSequence(Sequence);
// int offlineID = checkOfflineID(LineName, StartStation,
// EndStation);
if (OfflineID > 0)
child.setOfflineID(OfflineID);
if (!keySet.contains(StationName)) {
Group group = new Group(StationName, stationLat, stationLng);
group.setDistance(distance);
Log.i(TAG, StationName);
keySet.add(StationName);
group.addChildrenItem(child);
mGroups.add(group);
} else {
for (Group group : mGroups)
if (group.getStationName().trim()
.equalsIgnoreCase(StationName)) {
group.addChildrenItem(child);
break;
}
}
}
cursor.close();
Comparator<Group> comparator = new Comparator<Group>() {
public int compare(Group s1, Group s2) {
double distance1 = s1.getDistance();
double distance2 = s2.getDistance();
if (distance1 > distance2) {
return 1;
} else if (distance1 < distance2) {
return -1;
}
return 0;
}
};
if (location != null)
Collections.sort(mGroups, comparator);
return mGroups;
}
public List<Child> acquireFavInfoWithLocation(List<Child> old) {
String updateFav = mSharePrefrenceUtil.getValue("UPDATEFAV", "no");
if (updateFav.equalsIgnoreCase("no")) {
Log.i(TAG, "acquireFavInfoWithLocation update1");
updateFavorite();
mSharePrefrenceUtil.setKey("UPDATEFAV", "yes");
}
List<Child> mChildren = new ArrayList();
String sql = "select * from Favorite order by _id desc";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
while (cursor.moveToNext()) {
double stationLat = cursor.getDouble(cursor
.getColumnIndex("Latitude"));
double stationLng = cursor.getDouble(cursor
.getColumnIndex("Longitude"));
String StationName = cursor.getString(cursor
.getColumnIndex("StationName"));
String LineName = cursor.getString(cursor
.getColumnIndex("LineName"));
String StartStation = cursor.getString(cursor
.getColumnIndex("StartStation"));
String EndStation = cursor.getString(cursor
.getColumnIndex("EndStation"));
int LineID = cursor.getInt(cursor.getColumnIndex("LineID"));
int StationID = cursor.getInt(cursor.getColumnIndex("StationID"));
int Azimuth = cursor.getInt(cursor.getColumnIndex("Azimuth"));
int Type = cursor.getInt(cursor.getColumnIndex("Type"));
int Sequence = cursor.getInt(cursor.getColumnIndex("Sequence"));
int OfflineID = cursor.getInt(cursor.getColumnIndex("OfflineID"));
String FullName = LineName + "(" + StartStation + "-" + EndStation
+ ")";
Child child = new Child(LineID, StationID, LineName, FullName,
StationName, stationLat, stationLng);
child.setLineID(LineID);
child.setStartStation(StartStation);
child.setEndStation(EndStation);
child.setAZ(Azimuth);
child.setType(Type);
child.setSequence(Sequence);
if (OfflineID > 0)
child.setOfflineID(OfflineID);
mChildren.add(child);
}
cursor.close();
return mChildren;
}
// private int checkOfflineID(String LineName, String StartStation,
// String EndStation) {
// Map<String, Object> map = BuslineDBHelper.getInstance(myContext)
// .AcquireOffLineInfoWithBuslineInfo(LineName, StartStation,
// EndStation);
// if (map.size() > 0) {
// return Integer.parseInt(map.get("line_id").toString());
// } else
// return -1;
// }
public void addFavRecord(Child child) {
int LineID = child.getLineID();
int StationID = child.getStationID();
int Sequence = child.getSequence();
int OfflineID = child.getOfflineID();
String LineName = child.getLineName();
String StationName = child.getStationName();
String StartStation = child.getStartStation();
String EndStation = child.getEndStation();
double Latitude = child.getLatitude();
double Longitude = child.getLongitude();
int Amizuth = child.getAZ();
int Type = child.getType();
if (IsFavStation(LineID, StationID)) {
changeFavKind(LineID, StationID, Type);
} else {
String sql = "insert into Favorite (LineID,StationID,Sequence,LineName,StationName,StartStation,EndStation,Latitude,Longitude,Azimuth,Type,OfflineID) values (\'"
+ LineID
+ "\',\'"
+ StationID
+ "\',\'"
+ Sequence
+ "\',\'"
+ LineName
+ "\',\'"
+ StationName
+ "\',\'"
+ StartStation
+ "\',\'"
+ EndStation
+ "\',\'"
+ Latitude
+ "\',\'"
+ Longitude
+ "\',\'"
+ Amizuth
+ "\',\'"
+ Type
+ "\',\'" + OfflineID + "\')";
myDataBase.execSQL(sql);
}
}
public boolean IsFavStation(int LineID, int StationID) {
String sql = "select * from Favorite where LineID = \'" + LineID
+ "\' and StationID = \'" + StationID + "\'";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
if (cursor.moveToNext()) {
cursor.close();
return true;
} else {
cursor.close();
return false;
}
}
public int IsWhichKindFavInfo(int LineID, int StationID) {
String sql = "select * from Favorite where LineID = \'" + LineID
+ "\' and StationID=\'" + StationID + "\'";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
int favKindType = 0;
if (cursor.moveToFirst()) {
favKindType = cursor.getInt(cursor.getColumnIndex("Type"));
}
cursor.close();
return favKindType;// 未收藏0,全部1,上班2,回家3,其他4,没有收藏 5
}
public void changeFavKind(int LineID, int StationID, int type) {
String sql = "update Favorite set Type=\'" + type
+ "\' where LineID = \'" + LineID + "\' and StationID =\'"
+ StationID + "\'";
myDataBase.execSQL(sql);
}
public void cancelFav(int LineID, int StationID) {
String sql = "delete from Favorite where LineID = \'" + LineID
+ "\' and StationID =\'" + StationID + "\'";
myDataBase.execSQL(sql);
}
public List<Group> acquireAlertInfoWithLocation(LatLng location) {
String updateAlert = mSharePrefrenceUtil.getValue("UPDATEALERT", "no");
if (updateAlert.equalsIgnoreCase("no")) {
Log.i(TAG, "acquireAlertInfoWithLocation update");
updateAlertData();
mSharePrefrenceUtil.setKey("UPDATEALERT", "yes");
}
List<Group> mGroups = new ArrayList();
Set<String> keySet = new HashSet<String>();
String sql = "select * from Alert order by _id desc";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
while (cursor.moveToNext()) {
double stationLat = cursor.getDouble(cursor
.getColumnIndex("Latitude"));
double stationLng = cursor.getDouble(cursor
.getColumnIndex("Longitude"));
LatLng stationPoint = new LatLng(stationLat, stationLng);
double distance = 0.0;
if (location != null)
distance = DistanceUtil.getDistance(location, stationPoint);
String StationName = cursor.getString(cursor
.getColumnIndex("StationName"));
String LineName = cursor.getString(cursor
.getColumnIndex("LineName"));
int LineID = cursor.getInt(cursor.getColumnIndex("LineID"));
int StationID = cursor.getInt(cursor.getColumnIndex("StationID"));
int Azimuth = cursor.getInt(cursor.getColumnIndex("AZ"));
int Open = cursor.getInt(cursor.getColumnIndex("Open"));
Child child = new Child();
child.setLineID(LineID);
child.setStationID(StationID);
child.setLineName(LineName);
child.setStationName(StationName);
child.setAZ(Azimuth);
child.setAlertOpen(Open);
child.setAZ(Azimuth);
if (!keySet.contains(StationName)) {
Group group = new Group(StationName, stationLat, stationLng);
group.setDistance(distance);
Log.i(TAG, StationName);
keySet.add(StationName);
group.addChildrenItem(child);
mGroups.add(group);
} else {
for (Group group : mGroups)
if (group.getStationName().trim()
.equalsIgnoreCase(StationName)) {
group.addChildrenItem(child);
break;
}
}
}
cursor.close();
Comparator<Group> comparator = new Comparator<Group>() {
public int compare(Group s1, Group s2) {
double distance1 = s1.getDistance();
double distance2 = s2.getDistance();
if (distance1 > distance2) {
return 1;
} else if (distance1 < distance2) {
return -1;
}
return 0;
}
};
if (location != null)
Collections.sort(mGroups, comparator);
return mGroups;
}
public List<Child> acquireAlertLineWithLocation(LatLng location) {
String updateAlert = mSharePrefrenceUtil.getValue("UPDATEALERT", "no");
if (updateAlert.equalsIgnoreCase("no")) {
Log.i(TAG, "acquireAlertInfoWithLocation update1");
updateAlertData();
mSharePrefrenceUtil.setKey("UPDATEALERT", "yes");
}
List<Child> children = new ArrayList();
String sql = "select * from Alert order by _id desc";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
while (cursor.moveToNext()) {
double stationLat = cursor.getDouble(cursor
.getColumnIndex("Latitude"));
double stationLng = cursor.getDouble(cursor
.getColumnIndex("Longitude"));
LatLng stationPoint = new LatLng(stationLat, stationLng);
double distance = 0.0;
if (location != null)
distance = DistanceUtil.getDistance(location, stationPoint);
String StationName = cursor.getString(cursor
.getColumnIndex("StationName"));
String LineName = cursor.getString(cursor
.getColumnIndex("LineName"));
int LineID = cursor.getInt(cursor.getColumnIndex("LineID"));
int StationID = cursor.getInt(cursor.getColumnIndex("StationID"));
int Azimuth = cursor.getInt(cursor.getColumnIndex("AZ"));
int Open = cursor.getInt(cursor.getColumnIndex("Open"));
Child child = new Child();
child.setLineID(LineID);
child.setStationID(StationID);
child.setLineName(LineName);
child.setStationName(StationName);
child.setAZ(Azimuth);
child.setAlertOpen(Open);
child.setAZ(Azimuth);
child.setLatitude(stationLat);
child.setLongitude(stationLng);
child.setAlertOpen(Open);
children.add(child);
}
cursor.close();
return children;
}
public void addAlertRecord(Child child) {
// openDataBase();
String sql = "insert into Alert (LineID,LineName,StationID,StationName,Open,Latitude,Longitude,AZ) values (\'"
+ child.getLineID()
+ "\',\'"
+ child.getLineName()
+ "\',\'"
+ child.getStationID()
+ "\',\'"
+ child.getStationName()
+ "\',\'"
+ Child.OPEN
+ "\',\'"
+ child.getLatitude()
+ "\',\'"
+ child.getLongitude()
+ "\',\'"
+ child.getAZ()
+ "\')";// isOpen
// 0:close,1:open
myDataBase.execSQL(sql);
// close();
}
public boolean IsAlertBusline(int LineID, String StationName) {
// openDataBase();
String sql = "select * from Alert where StationName= \'" + StationName
+ "\' and LineID =\'" + LineID + "\'";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
if (cursor.moveToNext()) {
cursor.close();
Log.i(TAG, "IsAlertBusline true");
return true;
} else {
cursor.close();
Log.i(TAG, "IsAlertBusline false");
return false;
}
}
public boolean IsAlertStation(String StationName) {
// openDataBase();
String sql = "select * from Alert where StationName= \'" + StationName
+ "\'";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
while (cursor.moveToNext()) {
int open = cursor.getInt(cursor.getColumnIndex("Open"));
if (open == Child.OPEN) {
cursor.close();
return true;
}
}
cursor.close();
return false;
}
public boolean IsAlertOpenBusline(int LineID, String StationName) {
// openDataBase();
String sql = "select * from Alert where StationName= \'" + StationName
+ "\' and LineID =\'" + LineID + "\'";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
if (cursor.moveToNext()) {
if (cursor.getInt(cursor.getColumnIndex("Open")) == Child.OPEN) {
cursor.close();
return true;
}
}
cursor.close();
return false;
}
public boolean IsAlertOpenBusline(int LineID, int StationID) {
// openDataBase();
String sql = "select * from Alert where StationID= \'" + StationID
+ "\' and LineID =\'" + LineID + "\'";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
if (cursor.moveToNext()) {
if (cursor.getInt(cursor.getColumnIndex("Open")) == Child.OPEN) {
cursor.close();
return true;
}
}
cursor.close();
return false;
}
public boolean IsAllAlertOpen() {
// openDataBase();
String sql = "select * from Alert ";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
if (cursor.getCount() == 0)
return false;
if (cursor.moveToNext()) {
if (cursor.getInt(cursor.getColumnIndex("Open")) == Child.CLOSE) {
cursor.close();
return false;
}
}
cursor.close();
return true;
}
public void deleteAlertStation(String StationName) {
// openDataBase();
String sql = "delete from Alert where StationName = \'" + StationName
+ "\'";
myDataBase.execSQL(sql);
// close();
}
public void deleteAllAlertStation() {
// openDataBase();
String sql = "delete from Alert";
myDataBase.execSQL(sql);
// close();
}
public void closeAlertBusline(int LineID, String StationName) {
// openDataBase();
String sql = "update Alert set Open = " + Child.CLOSE
+ " where LineID = \'" + LineID + "\' and StationName=\'"
+ StationName + "\'";
myDataBase.execSQL(sql);
// close();
}
public void closeAllAlertBusline() {
// openDataBase();
String sql = "update Alert set Open = " + Child.CLOSE;
myDataBase.execSQL(sql);
// close();
}
public void openAlertBusline(int LineID, String StationName) {
// openDataBase();
String sql = "update Alert set Open = " + Child.OPEN
+ " where LineID = \'" + LineID + "\' and StationName=\'"
+ StationName + "\'";
myDataBase.execSQL(sql);
// close();
}
public void closeAlertBusline(Child child) {
// openDataBase();
int LineID = child.getLineID();
int AZ = child.getAZ();
String StationName = child.getStationName();
if (!IsAlertBusline(LineID, StationName))
addAlertRecord(child);
else {
String sql = "update Alert set Open = " + Child.CLOSE
+ " where LineID = \'" + LineID + "\' and StationName=\'"
+ StationName + "\' and AZ=\'" + AZ + "\'";
myDataBase.execSQL(sql);
}
// close();
}
public void openAlertBusline(Child child) {
int LineID = child.getLineID();
String StationName = child.getStationName();
int AZ = child.getAZ();
if (!IsAlertBusline(LineID, StationName))
addAlertRecord(child);
else {
String sql = "update Alert set Open = " + Child.OPEN
+ " where LineID = \'" + LineID + "\' and StationName=\'"
+ StationName + "\' and AZ=\'" + AZ + "\'";
myDataBase.execSQL(sql);
}
// close();
}
public void openAllAlertBusline() {
String sql = "update Alert set Open = " + Child.OPEN;
myDataBase.execSQL(sql);
// close();
}
public boolean checkAlertStationWithStation(ArrayList<String> station) {
// openDataBase();
int j = alertStations.size();
for (int i = 0; i < j; i++) {
if (alertStations.get(i).get(0).equalsIgnoreCase(station.get(0))) {
// 距离小于50m
return true;
}
}
return false;
// close();
}
public void updateAlertData() {
String sql = "select * from Alert";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
while (cursor.moveToNext()) {
int LineID = cursor.getInt(cursor.getColumnIndex("LineID"));
String StationName = cursor.getString(cursor
.getColumnIndex("StationName"));
double latitude = cursor.getDouble(cursor
.getColumnIndex("Latitude"));
double longitude = cursor.getDouble(cursor
.getColumnIndex("Longitude"));
int stationID = mPcDataBaseHelper.getStationID(LineID, StationName);
if (stationID != -1) {
sql = "update Alert set StationID=\'" + stationID
+ "\' where LineID=\'" + LineID
+ "\' and Latitude = \'" + latitude + "\'"
+ " and Longitude = \'" + longitude + "\'";
myDataBase.execSQL(sql);
}
}
cursor.close();
}
public void updateFavorite() {
String sql = "select * from Favorite";
Cursor cursor = getMyDataBase().rawQuery(sql, null);
while (cursor.moveToNext()) {
int LineID = cursor.getInt(cursor.getColumnIndex("LineID"));
int sequence = cursor.getInt(cursor.getColumnIndex("Sequence"));
double latitude = cursor.getDouble(cursor
.getColumnIndex("Latitude"));
double longitude = cursor.getDouble(cursor
.getColumnIndex("Longitude"));
String StationName = cursor.getString(cursor
.getColumnIndex("StationName"));
List<Integer> list = mPcDataBaseHelper.getStationID(LineID,
sequence, StationName);
if (list != null && list.size() > 0) {
String stationId = list.get(0) + "";
int seq = list.get(1);
Log.i(TAG, StationName + " " + stationId + " " + seq);
int offlineID = mPcDataBaseHelper.getOfflineID(LineID);
sql = "update Favorite set StationID=\'" + stationId
+ "\', Sequence=\'" + seq + "\', OfflineID=\'"
+ offlineID + "\' where LineID = \'" + LineID + "\'"
+ " and Latitude = \'" + latitude + "\'"
+ " and Longitude = \'" + longitude + "\'";
myDataBase.execSQL(sql);
// sql = "update Favorite set StationID=\'" + stationId
// + "\' where LineID = \'" + LineID + "\'"
// + " and Latitude = \'" + latitude + "\'"
// + " and Longitude = \'" + longitude + "\'";
// myDataBase.execSQL(sql);
}
}
cursor.close();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pelatihan.java.project.uts.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;
import pelatihan.java.project.uts.dto.AdminDto;
import pelatihan.java.project.uts.dto.UserDto;
import pelatihan.java.project.uts.model.AdminModel;
import pelatihan.java.project.uts.model.UserModel;
import pelatihan.java.project.uts.service.AdminService;
import pelatihan.java.project.uts.service.UserService;
/**
*
* @author ASUS
*/
@Controller
public class ProjectUtsController {
@Autowired
UserService userService;
@Autowired
AdminService adminService;
AdminModel aModel= new AdminModel();
AdminDto dto=new AdminDto();
HttpSession session;
UserModel uModel= new UserModel();
UserDto dtou=new UserDto();
String level;
void beda(ModelMap model,UserDto dto){
dto.setPasuser(level);
model.addAttribute("userDto", dto);
}
@RequestMapping(value = "/index",method = RequestMethod.GET)
public String viewindex(){
return "index";
}
@RequestMapping(value = "exit", method = RequestMethod.GET)
public void exit(HttpServletRequest request, HttpServletResponse response) throws IOException {
aModel = null;
session = request.getSession();
session.invalidate();
response.sendRedirect("index.htm");
}
@RequestMapping(value = "/turun",method = RequestMethod.GET)
public String viewturun(ModelMap model,UserDto dto){
beda( model,dto);
return "turun";
}
@RequestMapping(value = "/naik",method = RequestMethod.GET)
public String viewnaik(ModelMap model,UserDto dto){
beda( model,dto);
return "naik";
}
@RequestMapping(value = "/bmi",method = RequestMethod.GET)
public String viewbmi(ModelMap model,UserDto dto){
beda( model,dto);
return "hitungBmi";
}
@RequestMapping(value = "/ideal",method = RequestMethod.GET)
public String viewideal(ModelMap model,UserDto dto){
beda( model,dto);
return "hitungIdeal";
}
@RequestMapping(value = "/loginAdmin",method = RequestMethod.GET)
public String viewlog(){
return "loginAdmin";
}
@RequestMapping(value = "/loginUser",method = RequestMethod.GET)
public String viewlogy(){
return "loginUser";
}
@RequestMapping(value = "/tentang",method = RequestMethod.GET)
public String viewtentang(){
return "tentang";
}
@RequestMapping(value = "/menu",method = RequestMethod.GET)
public String viewmenu(ModelMap model,UserDto dto){
dto.setPasuser(level);
model.addAttribute("userDto", dto);
return "menu";
}
@RequestMapping(value = "/tabelUser", method = RequestMethod.GET)
public String viewtabelUser(ModelMap model){
try {
List<UserDto> listUserDto = userService.getListUser();
model.addAttribute("listUserDto", listUserDto);
} catch (Exception e) {
e.printStackTrace();
}
return "tabelUser";
}
@RequestMapping(value = "/doTambahDataUser", method = RequestMethod.GET)
public String doTambahDataUser(ModelMap model){
UserDto dto = null;
try {
dto = new UserDto();
model.addAttribute("userDto", dto);
} catch (Exception e) {
e.printStackTrace();
}
return "insertUser";
}
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public String saveDataUser(UserDto userDto, ModelMap model) throws Exception{
ModelAndView mdl = new ModelAndView();
userService.saveDataUser(userDto);
return "redirect:tabelUser.htm";
}
@RequestMapping(value = "/deleteDataUser", method = RequestMethod.GET)
public String hapusData(String iduser, ModelMap model) throws Exception{
userService.deleteDataUser(iduser);
return "redirect:tabelUser.htm";
}
@RequestMapping(value = "/getDataUpdateUser", method = RequestMethod.GET)
public String getUpdateDataUser(String iduser, ModelMap model) throws Exception{
UserDto userDto =userService.getUpdateDataUser(iduser);
model.addAttribute("userDto", userDto);
return "updateUser";
}
@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
public String editData(UserDto userDto) throws Exception{
userService.doUpdateDataUser(userDto);
return "redirect:tabelUser.htm";
}
/////////////////////////////////////////////////////////////////////////////////
@RequestMapping(value = "/tabelAdmin", method = RequestMethod.GET)
public String viewtabelAdmin(ModelMap model){
try {
List<AdminDto> listAdminDto = adminService.getListAdmin();
model.addAttribute("listAdminDto", listAdminDto);
} catch (Exception e) {
e.printStackTrace();
}
return "tabelAdmin";
}
@RequestMapping(value = "doLogin", method = RequestMethod.POST)
public void doLogin(AdminDto formDto, ModelMap model,HttpServletResponse response, HttpServletRequest request) throws Exception{
String u= null;
dto= adminService.getListDataAdminLogin(formDto);
model.addAttribute("adminDto", dto);
if(dto.getListDataAdmin().isEmpty()){
u="loginAdmin.htm";
} else{
aModel=dto.getListDataAdmin().get(0);
if(aModel.getUsadmin().equals(formDto.getUsadmin())){
level="admin";
u="menu.htm";
}
session= request.getSession(true);
session.setAttribute("level",level);
session.setAttribute("idadmin",dto.getIdadmin());
session.setAttribute("nmadmin",dto.getNmadmin());
session.setAttribute("usadmin",dto.getUsadmin());
session.setAttribute("pasadmin",dto.getPasadmin());
}
response.sendRedirect(u);
}
@RequestMapping(value = "/saveAdmin", method = RequestMethod.POST)
public String saveData(AdminDto adminDto, ModelMap model) throws Exception{
ModelAndView mdl = new ModelAndView();
adminService.saveDataAdmin(adminDto);
return "redirect:loginAdmin.htm";
}
@RequestMapping(value = "/doTambahDataAdmin", method = RequestMethod.GET)
public String doTambahDataAdmin(ModelMap model){
AdminDto dto = null;
try {
dto = new AdminDto();
model.addAttribute("adminDto", dto);
} catch (Exception e) {
e.printStackTrace();
}
return "tambahAdmin";
}
@RequestMapping(value = "doLoginUser", method = RequestMethod.POST)
public void doLoginUser(UserDto formDto, ModelMap model,HttpServletResponse response, HttpServletRequest request) throws Exception{
String u= null;
dtou= userService.getListDataUserLogin(formDto);
model.addAttribute("userDto", dtou);
if(dtou.getListDataUser().isEmpty()){
u="loginUser.htm";
} else{
uModel=dtou.getListDataUser().get(0);
if(uModel.getUsuser().equals(formDto.getUsuser())){
level="user";
u="menu.htm";
}
session= request.getSession(true);
session.setAttribute("level",level);
session.setAttribute("iduser",dtou.getIduser());
session.setAttribute("nmuser",dtou.getNmuser());
session.setAttribute("ususer",dtou.getUsuser());
session.setAttribute("pasuser",dtou.getPasuser());
session.setAttribute("almtuser",dtou.getAlmtuser());
session.setAttribute("notelp",dtou.getNotelp());
}
response.sendRedirect(u);
}
}
|
package com.funnums.funnums.animation;
/**
* Created by Rabia on 24/03/19.
*/
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
public class Animation {
private Frame[] frames;
private double[] frameEndTimes;
private int currentFrameIndex = 0;
private double totalDuration = 0;
private double currentTime = 0;
//boolean to control if animation is playing or not
public boolean playing;
public Animation(Frame... frames) {
this.frames = frames;
//initially animatins are static, unchanging
playing = false;
frameEndTimes = new double[frames.length];
//get a record of frame end times so we know when to change frames
for (int i = 0; i < frames.length; i++) {
Frame f = frames[i];
totalDuration += f.getDuration();
frameEndTimes[i] = totalDuration;
}
}
public void start(){
playing = true;
}
public synchronized void update(float increment) {
//if animation is not playing, do nothing
if(!playing)
return;
currentTime += increment;
//if current time excceds total duration of this animation, reset to first frame and stop playing
//we can make this more configurable for different animations, i.e if we want animation to loop
//or want it to stop on last frame without resetting
if (currentTime > totalDuration) {
wrapAnimation();
playing = false;
}
//if enough time has passed, move to next frame in animation
while (currentTime > frameEndTimes[currentFrameIndex]) {
currentFrameIndex++;
}
}
/*
restart the animation from first frame
*/
public synchronized void restart(){
currentFrameIndex = 0;
currentTime = 0;
start();
}
/*
move current frame to first frame
*/
private synchronized void wrapAnimation() {
currentFrameIndex = 0;
currentTime %= totalDuration;
}
public synchronized void render(Canvas g, int x, int y, Paint p) {
g.drawBitmap(frames[currentFrameIndex].getImage(), x, y, p);
}
/*
render a scaled image, given a width and height for scaling
*/
public synchronized void render(Canvas canvas, Paint p, int x, int y, int width,
int height) {
Bitmap currentFrameImage = frames[currentFrameIndex].getImage();
Rect srcRect = new Rect();
srcRect.set(0, 0, currentFrameImage.getWidth(), currentFrameImage.getHeight());
//get rect for scaled image, based on given width and height
Rect dstRect = new Rect();
dstRect.set(x, y, x + width, y + height);
canvas.drawBitmap(currentFrameImage, srcRect, dstRect, p);
}
public Bitmap getCurrentBitmap(){
return frames[currentFrameIndex].getImage();
}
} |
/* ComponentsCtrl.java
Purpose:
Description:
History:
Tue Aug 9 19:41:22 2005, Created by tomyeh
Copyright (C) 2005 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zk.ui.sys;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.io.StringWriter;
import java.net.URL;
import org.zkoss.lang.Classes;
import org.zkoss.lang.Objects;
import org.zkoss.lang.Library;
import org.zkoss.util.Pair;
import org.zkoss.util.MultiCache;
import org.zkoss.util.Cache;
import org.zkoss.util.Maps;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Path;
import org.zkoss.zk.ui.UiException;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.ComponentNotFoundException;
import org.zkoss.zk.ui.metainfo.LanguageDefinition;
import org.zkoss.zk.ui.metainfo.ComponentDefinition;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.metainfo.AnnotationMap;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.sys.JavaScriptValue;
import org.zkoss.zk.ui.sys.IdGenerator;
import org.zkoss.zk.ui.ext.RawId;
import org.zkoss.zk.au.AuRequest;
import org.zkoss.zk.au.AuService;
import org.zkoss.zk.xel.ExValue;
/**
* Utilities for implementing components.
*
* @author tomyeh
*/
public class ComponentsCtrl {
/** @deprecated
* The anonymous UUID. Used only internally.
*/
public static final String ANONYMOUS_ID = "z__i";
private static final ThreadLocal _compdef = new ThreadLocal();
/** Returns the automatically generate component's UUID/ID.
*/
public static final String toAutoId(String prefix, int val) {
return encodeId(new StringBuffer(16).append(prefix), val);
}
/** Returns an ID representing the specified number
* The ID consists of 0-9, a-z and _.
* @since 5.0.5
*/
public static final String encodeId(StringBuffer sb, int val) {
//Thus, the number will 0, 1... max, 0, 1..., max, 0, 1 (less conflict)
if (val < 0 && (val += Integer.MIN_VALUE) < 0)
val = -val; //impossible but just in case
do {
//IE6/7's ID case insensitive (safer, though jQuery fixes it)
int v = val % 37;
val /= 37;
if (v-- == 0) {
sb.append('_');
} else if (v < 10) {
sb.append((char)('0' + v));
// } else if (v < 36) {
} else {
sb.append((char)(v + ((int)'a' - 10)));
// } else {
// sb.append((char)(v + ((int)'A' - 36)));
}
} while (val != 0);
return sb.toString();
}
/** @deprecated As of release 5.0.3, replaced with {@link #isAutoUuid(String)}.
*/
public static final boolean isAutoId(String id) {
return isAutoUuid(id);
}
/** Returns whether an ID is generated automatically.
* Note: true is returned if id is null.
* Also notice that this method doesn't check if a custom ID generator
* ({@link org.zkoss.zk.ui.sys.IdGenerator}) is assigned.
* @since 5.0.3
*/
public static final boolean isAutoUuid(String id) {
if (id == null)
return true;
//0: lower, 1: digit or upper, 2: letter or digit, 3: upper
//See also DesktopImpl.updateUuidPrefix
if (id.length() < 5)
return false;
char cc;
return isLower(id.charAt(0))
&& (isUpper(cc = id.charAt(1)) || isDigit(cc))
&& (isUpper(cc = id.charAt(2)) || isLower(cc) || isDigit(cc))
&& isUpper(id.charAt(3));
}
private static boolean isUpper(char cc) {
return cc >= 'A' && cc <= 'Z';
}
private static boolean isLower(char cc) {
return cc >= 'a' && cc <= 'z';
}
private static boolean isDigit(char cc) {
return cc >= '0' && cc <= '9';
}
/** @deprecated As of release 5.0.2, replaced with {@link #isAutoUuid(String)}.
* If you want to varify UUID, use {@link #checkUuid}.
*/
public static final boolean isUuid(String id) {
return isAutoUuid(id);
}
/** Checks if the given UUID is valid.
* UUID cannot be empty and can only have alphanumeric characters or underscore.
* @exception UiException if uuid is not valid.
*/
public static void checkUuid(String uuid) {
int j;
if (uuid == null || (j = uuid.length()) == 0)
throw new UiException("uuid cannot be null or empty");
while (--j >= 0) {
final char cc = uuid.charAt(j);
if ((cc < 'a' || cc > 'z') && (cc < 'A' || cc > 'Z')
&& (cc < '0' || cc > '9') && cc != '_')
throw new UiException("Illegal character, "+cc+", not allowed in uuid, "+uuid);
}
}
/** Returns if the attribute name is reserved.
* If name is null, false is returned.
* @since 3.0.0
*/
public static final boolean isReservedAttribute(String name) {
return name != null && !"use".equals(name) && !"if".equals(name)
&& !"unless".equals(name) && !"apply".equals(name)
&& !"forEach".equals(name);
}
/** Returns the current component info {@link ComponentInfo},
* definition ({@link ComponentDefinition} or null, which is used only by
* {@link org.zkoss.zk.ui.sys.UiEngine} to communicate with
* {@link org.zkoss.zk.ui.AbstractComponent}.
* @since 3.0.0
*/
public static final Object getCurrentInfo() {
return _compdef.get();
}
/** Sets the current component definition, which is used only by
* {@link org.zkoss.zk.ui.sys.UiEngine} to communicate with
* {@link org.zkoss.zk.ui.AbstractComponent}.
* <p>Used only internally.
* @since 3.0.0
*/
public static final void setCurrentInfo(ComponentDefinition compdef) {
_compdef.set(compdef);
}
/** Sets the current component definition, which is used only by
* {@link org.zkoss.zk.ui.sys.UiEngine} to communicate with
* {@link org.zkoss.zk.ui.AbstractComponent}.
* <p>Used only internally.
* @since 3.0.0
*/
public static void setCurrentInfo(ComponentInfo compInfo) {
_compdef.set(compInfo);
}
/** Pares the event expression.
*
* <p>There are several formats for the event expression:
* <ul>
* <li>onClick</li>
* <li>self.onClick</li>
* <li>id.onClick</li>
* <li>../id1/id2.onClick</li>
* <li>${elexpr}.onClick</li>
* </ul>
*
* @param comp the component that the event expression is referenced to
* @param evtexpr the event expression.
* @param defaultComp the default component which is used when
* evtexpr doesn't specify the component.
* @param deferred whether to defer the conversion of the path
* to a component. If true and EL not specified or evaluated to a string,
* it returns the path directly rather than converting it to a component.
* @return a two element array. The first element is the component
* if deferred is false or EL is evaluated to a component,
* or a path, otherwise.
* The second component is the event name.
* @since 3.0.0
*/
public static Object[] parseEventExpression(Component comp,
String evtexpr, Component defaultComp, boolean deferred)
throws ComponentNotFoundException {
final int j = evtexpr.lastIndexOf('.');
final String evtnm;
Object target;
if (j >= 0) {
evtnm = evtexpr.substring(j + 1).trim();
String path = evtexpr.substring(0, j);
if (path.length() > 0) {
target = null;
if (path.indexOf("${") >= 0) {
final Object v =
Executions.evaluate(comp, path, Object.class);
if (v instanceof Component) {
target = (Component)v;
} else if (v == null) {
throw new ComponentNotFoundException("EL evaluated to null: "+path);
} else {
path = Objects.toString(v);
}
}
if (target == null) {
path = path.trim();
if ("self".equals(path)) path = ".";
target = deferred ? (Object)path:
".".equals(path) ? comp:
Path.getComponent(comp.getSpaceOwner(), path);
if (target == null && comp instanceof IdSpace && comp.getParent() != null) {
target = Path.getComponent(comp.getParent().getSpaceOwner(), path);
}
}
} else {
target = defaultComp;
}
} else {
evtnm = evtexpr.trim();
target = defaultComp;
}
if (!Events.isValid(evtnm))
throw new UiException("Not an event name: "+evtnm);
return new Object[] {target, evtnm};
}
/**
* Applies the forward condition to the specified component.
*
* <p>The basic format:<br/>
* <code>onEvent1=id1/id2.onEvent2,onEvent3=id3.onEvent4</code>
*
* <p>See {@link org.zkoss.zk.ui.metainfo.ComponentInfo#setForward}
* for more information.
*
* @since 3.0.0
*/
public static final void applyForward(Component comp, String forward) {
if (forward == null)
return;
final Map fwds = new LinkedHashMap(); //remain the order
Maps.parse(fwds, forward, ',', '\'', true, true, true);
for (Iterator it = fwds.entrySet().iterator(); it.hasNext();) {
final Map.Entry me = (Map.Entry)it.next();
final String orgEvent = (String)me.getKey();
if (orgEvent != null && !Events.isValid(orgEvent))
throw new UiException("Not an event name: "+orgEvent);
final Object cond = me.getValue();
if (cond instanceof Collection) {
for (Iterator e = ((Collection)cond).iterator(); e.hasNext();)
applyForward0(comp, orgEvent, (String)e.next());
} else {
applyForward0(comp, orgEvent, (String)cond);
}
}
}
private static final
void applyForward0(Component comp, String orgEvent, String cond) {
int len;
if (cond == null || (len = cond.length()) == 0)
len = (cond = orgEvent).length();
//if condition not specified, assume same as orgEvent (to space owenr)
Object data = null;
for (int j = 0; j < len; ++j) {
final char cc = cond.charAt(j);
if (cc == '\\') ++j; //skip next
else if (cc == '{') {
for (int k = j + 1, depth = 0;; ++k) {
if (k >= len) {
j = k;
break;
}
final char c2 = cond.charAt(k);
if (c2 == '{') ++depth;
else if (c2 == '}' && --depth < 0) { //found
j = k;
break;
}
}
} else if (cc == '(') { //found
final int k = cond.lastIndexOf(')');
if (k > j) {
data = Executions.evaluate(
comp, cond.substring(j + 1, k), Object.class);
cond = cond.substring(0, j);
break;
}
}
}
final Object[] result =
parseEventExpression(comp, cond, null, true);
final Object target = result[0];
if (target instanceof String)
comp.addForward(orgEvent, (String)target, (String)result[1], data);
else
comp.addForward(orgEvent, (Component)target, (String)result[1], data);
}
/** @deprecated As of release 5.0.0, use the script component instead.
*/
public static String parseClientScript(Component comp, String script) {
return "";
}
/** Returns the method for handling the specified event, or null
* if not available.
*/
public static final Method getEventMethod(Class cls, String evtnm) {
final Pair key = new Pair(cls, evtnm);
final Object o = _evtmtds.get(key);
if (o != null)
return o == Objects.UNKNOWN ? null: (Method)o;
Method mtd = null;
try {
mtd = Classes.getCloseMethodBySubclass(
cls, evtnm, new Class[] {Event.class}); //with event arg
} catch (NoSuchMethodException ex) {
try {
mtd = cls.getMethod(evtnm, null); //no argument case
} catch (NoSuchMethodException e2) {
}
}
_evtmtds.put(key, mtd != null ? mtd: Objects.UNKNOWN);
return mtd;
}
/** Sets the cache that stores the information about event handler methods.
*
* <p>Default: {@link MultiCache}. In additions, the number of caches is default
* to 97 and can be changed by use of the org.zkoss.zk.ui.eventMethods.cache.number
* property. The maximal allowed size of each cache, if GC, is default to 30
* and can be changed by use of the org.zkoss.zk.ui.eventMethods.cache.maxSize
* property.
*
* @param cache the cache. It cannot be null. It must be thread safe.
* Once assigned, the caller shall not access it again.
* @since 3.0.0
*/
public static final void setEventMethodCache(Cache cache) {
if (cache == null)
throw new IllegalArgumentException();
_evtmtds = cache;
}
/** A map of (Pair(Class,String evtnm), Method). */
private static Cache _evtmtds = new MultiCache(
Library.getIntProperty("org.zkoss.zk.ui.event.methods.cache.number", 97),
Library.getIntProperty("org.zkoss.zk.ui.event.methods.cache.maxSize", 30),
4*60*60*1000);
/** An utilities to create an array of JavaScript objects
* ({@link JavaScriptValue}) that can be used
* to mount the specified widget at the clients.
*
* @since 5.0.0
*/
public static final Collection redraw(Collection comps) {
try {
final StringWriter out = new StringWriter(1024*8);
final List js = new LinkedList();
for (Iterator it = comps.iterator(); it.hasNext();) {
((ComponentCtrl)it.next()).redraw(out);
final StringBuffer sb = out.getBuffer();
js.add(new JavaScriptValue(sb.toString()));
sb.setLength(0);
}
return js;
} catch (java.io.IOException ex) {
throw new InternalError();
}
}
/** Represents a dummy definition. */
public static final ComponentDefinition DUMMY =
new ComponentDefinition() {
public LanguageDefinition getLanguageDefinition() {
return null;
}
public String getName() {
return "[anonymous]";
}
public String getTextAs() {
return null;
}
public boolean isMacro() {
return false;
}
public String getMacroURI() {
return null;
}
public boolean isInlineMacro() {
return false;
}
public boolean isNative() {
return false;
}
public boolean isBlankPreserved() {
return false;
}
public Object getImplementationClass() {
return Component.class;
}
public void setImplementationClass(Class cls) {
throw new UnsupportedOperationException();
}
public void setImplementationClass(String clsnm) {
throw new UnsupportedOperationException();
}
public Class resolveImplementationClass(Page page, String clsnm)
throws ClassNotFoundException {
return Component.class;
}
public boolean isInstance(org.zkoss.zk.ui.Component comp) {
return comp != null;
}
public Component newInstance(Page page, String clsnm) {
throw new UnsupportedOperationException();
}
public Component newInstance(Class cls) {
throw new UnsupportedOperationException();
}
public void addMold(String name, String widgetClass) {
throw new UnsupportedOperationException();
}
/** @deprecated */
public void addMold(String name, String moldURI, String z2cURI) {
throw new UnsupportedOperationException();
}
/** @deprecated */
public String getWidgetClass(String moldName) {
return null;
}
/** @deprecated */
public String getDefaultWidgetClass() {
return null;
}
public String getWidgetClass(Component comp, String moldName) {
return null;
}
public String getDefaultWidgetClass(Component comp) {
return null;
}
public void setDefaultWidgetClass(String widgetClass) {
throw new UnsupportedOperationException();
}
public boolean hasMold(String name) {
return false;
}
public Collection getMoldNames() {
return Collections.EMPTY_LIST;
}
public void addProperty(String name, String value) {
throw new UnsupportedOperationException();
}
public void applyProperties(Component comp) {
}
public void applyAttributes(Component comp) {
}
public Map evalProperties(Map propmap, Page owner, Component parent) {
return propmap != null ? propmap: new HashMap(3);
}
public AnnotationMap getAnnotationMap() {
return null;
}
public String getApply() {
return null;
}
public ExValue[] getParsedApply() {
return null;
}
public void setApply(String apply) {
throw new UnsupportedOperationException();
}
public URL getDeclarationURL() {
return null;
}
public ComponentDefinition clone(LanguageDefinition langdef, String name) {
throw new UnsupportedOperationException();
}
public Object clone() {
throw new UnsupportedOperationException();
}
};
}
|
package controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import model.match.Match;
import model.match.MatchState;
import model.player.Country;
import model.player.Player;
import model.player.PlayerType;
import model.player.details.MatchDetails;
import model.team.Team;
import model.team.TeamMatchDetails;
import util.MiscUtilities;
import engine.ai.AI;
import engine.util.Misc;
public class TossScreenController implements IController, Initializable {
private MasterController masterController;
private String screenName;
private Match match;
@Override
public void initialize(URL location, ResourceBundle resources) {
}
@Override
public void setMasterController(MasterController masterController) {
this.masterController = masterController;
}
@Override
public String getScreenName() {
return this.screenName;
}
@Override
public void setScreenName(String name) {
this.screenName = name;
}
public Match getMatch() {
return match;
}
public void setMatch(Match match) {
this.match = match;
}
public TossScreenController(){
}
@FXML
private Label titleLabel, statusLabel, team2Label, team1Label;
@FXML
private TableView<Player> playingElevenTableView1, playingElevenTableView2;
@FXML
private TableColumn<Player, Country> countryColumn1, countryColumn2;
@FXML
private TableColumn<Player, Number> positionColumn1, positionColumn2;
@FXML
private TableColumn<Player, PlayerType> typeColumn1, typeColumn2;
@FXML
private TableColumn<Player, String> nameColumn1, nameColumn2;
@FXML
private Button button1, button2;
@FXML
private void handlleButtonClick(ActionEvent event) {
Button b = (Button)event.getSource();
if(b.getText().equals("Heads")||b.getText().equals("Tails"))
{
int rand = MiscUtilities.generateRandomInt(0, 1);
statusLabel.setText(match.getTeams().get(rand).getFullName() + " has won the toss");
if(match.getTeams().get(rand)==masterController.getTournament().getUserTeam())
{
button1.setText("Bat");
button2.setText("Bowl");
}
else
{
button1.setText("Bat");
button2.setText("Bowl");
String decision = AI.chooseBatOrBowl(match);
statusLabel.setText(statusLabel.getText() + " and elected to " + decision + " first");
if(decision.equals("bat"))
{
button1.setDisable(true);
}
else if(decision.equals("bowl"))
{
button2.setDisable(true);
}
}
}
else if(b.getText().equals("Bat"))
{
MiscUtilities.log("Bat clicked");
for(TeamMatchDetails tmd:match.getTeamsMatchDetails()) {
tmd.setBowling(true);
tmd.setBatting(false);
}
match.getTeamsMatchDetails().get(Misc.findUserTeamIndex(match, masterController.getTournament().getUserTeam())).setBatting(true);
match.getTeamsMatchDetails().get(Misc.findUserTeamIndex(match, masterController.getTournament().getUserTeam())).setBowling(false);
MatchScreenController msc = (MatchScreenController)masterController.getController("MatchScreen");
match.setMatchState(MatchState.InningsOneInProgress);
msc.setMatch(match);
msc.setUserTeamIndex(Misc.findUserTeamIndex(match, masterController.getTournament().getUserTeam()));
msc.setUpScreen();
masterController.changeScreenTo("MatchScreen");
}
else if(b.getText().equals("Bowl"))
{
MiscUtilities.log("Bowl clicked");
for(TeamMatchDetails tmd:match.getTeamsMatchDetails()) {
tmd.setBowling(false);
tmd.setBatting(true);
}
match.getTeamsMatchDetails().get(Misc.findUserTeamIndex(match, masterController.getTournament().getUserTeam())).setBowling(true);
match.getTeamsMatchDetails().get(Misc.findUserTeamIndex(match, masterController.getTournament().getUserTeam())).setBatting(false);
MatchScreenController msc = (MatchScreenController)masterController.getController("MatchScreen");
msc.setMatch(match);
match.setMatchState(MatchState.InningsOneInProgress);
msc.setUserTeamIndex(Misc.findUserTeamIndex(match, masterController.getTournament().getUserTeam()));
msc.setUpScreen();
masterController.changeScreenTo("MatchScreen");
}
}
private void createMatchDetails()
{
match.setTeamsMatchDetails(FXCollections.observableArrayList());
for(Team t: match.getTeams())
{
TeamMatchDetails tmd = new TeamMatchDetails();
tmd.setMatch(match);
tmd.setTeam(t);
tmd.setPlayingEleven(t.getCurrentPlayingEleven());
tmd.setBatting(false);
tmd.setBowling(false);
tmd.setBallsBowled(0);
tmd.setBallsPlayed(0);
tmd.setExtrasConceded(0);
tmd.setExtrasGained(0);
tmd.setMatchResult(null);
tmd.setOverNumber(0);
tmd.setTotalConceded(0);
tmd.setTotalScored(0);
tmd.setWicketsGained(0);
tmd.setWicketsLost(0);
for(Player p:tmd.getPlayingEleven())
{
if(p.getTournamentDetails().getMatchDetailsList()==null||p.getTournamentDetails().getMatchDetailsList().isEmpty())
{
p.getTournamentDetails().setMatchDetailsList(FXCollections.observableArrayList());
}
MatchDetails md = new MatchDetails();
md.setBatted(false);
md.setBattingBalls(0);
md.setBattingDots(0);
md.setBattingFours(0);
md.setBattingFours(0);
md.setBattingPoints(0);
md.setBattingPoints(0);
md.setBattingRuns(0);
md.setBattingSixes(0);
md.setBowlingBalls(0);
md.setBowlingDots(0);
md.setBowlingFours(0);
md.setBowlingMaidens(0);
md.setBowlingPoints(0);
md.setBowlingRuns(0);
md.setBowlingSixes(0);
md.setBowlingWickets(0);
md.setMatch(match);
md.setMom(false);
md.setOutWicket(false);
md.setOverallPoints(0);
md.setMatch(match);
md.setPlayer(p);
md.setPlayerTournamentDetails(p.getTournamentDetails());
p.getTournamentDetails().getMatchDetailsList().add(md);
}
match.getTeamsMatchDetails().add(tmd);
}
}
public void setUpScreen()
{
createMatchDetails();
button1.setText("Heads");
button2.setText("Tails");
button1.setDisable(false);
button2.setDisable(false);
titleLabel.setText(match.getTeams().get(0).getShortName() + " vs. " + match.getTeams().get(1).getShortName() + "\r\n" + "Live from " + match.getStadium().getName());
statusLabel.setText("Toss time!");
team1Label.setText(match.getTeams().get(0).getFullName());
team2Label.setText(match.getTeams().get(1).getFullName());
positionColumn1.setCellValueFactory(cellData->new SimpleIntegerProperty(1+match.getTeams().get(0).getCurrentPlayingEleven().indexOf(cellData.getValue())));
positionColumn2.setCellValueFactory(cellData->new SimpleIntegerProperty(1+match.getTeams().get(1).getCurrentPlayingEleven().indexOf(cellData.getValue())));
nameColumn1.setCellValueFactory(cellData-> cellData.getValue().lastNameProperty());
nameColumn2.setCellValueFactory(cellData-> cellData.getValue().lastNameProperty());
typeColumn1.setCellValueFactory(cellData->cellData.getValue().getGeneralDetails().playerTypeProperty());
typeColumn2.setCellValueFactory(cellData->cellData.getValue().getGeneralDetails().playerTypeProperty());
countryColumn1.setCellValueFactory(cellData -> cellData.getValue().getGeneralDetails().countryProperty());
countryColumn2.setCellValueFactory(cellData -> cellData.getValue().getGeneralDetails().countryProperty());
playingElevenTableView1.setItems(match.getTeams().get(0).currentPlayingElevenProperty());
playingElevenTableView2.setItems(match.getTeams().get(1).currentPlayingElevenProperty());
}
}
|
package egovframework.adm.cfg.ccm.service;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
public interface CourseClassificationService {
public List selectCourseClassificationList(Map<String, Object> commandMap) throws Exception;
public int updateCourseClassification(Map<String, Object> commandMap) throws Exception;
public int deleteCourseClassification(Map<String, Object> commandMap) throws Exception;
public String getNewClassCode(Map<String, Object> commandMap) throws Exception;
public List selectClassList(Map<String, Object> commandMap) throws Exception;
public int insertCourseClassification(Map<String, Object> commandMap) throws Exception;
}
|
public class test {
public static void main(String[] args) {
Cerchio c = new Cerchio(2);
System.out.println(c.toString());
}
}
|
import java.util.Scanner;
public class Game {
int welcome() throws InterruptedException {
System.out.println("Welcome to BlackJack!\n");
Thread.sleep(1000);
Scanner scanner = new Scanner(System.in);
int inputNum;
while (true) {
try {
System.out.println("How many people are playing? (1-5)");
inputNum = Integer.parseInt(scanner.nextLine());
} catch (Exception e) {
System.out.println("Invalid type. Please enter a number.");
continue;
}
if (inputNum >= 1 && inputNum <= 5) {
return inputNum;
}
}
}
int playerPlay(Better player, Deck newDeck) throws InterruptedException {
boolean isStick = false;
Thread.sleep(500);
int total;
while (!isStick) {
System.out.println("\n" + player.getName() + " Cards: \n");
player.showCards();
total = player.getTotal();
Thread.sleep(500);
System.out.println("\nYour sum is " + total);
player.setChoice();
String player1Choice = player.getChoice();
if (player1Choice.equals("Twist")) {
player.addCard(newDeck.getCards(1));
} else {
isStick = true;
}
total = player.getTotal();
if (total > 21) {
isStick = true;
}
}
System.out.println("\n||" + player.getName() + "||'s Final Cards: \n");
player.showCards();
total = player.getTotal();
Thread.sleep(500);
System.out.println("\nYour sum is " + total);
return total;
}
int dealerPlay(Player dealer, Deck newDeck) throws InterruptedException {
int dealerTotal = dealer.getTotal();
while (dealerTotal < 17) {
dealer.addCard(newDeck.getCards(1));
dealerTotal = dealer.getTotal();
}
System.out.println("The dealer had:\n");
dealer.showCards();
System.out.println("\nThe dealer's total is: ");
System.out.println(dealerTotal + "\n");
return dealerTotal;
}
int result(int total, int dealerTotal, String name) throws InterruptedException {
System.out.println("Hello, " + name);
if(total >21) {
System.out.println("You went bust!");
return -1;
}
else if(total > dealerTotal || dealerTotal > 21) {
System.out.println("You won!");
return 1;
} else if(total == dealerTotal) {
System.out.println("You drew!");
return 0;
} else {
System.out.println("You lost.");
return -1;
}
}
boolean isReplay() {
Scanner scanner = new Scanner(System.in);
System.out.println("Play again? (y/n)");
String replay;
while (true) {
replay = scanner.nextLine();
if (replay.equalsIgnoreCase("y") || replay.equalsIgnoreCase("yes")) {
return true;
} else if (replay.equalsIgnoreCase("n") || replay.equalsIgnoreCase("no")) {
return false;
} else {
System.out.println("Invalid input. Please enter either y or n.");
}
}
}
}
|
package com.github.sd;
import java.io.*;
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
import java.util.*;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.*;
import com.nimbusds.jwt.*;
import net.iharder.Base64;
/**
* User: Daniil Sosonkin
* Date: 4/4/2018 3:01 PM
*/
public class PublicKeyCredentials implements Credentials
{
private String filename;
public PublicKeyCredentials(String filename)
{
this.filename = filename;
}
@Override
public String getToken()
{
try
{
String keyId = filename.substring(0, filename.indexOf('.'));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(getPublicKey(filename), RSAPublicKeySpec.class);
RSAPublicKey publicRsaKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
JWTClaimsSet claimSet = new JWTClaimsSet.Builder()
.issuer("jAPI (" + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version") + " " + System.getProperty("java.version") + ")")
.expirationTime(new Date(System.currentTimeMillis() + 10 * 1000))
.notBeforeTime(new Date())
.issueTime(new Date())
.jwtID(UUID.randomUUID().toString())
.build();
JWEHeader header = new JWEHeader.Builder(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A128GCM)
.keyID(keyId)
.build();
EncryptedJWT jwt = new EncryptedJWT(header, claimSet);
RSAEncrypter encrypter = new RSAEncrypter(publicRsaKey);
jwt.encrypt(encrypter);
return jwt.serialize();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public String getScheme()
{
return "Key";
}
@Override
public void expired()
{ }
private static PublicKey getPublicKey(String filename) throws Exception
{
if (filename.toLowerCase().endsWith(".pem"))
return readPEM(filename);
File file = new File(filename);
try (DataInputStream dis = new DataInputStream(new FileInputStream(file)))
{
byte[] keyBytes = new byte[(int) file.length()];
dis.readFully(keyBytes);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
}
private static PublicKey readPEM(String filename) throws Exception
{
File file = new File(filename);
try (BufferedReader in = new BufferedReader(new FileReader(file)))
{
StringBuilder buf = new StringBuilder();
String line;
while ((line = in.readLine()) != null)
buf.append(line);
String publicKeyPEM = buf.toString();
publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
byte[] encoded = Base64.decode(publicKeyPEM);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(new X509EncodedKeySpec(encoded));
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package library.system.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import library.system.database.Database;
import library.system.model.IssueInfo;
/**
*
* @author Sithu
*/
public class IssueDAO {
public void saveIssueInfo(IssueInfo issueInfo) throws SQLException {
Connection conn = Database.getInstance().getConnection();
String sql = "insert into lbdb.issue (book_id,member_id,issue_date,renew_count) values (?,?,now(),0)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, issueInfo.getBookId());
stmt.setInt(2, issueInfo.getMemberId());
stmt.execute();
}
public IssueInfo getIssueInfo(int bookId) throws SQLException {
Connection conn = Database.getInstance().getConnection();
String sql = "select * from lbdb.issue where book_id=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, bookId);
ResultSet result = stmt.executeQuery();
IssueInfo issueInfo = null;
if(result.next()){
int memberId = result.getInt("member_id");
Date issuedDate = result.getDate(("issue_date"));
int renewCount = result.getInt("renew_count");
issueInfo = new IssueInfo(bookId, memberId, issuedDate, renewCount);
}
return issueInfo;
}
public void deleteIssueInfo(int bookId) throws SQLException {
Connection conn = Database.getInstance().getConnection();
String sql = "delete from lbdb.issue where book_id=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, bookId);
stmt.execute();
}
public void updateRenewCount(int bookId) throws SQLException {
Connection conn = Database.getInstance().getConnection();
String sql = "update lbdb.issue set renew_count=renew_count+1 where book_id=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, bookId);
stmt.execute();
}
}
|
package com.restcode.restcode.domain.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Table(name="categories")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String categoryName;
//Falta especificar la relación
//private Restaurant restaurant;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
}
|
/**
*
*/
package com.neu.html_factory;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.neu.html.B;
import com.neu.html.Body;
import com.neu.html.Div;
import com.neu.html.HTML;
import com.neu.html.Head;
import com.neu.html.Node;
import com.neu.html.Title;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* @author ideepakkrishnan
*
*/
public class LoggingHTMLFactoryTests extends TestCase {
private AbstractHTMLNodeFactory factory = new LoggingHTMLFactory();
/**
* Create the test case
*
* @param testName name of the test case
*/
public LoggingHTMLFactoryTests( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( LoggingHTMLFactoryTests.class );
}
public void testBWithContent() {
Map<String,String> bAtts = new HashMap<String,String>();
bAtts.put("class", "highlight");
B b = factory.makeB();
b.set(bAtts, new Div());
assertEquals(
b.textualRepresentation(),
"<b class=highlight><div></div></b>");
}
public void testBodyWithContent() {
Map<String,String> divAtts = new HashMap<String,String>();
divAtts.put("id", "second");
divAtts.put("class", "bar");
Div div = factory.makeDiv();
div.set(divAtts, "b");
List<Node> children = new LinkedList<Node>();
children.add(div);
Map<String,String> bodyAtts = new HashMap<String,String>();
bodyAtts.put("id", "content");
Body body = factory.makeBody();
body.set(bodyAtts, children);
assertEquals(
"<body id=content><div class=bar id=second>b</div></body>",
body.textualRepresentation());
}
public void testDivWithNoContent() {
Div div = factory.makeDiv();
assertEquals("<div></div>", div.textualRepresentation());
}
public void testDivWithContent() {
Map<String,String> divAtts = new HashMap<String,String>();
divAtts.put("id", "second");
divAtts.put("class", "bar");
Div div = factory.makeDiv();
div.set(divAtts, "b");
assertEquals(
"<div class=bar id=second>b</div>",
div.textualRepresentation());
}
public void testHeadWithNoContent() {
Head head = factory.makeHead();
assertEquals("<head></head>", head.textualRepresentation());
}
public void testHeadWithContent() {
Map<String,String> noAttributes = new HashMap<String,String>();
Title title = factory.makeTitle();
title.set(noAttributes, "Northeastern University");
List<Node> children = new LinkedList<Node>();
children.add(title);
Map<String,String> headAtts = new HashMap<String,String>();
headAtts.put("class", "header");
Head head = factory.makeHead();
head.set(headAtts, children);
assertEquals(
"<head class=header><title>Northeastern University</title></head>",
head.textualRepresentation());
}
public void testHtmlWithNoContent() {
HTML html = factory.makeHtml();
assertEquals("<html></html>", html.textualRepresentation());
}
public void testHtmlWithContent() {
Map<String,String> noAttributes = new HashMap<String,String>();
Title title = factory.makeTitle();
title.set(noAttributes, "Northeastern University");
List<Node> headChildren = new LinkedList<Node>();
headChildren.add(title);
Head head = factory.makeHead();
head.set(noAttributes, headChildren);
Body body = new Body();
List<Node> htmlChildren = new LinkedList<Node>();
htmlChildren.add(head);
htmlChildren.add(body);
Map<String,String> htmlAtts = new HashMap<String,String>();
htmlAtts.put("id", "container");
HTML html = factory.makeHtml();
html.set(htmlAtts, htmlChildren);
assertEquals(
"<html id=container><head><title>Northeastern University"
+ "</title></head><body></body></html>",
html.textualRepresentation());
}
public void testTitleWithContent()
{
Map<String,String> titleAtts = new HashMap<String,String>();
titleAtts.put("class", "titleStyle");
Title title = factory.makeTitle();
title.set(titleAtts, "Northeastern University");
assertEquals(
title.textualRepresentation(),
"<title class=titleStyle>Northeastern University</title>");
}
public void testTitleWithNoContent() {
Title title = factory.makeTitle();
assertEquals("<title></title>", title.textualRepresentation());
}
}
|
package com.dexter.myhome.menu;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatSpinner;
import com.dexter.myhome.R;
import com.dexter.myhome.model.ApartmentInfo;
import com.dexter.myhome.util.AppConstants;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Arrays;
public class ApartmentInfoActivity extends AppCompatActivity {
private AppCompatSpinner societies;
private AppCompatSpinner apartments;
private AppCompatSpinner flats;
private AppCompatButton save;
private String societyName;
private String apartmentName;
private String flatName;
private FirebaseAuth mAuth;
private DatabaseReference apartmentInfoReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apartment_info);
societies = findViewById(R.id.societies);
apartments = findViewById(R.id.apartments);
flats = findViewById(R.id.flats);
save = findViewById(R.id.save_apartment_info);
mAuth = FirebaseAuth.getInstance();
apartmentInfoReference = FirebaseDatabase.getInstance(AppConstants.FIREBASE_DB_URL).getReference("Users")
.child(mAuth.getCurrentUser().getUid()).child("ApartmentInfo");
getSupportActionBar().setTitle("Apartment Info");
apartments.setEnabled(Boolean.FALSE);
flats.setEnabled(Boolean.FALSE);
societies.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item, AppConstants.SOCITIES));
societies.setSelection(0);
apartments.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item, AppConstants.APARTMENTS));
apartments.setSelection(0);
flats.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item, AppConstants.FLATS));
flats.setSelection(0);
societies.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position != 0){
societyName = AppConstants.SOCITIES[position];
apartments.setEnabled(Boolean.TRUE);
} else {
apartments.setEnabled(Boolean.FALSE);
flats.setEnabled(Boolean.FALSE);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
apartments.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position != 0){
apartmentName = AppConstants.APARTMENTS[position];
flats.setEnabled(Boolean.TRUE);
} else {
flats.setEnabled(Boolean.FALSE);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
flats.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position != 0){
flatName = AppConstants.FLATS[position];
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
getApartmentInfo();
save.setOnClickListener(v -> {
ApartmentInfo apartmentInfo = new ApartmentInfo();
apartmentInfo.setSocietyName(societyName);
apartmentInfo.setApartmentName(apartmentName);
apartmentInfo.setFlatName(flatName);
apartmentInfoReference.setValue(apartmentInfo);
Toast.makeText(getApplicationContext(),"Apartment Info Saved !", Toast.LENGTH_LONG).show();
});
}
private void getApartmentInfo() {
apartmentInfoReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
ApartmentInfo apartmentInfo = dataSnapshot.getValue(ApartmentInfo.class);
societies.setSelection(Arrays.asList(AppConstants.SOCITIES).indexOf(apartmentInfo.getSocietyName()));
apartments.setSelection(Arrays.asList(AppConstants.APARTMENTS).indexOf(apartmentInfo.getApartmentName()));
flats.setSelection(Arrays.asList(AppConstants.FLATS).indexOf(apartmentInfo.getFlatName()));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.csci360.alarmclock;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
* @author benjaminmuldrow
*/
public class ULBAlarmClock extends Application{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(ULBAlarmClock.class, (java.lang.String[])null);
}
@Override
public void start(Stage primaryStage) throws IOException {
Pane main = (Pane) FXMLLoader.load(ULBAlarmClock.class.getResource("newMain.fxml"));
Scene scene = new Scene(main);
primaryStage.setScene(scene);
primaryStage.setTitle("ULB Radio Alarm Clock");
primaryStage.show();
}
}
|
package liu.test.Mockito;
/**
* 账户
* @author LIU
*
*/
public class Account {
private RailwayTicket railwayTicket; //火车票
public RailwayTicket getRailwayTicket() {
return railwayTicket;
}
public void setRailwayTicket(RailwayTicket railwayTicket) {
this.railwayTicket = railwayTicket;
}
}
|
package com.baitap;
import java.util.Scanner;
public class Bai1 {
public static void main(String[] args) {
String ten;
double diem;
Scanner sc = new Scanner(System.in);
System.out.println("Nhap ten :");
ten = sc.nextLine();
System.out.println("Nhap diem :");
diem = sc.nextDouble();
// Xuat ra man hinh
System.out.println("Ho va ten :" +ten+ "Diem :"+diem);
System.out.printf("%s %f điểm", ten, diem);
}
}
|
package com.HyperStandard.llr.app;
import android.app.Application;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
/**
* Created by mitch on 7/7/14.
*/
public class LLerApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
CalligraphyConfig.initDefault( "fonts/RobotoSlab-Regular.ttf", R.attr.fontPath );
}
}
|
package io.github.yizhiru.thulac4j;
import io.github.yizhiru.thulac4j.model.SegItem;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
/**
* SegOnly 分词,结果没有词性.
*/
public final class SegOnly extends BaseSegmenter<String> {
public SegOnly(String weightPath, String featurePathh) throws IOException {
super(weightPath, featurePathh);
}
@Override
List<String> process(List<SegItem> segItems) {
return segItems.stream()
.map(item -> (item.word))
.collect(Collectors.toList());
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DataOperations;
import DataObjects.Candidate_Profile_Object;
import java.lang.reflect.Array;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import static java.sql.DriverManager.getConnection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Shivam Patel
*/
public class Candidate_Profile_Operation
{
Connection con=null;
String url="jdbc:mysql://vvfv20el7sb2enn3.cbetxkdyhwsb.us-east-1.rds.amazonaws.com:3306/uioyzcynsq8h3m7h";
String un="fock27f4fz512g18";
String pass="puc2ocwfqnvrxed1";
ResultSet rs=null;
PreparedStatement pstmt;
Statement stmt;
Scanner sc = new Scanner(System.in);
public String msg="";
public Candidate_Profile_Operation()
{
try
{
//jdbc two lines load driver and connetion
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
msg=msg+"loaded";
con=DriverManager.getConnection(url,un,pass);
System.out.println("Connected");
msg=msg+"connectd";
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
msg=msg+ex.getMessage();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
msg=msg+ex.getMessage();
}
}
public String getError()
{
return msg;
}
public ArrayList<Candidate_Profile_Object> allids() throws SQLException
{
ArrayList<Candidate_Profile_Object> idlist=new ArrayList<Candidate_Profile_Object>();
String msg="";
// Candidate_Profile_Object cpob=new Candidate_Profile_Object();
String sql="select * from candidate_profile";
try {
stmt=con.createStatement();
rs=stmt.executeQuery(sql);
msg=msg+"72";
while(rs.next())
{
Candidate_Profile_Object cpo=new Candidate_Profile_Object();
String s=rs.getString("Candidate_ID");
cpo.setCandidate_ID(s);
s=rs.getString("Firstname");
cpo.setFirstname(s);
s=rs.getString("Middlename");
cpo.setMiddlename(s);
s=rs.getString("Lastname");
cpo.setLastname(s);
s=rs.getString("Gender");
cpo.setGender(s);
Date d=rs.getDate("DOB");
cpo.setDOB(d);
double db=rs.getDouble("Contact_No");
cpo.setContact_No(db);
db=rs.getDouble("Alternative_No");
cpo.setAlternative_No(db);
s=rs.getString("Email");
cpo.setEmail(s);
s=rs.getString("Address");
cpo.setAddress(s);
db=rs.getDouble("Pincode");
cpo.setPincode(db);
s=rs.getString("City");
cpo.setCity(s);
s=rs.getString("Image");
cpo.setImage(s);
s=rs.getString("Password");
cpo.setPassword(s);
System.out.println("----dndnd----");
idlist.add(cpo);
}
} catch (SQLException ex) {
msg=msg+ex.getMessage();
Logger.getLogger(Candidate_Profile_Operation.class.getName()).log(Level.SEVERE, null, ex);
}
return idlist;
}
public String InsertCandidateDetails(Candidate_Profile_Object cpo)
{
System.out.println(cpo);
String msg="";
String sql="insert into candidate_profile values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
System.out.println(sql);
System.out.println("---------------------------"+cpo.getCandidate_ID());
try
{
pstmt=con.prepareStatement(sql);
System.out.println(pstmt);
System.out.println("---"+cpo.getCandidate_ID());
pstmt.setString(1,cpo.getCandidate_ID());
System.out.println(cpo.getCandidate_ID());
pstmt.setString(2,cpo.getFirstname());
System.out.println(cpo.getFirstname());
pstmt.setString(3,cpo.getMiddlename());
pstmt.setString(4,cpo.getLastname());
pstmt.setString(5,cpo.getGender());
java.util.Date jud=cpo.getDOB();
java.sql.Date jsd=new java.sql.Date(jud.getTime());
pstmt.setDate(6,jsd);
pstmt.setDouble(7,cpo.getContact_No());
pstmt.setDouble(8,cpo.getAlternative_No());
pstmt.setString(9,cpo.getEmail());
pstmt.setString(10,cpo.getAddress());
pstmt.setDouble(11,cpo.getPincode());
pstmt.setString(12,cpo.getCity());
pstmt.setString(13,cpo.getImage());
pstmt.setString(14,cpo.getPassword());
System.out.println("-----------");
pstmt.executeUpdate();
System.out.println("-----------");
msg="Succusessfully Inserted";
pstmt.close();
} catch (SQLException ex) {
Logger.getLogger(Candidate_Profile_Operation.class.getName()).log(Level.SEVERE, null, ex);
}
return msg;
}
public String DeleteCandidateDetails(Candidate_Profile_Object cpo)
{
String msg="";
String sql="delete from candidate_profile where Candidate_ID=?";
try {
pstmt=con.prepareStatement(sql);
pstmt.setString(1,cpo.getCandidate_ID());
pstmt.executeUpdate();
System.out.println("Successfully Deleted");
} catch (SQLException ex) {
Logger.getLogger(Candidate_Profile_Operation.class.getName()).log(Level.SEVERE, null, ex);
}
return msg;
}
// public String UpdateCandidateDetails(Candidate_Profile_Object cpo)
// {
//
// }
public ArrayList<Candidate_Profile_Object> RetriveCandidateDetails(Candidate_Profile_Object cpo)
{
String msg="";
cpo=new Candidate_Profile_Object();
cpo.setCandidate_ID(cpo.getCandidate_ID());
String sql="select * from candidate_profile where Candidate_ID=?";
ArrayList<Candidate_Profile_Object> data=new ArrayList<Candidate_Profile_Object>();
try {
pstmt=con.prepareStatement(sql);
pstmt.setString(1,cpo.getCandidate_ID());
rs=pstmt.executeQuery();
while(rs.next())
{
Candidate_Profile_Object cpob=new Candidate_Profile_Object();
String s=rs.getString("Candidate_ID");
cpob.setCandidate_ID(s);
s=rs.getString("Firstname");
cpob.setFirstname(s);
s=rs.getString("Middlename");
cpob.setMiddlename(s);
s=rs.getString("Lastname");
cpob.setFirstname(s);
s=rs.getString("Gender");
cpob.setGender(s);
Date d=rs.getDate("DOB");
cpob.setDOB(d);
double db=rs.getDouble("Contact_No");
cpob.setContact_No(db);
db=rs.getDouble("Alternative_No");
cpob.setAlternative_No(db);
s=rs.getString("Email");
cpob.setEmail(s);
s=rs.getString("Address");
cpob.setAddress(s);
db=rs.getDouble("Pincode");
cpob.setPincode(db);
s=rs.getString("City");
cpob.setCity(s);
s=rs.getString("Image");
cpob.setImage(s);
s=rs.getString("Password");
cpob.setPassword(s);
System.out.println("----dndnd----");
data.add(cpob);
}
} catch (SQLException ex) {
Logger.getLogger(Candidate_Profile_Operation.class.getName()).log(Level.SEVERE, null, ex);
}
return data;
}
}
|
package com.hzero.order.app.service.impl;
import com.hzero.order.api.controller.dto.OrderReturnDTO;
import com.hzero.order.app.service.OrderService;
import com.hzero.order.app.service.SoLineService;
import com.hzero.order.domain.entity.Conditions;
import com.hzero.order.domain.entity.Order;
import com.hzero.order.domain.entity.SoHeader;
import com.hzero.order.domain.entity.SoLine;
import com.hzero.order.domain.repository.SoHeaderRepository;
import com.hzero.order.domain.repository.SoLineRepository;
import com.hzero.order.infra.mapper.OrderMapper;
import com.mysql.jdbc.StringUtils;
import io.choerodon.core.domain.Page;
import io.choerodon.mybatis.pagehelper.PageHelper;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.hzero.boot.platform.code.builder.CodeRuleBuilder;
import org.hzero.boot.platform.code.constant.CodeConstants;
import org.hzero.core.base.BaseAppService;
import org.hzero.core.util.Results;
import org.hzero.mybatis.helper.SecurityTokenHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class OrderServiceImpl extends BaseAppService implements OrderService {
@Autowired
OrderMapper orderMapper;
@Autowired
private SoLineService soLineService;
@Autowired
SoHeaderRepository soHeaderRepository;
@Autowired
private SoLineRepository soLineRepository;
@Autowired
private CodeRuleBuilder codeRuleBuilder;
private final String ORDERNUMBER = "HZERO.ORDER.NUMBER";
/**
* 多条件分页查询
*/
@Override
public Page<OrderReturnDTO> list(PageRequest pageRequest, Conditions conditions) {
Page<OrderReturnDTO> page = PageHelper.doPageAndSort(pageRequest,() -> orderMapper.list(conditions));
List<OrderReturnDTO> list = orderMapper.list(conditions);
Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
for (OrderReturnDTO orderReturnDTO:list) {
if(map.containsKey(orderReturnDTO.getOrderNumber())){
//通过Key值查询value值,value值不为空,代表为同一个订单,就把行金额相加
map.put(orderReturnDTO.getOrderNumber(),map.get(orderReturnDTO.getOrderNumber()).add(orderReturnDTO.getOrderAmount()));
}else {
//如果value为空代表还没有Map中的key值没有该Key值,就新增一个key值为订单编号,value值为行金额的的map
map.put(orderReturnDTO.getOrderNumber(),orderReturnDTO.getOrderAmount());//
}
}
for (OrderReturnDTO orderReturnDTO:page.getContent()){
//循环把订单的总金额放进对应每一个订单行数据中
if(map.containsKey(orderReturnDTO.getOrderNumber())){
orderReturnDTO.setOrderAmount(map.get(orderReturnDTO.getOrderNumber()));
}
}
return page;
}
/**
* 根据HeadId来删除Line
*/
@Override
public void deleteLineByHeadId(Long organizationId, Long soheaderid) {
List<SoLine> list = soLineService.selectById(soheaderid);
if (list == null) {
throw new RuntimeException("输入的订单头没有相应的订单");
}
SoHeader soHeader1 = soHeaderRepository.selectByPrimaryKey(soheaderid);
if (!soHeader1.getOrderStatus().equals("NEW") && !soHeader1.getOrderStatus().equals("REJECTED")) {
throw new RuntimeException("订单状态不能修改");
}
if (list.size() != 0) {
//遍历
for (SoLine soLine : list) {
SoLine soLine1 = soLineRepository.selectByPrimaryKey(soLine.getSoLineId());
soLine.set_token(soLine1.get_token());
soLine.setSoLineId(soLine.getSoLineId());
SecurityTokenHelper.validToken(soLine);
soLineRepository.deleteByPrimaryKey(soLine);
}
}
}
/**
* 根据订单头删除订单
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ResponseEntity<String> deleteOrder(Long organizationId, Long soHeaderId) {
List<SoLine> list = soLineService.selectById(soHeaderId);
if (list == null) {
throw new RuntimeException("输入的订单头没有相应的订单");
}
if (list.size() != 0) {
//先删除订单行数据再删除订单头数据,否则只需要删除订单头数据
for (SoLine soLine : list) {
SoLine soLine1 = soLineRepository.selectByPrimaryKey(soLine.getSoLineId());
soLine.set_token(soLine1.get_token());
soLine.setSoLineId(soLine.getSoLineId());
SecurityTokenHelper.validToken(soLine);
soLineRepository.deleteByPrimaryKey(soLine);
}
}
SoHeader soHeader1 = soHeaderRepository.selectByPrimaryKey(soHeaderId);
SoHeader soHeader = new SoHeader();
soHeader.set_token(soHeader1.get_token());
soHeader.setObjectVersionNumber(soHeader1.getObjectVersionNumber());
soHeader.setSoHeaderId(soHeaderId);
SecurityTokenHelper.validToken(soHeader);
soHeaderRepository.deleteByPrimaryKey(soHeader);
return Results.success("删除订单成功");
}
@Override
@Transactional(rollbackFor = Exception.class)
public Order addOrder(Long organizationId, Order order) {
//如果order的SoHeaderId不为空
if (order.getSoHeaderId()!=null) {
//当订单头不为空,表示更新订单头
SoHeader soHeader = soHeaderRepository.selectByPrimaryKey(order.getSoHeaderId());
if (order.getObjectVersionNumber()== null) {
throw new RuntimeException("object_version_number为空");
} else if (order.getObjectVersionNumber() != soHeader.getObjectVersionNumber()) {
throw new RuntimeException("object_version_number不一致");
} else {
if ("NEW".equals(soHeader.getOrderStatus()) || "REJECTED".equals(soHeader.getOrderStatus())) {
soHeaderRepository.updateByPrimaryKeySelective(soHeader);
}else {
throw new RuntimeException("当前订单状态无法更改");
}
}
}
else// (order.getSoHeaderId()!=null && order.getList()!=null)
{
//因为当soHeaderId为空的时候
//将原order中对象中的关于SoHeader信息取出
SoHeader soHeader = new SoHeader();
//订单号按照编码规则生成并设置到soHeader
String code = codeRuleBuilder.generateCode(organizationId, ORDERNUMBER,
CodeConstants.CodeRuleLevelCode.GLOBAL,
CodeConstants.CodeRuleLevelCode.GLOBAL,
null);
soHeader.setOrderNumber(code);
soHeader.setCompanyId(order.getCompanyId());
soHeader.setOrderDate(order.getOrderDate());
//使orderStatus默认是NEW
if (order.getOrderStatus() != null) {
soHeader.setOrderStatus(order.getOrderStatus());
} else {
soHeader.setOrderStatus("NEW");
}
soHeader.setCustomerId(order.getCustomerId());
soHeader.set_token(order.get_token());
//校验soHeader对象
validObject(soHeader);
//这个地方soHeaderId自动填充
soHeaderRepository.insertSelective(soHeader);
//将这个处理过得soHeader传递进orderResult
order.setSoHeaderId(soHeader.getSoHeaderId());
//insert有关SoLine
List<SoLine> list = order.getList();
int index = 0;
for (SoLine soLine :
list) {
//判断当前输入的soLine对象的soLineId是否为空,为空是添加,不为空是更新
if(soLine.getSoLineId() != null){
SoLine soLine1 = soLineRepository.selectByPrimaryKey(soLine.getSoLineId());
//更新
if (soLine.getObjectVersionNumber() != null) {
if (soLine1.getObjectVersionNumber() == soLine.getObjectVersionNumber()){
soLineRepository.updateByPrimaryKey(soLine);
index++;
}else {
throw new RuntimeException("当前obejct_version_number不匹配");
}
}else {
throw new RuntimeException("当前obejct_version_number为空");
}
}else {
//添加
soLine.setSoHeaderId(soHeader.getSoHeaderId());
validObject(soLine);
soLineRepository.insertSelective(soLine);
order.getList().get(index).setSoLineId(soLine.getSoLineId());
index++;
}
}
}
return order;
}
}
|
/*
* Copyright 2002-2019 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.test.context.cache;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.SpringProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.context.cache.ContextCache.DEFAULT_MAX_CONTEXT_CACHE_SIZE;
import static org.springframework.test.context.cache.ContextCache.MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME;
import static org.springframework.test.context.cache.ContextCacheUtils.retrieveMaxCacheSize;
/**
* Unit tests for {@link ContextCacheUtils}.
*
* @author Sam Brannen
* @since 4.3
*/
class ContextCacheUtilsTests {
@BeforeEach
@AfterEach
void clearProperties() {
System.clearProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME);
SpringProperties.setProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME, null);
}
@Test
void retrieveMaxCacheSizeFromDefault() {
assertDefaultValue();
}
@Test
void retrieveMaxCacheSizeFromBogusSystemProperty() {
System.setProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME, "bogus");
assertDefaultValue();
}
@Test
void retrieveMaxCacheSizeFromBogusSpringProperty() {
SpringProperties.setProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME, "bogus");
assertDefaultValue();
}
@Test
void retrieveMaxCacheSizeFromDecimalSpringProperty() {
SpringProperties.setProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME, "3.14");
assertDefaultValue();
}
@Test
void retrieveMaxCacheSizeFromSystemProperty() {
System.setProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME, "42");
assertThat(retrieveMaxCacheSize()).isEqualTo(42);
}
@Test
void retrieveMaxCacheSizeFromSystemPropertyContainingWhitespace() {
System.setProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME, "42\t");
assertThat(retrieveMaxCacheSize()).isEqualTo(42);
}
@Test
void retrieveMaxCacheSizeFromSpringProperty() {
SpringProperties.setProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME, "99");
assertThat(retrieveMaxCacheSize()).isEqualTo(99);
}
private static void assertDefaultValue() {
assertThat(retrieveMaxCacheSize()).isEqualTo(DEFAULT_MAX_CONTEXT_CACHE_SIZE);
}
}
|
package pl.dkiszka.bank.events;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import pl.dkiszka.bank.models.User;
/**
* @author Dominik Kiszka {dominikk19}
* @project bank-application
* @date 21.04.2021
*/
@AllArgsConstructor
@Builder
@Getter
public class UserRegisteredEvent {
private String id;
private User user;
}
|
package com.gp.extract.twitter.util;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class IOUtil {
public static interface Logger{
String getLogId();
}
public static interface Loadable{
void load() throws IOException;
void save() throws IOException;
}
public static void showError(Logger logger, String msg)
{
//TODO: make this output to the GUI
System.err.println("Error ["+logger.getLogId()+"]: " + msg + ".\n\n");
}
public static void showInfo(Logger logger, String msg)
{
//TODO: make this output to the GUI
System.out.println("Info ["+logger.getLogId()+"]: " + msg + ".\n\n");
}
public static File ensureFileExist(String filename) throws IOException {
File yourFile = new File(filename);
if(!yourFile.exists()) {
yourFile.createNewFile();
}
return yourFile;
}
public static OutputStreamWriter getUTF8FileWriter(String file_name, boolean createIfNotExist) throws IOException {
File s;
if(createIfNotExist)
{
s = ensureFileExist(file_name);
}
else
{
s = new File(file_name);
}
return new OutputStreamWriter(
new FileOutputStream(
s
), Charset.forName("UTF-8").newEncoder() );
}
public static InputStreamReader getUTF8FileReader(String file_name, boolean createIfNotExist) throws IOException {
File s;
if(createIfNotExist)
{
s = ensureFileExist(file_name);
}
else
{
s = new File(file_name);
}
return new InputStreamReader(
new FileInputStream(
s
),"UTF-8" );
}
public static class DatasetReader{
private String fileName;
private BufferedReader bufferedReader;
public DatasetReader(String fileName) throws IOException {
fileName = fileName;
bufferedReader = new BufferedReader(getUTF8FileReader(fileName, false));
}
/**
* Read a single line from file, and put the found tag and words in the given arguments.
* If current tweet finished it sets the word argument to null.
* If the file finished it return false.
* @param data
* @return boolean indicating whether file ended or not
* @throws IOException
*/
public boolean read(ArrayList<String> data) throws IOException {
try
{
String line = bufferedReader.readLine();
if(line == null)
return false;
line.trim();
if(line.isEmpty())
{
data.set(0,null);
}
else
{
String [] split = line.split("\\s");
data.set(0,split[0]);
data.set(1,split[1]);
}
}
catch (IOException e)
{
bufferedReader.close();
throw e;
}
return true;
}
}
}
|
package com.consumercredits.pagesdod;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class TriggerViewSearchPage {
public static WebElement element;
public static WebElement trigger_search(WebDriver driver, String trigger_name) {
String triggerXpath = ".//span[@class = 'ng-binding ng-scope' and contains(text(),'" + trigger_name + "')]";
element = driver.findElement(By.xpath(triggerXpath));
return element;
}
public static WebElement save_button(WebDriver driver) {
element = driver.findElement(By.xpath(".//span[contains(@class , 'ng-scope') and contains(text(),'Save')]"));
return element;
}
public static WebElement related_accounts_search(WebDriver driver,String account_number) {
String related_acc_xpath = ".//span[@class = 'col-xs-11 ng-binding' and not(contains(text(),'" + account_number + "'))]";
element = driver.findElement(By.xpath(related_acc_xpath));
return element;
}
public static WebElement saved_successfully(WebDriver driver) {
element = driver.findElement(By.xpath(".//span[contains(text(),'Saved')]"));
return element;
}
}
|
package com.itheima.service.impl;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private RoleDao roleDao;
@Override
public List<User> list() {
List<User> userList = userDao.findAll();
//封装userList中的每一个User的roles数据
for (User user : userList) {
//获得user的id
Long id = user.getId();
//将id作为参数,查询当前userId对应的role集合数据
List<Role> roles = roleDao.findRoleByUserId(id);
user.setRoles(roles);
}
return userList;
}
@Override
public void save(User user, Long[] roleIds) {
//向sys_user表中存储数据
Long userId = userDao.save(user);
//向sus_user_role关系表中存储多条数据
userDao.saveUserRoleRel(userId,roleIds);
}
@Override
public void delete(Long userId) {
//删除sys_user_role关系表
userDao.deleteUserRoleRel(userId);
//删除sys_user表
userDao.delete(userId);
}
}
|
package com.edasaki.rpg.help;
import java.util.ArrayList;
import java.util.Collections;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import com.edasaki.core.menus.MenuItem;
public class HelpCommandsSingleton {
protected static final Object[][] COMMANDS = {
{
"/spell",
"/sp /spl",
"Open your spell menu.",
"Need help? Type " + ChatColor.YELLOW + "!spells " + ChatColor.GRAY + "in chat for a link to a quick video guide on the Spell Menu!"
},
{
"/shard",
"/eco /bal",
"Open the shard menu.",
"Salvage shards from equipment, convert between Shard Cubes and Shards, and more!"
},
{
"/trade <name>",
"",
"Send a trade request to another player.",
"Trades are the safest way to sell your items!"
},
{
"/party",
"/p",
"Basic party system command.",
"Talk in a party by adding \\ to the front of your messages, like this:",
"\\Hi guys!",
},
{
"/quest",
"/q",
"Open the quest log.",
"The quest log contains COORDINATES for each quest, which can be extremely helpful!"
},
{
"/trinket",
"/t",
"Open the trinket menu.",
"Trinkets help you in many different ways, and can be changed at any time."
},
{
"/horse",
"/h",
"Ride your horse.",
"Better horses can be bought at stables throughout Zentrela."
},
{
"/class",
"",
"Open the class menu.",
"This will automatically open the spell menu instead if you have a class already."
},
{
"/effects",
"/e",
"Open the effects menu.",
"Effects are prizes from Cosmetic Crates. Type " + ChatColor.YELLOW + "!crates " + ChatColor.GRAY + "in chat for more info!"
},
{
"/rewards",
"",
"Open the rewards menu.",
"The rewards menu contains goodies that can be purchased with Reward Points. Reward Points are earned by voting."
},
{
"/sell",
"/salvage",
"Open the salvage menu.",
"A shortcut for the salvage menu located in /shard.",
},
{
"/roll [x]",
"",
"Roll a number between 1 and x (1 and 100 if you don't specify x).",
"The roll result is only sent to your party.",
},
{
"/clear",
"",
"Clear your inventory.",
"Be careful! This will PERMANENTLY delete all items from your inventory!",
},
{
"/played <name>",
"",
"View statistics on how long a person has played Zentrela.",
"You can just do /played without a <name> if you want your own information."
},
{
"/region",
"",
"Show your current region.",
"Remember, PvP is allowed in Danger Levels 3 and 4, but you only lose items in Danger Level 4!"
},
{
"/msg [name] <...> " + ChatColor.YELLOW + "and " + ChatColor.BOLD + "/r <...>",
"",
"Use the messaging system.",
"/msg <name> <message> will send a message to <name>.",
"/r <messsage> will send a message to the last person you talked to."
},
{
"/lookup <name>",
"",
"View a player's punishment history.",
"This will show all bans and mutes. Kicks are not recorded."
},
{
"/spy [name]",
"/info",
"View extra information about a player.",
"This is the same as clicking on a person's name in chat.",
},
{
"/online",
"",
"View a list of all online players.",
"The list is sorted by rank and name.",
},
{
"/options",
"/o /opt",
"Opens the options menu.",
"Have a suggestion for a new option? Post it on the Zentrela forums at zentrela.net!",
},
{
"/guild",
"/g",
"Open the guild menu.",
"COMING SOON. Guilds will be released in the near future."
},
{
"/bank",
"",
"Open your bank.",
"Your bank can only be accessed in Danger Level 1 zones."
},
{
"/spawn",
"",
"Teleport to the nearest spawn point.",
"You must stand still to warp.",
"May only be used once every 10 minutes."
},
{
"/ignore [name]",
"",
"Ignore a player.",
"You will not see any messages or requests from ignored players. Ignores are reset every time you log on."
},
{
"/ping",
"",
"Get your ping to the server.",
"If you are lagging badly, the /ping command may not work properly."
},
{
"/top",
"/leaderboard",
"View the top players in Zentrela!",
"The 5 best players in 5 categories are displayed."
},
{
"/worldboss",
"",
"Enter the World Boss Arena lobby.",
"You can spend your World Boss Points here."
}
};
protected static ArrayList<MenuItem> generated = new ArrayList<MenuItem>();
protected static ArrayList<MenuItem> fullListGenerated = new ArrayList<MenuItem>();
private static ArrayList<ListedCommand> temp = new ArrayList<ListedCommand>();
static {
for (Object[] o : HelpCommandsSingleton.COMMANDS) {
String name = (String) o[0];
String alias = (String) o[1];
String strippedName = ChatColor.stripColor(name);
name = ChatColor.YELLOW + ChatColor.BOLD.toString() + name + ChatColor.YELLOW + " " + alias;
String desc = (String) o[2];
String[] fullLore = new String[3 + o.length - 3];
fullLore[0] = "";
fullLore[1] = ChatColor.GREEN + desc;
fullLore[2] = "";
for (int k = 3; k < o.length; k++) {
fullLore[k] = ChatColor.GRAY + (String) o[k];
}
ListedCommand lc = new ListedCommand();
lc.name = name;
lc.strippedName = strippedName;
lc.desc = desc;
lc.fullLore = fullLore;
temp.add(lc);
}
int row = 1;
int col = 0;
Collections.sort(temp);
ArrayList<String> fullList = new ArrayList<String>();
for (ListedCommand lc : temp) {
generated.add(lc.generate(row, col));
col++;
if (col >= 9) {
row++;
col = 0;
if (row >= 5) {
System.out.println("ERROR: Ran out of space in /help.");
break;
}
}
fullList.add(ChatColor.YELLOW + lc.strippedName + ChatColor.DARK_GRAY + " - " + ChatColor.GRAY + lc.desc);
}
ArrayList<String> temp = new ArrayList<String>();
col = 0;
int page = 1;
for (int k = 0; k < fullList.size(); k++) {
if (k > 0 && k % 7 == 0) {
MenuItem mi = new MenuItem(0, col, new ItemStack(Material.BOOK_AND_QUILL), ChatColor.DARK_AQUA + "Commands List - Page " + page, temp, null);
fullListGenerated.add(mi);
temp = new ArrayList<String>();
col++;
page++;
}
temp.add(fullList.get(k));
}
// System.out.println("Generated: " + generated);
}
}
|
package com.school.book.controller;
import com.school.book.entity.UserInfo;
import com.school.book.service.UserInfoService;
import java.util.Date;
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.RestController;
@RestController
@RequestMapping("/userinfo")
public class UserInfoController {
@Autowired
UserInfoService userinfoService;
@RequestMapping("/login")
public Object login(@RequestBody UserInfo userinfo){
return userinfoService.login(userinfo);
}
@RequestMapping("/queryAll")
public Object queryAll(@RequestBody UserInfo userinfo) {
return userinfoService.queryAll(userinfo);
}
@RequestMapping("/add")
public Object add(@RequestBody UserInfo userinfo) {
return userinfoService.add(userinfo);
}
@RequestMapping("/operateStatus")
public Object operateStatus(@RequestBody UserInfo userinfo) {
return userinfoService.operateStatus(userinfo);
}
@RequestMapping("/update")
public Object update(@RequestBody UserInfo userinfo) {
return userinfoService.update(userinfo);
}
} |
package seleniumdemo;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class GoogleExample {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = SeleniumUtil.init();
driver.get("https://google.com");
WebElement inputBox = driver.findElement(By.name("q"));
inputBox.sendKeys("What is Bitcoin");
inputBox.sendKeys(Keys.ENTER);
List<WebElement> wikiLinks = driver.findElements(By.partialLinkText("Wikipedia"));
for (WebElement link : wikiLinks) {
System.out.println("here's a link: " + link.getText());
}
wikiLinks.get(0).click();
Thread.sleep(1000);
String wikiUrl = driver.getCurrentUrl();
// go back to Google!
driver.navigate().back();
System.out.println(wikiUrl);
driver.quit();
}
}
|
import java.io.*;
import java.util.Scanner;
class InvalidDirectory extends Exception{
public InvalidDirectory(){
super("InvalidDirectory");
}
public InvalidDirectory(String s){
super(s);
}
}
class HW01_1 {
public static void main(String[] args) {
try {
Scanner in=new Scanner(System.in);
System.out.print("Enter the directory you want to search: ");
String ini=in.nextLine();
File f=new File(ini);
String[] s=f.list();
if (s==null) {
throw new InvalidDirectory("Invalid Directory name,please enter the correct path");
}
String[] files=new String[s.length];
int N=0;
for (int i=0;i<s.length;i++) {
if (s[i].matches(".*.txt$")) {
files[N++]=s[i];
}
}
int sum=0;
for (int i=0; i<N; i++) {
File tmp=new File(files[i]);
System.out.println(tmp.length());
sum+=tmp.length();
}
double finale=sum/N;
System.out.println(finale);
}
catch (InvalidDirectory e) {
System.out.println(e);
}
}
} |
package chemistry;
/**
* a class that checks the chemical syntax of an input string
*
* @author ted
*
*/
public class ChemicalSyntaxChecker {
/**
* enum of the possible characters in a chemical molecule
* used to record what character was in the string
* @author ted
*
*/
public enum ChemicalCharacter{
openParenthesis, closedParenthesis,
upperLetter, lowerLetter, number;
/**
* takes in a character and returns what the character is in terms of chemical character
* @param c the character to convert
* @return the chemical character enum version
*/
public static ChemicalCharacter getCharacterClassification(char c){
String s = ""+c;
if (s.matches(UPPER_LETTER)){
return ChemicalCharacter.upperLetter;
}
if (s.matches(LOWER_LETTER)){
return ChemicalCharacter.lowerLetter;
}
if (s.matches(NUMBER)){
return ChemicalCharacter.number;
}
else {
return getParenthesisClassification(s);
}
}
/**
* a helper method that converts parenthesis character into chemical character
* @param s the string representing the character to convert
* @return the chemical character enum version
*/
private static ChemicalCharacter getParenthesisClassification(String s){
if (s.matches(OPEN_PARENTHESIS)){
return ChemicalCharacter.openParenthesis;
}
if (s.matches(CLOSED_PARENTHESIS)){
return ChemicalCharacter.closedParenthesis;
}
else{
return null;//in case user somehow bypasses the barricade
}
}
}
/**a field storing what chemical character came before*/
private ChemicalCharacter beforeCharacter;
/**a field that counts the number of parenthesis that remain open*/
private int openParenthesisCount;
/**a field that counts the number of letter encountered in an element*/
private int letterCount;
/**
* constants for regex of the different types of chemical characters
*/
public static final String LOWER_LETTER = "[a-z]";
public static final String UPPER_LETTER = "[A-Z]";
public static final String NUMBER = "[0-9]";
public static final String OPEN_PARENTHESIS = "[(]";
public static final String CLOSED_PARENTHESIS = "[)]";
/**
* constant for regex of characters that are not chemically valid
* used to sanitize the input string
*/
public static final String NOT_CHEMICALLY_VALID = "[^a-zA-Z0-9(-)]";
/**
* initializes ChemistrySyntaxChecker
*
* The first character of a molecule should only take in
* 1. Upper case letter
* 2. Number
* 3. Open parenthesis
*
* Lower case letter and closed parenthesis are not allowed
* Closed parenthesis is taken care of due to parenthesis count
* To make sure that lower case letter cannot be first,
* beforeCharacter is initialized as number
* because number does not allow lower case letter after it
*/
public ChemicalSyntaxChecker () {
beforeCharacter = ChemicalCharacter.number;
openParenthesisCount = 0;
letterCount = 0;
}
/**
* checks the syntax of an input string
* first the syntax is sanitized
* then all the characters are checked to see if they follow proper element and parenthesis rules
* @param s the input string
* @throws IllegalElementException thrown if an element exceeds 3 characters
* @throws IllegalParenthesisException thrown if there are unclosed parenthesis or closed parenthesis when there isn't an open parenthesis
*/
public void checkSyntax(String s) throws IllegalElementException, IllegalParenthesisException {
s = sanitize(s);
for (int i = 0; i<s.length(); i++){
processChemicalSyntax(s.charAt(i));
}
/**
* so that the very last character is processed
* the character input is irrelevant since it only gets saved as beforeCharacter but nothing is done to it
*/
processChemicalSyntax('A');
if (openParenthesisCount>0){
throw new IllegalParenthesisException();
}
}
/**
* a helper method that processes the individual character syntax check
* takes in a character and
* determines if the character is legal based on the character before it
*
* The cases in this method update count variables after the next character
* @param c the character to process
* @throws IllegalElementException thrown if this character is the 4th character in an element
* @throws IllegalParenthesisException thrown if this character closes parenthesis when there isn't an open parenthesis
*/
private void processChemicalSyntax(char c) throws IllegalElementException, IllegalParenthesisException{
switch(beforeCharacter){
//anything allowed
//capital letter CH
//lower letter Co
//number H2
//open parenthesis H(O)
//close parenthesis (H)
case upperLetter:
upperLetterCase(c);
break;
//anything allowed
//capital letter HeO
//another letter Hea as long as there aren't more than 2 lower letter
//number He2
//open parenthesis He(O)
//close parenthesis (He)
case lowerLetter:
lowerLetterCase(c);
break;
//capital letter H2O
//number H23
//open parenthesis H2(O)
//close parenthesis (O2)
case number:
numberCase(c);
break;
default:
parenthesisCase(c);
}
}
/**
* the case for upper letter
* resets letter count to 1 since this upper letter is a letter too
* @param c the character for the next iteration
*/
private void upperLetterCase(char c) {
assert(beforeCharacter == ChemicalCharacter.upperLetter);
letterCount=1;
updateBeforeLetter(c);
}
/**
* The case for lower letter
* Increments the letter count by 1
* If the letter count exceeds 3,
* then an illegal element exception is thrown
* @param c the character for the next iteration
* @throws IllegalElementException thrown if the letter count exceeds 3
*/
private void lowerLetterCase(char c) throws IllegalElementException {
assert(beforeCharacter == ChemicalCharacter.lowerLetter);
//post processing of lower letter count
letterCount++;
if (letterCount>3){
throw new IllegalElementException("Element with length greater than 3");
}
updateBeforeLetter(c);
}
/**
* The case for numbers
* @param c the character for the next iteration
* @throws IllegalElementException thrown if next character is illegal
*/
private void numberCase(char c) throws IllegalElementException {
assert(beforeCharacter == ChemicalCharacter.number);
String s = "" + c;
if (s.matches(UPPER_LETTER+"|" + NUMBER+"|"+OPEN_PARENTHESIS+"|"+CLOSED_PARENTHESIS)){
updateBeforeLetter(c);
}
else{
throw new IllegalElementException("Lower case letter after a number");
}
}
/**
* The case for parenthesis
* @param c the character for the next iteration
* @throws IllegalParenthesisException thrown if there is a closed parenthesis without an open parenthesis
* @throws IllegalElementException thrown if next character is illegal
*/
private void parenthesisCase(char c) throws IllegalParenthesisException, IllegalElementException{
switch(beforeCharacter){
//capital letter (H)
//number (3Co)
//open parenthesis ((He))
case openParenthesis:
openParenthesisCase(c);
break;
//capital letter (He)O
//number (He)3
//open parenthesis (He)(Ho)
//closed parenthesis ((He))
case closedParenthesis:
closedParenthesisCase(c);
break;
default:
throw new IllegalElementException("The string was not sanitized somehow");
}
}
/**
* The case for open parenthesis
* increments openParenthesis count by 1
* @param c the character for the next iteration
* @throws IllegalElementException thrown if next character is illegal
*/
private void openParenthesisCase(char c)
throws IllegalElementException {
assert(beforeCharacter == ChemicalCharacter.openParenthesis);
String s = "" + c;
openParenthesisCount++;
if (s.matches(UPPER_LETTER+"|"+NUMBER+"|"+OPEN_PARENTHESIS)){
updateBeforeLetter(c);
}
else{
throw new IllegalElementException("Illegal character after an open parenthesis");
}
}
/**
* The case for closed parenthesis
* @param c the character for the next iteration
* decrements openParenthesis count by 1
* if the count goes below 0,
* an illegal parenthesis exception is thrown
* @throws IllegalParenthesisException thrown if there is a closed parenthesis without an open parenthesis
* @throws IllegalElementException thrown if next character is illegal
*/
private void closedParenthesisCase(char c)
throws IllegalParenthesisException, IllegalElementException {
assert(beforeCharacter == ChemicalCharacter.closedParenthesis);
String s = "" + c;
openParenthesisCount--;
if (openParenthesisCount<0){
throw new IllegalParenthesisException("Tried to close a parenthesis when there was not an open parenthesis");
}
if (s.matches(UPPER_LETTER+"|"+NUMBER+"|"+OPEN_PARENTHESIS+"|"+CLOSED_PARENTHESIS)){
updateBeforeLetter(c);
}
else{
throw new IllegalElementException("Illegal character after a closed parenthesis");
}
}
/**
* updates the before character field with the character for the next iteration
* @param c the character for the next iteration
*/
private void updateBeforeLetter(char c) {
beforeCharacter = ChemicalCharacter.getCharacterClassification(c);
assert(beforeCharacter != null);
}
/**
* sanitizes the user input so that all illegal characters are removed
* @param s the user input
* @return the string that is sanitized
*/
private String sanitize(String s) {
ExceptionUtils.checkIllegalString(s);
String sanitized = s;
sanitized = sanitized.replaceAll(NOT_CHEMICALLY_VALID, "");
return sanitized;
}
} |
package alien4cloud.deployment.matching.services.location;
import java.util.Set;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import alien4cloud.component.CSARRepositorySearchService;
import alien4cloud.model.components.CSARDependency;
import alien4cloud.model.components.IndexedArtifactToscaElement;
import alien4cloud.model.components.IndexedArtifactType;
import alien4cloud.model.components.Interface;
import alien4cloud.model.components.Operation;
import alien4cloud.model.deployment.matching.LocationMatch;
import alien4cloud.model.topology.AbstractTemplate;
import alien4cloud.model.topology.NodeTemplate;
import alien4cloud.model.topology.RelationshipTemplate;
import alien4cloud.orchestrators.plugin.IOrchestratorPluginFactory;
import alien4cloud.orchestrators.services.OrchestratorService;
import alien4cloud.tosca.ToscaUtils;
import com.google.common.collect.Sets;
/**
* LocationMatch Elector based on supported artifacts. Checks if the artifacts of a given {@link NodeTemplate} are supported by the location's orchestrator.
*
*/
@Getter
@Setter
public class LocationMatchNodesArtifactsElector implements ILocationMatchElector {
// TypeMap cache = new TypeMap();
/**
* Template to check artifacts
*/
private NodeTemplate template;
/**
* dependencies in which to look for related {@link IndexedArtifactToscaElement}
*/
private Set<CSARDependency> dependencies = Sets.newHashSet();
private CSARRepositorySearchService csarSearchService;
private OrchestratorService orchestratorService;
@Override
public boolean isEligible(LocationMatch locationMatch) {
boolean isEligible = true;
if (template == null) {
return isEligible;
}
// first check the node interfaces operations artifacts are supported
isEligible = isEligible(template, locationMatch);
if (isEligible) {
// then check relationships interfaces
isEligible = areRelationshipsArtifactSupported(locationMatch, template);
}
return isEligible;
}
private boolean isEligible(AbstractTemplate template, LocationMatch locationMatch) {
if (template == null) {
return true;
}
IOrchestratorPluginFactory orchestratorFactory = orchestratorService.getPluginFactory(locationMatch.getOrchestrator());
// if no supported artifact defined, then return true
if (orchestratorFactory.getArtifactSupport() == null || ArrayUtils.isEmpty(orchestratorFactory.getArtifactSupport().getTypes())) {
return true;
}
String[] supportedArtifacts = orchestratorFactory.getArtifactSupport().getTypes();
IndexedArtifactToscaElement indexedArtifactToscaElement = csarSearchService.getRequiredElementInDependencies(IndexedArtifactToscaElement.class,
template.getType(), dependencies);
if (MapUtils.isNotEmpty(indexedArtifactToscaElement.getInterfaces())) {
for (Interface interfaz : indexedArtifactToscaElement.getInterfaces().values()) {
for (Operation operation : interfaz.getOperations().values()) {
if (operation.getImplementationArtifact() != null) {
String artifactTypeString = operation.getImplementationArtifact().getArtifactType();
IndexedArtifactType artifactType = csarSearchService.getRequiredElementInDependencies(IndexedArtifactType.class, artifactTypeString,
dependencies);
// stop the checking once one artifactType is not supported
if (!isFromOneOfTypes(supportedArtifacts, artifactType)) {
return false;
}
}
}
}
}
return true;
}
private boolean isFromOneOfTypes(String[] supportedArtifacts, IndexedArtifactType artifactType) {
for (String supportedArtifact : supportedArtifacts) {
if (ToscaUtils.isFromType(supportedArtifact, artifactType)) {
return true;
}
}
return false;
}
private boolean areRelationshipsArtifactSupported(LocationMatch locationMatch, NodeTemplate nodeTemplate) {
if (MapUtils.isNotEmpty(nodeTemplate.getRelationships())) {
for (RelationshipTemplate relTemplate : nodeTemplate.getRelationships().values()) {
if (!isEligible(relTemplate, locationMatch)) {
return false;
}
}
}
return true;
}
public LocationMatchNodesArtifactsElector(CSARRepositorySearchService csarSearchService, OrchestratorService orchestratorService) {
this.csarSearchService = csarSearchService;
this.orchestratorService = orchestratorService;
}
}
|
public class ToBinary {
public static void toBinary(long decimal, String result) {
if (decimal == 0) {
System.out.println("\nResult binary -> ");
for (int i = result.length() - 1; i >= 0; i--) {
System.out.print(result.charAt(i));
}
System.out.println(" ");
App.main(null);
} else {
if ((decimal % 2) == 1) {
result += "1";
toBinary(decimal / 2, result);
} else if ((decimal % 2) == 0) {
result += "0";
toBinary(decimal / 2, result);
}
}
}
} |
package com.training.domains;
import java.util.*;
public class University {
private String universityName;
private String city;
private List<Department> depts;
public void getDeptDetails(long deptId){
int i=0;
for(i=0;i<depts.size();i++){
if(depts.get(i).getDeptId()==deptId){
System.out.println(depts.get(i).toString());
break;
}
}
if(i==depts.size()){
System.err.println("No Such Department");
}
}
public String getUniversityName() {
return universityName;
}
public void setUniversityName(String universityName) {
this.universityName = universityName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public List<Department> getDepts() {
return depts;
}
public void setDepts(List<Department> depts) {
this.depts = depts;
}
public University(String universityName, String city, List<Department> depts) {
super();
this.universityName = universityName;
this.city = city;
this.depts = depts;
}
public University() {
super();
depts=new ArrayList<Department>();
// TODO Auto-generated constructor stub
}
}
|
package ch.alika.cukes.shopping.domain;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
class MoneyTest {
private static final Money $0_00 = new Money(0, 0);
private static final Money $8_40 = new Money(8, 40);
private static final Money $1_20 = new Money(1, 20);
private static final Money $1_60 = new Money(1, 60);
private static final Money $2_80 = new Money(2, 80);
private static final Money $1_80 = new Money(1, 80);
private static final Money $3_60 = new Money(3, 60);
@Test
void whereComparedForEquality() {
assertThat(new Money(2,80),is($2_80));
}
@Test
void whereConstructedUsingDefault() {
assertThat(new Money(),is($0_00));
}
@Test
void whereAdded() {
assertThat($0_00.plus($1_20),is($1_20));
assertThat($1_20.plus($1_60),is($2_80));
assertThat($1_80.plus($1_80),is($3_60));
}
@Test
void whereConstructedWithGreaterThan100Cents() {
assertThat(new Money(2,160), is($3_60));
}
@Test
void whereMultipliedByInteger() {
assertThat($1_20.multipliedBy(7),is($8_40));
assertThat($1_20.multipliedBy(3),is($3_60));
}
@Test
void whereParsedFromStrings() {
assertThat(Money.fromString("$3.60"),is($3_60));
assertThat(Money.fromString("1.60"),is($1_60));
}
}
|
import javax.naming.ldap.Control;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* Author: Natalie Dorshimer
* Last Modified: April 8, 2020
*/
/**
* This frame provides the user interface for interacting with the paint program
* It consists of a control panel, a painting panel, and a mouse location label
* The mouse label is for determining position in the painting panel
*/
public class PaintingFrame extends JFrame {
private ControlsPanel controls; //Provides the controls for specifying properties of shapes
private PaintingPanel colorPanel; //The painting panel the user can draw on
private JLabel mouseLocation; //Information labels
public PaintingFrame() {
//Constructing the components
controls = new ControlsPanel(e -> colorPanel.clearPanel(), e -> colorPanel.undo());
colorPanel = new PaintingPanel(controls);
mouseLocation = new JLabel();
//Handles for components
colorPanel.addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
mouseLocation.setText(String.format("(%d,%d)", e.getX(), e.getY()));
}
});
//Building the frame. GridBagLayout is the best option for this.
this.setLayout(new GridBagLayout());
int BOTH = GridBagConstraints.BOTH;
int CENTER = GridBagConstraints.CENTER;
int LEFT = GridBagConstraints.FIRST_LINE_START;
gridBagAdd(controls, 0, 0, 0, 2, BOTH, CENTER);
gridBagAdd(colorPanel, 0, 1, 20, 20, BOTH, CENTER);
gridBagAdd(mouseLocation, 0, 2, 0, 0, 0, LEFT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(700, 400);
}
//For simplifying adding to a GridBagLayout
private void gridBagAdd(Component component, int x, int y, int weightx, int weighty, int fill, int anchor) {
GridBagConstraints c = new GridBagConstraints();
c.gridx = x;
c.gridy = y;
c.weightx = weightx;
c.weighty = weighty;
c.fill = fill;
c.anchor = anchor;
this.add( component, c );
}
} |
package pl.edu.agh.to2.commands;
public class NopCommand implements Command {
@Override
public void execute() {
}
@Override
public void revert() {
}
@Override
public String toString() {
return "\\" + System.lineSeparator();
}
}
|
package com.yj.zzgjj.gjj.view.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.yj.zzgjj.gjj.R;
import com.yj.zzgjj.gjj.util.ResouceUtils;
import com.yj.zzgjj.gjj.widget.loadingandretry.LoadingAndRetryManager;
import com.yj.zzgjj.gjj.widget.loadingandretry.OnLoadingAndRetryListener;
/**
* Activity基类
*/
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSystemBarUI();
int layoutId = getMainContentViewId();
if (0 != layoutId){
setContentView(layoutId);
initView();
Object bindLARtryView = bindLoadingAndRetryView();
if (null != bindLARtryView){
LoadingAndRetryManager mLoadingAndRetryManager = LoadingAndRetryManager
.generate(bindLARtryView, getOnLoadingAndRetryListener());
setLoadingAndRetryManager(mLoadingAndRetryManager);
startLoading();
}
}
}
/**
* 设置状态栏和导航栏为透明的和沉浸式
*/
private void setSystemBarUI(){
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);
int color = ResouceUtils.getRescourceColor(this, R.color.colorPrimary);
if (!tintManager.isStatusBarTintEnabled()) {
// enable status bar tint
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintColor(color);
}
if (!tintManager.isNavBarTintEnabled()) {
// enable navigation bar tint
tintManager.setNavigationBarTintEnabled(true);
tintManager.setNavigationBarTintColor(color);
}
}
/**
* 启动Activity
* @param context 当前Activity上下文
* @param cls 跳转到的Activity
* @param bundle 携带的数据
* @param flags 不同界面的调整标识
*/
public static void startActivity(@NonNull Context context, @NonNull Class<?> cls,
@Nullable Bundle bundle, int flags){
Intent intent = new Intent(context, cls);
if (null != bundle){
intent.putExtra("bundle", bundle);
}
if (0 != flags){
intent.setFlags(flags);
}
context.startActivity(intent);
}
public static void startActivity(@NonNull Context context, @NonNull Class<?> cls){
Intent intent = new Intent(context, cls);
context.startActivity(intent);
}
public static void startActivityForResult(@NonNull Activity activity, @NonNull Class<?> cls,
@Nullable Bundle bundle, int flagsOrRequestCode){
Intent intent = new Intent(activity, cls);
if (bundle != null){
intent.putExtra("bundle", bundle);
}
if (0 != flagsOrRequestCode){
intent.setFlags(flagsOrRequestCode);
}
activity.startActivityForResult(intent, flagsOrRequestCode);
}
protected abstract void initView();
public void initTitleBar(){}
public void initEvent(){}
/**
* 获取xml布局id
* @return xml布局id
*/
@LayoutRes protected abstract int getMainContentViewId();
/**
* 绑定加载和重试界面
* @return 被绑定的视图
*/
@Nullable protected abstract Object bindLoadingAndRetryView();
@Nullable protected abstract OnLoadingAndRetryListener getOnLoadingAndRetryListener();
protected abstract void setLoadingAndRetryManager(LoadingAndRetryManager loadingAndRetryManager);
protected abstract void startLoading();
} |
package com.tdr.registrationv3.http;
import rx.Subscription;
/**
* Created by parry
*/
public interface LifeSubscription {
void bindSubscription(Subscription subscription);
}
|
package com.tessoft.nearhere.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.tessoft.common.Constants;
import com.tessoft.common.UploadTask;
import com.tessoft.common.Util;
import com.tessoft.domain.APIResponse;
import com.tessoft.domain.Post;
import com.tessoft.domain.PostReply;
import com.tessoft.domain.User;
import com.tessoft.nearhere.NearhereApplication;
import com.tessoft.nearhere.R;
import com.tessoft.nearhere.adapters.TaxiPostReplyListAdapter;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
public class TaxiPostDetailActivity extends BaseListActivity
implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener, OnClickListener{
private static final int DELETE_POST = 3;
private static final int POST_DETAIL = 1;
private static final int INSERT_POST_REPLY = 2;
private static final int REQUEST_MODIFY_POST = 0;
private static final int DELETE_POST_REPLY = 4;
private static final int HTTP_UPDATE_POST_AS_FINISHED = 10;
TaxiPostReplyListAdapter adapter = null;
Post post = null;
View header2 = null;
View fbHeader = null;
View headerPost = null;
View headerButtons = null;
GoogleMap map = null;
int ZoomLevel = 13;
ImageView imgProfile = null;
TextView txtUserName = null;
View footer2 = null;
View footerPadding = null;
Button btnFinish = null;
CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
header = getLayoutInflater().inflate(R.layout.taxi_post_detail_list_header_person, null);
if ( !FacebookSdk.isInitialized() )
FacebookSdk.sdkInitialize(getApplicationContext());
fbHeader = getLayoutInflater().inflate(R.layout.taxi_main_list_header_fb, null);
headerPost = getLayoutInflater().inflate(R.layout.taxi_post_detail_list_header_post, null);
headerButtons = getLayoutInflater().inflate(R.layout.taxi_post_detail_list_buttons, null);
// header = getLayoutInflater().inflate(R.layout.taxi_post_detail_list_header1, null);
header2 = getLayoutInflater().inflate(R.layout.taxi_post_detail_list_header2, null);
footer = getLayoutInflater().inflate(R.layout.taxi_post_detail_list_footer, null);
footer2 = getLayoutInflater().inflate(R.layout.taxi_post_detail_list_footer_2, null);
footerPadding = getLayoutInflater().inflate(R.layout.padding_bottom_50, null);
listMain = (ListView) findViewById(R.id.listMain);
listMain.addHeaderView(header, null, false );
listMain.addHeaderView(fbHeader, null, false );
listMain.addHeaderView(headerPost, null, false );
listMain.addHeaderView(headerButtons, null, false );
listMain.addHeaderView(header2);
listMain.setHeaderDividersEnabled(false);
listMain.addFooterView(footer, null, false);
listMain.addFooterView(footerPadding, null, false);
listMain.setFooterDividersEnabled(false);
listMain.setSelector(android.R.color.transparent);
adapter = new TaxiPostReplyListAdapter( getApplicationContext(), application.getLoginUser(),0 );
listMain.setAdapter(adapter);
adapter.setDelegate(this);
initializeComponent();
inquiryPostDetail();
setTitle("합승상세");
setupFacebookLogin();
registerReceiver(mMessageReceiver, new IntentFilter(Constants.BROADCAST_REFRESH));
registerReceiver(mMessageReceiver, new IntentFilter("updateUnreadCount"));
}
catch(Exception ex )
{
catchException(this, ex);
}
}
private void inquiryPostDetail() throws IOException,
JsonGenerationException, JsonMappingException {
HashMap hash = new HashMap();
findViewById(R.id.marker_progress).setVisibility(ViewGroup.VISIBLE);
listMain.setVisibility(ViewGroup.GONE);
if ( getIntent().getExtras() != null )
{
hash.put("postID", getIntent().getExtras().getString("postID") );
if ( getIntent().getExtras().containsKey("fromLatitude") )
hash.put("fromLatitude", getIntent().getExtras().getString("fromLatitude") );
if ( getIntent().getExtras().containsKey("fromLongitude") )
hash.put("fromLongitude", getIntent().getExtras().getString("fromLongitude") );
if ( getIntent().getExtras().containsKey("toLatitude") )
hash.put("toLatitude", getIntent().getExtras().getString("toLatitude") );
if ( getIntent().getExtras().containsKey("toLongitude") )
hash.put("toLongitude", getIntent().getExtras().getString("toLongitude") );
}
hash.put("userID", application.getLoginUser().getUserID() );
sendHttp("/taxi/getPostDetail.do", mapper.writeValueAsString(hash), POST_DETAIL );
}
public void initializeComponent() throws Exception
{
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
makeMapScrollable();
imgProfile = (ImageView) header.findViewById(R.id.imgProfile);
imgProfile.setImageResource(R.drawable.no_image);
imgProfile.setOnClickListener( this );
txtUserName = (TextView) header.findViewById(R.id.txtUserName);
btnFinish = (Button) footer2.findViewById(R.id.btnFinish);
btnFinish.setOnClickListener(this);
if ( "true".equals( application.getMetaInfoString("hideMapOnPostDetail") ) ||
"".equals( application.getMetaInfoString("hideMapOnPostDetail") ))
{
findViewById(R.id.map_layout).setVisibility(ViewGroup.GONE);
Button btnHideMap = (Button)findViewById(R.id.btnHideMap);
btnHideMap.setText("경로 보기");
}
else
{
findViewById(R.id.map_layout).setVisibility(ViewGroup.VISIBLE);
Button btnHideMap = (Button)findViewById(R.id.btnHideMap);
btnHideMap.setText("경로 숨기기");
}
Button btnRefresh = (Button) findViewById(R.id.btnRefresh);
btnRefresh.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
inquiryPostDetail();
} catch (Exception ex) {
// TODO Auto-generated catch block
catchException(this, ex);
}
}
});
options = new DisplayImageOptions.Builder()
.resetViewBeforeLoading(true)
.cacheInMemory(true)
.showImageOnLoading(R.drawable.no_image)
.showImageForEmptyUri(R.drawable.no_image)
.showImageOnFail(R.drawable.no_image)
.displayer(new RoundedBitmapDisplayer(20))
.delayBeforeLoading(100)
.build();
findViewById(R.id.btnViewProfile).setOnClickListener(this);
findViewById(R.id.btnFbLogin).setOnClickListener(this);
}
DisplayImageOptions options = null;
private void makeMapScrollable() {
ImageView transparentImageView = (ImageView) header2.findViewById(R.id.transparent_image);
transparentImageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
try
{
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
listMain.requestDisallowInterceptTouchEvent(true);
// Disable touch on transparent view
return false;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
listMain.requestDisallowInterceptTouchEvent(false);
return true;
case MotionEvent.ACTION_MOVE:
listMain.requestDisallowInterceptTouchEvent(true);
return false;
default:
return true;
}
}
catch( Exception ex )
{
Log.e("error", ex.getMessage());
}
return true;
}
});
}
private Menu menu = null;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.taxi_post_detail, menu);
this.menu = menu;
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
try
{
if (id == R.id.action_refresh) {
inquiryPostDetail();
return true;
}
}
catch( Exception ex )
{
catchException(this, ex);
}
return super.onOptionsItemSelected(item);
}
@Override
public void yesClicked(Object param) {
// TODO Auto-generated method stub
super.yesClicked(param);
try
{
if ( param instanceof String && "postDelete".equals( param ) )
{
sendHttp("/taxi/deletePost.do", mapper.writeValueAsString(post), DELETE_POST );
}
else if ( param instanceof PostReply )
{
sendHttp("/taxi/deletePostReply.do", mapper.writeValueAsString(param), DELETE_POST_REPLY );
}
else if ( param instanceof String && "DIALOG_FINISH_POST".equals(param) )
{
post.setStatus("종료됨");
sendHttp("/taxi/modifyPost.do", mapper.writeValueAsString(post), HTTP_UPDATE_POST_AS_FINISHED );
Intent data = new Intent();
data.putExtra("reload", true);
setResult(RESULT_OK, data);
}
}
catch( Exception ex )
{
catchException(this, ex);
}
}
public void goUserProfileActivity( String userID )
{
/*
Intent intent = new Intent( this, UserProfileActivity.class);
intent.putExtra("userID", userID );
startActivity(intent);
overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.stay);
*/
String url = Constants.getServerSSLURL() + "/user/userInfo.do?userID=" + userID + "&isApp=Y";
Intent intent = new Intent(this, PopupWebViewActivity.class);
intent.putExtra("url", url);
intent.putExtra("title", "사용자 정보" );
startActivity(intent);
}
public void goUserChatActivity()
{
Intent intent = new Intent( this, UserMessageActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.stay);
}
Marker departureMarker = null;
Marker destinationMarker = null;
@Override
public void onMapReady(GoogleMap m ) {
// TODO Auto-generated method stub
try
{
this.map = m;
//강남역
moveMap(new LatLng(37.497916, 127.027546));
}
catch( Exception ex )
{
catchException(this, ex);
}
}
private void drawPostOnMap() {
double fromLatitude = Double.parseDouble(post.getFromLatitude());
double fromLongitude = Double.parseDouble(post.getFromLongitude());
LatLng Fromlocation = new LatLng( fromLatitude, fromLongitude );
double latitude = Double.parseDouble(post.getLatitude());
double longitude = Double.parseDouble(post.getLongitude());
LatLng location = new LatLng( latitude, longitude );
departureMarker = map.addMarker(new MarkerOptions()
.position( Fromlocation )
.title("출발지"));
destinationMarker = map.addMarker(new MarkerOptions()
.position( location )
.title("도착지"));
PolylineOptions rectOptions = new PolylineOptions()
.add( Fromlocation )
.add( location );
Polyline polyline = map.addPolyline(rectOptions);
moveMap( location );
destinationMarker.showInfoWindow();
}
@Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right);
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
private void moveMap( LatLng location )
{
CameraUpdate center=
CameraUpdateFactory.newLatLng( location );
map.moveCamera(center);
CameraUpdate zoom=CameraUpdateFactory.zoomTo(ZoomLevel);
map.animateCamera(zoom);
}
public void addPostReply( View v )
{
try
{
EditText edtPostReply = (EditText) footer.findViewById(R.id.edtPostReply);
if ( "Guest".equals( application.getLoginUser().getType()))
{
showOKDialog("확인", "SNS 계정연동 후에 등록하실 수 있습니다.\r\n\r\n메인 화면에서 SNS연동을 할 수 있습니다.", "kakaoLoginCheck" );
return;
}
if ( TextUtils.isEmpty(edtPostReply.getText()) )
{
edtPostReply.setError("댓글을 입력해 주시기 바랍니다.");
return;
}
PostReply postReply = new PostReply();
postReply.setPostID( post.getPostID() );
postReply.setUser( application.getLoginUser() );
postReply.setLatitude( NearhereApplication.latitude );
postReply.setLongitude( NearhereApplication.longitude );
postReply.setMessage( edtPostReply.getText().toString() );
edtPostReply.setText("");
sendHttp("/taxi/insertPostReply.do", mapper.writeValueAsString(postReply), INSERT_POST_REPLY );
findViewById(R.id.marker_progress).setVisibility(ViewGroup.VISIBLE);
listMain.setVisibility(ViewGroup.GONE);
}
catch( Exception ex )
{
catchException(this, ex);
}
}
@Override
public void doPostTransaction(int requestCode, Object result) {
// TODO Auto-generated method stub
try
{
findViewById(R.id.marker_progress).setVisibility(ViewGroup.GONE);
if ( Constants.FAIL.equals(result) )
{
showOKDialog("통신중 오류가 발생했습니다.\r\n다시 시도해 주십시오.", null);
return;
}
super.doPostTransaction(requestCode, result);
APIResponse response = mapper.readValue(result.toString(), new TypeReference<APIResponse>(){});
if ( "0000".equals( response.getResCode() ) )
{
listMain.setVisibility(ViewGroup.VISIBLE);
if ( requestCode == POST_DETAIL )
{
String postData = mapper.writeValueAsString( response.getData() );
post = mapper.readValue( postData, new TypeReference<Post>(){});
drawPostOnMap();
setUserData();
setPostData();
adapter.setItemList( post.getPostReplies() );
if ( !Util.isEmptyString(application.getLoginUser().getFacebookID()) ||
!post.getUser().getUserID().equals( application.getLoginUser().getUserID() ))
{
listMain.removeHeaderView(fbHeader);
LinearLayout layoutFacebookLogin = (LinearLayout) findViewById(R.id.layoutFacebookLogin);
if ( layoutFacebookLogin != null )
layoutFacebookLogin.setVisibility(ViewGroup.GONE);
}
else
{
LinearLayout layoutFacebookLogin = (LinearLayout) findViewById(R.id.layoutFacebookLogin);
if ( layoutFacebookLogin != null )
layoutFacebookLogin.setVisibility(ViewGroup.VISIBLE);
}
boolean bAddedFooterButon = false;
if ( post.getUser().getUserID().equals( application.getLoginUser().getUserID() ) )
{
if ( listMain.getFooterViewsCount() == 3 )
listMain.removeFooterView(footer2);
listMain.addFooterView(footer2, null, false );
bAddedFooterButon = true;
findViewById(R.id.btnSendMessage).setVisibility(ViewGroup.GONE);
}
else
{
listMain.removeFooterView(footer2);
findViewById(R.id.btnSendMessage).setVisibility(ViewGroup.VISIBLE);
}
if ( bAddedFooterButon == false && Constants.bAdminMode )
{
if ( listMain.getFooterViewsCount() == 3 )
listMain.removeFooterView(footer2);
listMain.addFooterView(footer2, null, false );
}
}
else if ( requestCode == INSERT_POST_REPLY )
{
inquiryPostDetail();
}
else if ( requestCode == DELETE_POST )
{
Intent data = new Intent();
data.putExtra("reload", true);
setResult(RESULT_OK, data);
finish();
}
else if ( requestCode == DELETE_POST_REPLY || requestCode == HTTP_UPDATE_POST_AS_FINISHED )
{
inquiryPostDetail();
Intent intent = new Intent( Constants.BROADCAST_TAXI_REFRESH );
getApplicationContext().sendBroadcast(intent);
finish();
}
else if ( requestCode == Constants.HTTP_PROFILE_IMAGE_UPLOAD )
{
String userString = mapper.writeValueAsString( response.getData2() );
User user = mapper.readValue(userString, new TypeReference<User>(){});
application.setLoginUser(user);
user.setFacebookID(id);
user.setUserName(name);
if ("male".equals( gender.toLowerCase() ) || "남성".equals( gender ))
user.setSex("M");
else
user.setSex("F");
user.setFacebookURL(facebookURL);
user.setFacebookProfileImageURL(facebookProfileImageURL);
listMain.setVisibility(ViewGroup.GONE);
findViewById(R.id.marker_progress).setVisibility(ViewGroup.VISIBLE);
sendHttp("/taxi/updateFacebookInfo.do", mapper.writeValueAsString(user), Constants.HTTP_UPDATE_FACEBOOK_INFO );
}
else if ( requestCode == Constants.HTTP_UPDATE_FACEBOOK_INFO )
{
String addInfoString = mapper.writeValueAsString( response.getData() );
HashMap addInfo = mapper.readValue( addInfoString, new TypeReference<HashMap>(){});
String userString = mapper.writeValueAsString( addInfo.get("user") );
User user = mapper.readValue(userString, new TypeReference<User>(){});
application.setLoginUser(user);
findViewById(R.id.marker_progress).setVisibility(ViewGroup.GONE);
listMain.setVisibility(ViewGroup.VISIBLE);
inquiryPostDetail();
Intent resultIntent = new Intent();
resultIntent.putExtra("reload", true);
setResult(RESULT_OK, resultIntent);
}
}
else
{
listMain.setVisibility(ViewGroup.GONE);
showOKDialog("경고", response.getResMsg(), "error" );
return;
}
}
catch( Exception ex )
{
// catchException(this, ex);
}
}
private void setPostData() throws Exception {
String title = post.getMessage();
if ( title != null ) title = title.trim();
TextView txtTitle = (TextView) headerPost.findViewById(R.id.txtTitle);
txtTitle.setText( title );
TextView txtStatus = (TextView) headerPost.findViewById(R.id.txtStatus);
if ( "진행중".equals( post.getStatus() ) )
{
txtStatus.setText( post.getStatus() );
txtStatus.setBackgroundColor(Color.parseColor("#fe6f2b"));
if ( post.getUser().getUserID().equals( application.getLoginUser().getUserID() ))
btnFinish.setVisibility(ViewGroup.VISIBLE);
}
else
{
txtStatus.setBackgroundColor(Color.parseColor("#6f6f6f"));
txtStatus.setText( post.getStatus() );
btnFinish.setVisibility(ViewGroup.GONE);
}
TextView txtDeparture = (TextView) headerPost.findViewById(R.id.txtDeparture);
txtDeparture.setText( post.getFromAddress() );
TextView txtDestination = (TextView) headerPost.findViewById(R.id.txtDestination);
txtDestination.setText( post.getToAddress() );
if ( post.getDepartureDate() != null )
{
TextView txtDepartureDateTime = (TextView) headerPost.findViewById(R.id.txtDepartureDateTime);
String departureDateTime = "";
if ( post.getDepartureDate().indexOf("오늘") >= 0 )
{
if ( post.getDepartureTime().indexOf("지금") >= 0 )
departureDateTime = Util.getFormattedDateString(post.getCreatedDate(), "MM-dd HH:mm") + " 출발";
else
departureDateTime = Util.getFormattedDateString(post.getCreatedDate(), "MM-dd") + " " + post.getDepartureTime() + " 출발";
}
else
{
if ( post.getDepartureTime().indexOf("지금") >= 0 )
departureDateTime = Util.getFormattedDateString(post.getDepartureDate() , "MM-dd") + " " + Util.getFormattedDateString(post.getCreatedDate(), "HH:mm") + " 출발";
else
departureDateTime = Util.getFormattedDateString(post.getDepartureDate() + " " + post.getDepartureTime() + ":00", "MM-dd HH:mm") + " 출발";
}
txtDepartureDateTime.setText( departureDateTime );
}
TextView txtCreatedDate = (TextView) headerPost.findViewById(R.id.txtCreatedDate);
txtCreatedDate.setText( Util.getFormattedDateString(post.getCreatedDate(), "MM-dd HH:mm") + " 등록");
setControlsVisibility( post );
}
private void setUserData() {
if ( !Util.isEmptyString(post.getUser().getProfileImageURL()))
{
ImageLoader.getInstance().displayImage( Constants.getThumbnailImageURL() +
post.getUser().getProfileImageURL() , imgProfile, options );
}
txtUserName.setText( post.getUser().getUserName() );
ImageView imgSex = (ImageView) header.findViewById(R.id.imgSex);
imgSex.setVisibility(ViewGroup.VISIBLE);
if ( "M".equals( post.getUser().getSex() ))
{
imgSex.setImageResource(R.drawable.ic_male);
}
else if ( "F".equals( post.getUser().getSex() ))
{
imgSex.setImageResource(R.drawable.ic_female);
}
else
imgSex.setVisibility(ViewGroup.GONE);
if ( !Util.isEmptyString( post.getUser().getKakaoID() ) )
findViewById(R.id.imgKakaoIcon).setVisibility(ViewGroup.VISIBLE);
else
findViewById(R.id.imgKakaoIcon).setVisibility(ViewGroup.GONE);
if ( !Util.isEmptyString( post.getUser().getFacebookURL() ) )
{
findViewById(R.id.imgFacebookIcon).setVisibility(ViewGroup.VISIBLE);
findViewById(R.id.btnGoFacebook).setVisibility(ViewGroup.VISIBLE);
}
else
{
findViewById(R.id.imgFacebookIcon).setVisibility(ViewGroup.GONE);
findViewById(R.id.btnGoFacebook).setVisibility(ViewGroup.GONE);
}
TextView txtCreditValue = (TextView) header.findViewById(R.id.txtCreditValue);
txtCreditValue.setText( post.getUser().getProfilePoint() + "%" );
ProgressBar progressCreditValue = (ProgressBar) header.findViewById(R.id.progressCreditValue);
progressCreditValue.setProgress( Integer.parseInt( post.getUser().getProfilePoint() ));
}
private void setControlsVisibility( Post item ) {
if ( !Util.isEmptyString( item.getVehicle() ) )
{
TextView txtVehicle = (TextView) findViewById(R.id.txtVehicle);
txtVehicle.setVisibility(ViewGroup.VISIBLE);
txtVehicle.setText( item.getVehicle() );
}
else
findViewById(R.id.txtVehicle).setVisibility(ViewGroup.GONE);
if ( !Util.isEmptyString( item.getFareOption() ) )
{
TextView txtFareOption = (TextView) findViewById(R.id.txtFareOption);
txtFareOption.setVisibility(ViewGroup.VISIBLE);
txtFareOption.setText( item.getFareOption() );
}
else
findViewById(R.id.txtFareOption).setVisibility(ViewGroup.GONE);
if ( "Y".equals( item.getRepetitiveYN() ) )
{
TextView txtRepeat = (TextView) findViewById(R.id.txtRepeat);
txtRepeat.setVisibility(ViewGroup.VISIBLE);
}
else
findViewById(R.id.txtRepeat).setVisibility(ViewGroup.GONE);
if ( !"상관없음".equals( item.getSexInfo() ) && !Util.isEmptyString( item.getSexInfo() ) )
{
TextView txtSex = (TextView) findViewById(R.id.txtSex);
txtSex.setVisibility(ViewGroup.VISIBLE);
txtSex.setText( item.getSexInfo() );
}
else
findViewById(R.id.txtSex).setVisibility(ViewGroup.GONE);
if ( !"상관없음".equals( item.getNumOfUsers() ) && !Util.isEmptyString( item.getNumOfUsers() ) )
{
TextView txtNOP = (TextView) findViewById(R.id.txtNOP);
txtNOP.setVisibility(ViewGroup.VISIBLE);
txtNOP.setText( item.getNumOfUsers() );
}
else
findViewById(R.id.txtNOP).setVisibility(ViewGroup.GONE);
TextView readCount = (TextView) findViewById(R.id.txtReadCount);
if ( item.getReadCount() > 0 )
{
readCount.setVisibility(ViewGroup.VISIBLE);
readCount.setText( "조회 : " + item.getReadCount() );
}
else
readCount.setVisibility(ViewGroup.GONE);
}
@Override
public void okClicked(Object param) {
// TODO Auto-generated method stub
super.okClicked(param);
if ( "error".equals( param ) )
onBackPressed();
}
public void modifyPost( View v )
{
/*
Intent intent = new Intent( this, NewTaxiPostActivity.class);
intent.putExtra("mode", "modify");
intent.putExtra("post", post);
startActivityForResult(intent, REQUEST_MODIFY_POST );
overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.stay);
*/
Intent intent = new Intent( this, NewTaxiPostActivity2.class);
intent.putExtra("mode", "modify");
intent.putExtra("post", post);
startActivity(intent);
}
@Override
protected void onActivityResult(int requestCode, int responseCode, Intent data ) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, responseCode, data);
try
{
callbackManager.onActivityResult(requestCode, responseCode, data);
if ( responseCode == RESULT_OK )
{
inquiryPostDetail();
Intent intent = new Intent( Constants.BROADCAST_TAXI_REFRESH );
getApplicationContext().sendBroadcast(intent);
}
}
catch( Exception ex )
{
catchException(this, ex);
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
int id = v.getId();
if ( id == R.id.txtUserName || id == R.id.imgProfile || id == R.id.btnViewProfile )
{
goUserProfileActivity( post.getUser().getUserID() );
}
else if ( id == R.id.btnFinish )
{
showYesNoDialog("확인", "정말 종료하시겠습니까?", "DIALOG_FINISH_POST");
return;
}
else if ( id == R.id.btnFbLogin )
{
findViewById(R.id.marker_progress).setVisibility(ViewGroup.VISIBLE);
listMain.setVisibility(ViewGroup.GONE);
}
}
catch( Exception ex )
{
catchException(this, ex);
}
}
@Override
public void doAction(String actionName, Object param) {
// TODO Auto-generated method stub
try
{
super.doAction(actionName, param);
if ( "userProfile".equals( actionName ) )
goUserProfileActivity( param.toString() );
else if ( "deleteReply".equals( actionName ) )
{
showYesNoDialog("확인", "정말 삭제하시겠습니까?", param );
return;
}
}
catch( Exception ex )
{
catchException(this, ex);
}
}
//This is the handler that will manager to process the broadcast intent
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try
{
if ( Constants.BROADCAST_REFRESH.equals( intent.getAction() ) )
{
inquiryPostDetail();
}
else if ( intent.getExtras() != null && intent.getExtras().containsKey("type"))
{
String type = intent.getExtras().getString("type");
if ( "postReply".equals( type ) && intent.getExtras().containsKey("postID"))
{
String postID = intent.getExtras().getString("postID");
if ( post.getPostID().equals( postID ) )
inquiryPostDetail();
}
}
}
catch( Exception ex )
{
catchException(this, ex);
}
}
};
@Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
try
{
}
catch( Exception ex )
{
catchException(this, ex);
}
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mMessageReceiver);
}
@Override
public void onBackPressed() {
finish();
if ( MainActivity.active == false )
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
public void toggleMapVisibility( View v )
{
Button btn = (Button) v;
if ( findViewById(R.id.map_layout).getVisibility() == ViewGroup.GONE )
{
findViewById(R.id.map_layout).setVisibility(ViewGroup.VISIBLE);
btn.setText("경로 숨기기");
application.setMetaInfo("hideMapOnPostDetail", "false");
}
else
{
findViewById(R.id.map_layout).setVisibility(ViewGroup.GONE);
btn.setText("경로 보기");
application.setMetaInfo("hideMapOnPostDetail", "true");
}
}
public void goFacebook( View v )
{
try
{
String facebookURL = post.getUser().getFacebookURL();
if ( Util.isEmptyString( facebookURL ) ) return;
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( facebookURL ));
startActivity(browserIntent);
}
catch( Exception ex )
{
}
}
@SuppressWarnings({ "rawtypes", "unchecked"})
public void goUserMessageActivity( View v ) {
if ( "Guest".equals( application.getLoginUser().getType()))
{
showOKDialog("확인", "SNS 계정연동 후에 등록하실 수 있습니다.\r\n\r\n메인 화면에서 SNS연동을 할 수 있습니다.", "kakaoLoginCheck" );
return;
}
HashMap hash = new HashMap();
hash.put("fromUserID", post.getUser().getUserID() );
hash.put("userID", application.getLoginUser().getUserID() );
Intent intent = new Intent( this, UserMessageActivity.class);
intent.putExtra("messageInfo", hash );
startActivity(intent);
overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
}
private void setupFacebookLogin() {
LoginButton loginButton = (LoginButton) findViewById(R.id.btnFbLogin);
loginButton.setOnClickListener(this);
loginButton.setReadPermissions("user_friends");
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// App code
try
{
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
listMain.setVisibility(ViewGroup.GONE);
findViewById(R.id.marker_progress).setVisibility(ViewGroup.VISIBLE);
registerUserProceed( object );
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,gender, first_name, last_name, picture.width(9999) ");
parameters.putString("locale","ko_KR");
request.setParameters(parameters);
request.executeAsync();
}
catch( Exception ex )
{
}
}
@Override
public void onCancel() {
// App code
findViewById(R.id.marker_progress).setVisibility(ViewGroup.GONE);
listMain.setVisibility(ViewGroup.VISIBLE);
}
@Override
public void onError(FacebookException exception) {
// App code
findViewById(R.id.marker_progress).setVisibility(ViewGroup.GONE);
listMain.setVisibility(ViewGroup.VISIBLE);
}
});
}
String id = "";
String name = "";
String gender = "";
String facebookURL = "";
String facebookProfileImageURL = "";
private void registerUserProceed( JSONObject object )
{
try
{
if ( object == null )
{
showOKDialog("오류", "로그인 데이터가 올바르지 않습니다.\r\n다시 시도해 주십시오.", null );
return;
}
id = object.getString("id");
name = object.getString("name");
gender = object.getString("gender");
facebookURL = object.getString("link");
facebookProfileImageURL = "";
if ( object.has("picture") && object.getJSONObject("picture") != null )
{
JSONObject pictureObj = object.getJSONObject("picture");
if ( pictureObj.has("data") )
facebookProfileImageURL = pictureObj.getJSONObject("data").getString("url");
}
if ( !Util.isEmptyString( facebookProfileImageURL ) )
{
ImageLoader imageLoader = ImageLoader.getInstance();
ImageSize targetSize = new ImageSize(640, 640);
imageLoader.loadImage( facebookProfileImageURL, targetSize, new SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null )
{
Log.d("imageResult", "image loaded. " + loadedImage.getWidth() + " " + loadedImage.getHeight() );
new UploadTask( getApplicationContext(), application.getLoginUser().getUserID() ,
Constants.HTTP_PROFILE_IMAGE_UPLOAD, TaxiPostDetailActivity.this ).execute( loadedImage );
}
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
// TODO Auto-generated method stub
super.onLoadingFailed(imageUri, view, failReason);
Log.d("debug", "onLoadingFailed:" + failReason );
}
});
}
}
catch( Exception ex )
{
application.debug(ex.getMessage());
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package decription;
/**
*
* @author eliot
*/
import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
public class DHKeyAgreement2 {
KeyPair alphaPair= null;
KeyAgreement alphaKeyAgreement = null;
KeyAgreement bravoKeyAgreement= null;
byte[] alphaPublicKeyEncoded=null;
byte[] bravoPublicKeyEncoded = null;
KeyFactory bravoKeyFactory =null;
X509EncodedKeySpec x509KS= null;
PublicKey alphaPub= null;
KeyPairGenerator bravoKeyPairGen= null;
KeyFactory alphaKeyFactory = null;
PublicKey bravoPub= null;
public void alphaKeyGenerator() throws InvalidKeyException, NoSuchAlgorithmException {
System.out.println("Alpha: Generate DH keys ...");
KeyPairGenerator alphaKeyPairGen= KeyPairGenerator.getInstance("DH");
alphaKeyPairGen.initialize(2048);
alphaPair = alphaKeyPairGen.generateKeyPair();
System.out.println("Alpha: Initilization");
alphaKeyAgreement = KeyAgreement.getInstance("DH");
alphaKeyAgreement.init(alphaPair.getPrivate());
alphaPublicKeyEncoded = alphaPair.getPublic().getEncoded();
} // close alpha method
public void BravoKeyGenerator(DHParameterSpec dhParamFromAlphaKey) throws NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
System.out.println("Bravo: Generate Dh keys");
bravoKeyPairGen= KeyPairGenerator.getInstance("DH");
bravoKeyPairGen.initialize(dhParamFromAlphaKey);
KeyPair bravoPair = bravoKeyPairGen.generateKeyPair();
System.out.println("Bravo: Initilization");
bravoKeyAgreement= KeyAgreement.getInstance("DH");
bravoKeyAgreement.init(bravoPair.getPrivate());
bravoPublicKeyEncoded = bravoPair.getPublic().getEncoded();
}// close bravo method
public void guide() throws Exception {
try {
//alpha creates key pair with 2048-bit size
alphaKeyGenerator();
//now bravo uses this key info to create a message
bravoKeyFactory = KeyFactory.getInstance("DH");
x509KS = new X509EncodedKeySpec(alphaPublicKeyEncoded);
alphaPub = bravoKeyFactory.generatePublic(x509KS);
//embodies the exchange of the keys across some network
//assuming both computers are speaking Java
DHParameterSpec dhParamFromAlphaKey = ((DHPublicKey)alphaPub).getParams();
BravoKeyGenerator(dhParamFromAlphaKey);
//now Alpha uses Bravo's public key
alphaKeyFactory = KeyFactory.getInstance("DH");
x509KS = new X509EncodedKeySpec(bravoPublicKeyEncoded);
bravoPub = alphaKeyFactory.generatePublic(x509KS);
System.out.println("Alpha: Executing Phase 1 of DH protocol");
alphaKeyAgreement.doPhase(bravoPub, true);
//now Bravo uses Alpha's public key
System.out.println("Bravo: Executing Phase 1 of DH protocol");
bravoKeyAgreement.doPhase(alphaPub, true);
//now generate the same secret
} catch (NoSuchAlgorithmException ex) {
System.out.println("No such algo");
System.out.println(ex);
} catch (InvalidKeyException ex) {
System.out.println("Invalid Key");
System.out.println(ex);
} catch (InvalidKeySpecException ex) {
System.out.println("InvalidKeySpecException");
System.out.println(ex);
} catch (InvalidAlgorithmParameterException ex) {
System.out.println("Invalid Algo");
System.out.println(ex);
}// close catch
byte[] alphSharedSecret = null;
byte[] bravoSharedSecret = null;
int alphaLen;
int bravoLen;
if(alphaKeyAgreement != null){
try {
alphSharedSecret = alphaKeyAgreement.generateSecret();
alphaLen = alphSharedSecret.length;
bravoSharedSecret = new byte[alphaLen];
if(bravoKeyAgreement != null){
bravoLen = bravoKeyAgreement.generateSecret(bravoSharedSecret, 0);
}
System.out.println("Alpha secret: " + toHexString(alphSharedSecret));
System.out.println("Bravo secret: " + toHexString(bravoSharedSecret));
if(!java.util.Arrays.equals(bravoSharedSecret, alphSharedSecret)){
throw new Exception("Shared secrets differ!");
} else {
System.out.println("Shared secrets are the same");
}
} catch (IllegalStateException | ShortBufferException ex) {
System.out.println(ex);
} catch (Exception ex) {
System.out.println(ex);
}
} // end null check
System.out.println("Use shared secret as SecretKey object");
SecretKeySpec deloAESKey = new SecretKeySpec(alphSharedSecret, 0, 16, "AES");
SecretKeySpec bravoAESKey = new SecretKeySpec(bravoSharedSecret, 0, 16, "AES");
System.out.println("Secret (symmetric) Key: " + toHexString(deloAESKey.getEncoded()));
Cipher alphaCipher;
Cipher bravoCipher;
byte[] clearText;
byte[] cipherText;
byte[] encodedParams;
byte[] recoveredText;
AlgorithmParameters aesParams;
try {
// USE AES in CBC mode
bravoCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
bravoCipher.init(Cipher.ENCRYPT_MODE, bravoAESKey);
clearText = "I'm Vengence, I'm the Knight, I'm Batman".getBytes();
cipherText = bravoCipher.doFinal(clearText);
encodedParams = bravoCipher.getParameters().getEncoded();
// alpha decrypts
aesParams = AlgorithmParameters.getInstance("AES");
aesParams.init(encodedParams);
alphaCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
alphaCipher.init(Cipher.DECRYPT_MODE, deloAESKey, aesParams);
recoveredText = alphaCipher.doFinal(cipherText);
if(!java.util.Arrays.equals(clearText, recoveredText)){
throw new Exception("AES in CBC mode recovered text is diff from clear!");
} else {
System.out.print("Matching recovered text: ");
System.out.println(new String(recoveredText, "UTF-8"));
}
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException ex) {
System.out.println(ex);
} catch (IllegalBlockSizeException ex) {
System.out.println("Illegal blocksize ex");
System.out.println(ex);
} catch (BadPaddingException ex) {
System.out.println("Bad Padding");
System.out.println(ex);
} catch (IOException ex) {
System.out.println("IO Ex");
System.out.println(ex);
} catch (InvalidAlgorithmParameterException ex) {
System.out.println("Invalid algo");
System.out.println(ex);
} catch (Exception ex) {
System.out.println("Decrypt Doesn't work");
System.out.println(ex);
}// close main method
}
/*
Convertys a bute to hex digit and wires to the supplied buffer
*/
private static void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F' };
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
/*
Converts bute array to hex String
*/
private static String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();
int len = block.length;
for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
if (i < len-1) {
buf.append(":");
}//close if
}// close for
return buf.toString();
}//close method
}// close class |
package test.pageObject.scenario;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import test.components.JSExecutorService;
import test.pageObject.AnswerContainerPageObject;
import test.pageObject.SearchContainerPageObject;
import java.util.List;
/**
* Created by Inna on 04.07.2016.
* Common methods for search answer.
*/
@Component
public class SearchAnswerScenario {
@Autowired
private SearchContainerPageObject searchContainer;
@Autowired
private AnswerContainerPageObject answerContainer;
@Autowired
private WebDriver driver;
@Autowired
private JSExecutorService jse;
/**
* Input the question and choose suggestion by index
* @param question - question for search
* @param suggestionIndex - suggestion index
*/
public void findBySuggestionIndex(String question, int suggestionIndex) {
// Switch to search frame
searchContainer.switchToMainPageFrame();
// input the question
searchContainer.getTxtSearch().sendKeys(question);
// Get suggestion list
List<WebElement> list = searchContainer.getSuggestionList();
// Choose suggestion by index
list.get(suggestionIndex).click();
// Switch to answer frame
searchContainer.switchToMainPageFrame();
}
/**
* Input the question and choose suggestion by text
* @param question - question for search
* @param suggestionText - suggestion text
*/
public void findBySuggestionText(String question, String suggestionText) {
// Switch to search frame
searchContainer.switchToMainPageFrame();
// input the question
searchContainer.getTxtSearch().sendKeys(question);
// Get suggestion list
List<WebElement> list = searchContainer.getSuggestionList();
// Choose suggestion by text
for(WebElement e : list) {
if((suggestionText).equals(e.getText())) {
e.click();
break;
}
}
// Switch to answer frame
searchContainer.switchToMainPageFrame();
}
/**
* Scroll down to like/dislike field location
* @param likeId - like/dislike field index
*/
public void scrollToLikesLocation(int likeId) {
// Get likes list
List<WebElement> likes = answerContainer.getLikesList();
likes.get(likeId);
// Scroll down the page
scrollToElementLocation(likes.get(likeId));
}
/**
* Scroll down the page
* @param e - element for determining the position of the scroll
*/
public void scrollToElementLocation(WebElement e) {
// Get Y coordinate
int y = e.getLocation().getY();
// Switch to the top of the hierarchy (to the browser page model)
driver.switchTo().defaultContent();
// Use JavaScript for scrolling page
jse.getJs().executeScript("scroll(0," + y +");");
answerContainer.switchToMainPageFrame();
}
}
|
import java.util.Vector;
public class RunnerVertex
{
public static void main(String[] args)
{
/*Vector<Vertex> vec = new Vector<Vertex>();
String[] strArray = new String[]{"LA", "NYC", "BASKING RIDGE", "MORRISTOWN"};
for(String s : strArray)
{
Vertex<String> v = new Vertex<String>(s);
vec.add(v);
}
//System.out.println(vec);
for(Vertex<String> v : vec)
{
for(Vertex<String> vOther : vec)
{
if(v.getItem().equals(vOther.getItem() == false)
{
v.addConnection(vOther, (double)Math.
}
}
}*/
TravellingSalesmanGraph g = new TravellingSalesmanGraph(5);
System.out.println(g.travel(0));
}
} |
import java.util.ArrayList;
import java.util.List;
public class ObserverExample_03 {
public static void main(String[] args) {
JavaDeveloperJobSite jobSite = new JavaDeveloperJobSite();
jobSite.addVacancy("First Java Position");
jobSite.addVacancy("Second Java Position");
Observer firstSubscriber = new MySubscriber("Sasha");
Observer secondSubscriber = new MySubscriber("Masha");
jobSite.addObserver(firstSubscriber);
jobSite.addObserver(secondSubscriber);
jobSite.addVacancy("Third Java Position");
jobSite.removeVacancy("First Java Position");
}
}
interface Observer {
void handleEvent(List<String> vacancies);
}
interface Observed {
void addObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
class MySubscriber implements Observer {
private String name;
public MySubscriber(final String name) {
this.name = name;
}
@Override
public void handleEvent(final List<String> vacancies) {
System.out.println("Dear " + this.name + "\nWe have some changes in out vacancies:\n " + vacancies +
"\n=============================================================\n");
}
}
class JavaDeveloperJobSite implements Observed {
private List<Observer> subscribers = new ArrayList<>();
private List<String> vacancies = new ArrayList<>();
public void addVacancy(String vacancy) {
this.vacancies.add(vacancy);
this.notifyObservers();
}
public void removeVacancy(String vacancy) {
this.vacancies.remove(vacancy);
this.notifyObservers();
}
@Override
public void addObserver(final Observer observer) {
this.subscribers.add(observer);
}
@Override
public void removeObserver(final Observer observer) {
this.subscribers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer subscriber : this.subscribers) {
subscriber.handleEvent(this.vacancies);
}
}
} |
package com.github.hualuomoli.core.spring.prop;
import java.util.Properties;
/**
* 配置文件预处理,如果配置文件需要对内容处理,需要实现该接口
* @see 如数据库密码加密,需要指定处理类的class全路径property.pre.class=....
* @author hualuomoli
*
*/
public interface PropertyPreDealWith {
// 预处理,将处理的key放回原props
void deal(Properties props);
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vista;
import controlador.Controlador;
import controlador.controllerCategoria;
import controlador.controllerCompra;
import controlador.controllerDistribuidor;
import controlador.controllerEditorial;
import controlador.controllerEstado;
import controlador.controllerFactura;
import controlador.controllerIdioma;
import controlador.controllerLibro;
import controlador.controllerMetodoPago;
/**
*
* @author Cristobal Torres
* Clase principal main para llamada a las demas vistas
*/
public class Main extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public Main() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
menuBarArchivo = new javax.swing.JMenu();
menuEmpleado = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
menuBarRegistro = new javax.swing.JMenu();
menuAutor = new javax.swing.JMenuItem();
menuCategoria = new javax.swing.JMenuItem();
menuIdioma = new javax.swing.JMenu();
jMenuItem9 = new javax.swing.JMenuItem();
menuLibro = new javax.swing.JMenuItem();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
jMenuItem6 = new javax.swing.JMenuItem();
jMenu4 = new javax.swing.JMenu();
menuFactura = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
jMenuItem7 = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem8 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel1.setText("Sistema Biblioteca");
jLabel2.setFont(new java.awt.Font("Dialog", 1, 36)); // NOI18N
jLabel2.setText("FAST DEVELOPMENT");
jLabel3.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
jLabel3.setText("Sistema biblioteca version beta");
menuBarArchivo.setText("Archivo");
menuEmpleado.setText("Empleado");
menuEmpleado.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menuEmpleadoMouseClicked(evt);
}
});
menuEmpleado.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuEmpleadoActionPerformed(evt);
}
});
menuBarArchivo.add(menuEmpleado);
jMenuItem4.setText("Cerrar sesion");
menuBarArchivo.add(jMenuItem4);
jMenuBar1.add(menuBarArchivo);
menuBarRegistro.setText("Registro");
menuAutor.setText("Autor");
menuAutor.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menuAutorMouseClicked(evt);
}
});
menuAutor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuAutorActionPerformed(evt);
}
});
menuBarRegistro.add(menuAutor);
menuCategoria.setText("Categoria");
menuCategoria.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuCategoriaActionPerformed(evt);
}
});
menuBarRegistro.add(menuCategoria);
jMenuBar1.add(menuBarRegistro);
menuIdioma.setText("Libro");
jMenuItem9.setText("Compra");
jMenuItem9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem9ActionPerformed(evt);
}
});
menuIdioma.add(jMenuItem9);
menuLibro.setText("Libros");
menuLibro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuLibroActionPerformed(evt);
}
});
menuIdioma.add(menuLibro);
jMenuItem1.setText("Idioma");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
menuIdioma.add(jMenuItem1);
jMenuItem5.setText("Editorial");
jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem5ActionPerformed(evt);
}
});
menuIdioma.add(jMenuItem5);
jMenuItem6.setText("Estado");
jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem6ActionPerformed(evt);
}
});
menuIdioma.add(jMenuItem6);
jMenuBar1.add(menuIdioma);
jMenu4.setText("Venta");
menuFactura.setText("Factura");
menuFactura.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuFacturaActionPerformed(evt);
}
});
jMenu4.add(menuFactura);
jMenuItem3.setText("Distribuidor");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu4.add(jMenuItem3);
jMenuItem7.setText("Metodo Pago");
jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem7ActionPerformed(evt);
}
});
jMenu4.add(jMenuItem7);
jMenuBar1.add(jMenu4);
jMenu3.setText("Ayuda");
jMenuItem2.setText("Acerca de ...");
jMenu3.add(jMenuItem2);
jMenuItem8.setText("FAQ");
jMenu3.add(jMenuItem8);
jMenuBar1.add(jMenu3);
setJMenuBar(jMenuBar1);
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(0, 471, Short.MAX_VALUE)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(120, 120, 120)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(209, 209, 209)
.addComponent(jLabel1)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 141, Short.MAX_VALUE)
.addComponent(jLabel3)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void menuAutorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuAutorActionPerformed
frmAutor v = new frmAutor();
Controlador c = new Controlador(v);
v.setVisible(true);
v.setLocationRelativeTo(v);
}//GEN-LAST:event_menuAutorActionPerformed
private void menuEmpleadoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuEmpleadoMouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_menuEmpleadoMouseClicked
private void menuAutorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuAutorMouseClicked
}//GEN-LAST:event_menuAutorMouseClicked
private void menuEmpleadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuEmpleadoActionPerformed
frmEmpleado v = new frmEmpleado();
v.setVisible(true);
}//GEN-LAST:event_menuEmpleadoActionPerformed
private void menuCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCategoriaActionPerformed
frmCategoria v = new frmCategoria();
controllerCategoria c = new controllerCategoria(v);
v.setVisible(true);
v.setLocationRelativeTo(v);
}//GEN-LAST:event_menuCategoriaActionPerformed
private void menuLibroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuLibroActionPerformed
frmLibro v = new frmLibro();
controllerLibro c = new controllerLibro(v);
v.setVisible(true);
v.setLocationRelativeTo(v);
}//GEN-LAST:event_menuLibroActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
frmIdioma v = new frmIdioma();
controllerIdioma c = new controllerIdioma(v);
v.setVisible(true);
v.setLocationRelativeTo(v);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
frmEditorial v = new frmEditorial();
controllerEditorial c = new controllerEditorial(v);
v.setVisible(true);
v.setLocationRelativeTo(v);
}//GEN-LAST:event_jMenuItem5ActionPerformed
private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
frmEstado v = new frmEstado();
controllerEstado c = new controllerEstado(v);
v.setVisible(true);
v.setLocationRelativeTo(v);
}//GEN-LAST:event_jMenuItem6ActionPerformed
private void menuFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuFacturaActionPerformed
frmFactura v = new frmFactura();
controllerFactura c = new controllerFactura(v);
v.setVisible(true);
v.setLocationRelativeTo(v);
}//GEN-LAST:event_menuFacturaActionPerformed
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
frmDistribuidor v = new frmDistribuidor();
controllerDistribuidor c = new controllerDistribuidor(v);
v.setVisible(true);
v.setLocationRelativeTo(v);
}//GEN-LAST:event_jMenuItem3ActionPerformed
private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed
frmMetodoPago v = new frmMetodoPago();
controllerMetodoPago c = new controllerMetodoPago(v);
v.setVisible(true);
v.setLocationRelativeTo(v);
}//GEN-LAST:event_jMenuItem7ActionPerformed
private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed
frmCompra v = new frmCompra();
controllerCompra c = new controllerCompra(v);
v.setVisible(true);
v.setLocationRelativeTo(v);
}//GEN-LAST:event_jMenuItem9ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
public javax.swing.JMenu jMenu3;
public javax.swing.JMenu jMenu4;
private javax.swing.JMenuBar jMenuBar1;
public javax.swing.JMenuItem jMenuItem1;
public javax.swing.JMenuItem jMenuItem2;
public javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuItem jMenuItem7;
private javax.swing.JMenuItem jMenuItem8;
private javax.swing.JMenuItem jMenuItem9;
public javax.swing.JMenuItem menuAutor;
public javax.swing.JMenu menuBarArchivo;
public javax.swing.JMenu menuBarRegistro;
public javax.swing.JMenuItem menuCategoria;
private javax.swing.JMenuItem menuEmpleado;
public javax.swing.JMenuItem menuFactura;
public javax.swing.JMenu menuIdioma;
public javax.swing.JMenuItem menuLibro;
// End of variables declaration//GEN-END:variables
}
|
package com.tutorial.minirest.controller;
import com.tutorial.minirest.DTOTicket;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class HelloWorld {
@ResponseBody
@PostMapping("/post")
public DTOTicket postHelloWorld(@RequestBody DTOTicket response){
return response;
}
}
|
/**
* 21-03-03
* 13_FibonacciNumbers_FibFrog
*/
package codility.lesson;
import java.util.*;
class FibFrog {
// Other Solution
// 참고) https://jackjeong.tistory.com/47
final static Map<Integer, Integer> fiboMap=new HashMap<>();
public int solution(int[] A) {
int N=A.length;
for(int i=0; fibo(i)<=N+1; i++) fibo(i);
List<Integer> fiboList=new ArrayList<>(fiboMap.values());
Collections.reverse(fiboList);
Queue<Point> queue=new LinkedList<>();
boolean[] check=new boolean[N+1];
queue.add(new Point(-1,0)); // start
while( !queue.isEmpty() ) {
Point curPoint=queue.poll();
for(int fibo: fiboList) {
int next=curPoint.x + fibo;
if ( next==N ) {
return curPoint.y+1;
} else if ( next<N && next>=0 ) {
if ( A[next]==1 && !check[next] ) {
check[next]=true;
Point point=new Point(next, curPoint.y+1);
queue.add(point);
}
}
}
}
return -1;
}
public int fibo(int num) {
if ( num==0 ) return 0;
if ( num==1 ) return 1;
if ( fiboMap.containsKey(num) ) return fiboMap.get(num);
fiboMap.put(num, fibo(num-1)+fibo(num-2));
return fiboMap.get(num);
}
class Point {
int x,y;
public Point(int x, int y) {
this.x=x;
this.y=y;
}
}
public static void main(String [] args) {
int[] A = {0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0};
int[] t1 = {};
int[] t2 = {0,0,0};
int[] t3 = {1,1,1};
FibFrog s = new FibFrog();
int res = s.solution(A);
System.out.println(res);
System.out.println(s.solution(t1));
System.out.println(s.solution(t2));
System.out.println(s.solution(t3));
}
}
|
package com.t1808a.entity;
import com.t1808a.model.StudentModel;
import java.util.ArrayList;
public class Student extends Person {
private String rollNumber;
private ArrayList<String> errors;
public Student(){
}
public Student(String rollNumber , String name, String dob, String address, String phone, String email) {
super(name, dob, address, phone, email);
this.rollNumber = rollNumber;
}
public ArrayList<String> getErrors() {
return errors;
}
public void setErrors(ArrayList<String> errors) {
this.errors = errors;
}
public String getRollNumber() {
return rollNumber;
}
public void setRollNumber(String rollNumber) {
this.rollNumber = rollNumber;
}
public boolean isValid() {
if (this.getName().length() == 0 || this.getName() == null) {
errors.add("Vui lòng nhập tên!");
}
if (errors.size() > 0) { return false; }
return true;
}
public boolean isValidRollNumber() {
StudentModel model = new StudentModel();
this.errors = new ArrayList<String>();
if (this.rollNumber == null || this.rollNumber.length() == 0 ) {
errors.add("Vui lòng nhập mã sinh viên!");
}else {
if (model.FindById(this.rollNumber) != null){
errors.add("Mã sinh viên đã tồn tại !!");
}
}
if (errors.size() > 0) { return false; }
return true;
}
public void printErrors() {
for (String err: errors) {
System.err.println("-"+err);
}
}
}
|
package com.just4fun.dao;
/**
* Created by sdt14096 on 2017/4/13.
*/
public interface UserDao {
void add(String user);
}
|
import java.util.Scanner;
public class main{
public static void main(String[]args){
Scanner l=new Scanner(System.in);
System.out.print("Hora :");
int a=l.nextInt();
int b=l.nextInt();
int c=l.nextInt();
if(a>=0&&a<24){
if(b>=0&&b<60){
if(c>=0&&c<60){
System.out.println("La hora: "+a+":"+b+":"+c+" Es correcta");
}
}
}else{
System.out.println("La hora: "+a+":"+b+":"+c+" Es incorrecta");
}
}
} |
package com.sims.validator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.sims.model.Category;
@Component
public class MedicineValidator implements Validator {
@Override
public boolean supports(Class<?> arg0) {
// TODO Auto-generated method stub
return Category.class.equals(arg0);
}
@Override
public void validate(Object obj, Errors err) {
// TODO Auto-generated method stub
ValidationUtils.rejectIfEmpty(err, "description", "description.empty");
}
}
|
package com.example.sinoyd.frameapplication.KotlinFrame.Code.db_Weekly_inspection;
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;
/**
* 作者: scj
* 创建时间: 2018/6/12
* 版权: 江苏远大信息股份有限公司
* 描述: com.example.sinoyd.frameapplication.KotlinFrame.Code.db_Weekly_inspection
*/
@Table(name = "Consumables")
public class Consumables {
@Column(name = "id", isId = true)
private int id;
@Column(name = "RowGuid")//任务id
private String RowGuid;
@Column(name = "MonitoringinstrumentUid")//仪器id
private String MonitoringinstrumentUid;
@Column(name = "PointId")//站点id
private int PointId;
@Column(name = "MonitoringPointUid")//站点id
private String MonitoringPointUid;
@Column(name = "MonitoringPointName")//站点名称
private String MonitoringPointName;
@Column(name = "InstrumentUid")//仪器id
private String InstrumentUid;
@Column(name = "InstrumentName")//仪器name
private String InstrumentName;
@Column(name = "StanLiquidName")//耗材选项
private String StanLiquidName;
@Column(name = "Consumablesresult")//耗材选择结果
private String Consumablesresult;
@Column(name = "UsageValue")//用量
private String UsageValue;
@Column(name = "Reason")//原因
private String Reason;
@Column(name = "RecordStr")//记录
private String RecordStr;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRowGuid() {
return RowGuid;
}
public void setRowGuid(String rowGuid) {
RowGuid = rowGuid;
}
public String getMonitoringinstrumentUid() {
return MonitoringinstrumentUid;
}
public void setMonitoringinstrumentUid(String monitoringinstrumentUid) {
MonitoringinstrumentUid = monitoringinstrumentUid;
}
public int getPointId() {
return PointId;
}
public void setPointId(int pointId) {
PointId = pointId;
}
public String getMonitoringPointUid() {
return MonitoringPointUid;
}
public void setMonitoringPointUid(String monitoringPointUid) {
MonitoringPointUid = monitoringPointUid;
}
public String getMonitoringPointName() {
return MonitoringPointName;
}
public void setMonitoringPointName(String monitoringPointName) {
MonitoringPointName = monitoringPointName;
}
public String getInstrumentUid() {
return InstrumentUid;
}
public void setInstrumentUid(String instrumentUid) {
InstrumentUid = instrumentUid;
}
public String getInstrumentName() {
return InstrumentName;
}
public void setInstrumentName(String instrumentName) {
InstrumentName = instrumentName;
}
public String getStanLiquidName() {
return StanLiquidName;
}
public void setStanLiquidName(String stanLiquidName) {
StanLiquidName = stanLiquidName;
}
public String getConsumablesresult() {
return Consumablesresult;
}
public void setConsumablesresult(String consumablesresult) {
Consumablesresult = consumablesresult;
}
public String getUsageValue() {
return UsageValue;
}
public void setUsageValue(String usageValue) {
UsageValue = usageValue;
}
public String getReason() {
return Reason;
}
public void setReason(String reason) {
Reason = reason;
}
public String getRecordStr() {
return RecordStr;
}
public void setRecordStr(String recordStr) {
RecordStr = recordStr;
}
}
|
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class OneOreFourParameters {
@Parameterized.Parameters
public static Collection<Object> params(){
return Arrays.asList(new Object[][]{
{new int[]{1,2,3,4,3,2,4,1,1}, false},
{new int[]{8,7,5,12,43,35,1,11,12,3}, false},
{new int[]{16,2,4,7,4,3,42,11,14,3}, false},
{new int[]{1,2,4,7,2,12,42,11,6,3}, false},
{new int[]{1,1,1,1,1,1,1,1,1,4}, true},
{new int[]{4}, false},
});
}
public OneOreFourParameters(int[] in, boolean oneOrFour1) {
this.in = in;
this.oneOrFour1 = oneOrFour1;
}
private int[]in;
private boolean oneOrFour1;
private OneOrFour oneOrFour;
@Before
public void init(){
oneOrFour = new OneOrFour();
}
@Test
public void test(){
Assert.assertEquals(oneOrFour1, oneOrFour.oneOreFour(in));
}
}
|
package br.com.filemanager.ejb.service.impl;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import br.com.filemanager.ejb.dao.ConteudoDAO;
import br.com.filemanager.ejb.model.Conteudo;
import br.com.filemanager.ejb.service.ConteudoService;
@Stateless
public class ConteudoServiceImpl implements ConteudoService {
@EJB
private ConteudoDAO conteudoDAO;
@Override
public Conteudo listarConteudo(Integer codArquivo) throws Exception {
try {
return conteudoDAO.listarConteudo(codArquivo);
}catch(Exception e) {
throw new Exception(e);
}
}
} |
/*
* Copyright 2019 Google LLC
*
* 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 com.google.android.gnd.ui.basemapselector;
import androidx.lifecycle.ViewModel;
import javax.inject.Inject;
/**
* This view model is responsible for managing state for the {@link BasemapSelectorFragment}.
* Together, they constitute a basemap selector that users can interact with to select portions of a
* basemap for offline viewing. Among other things, this view model is responsible for receiving
* requests to download basemap files and for scheduling those requests with an {@link
* com.google.android.gnd.workers.FileDownloadWorker}.
*/
public class BasemapSelectorViewModel extends ViewModel {
@Inject
BasemapSelectorViewModel() {}
// TODO: Implement view model.
}
|
package lka.wine.jdbc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lka.wine.dao.PurchaseDetail;
import lka.wine.dao.TastingNote;
import lka.wine.dao.WineDetails;
public class WineDetailsQuery implements Restable<WineDetails> {
@Override
public WineDetails select(int wineId) throws Exception {
List<TastingNote> tastingNotes = new TastingNotesTable().selectByWineId(wineId);
List<PurchaseDetail> purchaseDetails = new PurchaseDetailsView().selectByWineId(wineId);
List<WineDetails> wineDetails = getWineDetails(tastingNotes, purchaseDetails);
return wineDetails.size() > 0 ? wineDetails.get(0) : null;
}
@Override
public List<WineDetails> select() throws Exception {
List<TastingNote> tastingNotes = new TastingNotesTable().select();
List<PurchaseDetail> purchaseDetails = new PurchaseDetailsView().select();
return getWineDetails(tastingNotes, purchaseDetails);
}
protected List<WineDetails> getWineDetails(List<TastingNote> tastingNotes, List<PurchaseDetail> purchaseDetails) {
Map<Integer, WineDetails> wineDetails = new HashMap<Integer, WineDetails>();
if(tastingNotes != null) {
for(TastingNote tastingNote : tastingNotes) {
Integer wineId = Integer.valueOf(tastingNote.getWineId());
WineDetails wd = wineDetails.get(wineId);
if(wd == null) {
wd = new WineDetails();
wd.setWineId(wineId);
wd.setPurchaseDetails(new ArrayList<PurchaseDetail>());
wd.setTastingNotes(new ArrayList<TastingNote>());
wineDetails.put(wineId, wd);
}
wd.getTastingNotes().add(tastingNote);
}
}
if(purchaseDetails != null) {
for(PurchaseDetail purchaseDetail : purchaseDetails) {
Integer wineId = Integer.valueOf(purchaseDetail.getWineId());
WineDetails wd = wineDetails.get(wineId);
if(wd == null) {
wd = new WineDetails();
wd.setWineId(wineId);
wd.setPurchaseDetails(new ArrayList<PurchaseDetail>());
wd.setTastingNotes(new ArrayList<TastingNote>());
wineDetails.put(wineId, wd);
}
wd.getPurchaseDetails().add(purchaseDetail);
}
}
return new ArrayList<WineDetails>(wineDetails.values());
}
@Override
public int insert(WineDetails obj) throws Exception {
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(WineDetails obj) throws Exception {
// TODO Auto-generated method stub
return 0;
}
@Override
public int delete(WineDetails obj) throws Exception {
// TODO Auto-generated method stub
return 0;
}
@Override
public int delete(int id) throws Exception {
// TODO Auto-generated method stub
return 0;
}
}
|
package com.vuze.tests.swt.tableview;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.gudy.azureus2.core3.util.Debug;
import org.gudy.azureus2.plugins.ui.tables.*;
import org.gudy.azureus2.ui.swt.shells.GCStringPrinter;
import org.gudy.azureus2.ui.swt.views.table.TableCellSWT;
import org.gudy.azureus2.ui.swt.views.table.TableCellSWTPaintListener;
import org.gudy.azureus2.ui.swt.views.table.utils.CoreTableColumn;
import com.aelitis.azureus.ui.common.table.TableCellCore;
import com.aelitis.azureus.ui.common.table.TableRowCore;
import com.aelitis.azureus.util.MapUtils;
public class CT_ID
extends CoreTableColumn
implements TableCellAddedListener, TableCellSWTPaintListener, TableCellRefreshListener, TableCellToolTipListener
{
public static double id = 0;
public static String name = new Object() { }.getClass().getEnclosingClass().getSimpleName();
public CT_ID() {
super(name, 170, "test");
addDataSourceType(TableViewTestDS.class);
setRefreshInterval(TableColumn.INTERVAL_INVALID_ONLY);
setVisible(true);
}
public void cellAdded(TableCell cell) {
TableRowCore row = (cell.getTableRow() instanceof TableRowCore) ? (TableRowCore)cell.getTableRow() : null;
// if (row != null) {
// row.setHeight((int) (16 + (Math.random() * 100)));
// }
String indent = row == null || row.getParentRowCore() == null ? "" : " ";
TableViewTestDS ds = (TableViewTestDS) cell.getDataSource();
Object mapObject = MapUtils.getMapObject(ds.map, "ID", null, Number.class);
if (mapObject instanceof Number) {
double overideID = ((Double) mapObject).doubleValue();
cell.setSortValue(overideID);
cell.setText(indent + overideID + (row == null ? "" : ":" + row.getHeight()));
} else {
id++;
cell.setSortValue(id);
cell.setText(indent + Double.toString(id) + (row == null ? "" : ":" + row.getHeight()));
ds.map.put("ID", id);
}
}
public void refresh(TableCell cell) {
int id = ((Number) cell.getSortValue()).intValue();
if (id % 10 == 1) {
cell.setForeground(200, 0, 0);
cell.getTableRow().setForeground(150, 0, 0);
}
}
public void cellPaint(GC gc, TableCellSWT cell) {
TableViewTestDS ds = (TableViewTestDS) cell.getDataSource();
int num = MapUtils.getMapInt(ds.map, name + ".numCP", 0) + 1;
ds.map.put(name + ".numCP", num);
GCStringPrinter.printString(gc, Integer.toString(num), cell.getBounds(), true, true, SWT.RIGHT);
}
public void cellHover(TableCell cell) {
TableRow row = cell.getTableRow();
if (row instanceof TableRowCore) {
TableRowCore rowCore = (TableRowCore)cell.getTableRow();
TableCellCore cellCore = (TableCellCore) cell;
cell.setToolTip(rowCore.getIndex() + ". r.vis? " + rowCore.isVisible());
}
}
public void cellHoverComplete(TableCell cell) {
}
}
|
package statemachine.parsing.builders;
import statemachine.models.State;
import statemachine.models.Transition;
import statemachine.parsing.Definition;
import statemachine.utils.exceptions.StateMachineException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TransitionBuilder {
private static final String TRANSITION_DEFINITION_REGEX = "\\(([a-zA-Z]+[0-9]+),([a-zA-Z0-9])->([a-zA-Z]+[0-9]+)\\)";
public static List<Transition> buildTransitionsFromDefinitions(List<Definition> definitions, List<State> states)
throws StateMachineException {
List<Transition> transitions = new ArrayList<>();
for (Definition definition : definitions) {
transitions.add(buildTransition(definition, states));
}
return transitions;
}
private static Transition buildTransition(Definition definition, List<State> states) throws StateMachineException {
validateDefinition(definition);
String transitionDefinition = definition.getDefinition();
String[] data = findDataFromDefinition(transitionDefinition);
State fromState = StateBuilder.findStateByName(data[0], states);
State toState = StateBuilder.findStateByName(data[2], states);
Transition transition = new Transition(fromState, toState, data[1]);
return transition;
}
private static void validateDefinition(Definition definition) throws StateMachineException {
String transitionDefiniton = definition.getDefinition();
if (!transitionDefiniton.matches(TRANSITION_DEFINITION_REGEX)) {
throw new StateMachineException("A definição da transição ("+ transitionDefiniton +") está incorreta");
}
}
private static String[] findDataFromDefinition(String definition) {
String[] data = new String[3];
Pattern pattern = Pattern.compile(TRANSITION_DEFINITION_REGEX);
Matcher matcher = pattern.matcher(definition);
if (matcher.find()) {
data[0] = matcher.group(1);
data[1] = matcher.group(2);
data[2] = matcher.group(3);
}
return data;
}
}
|
package com.example.student.cmpe137_android_lab3v2;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity {
private static final int RECOVERY_REQUEST = 1;
// My created button
Button btn;
// The video layout reference
private YouTubePlayerView youTubePlayerView;
// Input handler for youtube compressed video link format
private YouTubePlayer.OnInitializedListener onInitializedListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instance of YTPV
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// Generates video on successful data entry
onInitializedListener = new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restore) {
if(!restore) {
// Dog video
youTubePlayer.loadVideo("SfLV8hD7zX4");
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult error) {
// // Issue with playback, but you can recover
// if(error.isUserRecoverableError()) {
// error.getErrorDialog(getParent(), RECOVERY_REQUEST).show();
// } else {
// // Cannot playback, error code from Youtube API pop up
// String issue = error.toString();
// Toast.makeText(getApplicationContext(), issue, Toast.LENGTH_LONG).show();
// }
}
};
// Assign button to View button in XML
btn = (Button) findViewById(R.id.button);
// Assign that button to control Youtube Player
btn.setOnClickListener(new View.OnClickListener(){
// API Key intialization
@Override
public void onClick(View view) {
youTubePlayerView.initialize("AIzaSyCuunGSBhBPOsgSVZrD4mwS8co3FkZx9OI", onInitializedListener);
}
});
}
}
|
package com.gsccs.sme.plat.svg.service;
import java.util.List;
import com.alibaba.fastjson.JSONArray;
import com.gsccs.sme.plat.svg.model.RegTypeT;
public interface RegtypeService {
public void insert(RegTypeT regtype);
public void update(RegTypeT regtype);
public void delChannel(Long id);
public RegTypeT findById(Long id);
public List<RegTypeT> find(RegTypeT regtype, String orderstr, int page,
int pagesize);
public List<RegTypeT> find(RegTypeT regtype);
public List<RegTypeT> findSubChannel(Long parid);
public int count(RegTypeT regtype);
public List<RegTypeT> findByParids(String string);
public JSONArray findChannelTree();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.