text stringlengths 10 2.72M |
|---|
package com.example.nutan.mescomplain;
//import com.squareup.http.Response;
import retrofit.client.Response;
import retrofit.http.Body;
import retrofit.http.POST;
import rx.Observable;
/**
* Created by nutan on 9/21/15.
*/
public interface MESServices {
// /**
// * Creates an Observable with a Function to execute when it is subscribed to.
// * <p>
// * <em>Note:</em> Use {@link #create(OnSubscribe)} to create an Observable, instead of this constructor,
// * unless you specifically have a need for inheritance.
// *
// * @param f {@link OnSubscribe} to be executed when {@link #subscribe(Subscriber)} is called
// */
// protected MESServices(OnSubscribe<MESServices> f) {
// super(f);
// }
@POST("/user/sign_in")
Observable<Response> userSignIn(@Body User user);
}
|
package com.atguigu.java;
/**
* 1.用来保存数据。
* 2.对数组中的数据进行 增,删,改,查等操作。
* @author Administrator
*
*/
public class CustomerList {
private Customer[] customers;//用来保存数据
/*
* 1.用来存放数据的索引值
* 2.当前用户的数量
*/
private int total = 0; //用来记录当前用户的数量
/**
* 构造器 : 初始化数组
* @param totalCustomer
*/
public CustomerList(int totalCustomer) {
customers = new Customer[totalCustomer];
}
/**
* 添加用户
* @param customer 需要添加的用户
* @return boolean 如果为true添加成功,如果为false则添加失败
*/
public boolean addCustomer(Customer customer) {
//校验 : 1.当前用户是否已满 2.customer是否为null
if(total >= customers.length){
return false;
}
if(customer == null){
return false;
}
customers[total] = customer;
total++;
return true;
}
/**
* 修改用户
* @param index 被修改用户的索引值
* @param cust 需要替换的新用户
* @return boolean 如果为true修改成功,如果为false则修改失败
*/
public boolean replaceCustomer(int index, Customer cust){
//校验 : 1.索引值的合理范围 2.cust是否为null
//索引值范围 : 0 ~ total -1 (index >= 0 && index < total)
if(index < 0 || index >= total){
return false;
}
if(cust == null){
return false;
}
customers[index] = cust;
return true;
}
/**
* 删除用户
* @param index 被删除的用户的索引值
* @return boolean 如果为true删除成功,如果为false则删除失败
*/
public boolean deleteCustomer(int index){
//校验:1.索引值是否在合理范围之内
if(index < 0 || index >= total){
return false;
}
for(int i = index; i < total - 1; i++){
customers[i] = customers[i + 1];
}
//将最后一个元素变为null
customers[total - 1] = null;
//总人数减去1
total--;
// customers[--total] = null; 和上面的写法是一样的
return true;
}
/**
* 获取所有的用户
* @return Customer[] 该数组中存放了所有的用户
*/
public Customer[] getAllCustomers() {
//创建一个新的数组
Customer[] cs = new Customer[total];
//将原数组中所有的数据(不包括null)放入到新的数组中
for (int i = 0; i < total; i++) {
cs[i] = customers[i];
}
return cs;
}
/**
* 获取指定的用户
* @param index 需要获取的用户的索引值
* @return Customer 获取的用户
*/
public Customer getCustomer(int index) {
//校验:1.索引值是否在合理范围之内 - 如果不校验有可能发生ArrayIndexOutOfBoundsException
if(index < 0 || index >= total){
return null;
}
return customers[index];
}
}
|
package com.lyzn.srcb.resource;
public interface ResourceField {
}
|
/*
* 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.beans.factory.xml;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* {@link EntityResolver} implementation that attempts to resolve schema URLs into
* local {@link ClassPathResource classpath resources} using a set of mappings files.
*
* <p>By default, this class will look for mapping files in the classpath using the
* pattern: {@code META-INF/spring.schemas} allowing for multiple files to exist on
* the classpath at any one time.
*
* <p>The format of {@code META-INF/spring.schemas} is a properties file where each line
* should be of the form {@code systemId=schema-location} where {@code schema-location}
* should also be a schema file in the classpath. Since {@code systemId} is commonly a
* URL, one must be careful to escape any ':' characters which are treated as delimiters
* in properties files.
*
* <p>The pattern for the mapping files can be overridden using the
* {@link #PluggableSchemaResolver(ClassLoader, String)} constructor.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
*/
public class PluggableSchemaResolver implements EntityResolver {
/**
* The location of the file that defines schema mappings.
* Can be present in multiple JAR files.
*/
public static final String DEFAULT_SCHEMA_MAPPINGS_LOCATION = "META-INF/spring.schemas";
private static final Log logger = LogFactory.getLog(PluggableSchemaResolver.class);
@Nullable
private final ClassLoader classLoader;
private final String schemaMappingsLocation;
/** Stores the mapping of schema URL → local schema path. */
@Nullable
private volatile Map<String, String> schemaMappings;
/**
* Loads the schema URL → schema file location mappings using the default
* mapping file pattern "META-INF/spring.schemas".
* @param classLoader the ClassLoader to use for loading
* (can be {@code null} to use the default ClassLoader)
* @see PropertiesLoaderUtils#loadAllProperties(String, ClassLoader)
*/
public PluggableSchemaResolver(@Nullable ClassLoader classLoader) {
this.classLoader = classLoader;
this.schemaMappingsLocation = DEFAULT_SCHEMA_MAPPINGS_LOCATION;
}
/**
* Loads the schema URL → schema file location mappings using the given
* mapping file pattern.
* @param classLoader the ClassLoader to use for loading
* (can be {@code null} to use the default ClassLoader)
* @param schemaMappingsLocation the location of the file that defines schema mappings
* (must not be empty)
* @see PropertiesLoaderUtils#loadAllProperties(String, ClassLoader)
*/
public PluggableSchemaResolver(@Nullable ClassLoader classLoader, String schemaMappingsLocation) {
Assert.hasText(schemaMappingsLocation, "'schemaMappingsLocation' must not be empty");
this.classLoader = classLoader;
this.schemaMappingsLocation = schemaMappingsLocation;
}
@Override
@Nullable
public InputSource resolveEntity(@Nullable String publicId, @Nullable String systemId) throws IOException {
if (logger.isTraceEnabled()) {
logger.trace("Trying to resolve XML entity with public id [" + publicId +
"] and system id [" + systemId + "]");
}
if (systemId != null) {
String resourceLocation = getSchemaMappings().get(systemId);
if (resourceLocation == null && systemId.startsWith("https:")) {
// Retrieve canonical http schema mapping even for https declaration
resourceLocation = getSchemaMappings().get("http:" + systemId.substring(6));
}
if (resourceLocation != null) {
Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
try {
InputSource source = new InputSource(resource.getInputStream());
source.setPublicId(publicId);
source.setSystemId(systemId);
if (logger.isTraceEnabled()) {
logger.trace("Found XML schema [" + systemId + "] in classpath: " + resourceLocation);
}
return source;
}
catch (FileNotFoundException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not find XML schema [" + systemId + "]: " + resource, ex);
}
}
}
}
// Fall back to the parser's default behavior.
return null;
}
/**
* Load the specified schema mappings lazily.
*/
private Map<String, String> getSchemaMappings() {
Map<String, String> schemaMappings = this.schemaMappings;
if (schemaMappings == null) {
synchronized (this) {
schemaMappings = this.schemaMappings;
if (schemaMappings == null) {
if (logger.isTraceEnabled()) {
logger.trace("Loading schema mappings from [" + this.schemaMappingsLocation + "]");
}
try {
Properties mappings =
PropertiesLoaderUtils.loadAllProperties(this.schemaMappingsLocation, this.classLoader);
if (logger.isTraceEnabled()) {
logger.trace("Loaded schema mappings: " + mappings);
}
schemaMappings = new ConcurrentHashMap<>(mappings.size());
CollectionUtils.mergePropertiesIntoMap(mappings, schemaMappings);
this.schemaMappings = schemaMappings;
}
catch (IOException ex) {
throw new IllegalStateException(
"Unable to load schema mappings from location [" + this.schemaMappingsLocation + "]", ex);
}
}
}
}
return schemaMappings;
}
@Override
public String toString() {
return "EntityResolver using schema mappings " + getSchemaMappings();
}
}
|
package by.epam.kooks.entity;
/**
* @author Eugene Kooks
*/
public class BookInfo extends BaseEntity {
@Override
public String toString() {
return "BookInfo{" +
"amount=" + amount +
", price=" + price +
", book=" + book +
'}';
}
private int amount;
private int price;
private Book book;
public BookInfo() {
book = new Book();
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
}
|
package com.zlsu.dao.imp;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;
import com.zlsu.dao.PersionDao;
import com.zlsu.doma.Persion;
@Repository("persionDao")
public class PersionDaoImp implements PersionDao {
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession = null;
private PersionDao persionDao = null;
public PersionDaoImp() {
sqlSession = sqlSessionFactory.openSession();
persionDao = sqlSession.getMapper(PersionDao.class);
}
public SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
@Resource
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public List<Persion> findAll() {
List<Persion> persions = persionDao.findAll();
sqlSession.close();
return persions;
}
@Override
public void insert(Persion persion) {
persionDao.insert(persion);
sqlSession.commit();
sqlSession.close();
}
@Override
public void updata(Persion persion) {
persionDao.updata(persion);
sqlSession.commit();
sqlSession.close();
}
@Override
public void deleteByid(int id) {
persionDao.deleteByid(id);
sqlSession.commit();
sqlSession.close();
}
}
|
package arranger;
import dotplot.*;
/**
* Class <code>DPArrangerResults</code> will set the sub-chain run for the block when results are added.
*
* @author "Austin Shoemaker" <austin@genome.arizona.edu>
*/
public class DPArrangerResults extends ArrangerResults {
private Tile block;
public DPArrangerResults(Tile block, ABlock ib) {
super(ib);
this.block = block;
}
public DPArrangerResults(Tile block, ABlock[] ibs) {
super(ibs);
this.block = block;
}
public DPArrangerResults(Tile block, int altRun) {
super(block,altRun);
this.block = block;
}
public void addResults(SubBlock[] sblocks) {
super.addResults(sblocks);
block.setAltBlocksRun(DotPlot.SUB_CHAIN_RUN,new AltBlocksRun(0,(ABlock[])sblocks));
}
}
|
package QaJava;
public class compass{
static int[] nthPos= {0};
static int[] estPos= {0};
static int[] wstPos= {0};
static int[] sthPos= {0};
public void playerMapLocation() {
if((nthPos[0]== 1) && (estPos[0]==1)) {
System.out.println("you found a shard");
}
}
public void currentPos() {
System.out.println(nthPos[0] + "\n"+ estPos[0]);
}
public void location() {
}
}
|
/**
* Created with IntelliJ IDEA.
* User: dexctor
* Date: 12-11-20
* Time: 上午10:51
* To change this template use File | Settings | File Templates.
*/
public class p1_2_2 {
public static void main(String[] args)
{
int N = StdIn.readInt();
Interval1D[] intervals = new Interval1D[N];
for(int i = 0; i < N; ++i)
{
double left = StdRandom.uniform();
double right = StdRandom.uniform();
if(left > right)
{
double tmp = left;
left = right;
right = tmp;
}
Interval1D inter = new Interval1D(left, right);
intervals[i] = inter;
}
for(int i = 0; i < N; ++i)
{
for(int j = i + 1; j < N; ++j)
{
if(intervals[i].intersects(intervals[j]))
StdOut.println(i + " " + j);
}
}
}
}
|
package com.hdy.myhxc.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class UserDepExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public UserDepExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andUuidIsNull() {
addCriterion("UUID is null");
return (Criteria) this;
}
public Criteria andUuidIsNotNull() {
addCriterion("UUID is not null");
return (Criteria) this;
}
public Criteria andUuidEqualTo(String value) {
addCriterion("UUID =", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidNotEqualTo(String value) {
addCriterion("UUID <>", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidGreaterThan(String value) {
addCriterion("UUID >", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidGreaterThanOrEqualTo(String value) {
addCriterion("UUID >=", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidLessThan(String value) {
addCriterion("UUID <", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidLessThanOrEqualTo(String value) {
addCriterion("UUID <=", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidLike(String value) {
addCriterion("UUID like", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidNotLike(String value) {
addCriterion("UUID not like", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidIn(List<String> values) {
addCriterion("UUID in", values, "uuid");
return (Criteria) this;
}
public Criteria andUuidNotIn(List<String> values) {
addCriterion("UUID not in", values, "uuid");
return (Criteria) this;
}
public Criteria andUuidBetween(String value1, String value2) {
addCriterion("UUID between", value1, value2, "uuid");
return (Criteria) this;
}
public Criteria andUuidNotBetween(String value1, String value2) {
addCriterion("UUID not between", value1, value2, "uuid");
return (Criteria) this;
}
public Criteria andDepNameIsNull() {
addCriterion("Dep_Name is null");
return (Criteria) this;
}
public Criteria andDepNameIsNotNull() {
addCriterion("Dep_Name is not null");
return (Criteria) this;
}
public Criteria andDepNameEqualTo(String value) {
addCriterion("Dep_Name =", value, "depName");
return (Criteria) this;
}
public Criteria andDepNameNotEqualTo(String value) {
addCriterion("Dep_Name <>", value, "depName");
return (Criteria) this;
}
public Criteria andDepNameGreaterThan(String value) {
addCriterion("Dep_Name >", value, "depName");
return (Criteria) this;
}
public Criteria andDepNameGreaterThanOrEqualTo(String value) {
addCriterion("Dep_Name >=", value, "depName");
return (Criteria) this;
}
public Criteria andDepNameLessThan(String value) {
addCriterion("Dep_Name <", value, "depName");
return (Criteria) this;
}
public Criteria andDepNameLessThanOrEqualTo(String value) {
addCriterion("Dep_Name <=", value, "depName");
return (Criteria) this;
}
public Criteria andDepNameLike(String value) {
addCriterion("Dep_Name like", value, "depName");
return (Criteria) this;
}
public Criteria andDepNameNotLike(String value) {
addCriterion("Dep_Name not like", value, "depName");
return (Criteria) this;
}
public Criteria andDepNameIn(List<String> values) {
addCriterion("Dep_Name in", values, "depName");
return (Criteria) this;
}
public Criteria andDepNameNotIn(List<String> values) {
addCriterion("Dep_Name not in", values, "depName");
return (Criteria) this;
}
public Criteria andDepNameBetween(String value1, String value2) {
addCriterion("Dep_Name between", value1, value2, "depName");
return (Criteria) this;
}
public Criteria andDepNameNotBetween(String value1, String value2) {
addCriterion("Dep_Name not between", value1, value2, "depName");
return (Criteria) this;
}
public Criteria andDepLevelIsNull() {
addCriterion("Dep_Level is null");
return (Criteria) this;
}
public Criteria andDepLevelIsNotNull() {
addCriterion("Dep_Level is not null");
return (Criteria) this;
}
public Criteria andDepLevelEqualTo(Integer value) {
addCriterion("Dep_Level =", value, "depLevel");
return (Criteria) this;
}
public Criteria andDepLevelNotEqualTo(Integer value) {
addCriterion("Dep_Level <>", value, "depLevel");
return (Criteria) this;
}
public Criteria andDepLevelGreaterThan(Integer value) {
addCriterion("Dep_Level >", value, "depLevel");
return (Criteria) this;
}
public Criteria andDepLevelGreaterThanOrEqualTo(Integer value) {
addCriterion("Dep_Level >=", value, "depLevel");
return (Criteria) this;
}
public Criteria andDepLevelLessThan(Integer value) {
addCriterion("Dep_Level <", value, "depLevel");
return (Criteria) this;
}
public Criteria andDepLevelLessThanOrEqualTo(Integer value) {
addCriterion("Dep_Level <=", value, "depLevel");
return (Criteria) this;
}
public Criteria andDepLevelIn(List<Integer> values) {
addCriterion("Dep_Level in", values, "depLevel");
return (Criteria) this;
}
public Criteria andDepLevelNotIn(List<Integer> values) {
addCriterion("Dep_Level not in", values, "depLevel");
return (Criteria) this;
}
public Criteria andDepLevelBetween(Integer value1, Integer value2) {
addCriterion("Dep_Level between", value1, value2, "depLevel");
return (Criteria) this;
}
public Criteria andDepLevelNotBetween(Integer value1, Integer value2) {
addCriterion("Dep_Level not between", value1, value2, "depLevel");
return (Criteria) this;
}
public Criteria andDepTopidIsNull() {
addCriterion("Dep_TopID is null");
return (Criteria) this;
}
public Criteria andDepTopidIsNotNull() {
addCriterion("Dep_TopID is not null");
return (Criteria) this;
}
public Criteria andDepTopidEqualTo(String value) {
addCriterion("Dep_TopID =", value, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidNotEqualTo(String value) {
addCriterion("Dep_TopID <>", value, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidGreaterThan(String value) {
addCriterion("Dep_TopID >", value, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidGreaterThanOrEqualTo(String value) {
addCriterion("Dep_TopID >=", value, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidLessThan(String value) {
addCriterion("Dep_TopID <", value, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidLessThanOrEqualTo(String value) {
addCriterion("Dep_TopID <=", value, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidLike(String value) {
addCriterion("Dep_TopID like", value, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidNotLike(String value) {
addCriterion("Dep_TopID not like", value, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidIn(List<String> values) {
addCriterion("Dep_TopID in", values, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidNotIn(List<String> values) {
addCriterion("Dep_TopID not in", values, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidBetween(String value1, String value2) {
addCriterion("Dep_TopID between", value1, value2, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopidNotBetween(String value1, String value2) {
addCriterion("Dep_TopID not between", value1, value2, "depTopid");
return (Criteria) this;
}
public Criteria andDepTopnameIsNull() {
addCriterion("Dep_TopName is null");
return (Criteria) this;
}
public Criteria andDepTopnameIsNotNull() {
addCriterion("Dep_TopName is not null");
return (Criteria) this;
}
public Criteria andDepTopnameEqualTo(String value) {
addCriterion("Dep_TopName =", value, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameNotEqualTo(String value) {
addCriterion("Dep_TopName <>", value, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameGreaterThan(String value) {
addCriterion("Dep_TopName >", value, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameGreaterThanOrEqualTo(String value) {
addCriterion("Dep_TopName >=", value, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameLessThan(String value) {
addCriterion("Dep_TopName <", value, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameLessThanOrEqualTo(String value) {
addCriterion("Dep_TopName <=", value, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameLike(String value) {
addCriterion("Dep_TopName like", value, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameNotLike(String value) {
addCriterion("Dep_TopName not like", value, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameIn(List<String> values) {
addCriterion("Dep_TopName in", values, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameNotIn(List<String> values) {
addCriterion("Dep_TopName not in", values, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameBetween(String value1, String value2) {
addCriterion("Dep_TopName between", value1, value2, "depTopname");
return (Criteria) this;
}
public Criteria andDepTopnameNotBetween(String value1, String value2) {
addCriterion("Dep_TopName not between", value1, value2, "depTopname");
return (Criteria) this;
}
public Criteria andShowIdxIsNull() {
addCriterion("Show_Idx is null");
return (Criteria) this;
}
public Criteria andShowIdxIsNotNull() {
addCriterion("Show_Idx is not null");
return (Criteria) this;
}
public Criteria andShowIdxEqualTo(Integer value) {
addCriterion("Show_Idx =", value, "showIdx");
return (Criteria) this;
}
public Criteria andShowIdxNotEqualTo(Integer value) {
addCriterion("Show_Idx <>", value, "showIdx");
return (Criteria) this;
}
public Criteria andShowIdxGreaterThan(Integer value) {
addCriterion("Show_Idx >", value, "showIdx");
return (Criteria) this;
}
public Criteria andShowIdxGreaterThanOrEqualTo(Integer value) {
addCriterion("Show_Idx >=", value, "showIdx");
return (Criteria) this;
}
public Criteria andShowIdxLessThan(Integer value) {
addCriterion("Show_Idx <", value, "showIdx");
return (Criteria) this;
}
public Criteria andShowIdxLessThanOrEqualTo(Integer value) {
addCriterion("Show_Idx <=", value, "showIdx");
return (Criteria) this;
}
public Criteria andShowIdxIn(List<Integer> values) {
addCriterion("Show_Idx in", values, "showIdx");
return (Criteria) this;
}
public Criteria andShowIdxNotIn(List<Integer> values) {
addCriterion("Show_Idx not in", values, "showIdx");
return (Criteria) this;
}
public Criteria andShowIdxBetween(Integer value1, Integer value2) {
addCriterion("Show_Idx between", value1, value2, "showIdx");
return (Criteria) this;
}
public Criteria andShowIdxNotBetween(Integer value1, Integer value2) {
addCriterion("Show_Idx not between", value1, value2, "showIdx");
return (Criteria) this;
}
public Criteria andCreateUserIsNull() {
addCriterion("Create_User is null");
return (Criteria) this;
}
public Criteria andCreateUserIsNotNull() {
addCriterion("Create_User is not null");
return (Criteria) this;
}
public Criteria andCreateUserEqualTo(String value) {
addCriterion("Create_User =", value, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserNotEqualTo(String value) {
addCriterion("Create_User <>", value, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserGreaterThan(String value) {
addCriterion("Create_User >", value, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserGreaterThanOrEqualTo(String value) {
addCriterion("Create_User >=", value, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserLessThan(String value) {
addCriterion("Create_User <", value, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserLessThanOrEqualTo(String value) {
addCriterion("Create_User <=", value, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserLike(String value) {
addCriterion("Create_User like", value, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserNotLike(String value) {
addCriterion("Create_User not like", value, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserIn(List<String> values) {
addCriterion("Create_User in", values, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserNotIn(List<String> values) {
addCriterion("Create_User not in", values, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserBetween(String value1, String value2) {
addCriterion("Create_User between", value1, value2, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserNotBetween(String value1, String value2) {
addCriterion("Create_User not between", value1, value2, "createUser");
return (Criteria) this;
}
public Criteria andCreateDateIsNull() {
addCriterion("Create_Date is null");
return (Criteria) this;
}
public Criteria andCreateDateIsNotNull() {
addCriterion("Create_Date is not null");
return (Criteria) this;
}
public Criteria andCreateDateEqualTo(Date value) {
addCriterion("Create_Date =", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateNotEqualTo(Date value) {
addCriterion("Create_Date <>", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateGreaterThan(Date value) {
addCriterion("Create_Date >", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateGreaterThanOrEqualTo(Date value) {
addCriterion("Create_Date >=", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateLessThan(Date value) {
addCriterion("Create_Date <", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateLessThanOrEqualTo(Date value) {
addCriterion("Create_Date <=", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateIn(List<Date> values) {
addCriterion("Create_Date in", values, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateNotIn(List<Date> values) {
addCriterion("Create_Date not in", values, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateBetween(Date value1, Date value2) {
addCriterion("Create_Date between", value1, value2, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateNotBetween(Date value1, Date value2) {
addCriterion("Create_Date not between", value1, value2, "createDate");
return (Criteria) this;
}
public Criteria andUpdateUserIsNull() {
addCriterion("Update_User is null");
return (Criteria) this;
}
public Criteria andUpdateUserIsNotNull() {
addCriterion("Update_User is not null");
return (Criteria) this;
}
public Criteria andUpdateUserEqualTo(String value) {
addCriterion("Update_User =", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserNotEqualTo(String value) {
addCriterion("Update_User <>", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserGreaterThan(String value) {
addCriterion("Update_User >", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserGreaterThanOrEqualTo(String value) {
addCriterion("Update_User >=", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserLessThan(String value) {
addCriterion("Update_User <", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserLessThanOrEqualTo(String value) {
addCriterion("Update_User <=", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserLike(String value) {
addCriterion("Update_User like", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserNotLike(String value) {
addCriterion("Update_User not like", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserIn(List<String> values) {
addCriterion("Update_User in", values, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserNotIn(List<String> values) {
addCriterion("Update_User not in", values, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserBetween(String value1, String value2) {
addCriterion("Update_User between", value1, value2, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserNotBetween(String value1, String value2) {
addCriterion("Update_User not between", value1, value2, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateDateIsNull() {
addCriterion("Update_Date is null");
return (Criteria) this;
}
public Criteria andUpdateDateIsNotNull() {
addCriterion("Update_Date is not null");
return (Criteria) this;
}
public Criteria andUpdateDateEqualTo(Date value) {
addCriterion("Update_Date =", value, "updateDate");
return (Criteria) this;
}
public Criteria andUpdateDateNotEqualTo(Date value) {
addCriterion("Update_Date <>", value, "updateDate");
return (Criteria) this;
}
public Criteria andUpdateDateGreaterThan(Date value) {
addCriterion("Update_Date >", value, "updateDate");
return (Criteria) this;
}
public Criteria andUpdateDateGreaterThanOrEqualTo(Date value) {
addCriterion("Update_Date >=", value, "updateDate");
return (Criteria) this;
}
public Criteria andUpdateDateLessThan(Date value) {
addCriterion("Update_Date <", value, "updateDate");
return (Criteria) this;
}
public Criteria andUpdateDateLessThanOrEqualTo(Date value) {
addCriterion("Update_Date <=", value, "updateDate");
return (Criteria) this;
}
public Criteria andUpdateDateIn(List<Date> values) {
addCriterion("Update_Date in", values, "updateDate");
return (Criteria) this;
}
public Criteria andUpdateDateNotIn(List<Date> values) {
addCriterion("Update_Date not in", values, "updateDate");
return (Criteria) this;
}
public Criteria andUpdateDateBetween(Date value1, Date value2) {
addCriterion("Update_Date between", value1, value2, "updateDate");
return (Criteria) this;
}
public Criteria andUpdateDateNotBetween(Date value1, Date value2) {
addCriterion("Update_Date not between", value1, value2, "updateDate");
return (Criteria) this;
}
public Criteria andDelfgIsNull() {
addCriterion("DelFg is null");
return (Criteria) this;
}
public Criteria andDelfgIsNotNull() {
addCriterion("DelFg is not null");
return (Criteria) this;
}
public Criteria andDelfgEqualTo(String value) {
addCriterion("DelFg =", value, "delfg");
return (Criteria) this;
}
public Criteria andDelfgNotEqualTo(String value) {
addCriterion("DelFg <>", value, "delfg");
return (Criteria) this;
}
public Criteria andDelfgGreaterThan(String value) {
addCriterion("DelFg >", value, "delfg");
return (Criteria) this;
}
public Criteria andDelfgGreaterThanOrEqualTo(String value) {
addCriterion("DelFg >=", value, "delfg");
return (Criteria) this;
}
public Criteria andDelfgLessThan(String value) {
addCriterion("DelFg <", value, "delfg");
return (Criteria) this;
}
public Criteria andDelfgLessThanOrEqualTo(String value) {
addCriterion("DelFg <=", value, "delfg");
return (Criteria) this;
}
public Criteria andDelfgLike(String value) {
addCriterion("DelFg like", value, "delfg");
return (Criteria) this;
}
public Criteria andDelfgNotLike(String value) {
addCriterion("DelFg not like", value, "delfg");
return (Criteria) this;
}
public Criteria andDelfgIn(List<String> values) {
addCriterion("DelFg in", values, "delfg");
return (Criteria) this;
}
public Criteria andDelfgNotIn(List<String> values) {
addCriterion("DelFg not in", values, "delfg");
return (Criteria) this;
}
public Criteria andDelfgBetween(String value1, String value2) {
addCriterion("DelFg between", value1, value2, "delfg");
return (Criteria) this;
}
public Criteria andDelfgNotBetween(String value1, String value2) {
addCriterion("DelFg not between", value1, value2, "delfg");
return (Criteria) this;
}
public Criteria andBeizhuIsNull() {
addCriterion("Beizhu is null");
return (Criteria) this;
}
public Criteria andBeizhuIsNotNull() {
addCriterion("Beizhu is not null");
return (Criteria) this;
}
public Criteria andBeizhuEqualTo(String value) {
addCriterion("Beizhu =", value, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuNotEqualTo(String value) {
addCriterion("Beizhu <>", value, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuGreaterThan(String value) {
addCriterion("Beizhu >", value, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuGreaterThanOrEqualTo(String value) {
addCriterion("Beizhu >=", value, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuLessThan(String value) {
addCriterion("Beizhu <", value, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuLessThanOrEqualTo(String value) {
addCriterion("Beizhu <=", value, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuLike(String value) {
addCriterion("Beizhu like", value, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuNotLike(String value) {
addCriterion("Beizhu not like", value, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuIn(List<String> values) {
addCriterion("Beizhu in", values, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuNotIn(List<String> values) {
addCriterion("Beizhu not in", values, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuBetween(String value1, String value2) {
addCriterion("Beizhu between", value1, value2, "beizhu");
return (Criteria) this;
}
public Criteria andBeizhuNotBetween(String value1, String value2) {
addCriterion("Beizhu not between", value1, value2, "beizhu");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table m_userdep
*
* @mbg.generated do_not_delete_during_merge Mon Aug 26 14:48:07 CST 2019
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table m_userdep
*
* @mbg.generated Mon Aug 26 14:48:07 CST 2019
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} |
/*
* Copyright (c) 2008-2019 Haulmont.
*
* 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.haulmont.reports.desktop.exception;
import com.haulmont.cuba.core.global.AppBeans;
import com.haulmont.cuba.core.global.Messages;
import com.haulmont.cuba.desktop.App;
import com.haulmont.cuba.desktop.TopLevelFrame;
import com.haulmont.cuba.desktop.exception.AbstractExceptionHandler;
import com.haulmont.cuba.desktop.sys.DialogWindow;
import com.haulmont.cuba.desktop.sys.JXErrorPaneExt;
import com.haulmont.cuba.gui.components.Frame;
import com.haulmont.reports.exception.*;
import org.jdesktop.swingx.JXErrorPane;
import org.jdesktop.swingx.error.ErrorInfo;
import javax.annotation.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* Handles reporting exceptions.
*
*/
public class ReportExceptionHandler extends AbstractExceptionHandler {
public ReportExceptionHandler() {
super(
ReportingException.class.getName(),
NoOpenOfficeFreePortsException.class.getName(),
FailedToConnectToOpenOfficeException.class.getName(),
UnsupportedFormatException.class.getName(),
FailedToLoadTemplateClassException.class.getName()
);
}
@Override
protected void doHandle(Thread thread, String className, String message, @Nullable Throwable throwable) {
Messages messages = AppBeans.get(Messages.class);
final App app = App.getInstance();
final TopLevelFrame mainFrame = app.getMainFrame();
if (FailedToConnectToOpenOfficeException.class.getName().equals(className)) {
String msg = messages.getMessage(getClass(), "reportException.failedConnectToOffice");
mainFrame.getWindowManager().showNotification(msg, Frame.NotificationType.ERROR);
} else if (NoOpenOfficeFreePortsException.class.getName().equals(className)) {
String msg = messages.getMessage(getClass(), "reportException.noOpenOfficeFreePorts");
mainFrame.getWindowManager().showNotification(msg, com.haulmont.cuba.gui.components.Frame.NotificationType.ERROR);
} else {
JXErrorPane errorPane = new JXErrorPaneExt();
ErrorInfo errorInfo = new ErrorInfo(
messages.getMessage(getClass(), "reportException.message"), message,
null, null, throwable, null, null);
errorPane.setErrorInfo(errorInfo);
JDialog dialog = JXErrorPane.createDialog(mainFrame, errorPane);
dialog.setMinimumSize(new Dimension(600, (int) dialog.getMinimumSize().getHeight()));
final DialogWindow lastDialogWindow = getLastDialogWindow(mainFrame);
dialog.addWindowListener(
new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
if (lastDialogWindow != null)
lastDialogWindow.enableWindow();
else {
mainFrame.activate();
}
}
}
);
dialog.setModal(false);
if (lastDialogWindow != null)
lastDialogWindow.disableWindow(null);
else
mainFrame.deactivate(null);
dialog.setVisible(true);
}
}
protected DialogWindow getLastDialogWindow(TopLevelFrame mainFrame) {
try {
return mainFrame.getWindowManager().getLastDialogWindow();
} catch (Exception e) {
// this may happen in case of initialization error
return null;
}
}
} |
import java.util.Scanner;
public class CalculoFatorial {
/*
* Para uma sequência matemática onde cada elemento é calculado da seguinte forma:
* 1!/N! ; 2!/(N-1)!; 3!/(N-2)!; ... ; (N! / 1!)
* Crie um programa onde o usuário digite a quantidade de elementos que deseja exibir e
* sejam exibidos os elementos da sequência.
*
*/
public static void main(String[] args) {
Scanner leitor = new Scanner(System.in);
int valorN;
int contador = 0;
int dividendo;
int divisor;
int sequencia;
double resultado;
System.out.println("Informe o valor de N: ");
valorN = leitor.nextInt();
while(contador < valorN) {
sequencia = contador + 1;
dividendo = 1;
while (sequencia > 0) {
dividendo = dividendo * sequencia;
sequencia --;
}
sequencia = valorN - contador;
divisor = 1;
while (sequencia > 0) {
divisor = divisor * sequencia;
sequencia --;
}
resultado = (double) dividendo/divisor;
System.out.println((contador + 1) + "!/" + (valorN - contador) + "! = " +
dividendo + "/" + divisor + " = "
+ resultado);
contador ++;
}
leitor.close();
}
}
|
package com.lenovohit.hwe.treat.service.impl;
import java.util.Map;
import com.lenovohit.hwe.treat.dto.GenericRestDto;
import com.lenovohit.hwe.treat.model.Feeitem;
import com.lenovohit.hwe.treat.service.HisFeeitemService;
import com.lenovohit.hwe.treat.transfer.RestEntityResponse;
import com.lenovohit.hwe.treat.transfer.RestListResponse;
/**
*
* @author xiaweiyi
*/
public class HisFeeitemRestServiceImpl implements HisFeeitemService {
GenericRestDto<Feeitem> dto;
public HisFeeitemRestServiceImpl(final GenericRestDto<Feeitem> dto) {
super();
this.dto = dto;
}
@Override
public RestEntityResponse<Feeitem> getInfo(Feeitem model, Map<String, ?> variables) {
// TODO Auto-generated method stub
return null;
}
@Override
public RestListResponse<Feeitem> findList(Feeitem model, Map<String, ?> variables) {
// TODO Auto-generated method stub
return null;
}
}
|
package com.gaoshin.cj.api;
public enum LinkType {
Banner("1", "Banner"),
AdvancedLink("2", "Advanced Link"),
TextLink("3", "Text Link"),
ContentLink("7", "Content Link"),
SmartLink("9", "SmartLink"),
Catalog("10", "Product Catalog"),
AdvertiserSmartZone("11", "Advertiser SmartZone"),
FlashLink("15", "Flash Link"),
LeadForm("14", "Lead Form"),
;
private String id;
private String label;
private LinkType(String id, String label) {
this.id = id;
this.label = label;
}
public String getId() {
return id;
}
public String getLabel() {
return label;
}
}
|
package patterns.behavioral.interpreter;
import java.math.BigDecimal;
public abstract class Expression
{
public abstract BigDecimal interpret(Context context);
}
|
package com.example.springhibernate.hibernate.repositories;
import com.example.springhibernate.hibernate.models.Writer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface WriterRepository extends JpaRepository<Writer, Long> {
}
|
package edu.nps.deep.beArtifactGui.d3;
import java.io.Serializable;
import java.util.ArrayList;
import com.vaadin.annotations.JavaScript;
import com.vaadin.ui.AbstractJavaScriptComponent;
import elemental.json.JsonArray;
@JavaScript({ "d3.min.js", "d3forcedirected.js", "forcedirected-connector.js"})
public class ForceDirected extends AbstractJavaScriptComponent
{
public ForceDirected()
{ /*
addFunction("toJava", new JavaScriptFunction() {
@Override
public void call(JsonArray arguments) {
setValue(arguments);
for (ValueChangeListener listener: listeners)
listener.valueChange();
}
}); */
}
public interface ValueChangeListener extends Serializable
{
void valueChange();
}
ArrayList<ValueChangeListener> listeners = new ArrayList<ValueChangeListener>();
public void addValueChangeListener(ValueChangeListener listener)
{
listeners.add(listener);
}
//-------------------
public void setValue(JsonArray value)
{
getState().value = value;
}
public JsonArray getValue()
{
return getState().value;
}
@Override
protected ForceDirectedState getState()
{
return (ForceDirectedState) super.getState();
}
}
|
package com.acagild.oopspart2.shirt;
public class Shirt {
private int shirtCollarSize,shirtSleeveLength;
private String shirtMaterial;
public int getShirtCollarSize() {
return shirtCollarSize;
}
public void setShirtCollarSize(int shirtCollarSize) {
this.shirtCollarSize = shirtCollarSize;
}
public int getShirtSleeveLength() {
return shirtSleeveLength;
}
public void setShirtSleeveLength(int shirtSleeveLength) {
this.shirtSleeveLength = shirtSleeveLength;
}
public String getShirtMaterial() {
return shirtMaterial;
}
public void setShirtMaterial(String shirtMaterial) {
this.shirtMaterial = shirtMaterial;
}
@Override
public String toString() {
return "Shirt [shirtCollarSize=" + shirtCollarSize + ", shirtSleeveLength=" + shirtSleeveLength
+ ", shirtMaterial=" + shirtMaterial + "]";
}
public Shirt() {
super();
shirtMaterial = "Cotton";
}
public Shirt(int shirtCollarSize, int shirtSleeveLength) {
super();
this.shirtCollarSize = shirtCollarSize;
this.shirtSleeveLength = shirtSleeveLength;
shirtMaterial = "Cotton";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Shirt shirt = new Shirt();
Shirt shirt1 = new Shirt(24, 36);
Shirt shirt2 = new Shirt(56, 41);
System.out.println(shirt.toString());
System.out.println(shirt1.toString());
System.out.println(shirt2.toString());
}
} |
package io.jrevolt.sysmon.cloud.model;
/**
* @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a>
*/
public class ListHostsResponse extends ApiObject {
}
|
package com.hr.personnel.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.hr.login.model.LoginModel;
import com.hr.login.service.LoginService;
import com.hr.overtime.service.OverTimeService;
import com.hr.personnel.model.Personnel;
import com.hr.personnel.service.PersonnelService;
@Controller
@SessionAttributes("loginModel")
public class PersonnelController {
@Autowired
PersonnelService personnelService;
@Autowired
LoginService loginService;
@Autowired
OverTimeService overTimeService;
@GetMapping(path="/editPersonalInfo")
public String editPersonalInfo() {
return "/personnel/editPersonalInfo";
}
@GetMapping(path="/personnel")
public String personnel(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String empNo = authentication.getName();
LoginModel loginModel = loginService.getLoginModelByEmpNo(empNo);
Double sumHours = overTimeService.sumOverTimeHours(empNo);
Double remainingHours = 46 - sumHours ;
model.addAttribute("sumHours",sumHours);
model.addAttribute("remainingHours",remainingHours);
model.addAttribute("loginModel", loginModel);
return "/personnel/personnel";
}
@GetMapping(path="/personnelAuthorization", produces = { "application/json; charset=UTF-8" })
public @ResponseBody Map<String, String> personnelAuthorization(
@ModelAttribute("loginModel") LoginModel loginModel
) {
Boolean result = personnelService.personnelAuthorization(loginModel);
Map<String, String> map = new HashMap<String, String>();
map.put("result", result.toString());
return map;
}
/**
* This map problem should be done in service
* I will later on to amend below 2 methods and delete this note if it's finished
* Please do not hesitate about amending if seeing this note
* @param loginModel
* @return
*/
@GetMapping(path="/personalInformation")
public @ResponseBody Map<String, String> personalInformation(@ModelAttribute("loginModel") LoginModel loginModel) {
Personnel personnel = personnelService.loadPersonalInfoByPk(loginModel.getPk());
Map<String, String> map = new HashMap<String, String>();
map.put("phoneNumber", personnel.getPhoneNumber());
map.put("email", personnel.getEmail());
map.put("address", personnel.getAddress());
return map;
}
@PutMapping(path="/personalInformationUpdate", produces = { "application/json; charset=UTF-8" }, consumes = { "application/json; charset=UTF-8" })
public @ResponseBody Map<String, String> personalInformationUpdate(
@ModelAttribute("loginModel") LoginModel loginModel,
@RequestBody Personnel personnel) {
personnel.setEmpId(loginModel.getPk());
boolean updateResult = personnelService.personalInformationUpdate(personnel);
Personnel updatedPersonnel = personnelService.loadPersonalInfoByPk(loginModel.getPk());
Map<String, String> map = new HashMap<String, String>();
map.put("phoneNumber", updatedPersonnel.getPhoneNumber());
map.put("email", updatedPersonnel.getEmail());
map.put("address", updatedPersonnel.getAddress());
if(!updateResult) {
map.put("result", "Update failed");
return map;
}
map.put("result", "Update successfull");
return map;
}
}
|
package net.pravian.soiler.listener;
import net.pravian.soiler.SeedType;
import net.pravian.soiler.Soiler;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
public class BlockListener implements Listener {
private final Soiler plugin;
public BlockListener(Soiler plugin) {
this.plugin = plugin;
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (plugin.currentType == SeedType.OFF) {
return;
}
if (!event.getPlayer().hasPermission("soiler.soil")) {
return;
}
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
if (!(event.getClickedBlock().getType() == Material.DIRT || event.getClickedBlock().getType() == Material.GRASS)) {
return;
}
final Material mat = event.getPlayer().getItemInHand().getType();
if (mat != Material.WOOD_HOE
&& mat != Material.STONE_HOE
&& mat != Material.IRON_HOE
&& mat != Material.GOLD_HOE
&& mat != Material.DIAMOND_HOE) {
return;
}
final Block block = event.getClickedBlock().getLocation().getBlock();
block.setType(Material.SOIL);
if (plugin.currentType != SeedType.RANDOM) {
block.getRelative(BlockFace.UP).setTypeIdAndData(plugin.currentType.getId(), plugin.currentType.getData(), true);
} else {
final SeedType type = SeedType.getRandom();
block.getRelative(BlockFace.UP).setTypeIdAndData(type.getId(), type.getData(), true);
}
}
}
|
package com.joalib.donate.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.joalib.DAO.DonateDAO;
import com.joalib.DTO.ActionForward;
import com.joalib.DTO.Donate_ApplicationDTO;
public class DonateApplicationDelAction implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
int donate_no = Integer.parseInt(request.getParameter("donate_no"));
String donate_application_member = request.getParameter("donateApplicationMember");
Donate_ApplicationDTO dto = new Donate_ApplicationDTO();
dto.setDonate_no(donate_no);
dto.setDonate_application_member(donate_application_member);
DonateDAO dao = DonateDAO.getinstance();
int i = dao.DonateApplicationDel(dto);
return null;
}
}
|
package com.huangfu.assembly.interception.config;
import com.huangfu.assembly.interception.interceptions.MyInterceptionOne;
import com.huangfu.assembly.interception.interceptions.MyInterceptionTwo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* web拦截器配置
*
* @author huangfu
* @date 2021年2月20日11:29:34
*/
@Configuration
@EnableWebMvc
public class InterceptionWebMvc implements WebMvcConfigurer {
/**
* 指定字符编码集
*
* @return 字符转换器
*/
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
return new StringHttpMessageConverter(StandardCharsets.UTF_8);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截全部的请求
registry.addInterceptor(new MyInterceptionOne()).addPathPatterns("/**").excludePathPatterns("/favicon.ico");
//拦截前缀为huangfu的请求 huangfu也算
registry.addInterceptor(new MyInterceptionTwo()).addPathPatterns("/huangfu/**").excludePathPatterns("/favicon.ico");
}
/**
* 添加字符转换器
*
* @param converters 全部的转换器
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(responseBodyConverter());
}
}
|
package org.point85.domain.plant;
import org.point85.domain.i18n.DomainLocalizer;
public enum EntityLevel {
ENTERPRISE, SITE, AREA, PRODUCTION_LINE, WORK_CELL, EQUIPMENT;
@Override
public String toString() {
String key = null;
switch (this) {
case AREA:
key = "area.level";
break;
case ENTERPRISE:
key = "enterprise.level";
break;
case EQUIPMENT:
key = "equipment.level";
break;
case PRODUCTION_LINE:
key = "line.level";
break;
case SITE:
key = "site.level";
break;
case WORK_CELL:
key = "cell.level";
break;
default:
break;
}
return DomainLocalizer.instance().getLangString(key);
}
}
|
package com.shensu.tool;
public class UpdataName {
// Maven_Project RegCompany 修改项目 appid 密钥 域名
public static String projectName="yhsc";
//玉先的
//public static String appid = "wxbe3edd9434a14587";
//public static String secret = "47b0814befd1ee161bdb32f462c65b71";
//我们公司注册
//public static String appid = "wxc40b6179d3eb2ba4";
//public static String secret = "947f146a015cb8653e55ef2ad26987b1";
//超级vip的appid
/*public static String appid = "wxb8d9c1eb37840597";
public static String secret = "0ee208a424bd050518ee1d632bd768e7";*/
//新注冊的小程序
// public static String appid = "wxb39d67b4e5dda79d";
// public static String secret = "f514f321c7fb57cb082a6a4ddf834d89";
//https://www.chuanshoucs.com http://localhost
//public static String urlName = "https://www.thegooding.vip";
//public static String urlName = "https://www.chuanshoucs.com";
//public static String urlName = "https://www.chuanshoucs.com";
public static String urlName = "https://www.chuanshoucs.com";
//测试小程序
public static String appid = "wxfbe5b59f9aef6f4f";
public static String secret = "4849fd74cbec56f17f9e0ca243978546";
//public static String urlName = "http://localhost";
//public static String urlName = "http://localhost";
//淘宝课接口
public static String tburl = "https://eco.taobao.com/router/rest";
public static String tbappkey = "24881954";
public static String tbsecret = "b77be4246bbc86f526d3ad76008bad46";
//public static String urlName = "https://www.chuanshoucs.com";
//
public static String mch_id = "1488354722";
public static String key = "Shanghaishensuchuanshoux57630970";
public static String template1="UxTwVF30IlrhS1E79gpdNrJNAQu74Ht7H38yuj-LHn0";//账号审核不通过模板id
public static String template2="OSQfu1T05gKUkTvQkbabw8tUSM6uZkkqO1t7TainaP8";//账号审核通过模板id
public static String template3="5PvCzrMbqpmIGXzNGy4ZHIsCRViHTnwLpVptFnkg7NI";//退款不通过模板
}
|
import java.util.*;
import java.io.*;
public class prob10 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//Scanner in = new Scanner(System.in);
Scanner in = new Scanner(new File("prob10-1-in.txt"));
while (true) {
String line = in.nextLine();
if (!line.contains("X") && !line.contains("O")) break;
char[][] arr = new char[3][3];
for (int i = 0; i < 9; i++)
arr[i / 3][i % 3] = line.charAt(i);
if (checkrow(arr).length() > 0) {
System.out.println("Player " + checkrow(arr) + " is the winner.");
print(arr);
continue;
}
else if (checkcol(arr).length() > 0) {
System.out.println("Player " + checkcol(arr) + " is the winner.");
print(arr);
continue;
}
else if (checkdiag1(arr).length() > 0) {
System.out.println("Player " + checkdiag1(arr) + " is the winner.");
print(arr);
continue;
}
else if (checkdiag2(arr).length() > 0) {
System.out.println("Player " + checkdiag2(arr) + " is the winner.");
print(arr);
continue;
}
else {
System.out.println("There was a tie.");
print(arr);
}
}
in.close();
}
public static void print(char[][] arr) {
for (char[] x: arr)
{
for (char a: x) System.out.print(a);
System.out.println();
}
System.out.println();
}
public static String checkdiag1(char[][] arr)
{
String l = "" + arr[0][0] + arr[1][1] + arr[2][2];
if (l.contains("=") || l.contains("$")|| (l.contains("X") && l.contains("O"))) return "";
filldiag1(arr);
if (l.contains("O")) return "O";
else return "X";
}
public static String checkdiag2(char[][] arr)
{
String l = "" + arr[0][2] + arr[1][1] + arr[2][0];
if (l.contains("=") || l.contains("$")|| (l.contains("X") && l.contains("O"))) return "";
filldiag2(arr);
if (l.contains("O")) return "O";
else return "X";
}
public static void filldiag1(char[][] arr)
{
for (int i = 0; i < 3; i++) arr[i][i] = '$';
}
public static void filldiag2(char[][] arr)
{
for (int i = 0; i < 3; i++) arr[i][3 - 1] = '$';
}
public static String checkrow(char[][] arr)
{
for (int i = 0; i < 3; i++)
{
String l = "" + arr[i][0] + arr[i][1] + arr[i][2];
if (l.contains("=") || l.contains("$") || (l.contains("X") && l.contains("O"))) continue;
fillrow(i, arr);
if (l.contains("O")) return "O";
return "X";
}
return "";
}
public static String checkcol(char[][] arr)
{
for (int i = 0; i < 3; i++)
{
String l = "" + arr[0][i] + arr[1][i] + arr[2][i];
if (l.contains("=") || l.contains("$") || (l.contains("X") && l.contains("O"))) continue;
fillcol(i, arr);
if (l.contains("O")) return "O";
return "X";
}
return "";
}
public static void fillrow(int r, char[][] arr)
{
for (int i = 0; i < 3; i++) arr[r][i] = '$';
}
public static void fillcol(int r, char[][] arr)
{
for (int i = 0; i < 3; i++) arr[i][r] = '$';
}
} |
package com.fxn.adapters;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.fxn.modal.User;
import com.fxn.stashapp.R;
import java.util.ArrayList;
/**
* Created by akshay on 02/03/18.
*/
public class UserAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// private Context context;
private ArrayList<User> mDataset = new ArrayList<>();
/*public UserAdapter(Context context) {
this.context = context;
}*/
public void update(User user) {
this.mDataset.add(user);
notifyDataSetChanged();
}
public void updateAll(ArrayList<User> userlist) {
this.mDataset.clear();
this.mDataset.addAll(userlist);
notifyDataSetChanged();
}
public void clearAll() {
this.mDataset = new ArrayList<>();
notifyDataSetChanged();
}
public ArrayList<User> getList() {
return this.mDataset;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_row, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ViewHolder viewHolder = (ViewHolder) holder;
User user = mDataset.get(position);
viewHolder.Name.setText(user.getName());
viewHolder.Age.setText(String.valueOf(user.getAge()));
}
@Override
public int getItemCount() {
return mDataset.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView Name;
public TextView Age;
public ViewHolder(View v) {
super(v);
Name = v.findViewById(R.id.Name);
Age = v.findViewById(R.id.Age);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.una.clienteaeropuerto.controllers;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import org.una.clienteaeropuerto.dto.Areas_trabajoDTO;
import org.una.clienteaeropuerto.dto.MarcaHorarioDTO;
import org.una.clienteaeropuerto.dto.TransaccionDTO;
import org.una.clienteaeropuerto.dto.Usuarios_AreasDTO;
import org.una.clienteaeropuerto.service.MarcasHorarioService;
import org.una.clienteaeropuerto.service.TransaccionService;
import org.una.clienteaeropuerto.service.UsuariosAreasService;
import org.una.clienteaeropuerto.utils.AppContext;
import org.una.clienteaeropuerto.utils.AuthenticationSingleton;
import org.una.clienteaeropuerto.utils.CambiarVentana;
import org.una.clienteaeropuerto.utils.VigenciaToken;
/**
* FXML Controller class
*
* @author Luis
*/
public class CreacionMarcaHorarioController implements Initializable, Runnable {
@FXML
private CheckBox cbMarcaEntrada;
@FXML
private CheckBox cbMarcaSalida;
@FXML
private Label lbHora;
String hora, minutos, segundos;
Calendar calendario;
Thread h1;
MarcaHorarioDTO marcaHorarioDTO = new MarcaHorarioDTO();
MarcasHorarioService marcasHorarioService = new MarcasHorarioService();
Areas_trabajoDTO areas_trabajoDTO = new Areas_trabajoDTO();
Usuarios_AreasDTO usuarios_AreasDTO = new Usuarios_AreasDTO();
UsuariosAreasService usuariosAreasService = new UsuariosAreasService();
private List<Usuarios_AreasDTO> usuariosAreasList = new ArrayList<Usuarios_AreasDTO>();
java.util.Date date = new java.util.Date();
java.util.Date date2 = new java.util.Date();
CambiarVentana cambiarVentana = new CambiarVentana();
TransaccionDTO transaccionDTO = new TransaccionDTO();
TransaccionService transaccionService = new TransaccionService();
java.util.Date date3 = new java.util.Date();
VigenciaToken vigenciaToken = new VigenciaToken();
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
h1 = new Thread(this);
h1.start();
funcionAppContext();
}
@FXML
private void actionBtnGuardar(ActionEvent event) throws InterruptedException, ExecutionException, IOException {
if (!AppContext.getInstance().get("ed").equals("edit")) {
if (cbMarcaEntrada.isSelected()) {
CrearMarcaEntrada();
this.CrearMensaje();
} else {
this.FalloCrearMensaje();
}
} else {
if (cbMarcaSalida.isSelected()) {
CrearMarcaSalida();
this.EditarMensaje();
} else {
this.FalloEditarMensaje();
}
}
}
private void CrearMarcaEntrada() throws InterruptedException, ExecutionException, IOException {
CompararID();
marcaHorarioDTO.setUsuariosAreas(usuarios_AreasDTO);
marcaHorarioDTO.setEstado(true);
marcasHorarioService.add(marcaHorarioDTO);
AgregarTransaccion("Se creó una marca de entrada");
}
private void CrearMarcaSalida() throws InterruptedException, ExecutionException, IOException {
CompararID();
marcaHorarioDTO = (MarcaHorarioDTO) AppContext.getInstance().get("marcaHorarioDTO");
marcaHorarioDTO.setUsuariosAreas(usuarios_AreasDTO);
marcaHorarioDTO.setEstado(true);
marcaHorarioDTO.setMarca_salida(date);
marcasHorarioService.modify(marcaHorarioDTO.getId(), marcaHorarioDTO);
AgregarTransaccion("Se creó una marca de salida");
}
private void CrearMensaje() {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "", ButtonType.OK);
alert.setTitle("Mensaje");
alert.setHeaderText("La marca de entrada se ha creado con éxito.");
alert.show();
}
private void FalloCrearMensaje() {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "", ButtonType.OK);
alert.setTitle("Error");
alert.setHeaderText("No ha realizado la marca de entrada.");
alert.show();
}
private void EditarMensaje() {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "", ButtonType.OK);
alert.setTitle("Mensaje");
alert.setHeaderText("La marca de salida se ha creado con éxito.");
alert.show();
}
private void FalloEditarMensaje() {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "", ButtonType.OK);
alert.setTitle("Mensaje");
alert.setHeaderText("No ha realizado la marca de salida.");
alert.show();
}
private void calcularHora() {
Calendar calendar = new GregorianCalendar();
Date horaActual = new Date();
calendar.setTime(horaActual);
hora = calendar.get(Calendar.HOUR_OF_DAY) > 9 ? "" + calendar.get(Calendar.HOUR_OF_DAY) : "0" + calendar.get(Calendar.HOUR_OF_DAY);
minutos = calendar.get(Calendar.MINUTE) > 9 ? "" + calendar.get(Calendar.MINUTE) : "0" + calendar.get(Calendar.MINUTE);
segundos = calendar.get(Calendar.SECOND) > 9 ? "" + calendar.get(Calendar.SECOND) : "0" + calendar.get(Calendar.SECOND);
}
@Override
public void run() {
Thread hilo = Thread.currentThread();
while (hilo == h1) {
calcularHora();
lbHora.setText(hora + ":" + minutos);
}
}
private void funcionAppContext() {
if (AppContext.getInstance().get("ed").equals("edit")) {
MarcaHorarioDTO marcaHorarioDTO = new MarcaHorarioDTO();
marcaHorarioDTO = (MarcaHorarioDTO) AppContext.getInstance().get("marcaHorarioDTO");
marcaHorarioDTO.getMarca_entrada();
cbMarcaEntrada.setDisable(true);
} else {
if (AppContext.getInstance().get("ed").equals("insertar")) {
cbMarcaSalida.setDisable(true);
}
}
}
@FXML
private void actionBtnAtras(ActionEvent event) throws IOException {
if (vigenciaToken.validarVigenciaToken() == true) {
cambiarVentana.cambioVentana("ControlMarcasHorario", event);
} else {
MensajeTokenVencido();
cambiarVentana.cambioVentana("Login", event);
}
}
private void CompararID() {
try {
usuariosAreasList = UsuariosAreasService.getInstance().getAll();
System.out.println("aaaaaaa " + usuariosAreasList.toString());
} catch (InterruptedException ex) {
Logger.getLogger(CreacionMarcaHorarioController.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(CreacionMarcaHorarioController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CreacionMarcaHorarioController.class.getName()).log(Level.SEVERE, null, ex);
}
for (int i = 0; i < usuariosAreasList.size(); i++) {
if (usuariosAreasList.get(i).getUsuarios().getId() == AuthenticationSingleton.getInstance().getUsuario().getId()) {
usuarios_AreasDTO.setId(usuariosAreasList.get(i).getId());
usuarios_AreasDTO.setAreas_trabajo(usuariosAreasList.get(i).getAreas_trabajo());
usuarios_AreasDTO.setUsuarios(usuariosAreasList.get(i).getUsuarios());
}
}
}
private void AgregarTransaccion(String string) {
try {
transaccionDTO.setNombre(string);
transaccionDTO.setUsuarios(AuthenticationSingleton.getInstance().getUsuario());
transaccionDTO.setFecha_registro(date3);
transaccionDTO.setEstado(true);
transaccionService.add(transaccionDTO);
} catch (InterruptedException | ExecutionException | IOException ex) {
Logger.getLogger(CreacionMarcaHorarioController.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void MensajeTokenVencido() {
Alert alert = new Alert(Alert.AlertType.INFORMATION, "", ButtonType.OK);
alert.setTitle("Mensaje");
alert.setHeaderText("Su sesión ha caducado.");
alert.show();
}
}
|
package com.union.express.commons.model.logisticsstop;
/**
* Created by wq on 2016/10/6.
*/
public class VLogisticsStop {
private String id;
private String orderNumber;
private String stopName;
private String receiveTime;
private String outTime;
private String stopMsg;
private String sendName;
private String sendPhone;
private String logisticsStatus;
private String wayBillNumber;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public String getStopName() {
return stopName;
}
public void setStopName(String stopName) {
this.stopName = stopName;
}
public String getReceiveTime() {
return receiveTime;
}
public void setReceiveTime(String receiveTime) {
this.receiveTime = receiveTime;
}
public String getOutTime() {
return outTime;
}
public void setOutTime(String outTime) {
this.outTime = outTime;
}
public String getStopMsg() {
return stopMsg;
}
public void setStopMsg(String stopMsg) {
this.stopMsg = stopMsg;
}
public String getSendName() {
return sendName;
}
public void setSendName(String sendName) {
this.sendName = sendName;
}
public String getSendPhone() {
return sendPhone;
}
public void setSendPhone(String sendPhone) {
this.sendPhone = sendPhone;
}
public String getLogisticsStatus() {
return logisticsStatus;
}
public void setLogisticsStatus(String logisticsStatus) {
this.logisticsStatus = logisticsStatus;
}
public String getWayBillNumber() {
return wayBillNumber;
}
public void setWayBillNumber(String wayBillNumber) {
this.wayBillNumber = wayBillNumber;
}
}
|
package utility;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path) throws IOException {
if (!path.substring(0, 1).equals("/")) {
path = "/" + path;
}
image = ImageIO.read(getClass().getResource(path));
return image;
}
}
|
package oop_ex1;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class show {
JFrame fr = new JFrame("HCN");
JLabel lbl_tb =new JLabel("Hinh chu nhat");
JLabel lbl_cd = new JLabel(" Chieu dai: ");
JLabel lbl_cr= new JLabel(" Chieu rong: ");
public show(){
fr.add(lbl_tb);
fr.add(lbl_cd);
fr.add(lbl_cr);
fr.setVisible(true);
}
}
|
/* Copyright 2013 BurnerPat (https://github.com/BurnerPat)
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.burnerpat.rsreflect;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
public class TypeUtil {
private static final Map<Class<?>, Class<?>> WRAPPER_MAP;
static {
WRAPPER_MAP = new HashMap<Class<?>, Class<?>>();
WRAPPER_MAP.put(boolean.class, Boolean.class);
WRAPPER_MAP.put(byte.class, Byte.class);
WRAPPER_MAP.put(char.class, Character.class);
WRAPPER_MAP.put(double.class, Double.class);
WRAPPER_MAP.put(float.class, Float.class);
WRAPPER_MAP.put(int.class, Integer.class);
WRAPPER_MAP.put(long.class, Long.class);
WRAPPER_MAP.put(short.class, Short.class);
}
public static Class<?> getFieldType(int columnType) throws ReflectionException {
switch (columnType) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR: {
return String.class;
}
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY: {
return Byte[].class;
}
case Types.BIT: {
return Boolean.class;
}
case Types.TINYINT:
case Types.SMALLINT: {
return Short.class;
}
case Types.INTEGER: {
return Integer.class;
}
case Types.BIGINT: {
return Long.class;
}
case Types.REAL: {
return Float.class;
}
case Types.DOUBLE: {
return Double.class;
}
case Types.DECIMAL:
case Types.NUMERIC: {
return BigDecimal.class;
}
case Types.DATE: {
return Date.class;
}
case Types.TIME: {
return Time.class;
}
case Types.TIMESTAMP: {
return Timestamp.class;
}
case Types.BLOB: {
return Blob.class;
}
case Types.CLOB: {
return Clob.class;
}
case Types.ARRAY: {
return Array.class;
}
case Types.OTHER: {
return Object.class;
}
default: {
throw new ReflectionException("unsupported or unknown column type: " + columnType);
}
}
}
public static Object getValue(ResultSet resultSet, int columnIndex) throws ReflectionException, SQLException {
int columnType = resultSet.getMetaData().getColumnType(columnIndex);
switch (columnType) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR: {
return resultSet.getString(columnIndex);
}
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY: {
return resultSet.getBytes(columnIndex);
}
case Types.BIT: {
return resultSet.getBoolean(columnIndex);
}
case Types.TINYINT:
case Types.SMALLINT: {
return resultSet.getShort(columnIndex);
}
case Types.INTEGER: {
return resultSet.getInt(columnIndex);
}
case Types.BIGINT: {
return resultSet.getLong(columnIndex);
}
case Types.REAL: {
return resultSet.getFloat(columnIndex);
}
case Types.DOUBLE: {
return resultSet.getDouble(columnIndex);
}
case Types.DECIMAL:
case Types.NUMERIC: {
return resultSet.getBigDecimal(columnIndex);
}
case Types.DATE: {
return resultSet.getDate(columnIndex);
}
case Types.TIME: {
return resultSet.getTime(columnIndex);
}
case Types.TIMESTAMP: {
return resultSet.getTimestamp(columnIndex);
}
case Types.BLOB: {
return resultSet.getBlob(columnIndex);
}
case Types.CLOB: {
return resultSet.getClob(columnIndex);
}
case Types.ARRAY: {
return resultSet.getArray(columnIndex);
}
case Types.OTHER: {
return resultSet.getObject(columnIndex);
}
default: {
throw new ReflectionException("unsupported or unknown column type: " + columnType);
}
}
}
public static Class<?> getWrapper(Class<?> primitive) throws ReflectionException {
Class<?> wrapper = WRAPPER_MAP.get(primitive);
if (wrapper != null) {
return wrapper;
}
else {
throw new ReflectionException(primitive.getName() + " is not a primitive type");
}
}
}
|
package business.concretes;
import business.abstracts.GamePlayService;
import business.abstracts.ScoreService;
import entities.concretes.Gamer;
public class ManScoreCalculator implements ScoreService {
GamePlayService gamePlayService= new GamePlayManager();
@Override
public double calculateScore(Gamer gamer, double points) {
if (gamePlayService.calculateGender(gamer)!= true) {
System.out.println("Cinsiyetiniz Uygun Değil!");
return 0;
}else{
System.out.println(gamer.getFirstName()+ " Adlı oyuncu " + "Toplanan puan : " + points*0.70);
return points * 0.70;
}
}
}
|
package fabio.sicredi.evaluation.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class VoteKey implements Serializable {
private Long pollId;
private Long userId;
}
|
package com.alpha.toy.vo;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
public class CommentVofr {
private int comment_no;
private int board_no;
private int member_no;
private String comment_content;
@DateTimeFormat(pattern = "MM-dd")
private Date comment_writedate;
public CommentVofr(int comment_no, int board_no, int member_no, String comment_content, Date comment_writedate) {
super();
this.comment_no = comment_no;
this.board_no = board_no;
this.member_no = member_no;
this.comment_content = comment_content;
this.comment_writedate = comment_writedate;
}
public CommentVofr() {
super();
}
public int getComment_no() {
return comment_no;
}
public void setComment_no(int comment_no) {
this.comment_no = comment_no;
}
public int getBoard_no() {
return board_no;
}
public void setBoard_no(int board_no) {
this.board_no = board_no;
}
public int getMember_no() {
return member_no;
}
public void setMember_no(int member_no) {
this.member_no = member_no;
}
public String getComment_content() {
return comment_content;
}
public void setComment_content(String comment_content) {
this.comment_content = comment_content;
}
public Date getComment_writedate() {
return comment_writedate;
}
public void setComment_writedate(Date comment_writedate) {
this.comment_writedate = comment_writedate;
}
}
|
package leetcode.solution;
import leetcode.struct.ListNode;
/**
* 21. 合并两个有序链表
* <p>
* https://leetcode-cn.com/problems/merge-two-sorted-lists/
* <p>
* 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
* <p>
* 示例:
* <p>
* 输入:1->2->4, 1->3->4
* 输出:1->1->2->3->4->4
* <p>
* Solution: 同时遍历两个链表,比对两个链表的节点值,使新链表指向小的,并向后移动。
* 如果有一个遍历完,那么新链表后面就是没遍历完的部分。
*/
public class Solution21 {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
ListNode link = new ListNode();
ListNode heard = link;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) { //l1的值小
link.next = l1;
l1 = l1.next;
} else { //l2的值小
link.next = l2;
l2 = l2.next;
}
link = link.next;
}
link.next = l1 == null ? l2 : l1;
return heard.next;
}
public static void main(String[] args) {
ListNode a = ListNode.create(1, 2, 4);
ListNode b = ListNode.create(1, 3, 5);
Solution21 solution21 = new Solution21();
solution21.mergeTwoLists(a, b).print();
}
}
|
package com.itheima.rabbitmq.simpleQueue;
import com.itheima.rabbitmq.simpleQueue.Producer;
import com.itheima.util.ConnectionUtil;
import com.rabbitmq.client.*;
import java.io.IOException;
/**
* 简单模式:消费者接收消息
*/
public class Consumer {
public static void main(String[] args) throws IOException {
//创建连接工厂,创建连接(抽取一个获取连接的工具类)
Connection connection = ConnectionUtil.getConnection();
//创建频道
Channel channel = connection.createChannel();
//声明队列
/**
* 参数1:队列名称
* 参数2:是否定义持久化队列(消息会持久化保存在服务器上)
* 参数3:是否独占本连接
* 参数4:是否在不使用的时候队列自动删除
* 参数5:其它参数
*/
channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null);
//创建消费者
DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//路由key
System.out.println("路由key为:" + envelope.getRoutingKey());
//交换机
System.out.println("交换机为:" + envelope.getExchange());
//消息id
System.out.println("消息id为:" + envelope.getDeliveryTag());
//接收到的消息
System.out.println("接收到的消息为:" + new String(body, "utf-8"));
}
};
//监听队列
/**
* 参数1:队列名
* 参数2:是否要自动确认。设置为true表示小细节受到自动向MQ回复接收到了,
* MQ则会将消息从队列中删除;如果设置为false则需要手动确认
* 参数3:消费者
*/
channel.basicConsume(Producer.QUEUE_NAME, true, defaultConsumer);
}
}
|
/*
* Created on Jan 17, 2007
*
*/
package com.citibank.ods.persistence.pl.dao.rdb.oracle;
import com.citibank.ods.persistence.util.CitiStatement;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import com.citibank.ods.common.connection.rdb.ManagedRdbConnection;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.dataset.ResultSetDataSet;
import com.citibank.ods.common.exception.NoRowsReturnedException;
import com.citibank.ods.common.exception.UnexpectedException;
import com.citibank.ods.common.util.BaseConstraintDecoder;
import com.citibank.ods.common.util.ODSConstraintDecoder;
import com.citibank.ods.entity.pl.BaseTplProdRiskCatPrvtEntity;
import com.citibank.ods.entity.pl.TplProdRiskCatPrvtMovEntity;
import com.citibank.ods.entity.pl.valueobject.TplProdRiskCatPrvtMovEntityVO;
import com.citibank.ods.persistence.pl.dao.TplProdRiskCatPrvtMovDAO;
import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory;
/**
* @author angelica.almeida
*
* *** 20110321 ***
* As funcionalidades que utilizavam a tabela PL.TPL_PROD_RISK_CAT_PRVT devem utilizar a tabela
* PL.TPL_RISK_INVST_PROD_RDIP (apenas funcionalidades que utilizem consulta, as telas de
* inserção e alteração serão removidas)
*
*/
public class OracleTplProdRiskCatPrvtMovDAO extends
BaseOracleTplProdRiskCatPrvtDAO implements TplProdRiskCatPrvtMovDAO
{
private static final String C_TPL_PROD_RISK_CAT_PRVT_MOV = C_PL_SCHEMA
+ "TPL_PROD_RISK_CAT_PRVT_MOV";
private String C_OPERN_CODE = "OPERN_CODE";
protected String C_OPERN_TEXT = "OPERN_TEXT";
// /**
// * Este método altera os dados de uma categoria de risco
// *
// * @see com.citibank.ods.persistence.pl.dao.TplProdRiskCatPrvtMovDAO#update(com.citibank.ods.entity.pl.TplProdRiskCatPrvtMovEntity)
// */
// public void update( TplProdRiskCatPrvtMovEntity prodRiskCatPrvtMovEntity_ )
// {
// ManagedRdbConnection connection = null;
// CitiStatement preparedStatement = null;
// StringBuffer query = new StringBuffer();
//
// try
// {
// connection = OracleODSDAOFactory.getConnection();
// query.append( "UPDATE " + C_TPL_PROD_RISK_CAT_PRVT_MOV + " SET " );
// query.append( C_PROD_INVST_RISK_TEXT + "= ?," );
// query.append( C_LAST_UPD_DATE + "= ?," );
// query.append( C_LAST_UPD_USER_ID + "= ?," );
// query.append( C_OPERN_CODE + "= ? " );
// query.append( "WHERE " + C_PROD_INVST_RISK_CODE + "= ? " );
//
// preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
//
// preparedStatement.setString(
// 1,
// prodRiskCatPrvtMovEntity_.getData().getProdRiskCatText() );
// preparedStatement.setTimestamp(
// 2,
// new java.sql.Timestamp(
// prodRiskCatPrvtMovEntity_.getData().getLastUpdDate().getTime() ) );
// preparedStatement.setString(
// 3,
// prodRiskCatPrvtMovEntity_.getData().getLastUpdUserID() );
// preparedStatement.setString(
// 4,
// ( ( TplProdRiskCatPrvtMovEntityVO ) prodRiskCatPrvtMovEntity_.getData() ).getOpernCode() );
// preparedStatement.setLong(
// 5,
// prodRiskCatPrvtMovEntity_.getData().getProdRiskCatCode().longValue() );
//
// preparedStatement.executeUpdate();
// preparedStatement.replaceParametersInQuery(query.toString());
//
// }
// catch ( SQLException e )
// {
// throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
// }
// }
//
// /**
// * Este método exclui uma categoria de risco que se enquadre com o critérios
// * informados
// *
// * @see com.citibank.ods.persistence.pl.dao.TplProdRiskCatPrvtMovDAO#delete(com.citibank.ods.entity.pl.TplProdRiskCatPrvtMovEntity)
// */
// public void delete( TplProdRiskCatPrvtMovEntity prodRiskCatPrvtMovEntity_ )
// {
// ManagedRdbConnection connection = null;
// CitiStatement preparedStatement = null;
// StringBuffer query = new StringBuffer();
//
// try
// {
// connection = OracleODSDAOFactory.getConnection();
// query.append( "DELETE FROM " );
// query.append( C_TPL_PROD_RISK_CAT_PRVT_MOV );
// query.append( " WHERE " );
// query.append( C_PROD_INVST_RISK_CODE + " = ?" );
//
// preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
//
// preparedStatement.setLong(
// 1,
// prodRiskCatPrvtMovEntity_.getData().getProdRiskCatCode().longValue() );
//
// preparedStatement.executeUpdate();
// preparedStatement.replaceParametersInQuery(query.toString());
// }
// catch ( SQLException e )
// {
// throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
// }
//
// }
//
// /**
// * Este método insere um novo registro de categoria de risco
// *
// * @see com.citibank.ods.persistence.pl.dao.TplProdRiskCatPrvtMovDAO#insert(com.citibank.ods.entity.pl.TplProdRiskCatPrvtMovEntity)
// */
// public TplProdRiskCatPrvtMovEntity insert(
// TplProdRiskCatPrvtMovEntity prodRiskCatPrvtMovEntity_ )
// {
// ManagedRdbConnection connection = null;
// CitiStatement preparedStatement = null;
// StringBuffer query = new StringBuffer();
//
// try
// {
// connection = OracleODSDAOFactory.getConnection();
// query.append( "INSERT INTO " + C_TPL_PROD_RISK_CAT_PRVT_MOV + " ( " );
// query.append( C_PROD_INVST_RISK_CODE + ", " );
// query.append( C_PROD_INVST_RISK_TEXT + ", " );
// query.append( C_LAST_UPD_DATE + ", " );
// query.append( C_LAST_UPD_USER_ID + ", " );
// query.append( C_OPERN_CODE + ") " );
// query.append( "VALUES ( ?, ?, ?, ?, ? ) " );
//
// preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
//
// preparedStatement.setLong(
// 1,
// prodRiskCatPrvtMovEntity_.getData().getProdRiskCatCode().longValue() );
// preparedStatement.setString(
// 2,
// prodRiskCatPrvtMovEntity_.getData().getProdRiskCatText() );
// preparedStatement.setTimestamp(
// 3,
// new Timestamp(
// prodRiskCatPrvtMovEntity_.getData().getLastUpdDate().getTime() ) );
// preparedStatement.setString(
// 4,
// prodRiskCatPrvtMovEntity_.getData().getLastUpdUserID() );
// preparedStatement.setString(
// 5,
// ( ( TplProdRiskCatPrvtMovEntityVO ) prodRiskCatPrvtMovEntity_.getData() ).getOpernCode() );
// preparedStatement.execute();
// preparedStatement.replaceParametersInQuery(query.toString());
// }
// catch ( SQLException e )
// {
// throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
// }
//
// return prodRiskCatPrvtMovEntity_;
// }
//
// /**
// * Este método retorna uma lista de categoria de risco que se enquadre com os
// * critérios informados
// *
// * @see com.citibank.ods.persistence.pl.dao.TplProdRiskCatPrvtMovDAO#update(
// * java.math.BigInteger,java.lang.String,java.lang.String)
// */
// public DataSet list( BigInteger prodRiskCode_, String prodRiskText_,
// String lastUpdUserId_ )
// {
// ManagedRdbConnection connection = null;
// CitiStatement preparedStatement = null;
// ResultSet resultSet = null;
// ResultSetDataSet rsds = null;
// StringBuffer query = new StringBuffer();
//
// try
// {
// connection = OracleODSDAOFactory.getConnection();
// query.append( "SELECT " );
// query.append( C_PROD_INVST_RISK_CODE + ", " );
// query.append( C_PROD_INVST_RISK_TEXT + ", " );
// query.append( C_OPERN_CODE + ", " );
// query.append( C_LAST_UPD_USER_ID + ", " );
// query.append( C_LAST_UPD_DATE + " " );
// query.append( " FROM " );
// query.append( C_TPL_PROD_RISK_CAT_PRVT_MOV );
//
// String criteria = "";
//
// if ( prodRiskCode_ != null && prodRiskCode_.longValue() != 0 )
// {
// criteria = criteria + C_PROD_INVST_RISK_CODE + " = ? AND ";
// }
// if ( prodRiskText_ != null && !prodRiskText_.equals( "" ) )
// {
// criteria = criteria + "UPPER(\"" + C_PROD_INVST_RISK_TEXT
// + "\") LIKE ? AND ";
// }
// if ( lastUpdUserId_ != null && lastUpdUserId_.length() != 0 )
// {
// criteria = criteria + "UPPER(\"" + C_LAST_UPD_USER_ID
// + "\") LIKE ? AND ";
// }
//
// if ( criteria.length() > 0 )
// {
// criteria = criteria.substring( 0, criteria.length() - 5 );
// query.append( " WHERE " + criteria + " ORDER BY "
// + C_PROD_INVST_RISK_TEXT + " ASC " + " , "
// + C_PROD_INVST_RISK_CODE );
// }
// else
// {
// query.append( " ORDER BY " + C_PROD_INVST_RISK_TEXT + " ASC " + " , "
// + C_PROD_INVST_RISK_CODE );
// }
//
// preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
// int count = 1;
//
// if ( prodRiskCode_ != null && prodRiskCode_.longValue() != 0 )
// {
// preparedStatement.setLong( count++, prodRiskCode_.longValue() );
// }
// if ( prodRiskText_ != null && !prodRiskText_.equals( "" ) )
// {
// preparedStatement.setString( count++, "%" + prodRiskText_.toUpperCase() + "%" );
// }
// if ( lastUpdUserId_ != null && lastUpdUserId_.length() != 0 )
// {
// preparedStatement.setString( count++, "%" + lastUpdUserId_.toUpperCase() + "%" );
// }
//
// resultSet = preparedStatement.executeQuery();
// preparedStatement.replaceParametersInQuery(query.toString());
//
// rsds = new ResultSetDataSet( resultSet );
// resultSet.close();
// }
// catch ( SQLException e )
// {
// throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
// }
// finally
// {
// closeStatement( preparedStatement );
// closeConnection( connection );
// }
//
// String[] codeColumn = { C_OPERN_CODE };
// String[] nameColumn = { C_OPERN_TEXT };
// rsds.outerJoin( ODSConstraintDecoder.decodeOpern(), codeColumn, codeColumn,
// nameColumn );
//
// return rsds;
// }
//
// /**
// * Este método busca uma categoria de risco que se enquadre com os critérios
// * informados
// *
// * @see com.citibank.ods.persistence.pl.dao.TplProdRiskCatPrvtMovDAO#insert(com.citibank.ods.entity.pl.TplProdRiskCatPrvtMovEntity)
// */
// public BaseTplProdRiskCatPrvtEntity find(
// BaseTplProdRiskCatPrvtEntity prodRiskCatPrvtEntity_ )
// {
// ManagedRdbConnection connection = null;
// CitiStatement preparedStatement = null;
// ResultSet resultSet = null;
// StringBuffer query = new StringBuffer();
// ArrayList tplProdRiskCatEntities;
// BaseTplProdRiskCatPrvtEntity prodRiskCatPrvtEntity = null;
//
// try
// {
// connection = OracleODSDAOFactory.getConnection();
// query.append( "SELECT " );
// query.append( C_PROD_INVST_RISK_CODE + ", " );
// query.append( C_PROD_INVST_RISK_TEXT + ", " );
// query.append( C_LAST_UPD_DATE + ", " );
// query.append( C_LAST_UPD_USER_ID + ", " );
// query.append( C_OPERN_CODE + " " );
// query.append( " FROM " );
// query.append( C_TPL_PROD_RISK_CAT_PRVT_MOV );
// query.append( " WHERE " );
// query.append( C_PROD_INVST_RISK_CODE + " = ?" );
//
// preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
//
// preparedStatement.setLong(
// 1,
// prodRiskCatPrvtEntity_.getData().getProdRiskCatCode().longValue() );
//
// resultSet = preparedStatement.executeQuery();
// preparedStatement.replaceParametersInQuery(query.toString());
//
// tplProdRiskCatEntities = instantiateFromResultSet( resultSet );
//
// if ( tplProdRiskCatEntities.size() == 0 )
// {
// throw new NoRowsReturnedException();
// }
// else if ( tplProdRiskCatEntities.size() > 1 )
// {
// throw new UnexpectedException( C_ERROR_TOO_MANY_ROWS_RETURNED );
// }
// else
// {
// prodRiskCatPrvtEntity = ( BaseTplProdRiskCatPrvtEntity ) tplProdRiskCatEntities.get( 0 );
// }
//
// return prodRiskCatPrvtEntity;
// }
// catch ( SQLException e )
// {
// throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
// }
// }
//
// /**
// * Este método cria um array de Entity apartir de um result set
// *
// * @param resultSet_
// * @return ArrayList de TplProdRiskCatPrvtMovEntity
// */
// private ArrayList instantiateFromResultSet( ResultSet resultSet_ )
// {
//
// TplProdRiskCatPrvtMovEntity tplProdRiskCatPrvtMovEntity;
// Timestamp timestamp;
// Date date;
// ArrayList oracleTplOfficerCmplEntities = new ArrayList();
//
// try
// {
// while ( resultSet_.next() )
// {
// tplProdRiskCatPrvtMovEntity = new TplProdRiskCatPrvtMovEntity();
//
// timestamp = resultSet_.getTimestamp( this.C_LAST_UPD_DATE );
// date = new Date( timestamp.getTime() );
// tplProdRiskCatPrvtMovEntity.getData().setLastUpdDate( date );
// tplProdRiskCatPrvtMovEntity.getData().setLastUpdUserID(
// resultSet_.getString( this.C_LAST_UPD_USER_ID ) );
// tplProdRiskCatPrvtMovEntity.getData().setProdRiskCatCode(
// new BigInteger(
// resultSet_.getString( this.C_PROD_INVST_RISK_CODE ) ) );
// tplProdRiskCatPrvtMovEntity.getData().setProdRiskCatText(
// resultSet_.getString( this.C_PROD_INVST_RISK_TEXT ) );
// ( ( TplProdRiskCatPrvtMovEntityVO ) tplProdRiskCatPrvtMovEntity.getData() ).setOpernCode( resultSet_.getString( this.C_OPERN_CODE ) );
//
// oracleTplOfficerCmplEntities.add( tplProdRiskCatPrvtMovEntity );
// }
// }
// catch ( SQLException e )
// {
// throw new UnexpectedException( e.getErrorCode(), C_ERROR_INSTANTIATE_FROM_RESULT_SET, e );
// }
// return oracleTplOfficerCmplEntities;
// }
//
// /**
// *
// * Verifica se um determinado registro existe na base de dados.
// *
// * @param catPrvtMovEntity___ Entidade contendo o identificador do registro
// * que será verificada a existência.
// * @return Indicador de existência do registro (true/false).
// */
// public boolean exists( TplProdRiskCatPrvtMovEntity catPrvtMovEntity_ )
// {
// boolean exists = true;
//
// try
// {
// this.find( catPrvtMovEntity_ );
// }
// catch ( NoRowsReturnedException e )
// {
// exists = false;
// }
//
// return exists;
// }
public BaseTplProdRiskCatPrvtEntity find(BaseTplProdRiskCatPrvtEntity baseTplProdRiskCatPrvtEntity_) {
// TODO Auto-generated method stub
return null;
}
} |
package ru.avokin.highlighting;
import java.io.File;
/**
* User: Andrey Vokin
* Date: 05.10.2010
*/
public interface CodeHighlighterManager {
CodeHighlighter getCodeHighlighter(File f);
}
|
package com.needii.dashboard.service;
import java.util.List;
import com.needii.dashboard.model.Skus;
import com.needii.dashboard.model.form.SearchForm;
import com.needii.dashboard.utils.Pagination;
public interface SkuService {
List<Skus> findAll(SearchForm seachForm, Pagination pagination);
Long count(SearchForm seachForm);
List<Skus> findByProductId(long productId);
Skus findOne(long id);
void create(Skus model);
void update(Skus model);
void delete(Skus model);
}
|
package loecraftpack.common.logic;
import loecraftpack.LoECraftPack;
import loecraftpack.common.gui.GuiDialog;
import loecraftpack.common.gui.GuiIds;
import net.minecraft.client.Minecraft;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class LogicQuest
{
public static String questTitle = "Error: No Title - Contact An Admin.";
public static String[] questTask = {"Error: No Data", "Contact An Admin."}; //The task is the explicit instruction of what to do
public static String[] rewardText = {"Error: No Data", "Contact An Admin."};
public static void parseQuest(String[] params)
{
if (params.length == 4 && (Minecraft.getMinecraft().currentScreen == null || Minecraft.getMinecraft().currentScreen instanceof GuiDialog))
{
questTitle = params[1];
questTask = params[2].split("\\\\\\\\");
rewardText = params[3].split("\\\\\\\\");
for(int i = 0; i < rewardText.length; i++ )
{
if (rewardText[i].indexOf(' ') == -1)
{
try
{
int bits = Integer.parseInt(rewardText[i]);
rewardText[i] = LogicDialog.TranslateChatColor("&e" + bits + " &lBits");
}
catch(Exception e)
{}
}
else
{
try
{
String[] split = rewardText[i].split(" ");
int amount = Integer.parseInt(split[0]);
rewardText[i] = LogicDialog.TranslateChatColor("&e" + amount + " &f&n" + rewardText[i].substring(split[0].length() + 1));
}
catch(Exception e)
{}
}
}
Minecraft.getMinecraft().thePlayer.openGui(LoECraftPack.instance, GuiIds.QUEST.ordinal(), null, 0, 0, 0);
}
}
}
|
package graphics;
import static org.lwjgl.glfw.GLFW.GLFW_FALSE;
import static org.lwjgl.glfw.GLFW.GLFW_RESIZABLE;
import static org.lwjgl.glfw.GLFW.GLFW_TRUE;
import static org.lwjgl.glfw.GLFW.GLFW_VISIBLE;
import static org.lwjgl.glfw.GLFW.glfwCreateWindow;
import static org.lwjgl.glfw.GLFW.glfwDefaultWindowHints;
import static org.lwjgl.glfw.GLFW.glfwGetPrimaryMonitor;
import static org.lwjgl.glfw.GLFW.glfwGetVideoMode;
import static org.lwjgl.glfw.GLFW.glfwInit;
import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent;
import static org.lwjgl.glfw.GLFW.glfwSetWindowPos;
import static org.lwjgl.glfw.GLFW.glfwShowWindow;
import static org.lwjgl.glfw.GLFW.glfwSwapInterval;
import static org.lwjgl.glfw.GLFW.glfwWindowHint;
import static org.lwjgl.opengl.GL11.GL_BLEND;
import static org.lwjgl.opengl.GL11.GL_DEPTH_TEST;
import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA;
import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA;
import static org.lwjgl.opengl.GL11.GL_VERSION;
import static org.lwjgl.opengl.GL11.glBlendFunc;
import static org.lwjgl.opengl.GL11.glClearColor;
import static org.lwjgl.opengl.GL11.glEnable;
import static org.lwjgl.opengl.GL11.glGetString;
import static org.lwjgl.system.MemoryUtil.NULL;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
public class GraphicsUtils {
private GraphicsUtils() {
}
public static long createWindowOpenGl(int windowWidth, int windowHeight, String title) {
if (!glfwInit()) {
System.err.println("Could not initialize GLFW!");
return -1;
}
long window = setupWindow(windowWidth, windowHeight, title);
GL.createCapabilities(); //get opengl context
glClearColor(0.2f, 0.3f, 0.6f, 1.0f);
glEnable(GL_DEPTH_TEST);
//glActiveTexture(GL_TEXTURE1);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
System.out.println("OpenGL: " + glGetString(GL_VERSION));
glfwShowWindow(window);
return window;
}
private static long setupWindow(int width, int height, String title) {
glfwDefaultWindowHints(); // optional, the current window hints are already the default
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable
long window = glfwCreateWindow(width, height, title, NULL, NULL);
if (window == NULL) {
System.err.println("Could not create GLFW window!");
System.exit(-1);
return -1;
}
// Get the resolution of the primary monitor
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
// Center our window
glfwSetWindowPos(
window,
(vidmode.width() - width) / 2,
(vidmode.height() - height) / 2
);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);// Enable v-sync
return window;
}
}
|
package info.zhiqing.tinypiratebay.spider;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import info.zhiqing.tinypiratebay.entities.Torrent;
import info.zhiqing.tinypiratebay.entities.TorrentDetail;
import info.zhiqing.tinypiratebay.util.CategoryUtil;
import info.zhiqing.tinypiratebay.util.ConfigUtil;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
/**
* Created by zhiqing on 18-1-6.
*/
public class SpiderClient {
public static final String TAG = "SpiderClient";
private Spider spider;
private static SpiderClient instance;
public static SpiderClient getInstance() {
if (instance == null) {
instance = new SpiderClient(ConfigUtil.BASE_URL);
}
return instance;
}
public static void buildNewInstance() {
instance = new SpiderClient(ConfigUtil.BASE_URL);
}
private SpiderClient(String url) {
spider = new SpiderLocal(url);
}
public Observable<List<Torrent>> fetchTorrentsByUrl(final String url) {
return Observable.create(new ObservableOnSubscribe<List<Torrent>>() {
@Override
public void subscribe(ObservableEmitter<List<Torrent>> e) throws Exception {
List<Torrent> list = spider.list(url);
Log.d(TAG, "Get " + url + " : " + list.size());
if (!ConfigUtil.PORN_MODE) {
List<Torrent> newList = new ArrayList<>();
for (Torrent item : list) {
if (!CategoryUtil.parentCode(item.getTypeCode()).equals("500")) {
newList.add(item);
}
}
e.onNext(newList);
e.onComplete();
}
e.onNext(list);
e.onComplete();
}
});
}
public Observable<TorrentDetail> fetchTorrentDetail(final String code) {
return Observable.create(new ObservableOnSubscribe<TorrentDetail>() {
@Override
public void subscribe(ObservableEmitter<TorrentDetail> e) throws Exception {
TorrentDetail detail = spider.detail(code);
e.onNext(detail);
e.onComplete();
}
});
}
}
|
/*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
* See LICENSE in the project root for license information.
*/
package com.microsoft.office365.meetingfeedback.view;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import com.microsoft.office365.meetingfeedback.R;
import com.microsoft.office365.meetingfeedback.model.meeting.RatingData;
import com.microsoft.office365.meetingfeedback.model.webservice.payload.MeetingServiceResponseData;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class RatingsRecyclerViewAdapter extends RecyclerView.Adapter<RatingsRecyclerViewAdapter.RatingsViewHolder> {
private Context mContext;
private MeetingServiceResponseData mResponseData;
public RatingsRecyclerViewAdapter(Context context, MeetingServiceResponseData responseData) {
mContext = context;
mResponseData = responseData;
}
public List<RatingData> getRatings() {
if (mResponseData == null) {
return new ArrayList<>();
}
return mResponseData.mRatings;
}
@Override
public RatingsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.rating_view, parent, false);
return new RatingsViewHolder(view);
}
public RatingData getItem(int i) {
return getRatings().get(i);
}
@Override
public void onBindViewHolder(RatingsViewHolder holder, int position) {
RatingData item = getItem(position);
holder.mRatingBar.setRating(item.mRating);
DecimalFormat decimalFormat = new DecimalFormat("#.##");
holder.mRatingValue.setText(decimalFormat.format(item.mRating));
holder.mRatingComments.setText(item.getCommentString());
}
@Override
public int getItemCount() {
return getRatings().size();
}
public class RatingsViewHolder extends RecyclerView.ViewHolder {
RatingBar mRatingBar;
TextView mRatingValue;
TextView mRatingComments;
public RatingsViewHolder(View view) {
super(view);
mRatingBar = (RatingBar) view.findViewById(R.id.view_rating_rating_bar);
mRatingValue = (TextView) view.findViewById(R.id.view_rating_value);
mRatingComments = (TextView) view.findViewById(R.id.view_rating_description);
}
}
}
|
package gui;
import dao.ClienteDAO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import models.Cliente;
import validators.ClienteFormValidation;
public class MaisInformacoes extends javax.swing.JFrame {
private Cliente cliente;
private MenuPrincipal menuPrincipal;
private boolean isEditando;
public MaisInformacoes(Cliente cliente, MenuPrincipal menuPrincipal) {
initComponents();
this.cliente = cliente;
labelId.setText("ID: " + String.valueOf(cliente.getIdCliente()));
preencherCampos();
this.menuPrincipal = menuPrincipal;
isEditando = false;
ajustarCamposEdicao();
}
private void preencherCampos() {
campoNome.setText(cliente.getNome());
campoTelefone1.setText(cliente.getTelefone1());
campoTelefone2.setText(cliente.getTelefone2());
campoLogradouro.setText(cliente.getLogradouro());
campoNumero.setText(String.valueOf(cliente.getNumero()));
campoBairro.setText(cliente.getBairro());
campoCidade.setText(cliente.getCidade());
campoReferencia.setText(cliente.getReferencia());
}
private void ajustarCamposEdicao() {
labelCamposObrigatorios.setVisible(isEditando);
ast1.setVisible(isEditando);
ast2.setVisible(isEditando);
ast3.setVisible(isEditando);
ast4.setVisible(isEditando);
ast5.setVisible(isEditando);
ast6.setVisible(isEditando);
campoNome.setEnabled(isEditando);
campoTelefone1.setEnabled(isEditando);
campoTelefone2.setEnabled(isEditando);
campoLogradouro.setEnabled(isEditando);
campoNumero.setEnabled(isEditando);
campoBairro.setEnabled(isEditando);
campoCidade.setEnabled(isEditando);
campoReferencia.setEnabled(isEditando);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
labelId = new javax.swing.JLabel();
clientePanel = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
campoNome = new javax.swing.JTextField();
ast1 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
ast2 = new javax.swing.JLabel();
campoTelefone1 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
campoTelefone2 = new javax.swing.JTextField();
jSeparator1 = new javax.swing.JSeparator();
jLabel8 = new javax.swing.JLabel();
campoLogradouro = new javax.swing.JTextField();
ast3 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
ast4 = new javax.swing.JLabel();
campoNumero = new javax.swing.JTextField();
campoBairro = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
ast5 = new javax.swing.JLabel();
campoCidade = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
ast6 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
campoReferencia = new javax.swing.JTextField();
labelCamposObrigatorios = new javax.swing.JLabel();
botaoEditarInfo = new javax.swing.JButton();
botaoCancelarEdicao = new javax.swing.JButton();
botaoHistoricoEntregas = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Cliente");
setIconImage(new javax.swing.ImageIcon(getClass().getResource("/icons/motorcycle-48.png")).getImage());
setResizable(false);
labelId.setFont(new java.awt.Font("Noto Sans", 1, 18)); // NOI18N
labelId.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/customer-red.png"))); // NOI18N
labelId.setText("ID: 420");
clientePanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel3.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
jLabel3.setText("Nome:");
campoNome.setFont(new java.awt.Font("Noto Sans", 0, 14)); // NOI18N
campoNome.setName("nome"); // NOI18N
ast1.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
ast1.setForeground(new java.awt.Color(255, 47, 52));
ast1.setText("*");
jLabel5.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
jLabel5.setText("Telefone 1:");
ast2.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
ast2.setForeground(new java.awt.Color(255, 47, 52));
ast2.setText("*");
campoTelefone1.setFont(new java.awt.Font("Noto Sans", 0, 14)); // NOI18N
campoTelefone1.setName("telefone1"); // NOI18N
jLabel7.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
jLabel7.setText("Telefone 2:");
campoTelefone2.setFont(new java.awt.Font("Noto Sans", 0, 14)); // NOI18N
campoTelefone2.setName("telefone2"); // NOI18N
jLabel8.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
jLabel8.setText("Logradouro:");
campoLogradouro.setFont(new java.awt.Font("Noto Sans", 0, 14)); // NOI18N
campoLogradouro.setName("logradouro"); // NOI18N
ast3.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
ast3.setForeground(new java.awt.Color(255, 47, 52));
ast3.setText("*");
jLabel10.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
jLabel10.setText("Número:");
ast4.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
ast4.setForeground(new java.awt.Color(255, 47, 52));
ast4.setText("*");
campoNumero.setFont(new java.awt.Font("Noto Sans", 0, 14)); // NOI18N
campoNumero.setName("numero"); // NOI18N
campoBairro.setFont(new java.awt.Font("Noto Sans", 0, 14)); // NOI18N
campoBairro.setName("bairro"); // NOI18N
jLabel12.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
jLabel12.setText("Bairro:");
ast5.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
ast5.setForeground(new java.awt.Color(255, 47, 52));
ast5.setText("*");
campoCidade.setFont(new java.awt.Font("Noto Sans", 0, 14)); // NOI18N
campoCidade.setName("cidade"); // NOI18N
jLabel14.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
jLabel14.setText("Cidade:");
ast6.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
ast6.setForeground(new java.awt.Color(255, 47, 52));
ast6.setText("*");
jLabel16.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
jLabel16.setText("Referência:");
campoReferencia.setFont(new java.awt.Font("Noto Sans", 0, 14)); // NOI18N
campoReferencia.setName("referencia"); // NOI18N
javax.swing.GroupLayout clientePanelLayout = new javax.swing.GroupLayout(clientePanel);
clientePanel.setLayout(clientePanelLayout);
clientePanelLayout.setHorizontalGroup(
clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(clientePanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(campoReferencia)
.addGroup(clientePanelLayout.createSequentialGroup()
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(clientePanelLayout.createSequentialGroup()
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(campoNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(clientePanelLayout.createSequentialGroup()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ast4)))
.addGap(18, 18, 18)
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(campoBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(clientePanelLayout.createSequentialGroup()
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ast5)))
.addGap(18, 18, 18)
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(clientePanelLayout.createSequentialGroup()
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ast6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 145, Short.MAX_VALUE))
.addComponent(campoCidade)))
.addComponent(jSeparator1)
.addGroup(clientePanelLayout.createSequentialGroup()
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(clientePanelLayout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ast2))
.addComponent(campoTelefone1, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(clientePanelLayout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(campoTelefone2)))
.addComponent(campoLogradouro)
.addGroup(clientePanelLayout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ast1))
.addGroup(clientePanelLayout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ast3))
.addComponent(jLabel16)
.addComponent(campoNome))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
clientePanelLayout.setVerticalGroup(
clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(clientePanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(ast1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(clientePanelLayout.createSequentialGroup()
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(ast2)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(campoTelefone1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(clientePanelLayout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(campoTelefone2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 3, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(ast3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(campoLogradouro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(ast4)
.addComponent(jLabel12)
.addComponent(ast5)
.addComponent(jLabel14)
.addComponent(ast6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(clientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(campoNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(campoBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(campoCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(campoReferencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
labelCamposObrigatorios.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
labelCamposObrigatorios.setForeground(new java.awt.Color(255, 47, 52));
labelCamposObrigatorios.setText("* Campos obrigatórios");
botaoEditarInfo.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
botaoEditarInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/edit.png"))); // NOI18N
botaoEditarInfo.setText("Editar Informações");
botaoEditarInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botaoEditarInfoActionPerformed(evt);
}
});
botaoCancelarEdicao.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
botaoCancelarEdicao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/cancel.png"))); // NOI18N
botaoCancelarEdicao.setText("Cancelar Edição");
botaoCancelarEdicao.setEnabled(false);
botaoCancelarEdicao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botaoCancelarEdicaoActionPerformed(evt);
}
});
botaoHistoricoEntregas.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N
botaoHistoricoEntregas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/motorcycle-32.png"))); // NOI18N
botaoHistoricoEntregas.setText("Histórico de Entregas");
botaoHistoricoEntregas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botaoHistoricoEntregasActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelId)
.addGap(264, 264, 264)
.addComponent(labelCamposObrigatorios))
.addComponent(clientePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(botaoCancelarEdicao, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(botaoHistoricoEntregas)
.addComponent(botaoEditarInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(labelCamposObrigatorios)
.addComponent(labelId))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(botaoEditarInfo)
.addGap(18, 18, 18)
.addComponent(botaoCancelarEdicao)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(botaoHistoricoEntregas))
.addComponent(clientePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void botaoEditarInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoEditarInfoActionPerformed
if (isEditando) {
String[] options = {"SIM", "NÃO"};
int reply = JOptionPane.showOptionDialog(null, "Você realmente deseja salvar as alterações?", "Alterações",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (reply == 0 && new ClienteFormValidation(clientePanel).validate()) {
cliente.setNome(campoNome.getText().toUpperCase());
cliente.setTelefone1(campoTelefone1.getText());
cliente.setTelefone2(campoTelefone2.getText());
cliente.setLogradouro(campoLogradouro.getText().toUpperCase());
cliente.setNumero(Integer.parseInt(campoNumero.getText()));
cliente.setBairro(campoBairro.getText().toUpperCase());
cliente.setCidade(campoCidade.getText().toUpperCase());
cliente.setReferencia(campoReferencia.getText().toUpperCase());
ClienteDAO.updateCliente(cliente);
preencherCampos();
menuPrincipal.updateTabelaComBanco();
isEditando = false;
ajustarCamposEdicao();
botaoEditarInfo.setIcon(new ImageIcon(getClass().getResource("/icons/edit.png")));
botaoEditarInfo.setText("Editar Informações");
botaoCancelarEdicao.setEnabled(false);
botaoHistoricoEntregas.setEnabled(true);
}
} else {
isEditando = true;
ajustarCamposEdicao();
botaoEditarInfo.setIcon(new ImageIcon(getClass().getResource("/icons/save-alterations.png")));
botaoEditarInfo.setText("Salvar Alterações");
botaoCancelarEdicao.setEnabled(true);
botaoHistoricoEntregas.setEnabled(false);
}
}//GEN-LAST:event_botaoEditarInfoActionPerformed
private void botaoCancelarEdicaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCancelarEdicaoActionPerformed
isEditando = false;
preencherCampos();
ajustarCamposEdicao();
botaoEditarInfo.setIcon(new ImageIcon(getClass().getResource("/icons/edit.png")));
botaoEditarInfo.setText("Editar Informações");
botaoCancelarEdicao.setEnabled(false);
botaoHistoricoEntregas.setEnabled(true);
}//GEN-LAST:event_botaoCancelarEdicaoActionPerformed
private void botaoHistoricoEntregasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoHistoricoEntregasActionPerformed
new HistoricoEntregas(cliente).setVisible(true);
}//GEN-LAST:event_botaoHistoricoEntregasActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel ast1;
private javax.swing.JLabel ast2;
private javax.swing.JLabel ast3;
private javax.swing.JLabel ast4;
private javax.swing.JLabel ast5;
private javax.swing.JLabel ast6;
private javax.swing.JButton botaoCancelarEdicao;
private javax.swing.JButton botaoEditarInfo;
private javax.swing.JButton botaoHistoricoEntregas;
private javax.swing.JTextField campoBairro;
private javax.swing.JTextField campoCidade;
private javax.swing.JTextField campoLogradouro;
private javax.swing.JTextField campoNome;
private javax.swing.JTextField campoNumero;
private javax.swing.JTextField campoReferencia;
private javax.swing.JTextField campoTelefone1;
private javax.swing.JTextField campoTelefone2;
private javax.swing.JPanel clientePanel;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel labelCamposObrigatorios;
private javax.swing.JLabel labelId;
// End of variables declaration//GEN-END:variables
}
|
package Modele.Pracownicy;
public class Sprzedawca extends Pracownik {
public int IloscDniPoszukiwan;
public Sprzedawca(int StawkaMiesieczna, String imie, String nazwisko) {
super(StawkaMiesieczna, imie, nazwisko);
IloscDniPoszukiwan = 0;
}
public Sprzedawca() {
}
@Override
public Sprzedawca Kopiuj() {
return new Sprzedawca(StawkaMiesieczna, imie, nazwisko);
}
}
|
package com.crc.demo.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.crc.demo.model.Person;
import com.crcement.com.mystudydemo.R;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class BaseListViewActivity extends AppCompatActivity {
List<Person> p_list =new ArrayList<Person>();
@BindView(R.id.lv_person) ListView lv_person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_list_view);
ButterKnife.bind(this);
initdate();
lv_person.setAdapter(new MyAdapter());
}
//定义适配器
class MyAdapter extends BaseAdapter{
@Override
public int getCount() {
return p_list.size();
}
@Override
public Object getItem(int i) {
return p_list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view == null) {
view = View.inflate(BaseListViewActivity.this,R.layout.base_list_view_item,null);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
Person p=(Person)getItem(i);
//设置Item的值
viewHolder.tv_name.setText(p.getName());
viewHolder.tv_address.setText(p.getAdress());
viewHolder.tv_phone.setText(p.getPhone());
return view;
}
}
static class ViewHolder{
@BindView(R.id.tv_name) TextView tv_name;
@BindView(R.id.tv_address) TextView tv_address;
@BindView(R.id.tv_phone) TextView tv_phone;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
private void initdate() {
for(int i=0;i<30;i++){
p_list.add(new Person("admin"+i,"12345678901","中国广东深圳"));
}
}
}
|
package com.javawebtutor;
import java.util.concurrent.TimeUnit;
import com.javawebtutor.Entities.Dobavljac;
import com.javawebtutor.Entities.ProizvodiVeleprodaja;
public class DobavljacServiceImpl implements DobavljacService {
public Dobavljac d;
public void setDobavljac(Dobavljac dd)
{
d=dd;
}
public DobavljacServiceImpl(Dobavljac dd)
{
this.setDobavljac(dd);
}
@Override
public void dostavi(PorucivanjeServiceImpl ser, ProizvodiVeleprodaja pr)
{
System.out.println("Dobavljac dostavlja proizvod "+pr.getNazivProizvoda());
ser.dodajUBazu(pr);
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Proizvod je dostavljen");
}
}
|
/**
* MIT License
* <p>
* Copyright (c) 2019-2022 nerve.network
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package network.nerve.converter.heterogeneouschain.lib.helper;
import io.nuls.core.log.logback.NulsLogger;
import io.nuls.core.model.StringUtils;
import network.nerve.converter.enums.HeterogeneousChainTxType;
import network.nerve.converter.heterogeneouschain.lib.context.HtgConstant;
import network.nerve.converter.heterogeneouschain.lib.context.HtgContext;
import network.nerve.converter.heterogeneouschain.lib.core.HtgWalletApi;
import network.nerve.converter.heterogeneouschain.lib.listener.HtgListener;
import network.nerve.converter.heterogeneouschain.lib.management.BeanInitial;
import network.nerve.converter.heterogeneouschain.lib.model.HtgInput;
import network.nerve.converter.heterogeneouschain.lib.storage.HtgTxStorageService;
import network.nerve.converter.heterogeneouschain.lib.utils.HtgUtil;
import network.nerve.converter.model.bo.*;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.utils.Numeric;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author: Mimi
* @date: 2020-03-20
*/
public class HtgParseTxHelper implements BeanInitial {
private HtgERC20Helper htgERC20Helper;
private HtgTxStorageService htgTxStorageService;
private HtgWalletApi htgWalletApi;
private HtgListener htgListener;
private HtgContext htgContext;
private NulsLogger logger() {
return htgContext.logger();
}
public boolean isCompletedTransaction(String nerveTxHash) throws Exception {
return isCompletedTransactionByStatus(nerveTxHash, false);
}
public boolean isCompletedTransactionByLatest(String nerveTxHash) throws Exception {
return isCompletedTransactionByStatus(nerveTxHash, true);
}
private boolean isCompletedTransactionByStatus(String nerveTxHash, boolean latest) throws Exception {
Function isCompletedFunction = HtgUtil.getIsCompletedFunction(nerveTxHash);
List<Type> valueTypes = htgWalletApi.callViewFunction(htgContext.MULTY_SIGN_ADDRESS(), isCompletedFunction, latest);
if (valueTypes == null || valueTypes.size() == 0) {
return false;
}
boolean isCompleted = Boolean.parseBoolean(valueTypes.get(0).getValue().toString());
return isCompleted;
}
public boolean isMinterERC20(String erc20) throws Exception {
return isMinterERC20ByStatus(erc20, false);
}
public boolean isMinterERC20ByLatest(String erc20) throws Exception {
return isMinterERC20ByStatus(erc20, true);
}
private boolean isMinterERC20ByStatus(String erc20, boolean latest) throws Exception {
if (StringUtils.isBlank(erc20)) {
return true;
}
Function isMinterERC20Function = HtgUtil.getIsMinterERC20Function(erc20);
List<Type> valueTypes = htgWalletApi.callViewFunction(htgContext.MULTY_SIGN_ADDRESS(), isMinterERC20Function, latest);
boolean isMinterERC20 = Boolean.parseBoolean(valueTypes.get(0).getValue().toString());
return isMinterERC20;
}
/**
* 解析提现交易数据
*/
public HeterogeneousTransactionInfo parseWithdrawTransaction(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("解析交易的数据不存在或不完整");
return null;
}
String txHash = tx.getHash();
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isWithdraw;
if (tx.getInput().length() < 10) {
logger().warn("不是提现交易[0]");
return null;
}
String methodNameHash = tx.getInput().substring(0, 10);
// 提现交易的固定地址
if (htgListener.isListeningAddress(tx.getTo()) &&
HtgConstant.METHOD_HASH_CREATEORSIGNWITHDRAW.equals(methodNameHash)) {
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
// 解析交易收据
if (htgContext.getConverterCoreApi().isProtocol21()) {
// 协议v1.21
isWithdraw = this.newParseWithdrawTxReceiptSinceProtocol21(tx, txReceipt, txInfo);
} else if (htgContext.getConverterCoreApi().isSupportProtocol13NewValidationOfERC20()) {
// 协议v1.13
isWithdraw = this.newParseWithdrawTxReceipt(tx, txReceipt, txInfo);
} else {
isWithdraw = this.parseWithdrawTxReceipt(txReceipt, txInfo);
}
if (!isWithdraw) {
logger().warn("不是提现交易[1], hash: {}", txHash);
return null;
}
if (txInfo.isIfContractAsset()) {
htgERC20Helper.loadERC20(txInfo.getContractAddress(), txInfo);
}
} else {
logger().warn("不是提现交易[2], hash: {}, txTo: {}, methodNameHash: {}", txHash, tx.getTo(), methodNameHash);
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.WITHDRAW);
// 解析多签列表
this.loadSigners(txReceipt, txInfo);
return txInfo;
}
public HeterogeneousTransactionInfo parseWithdrawTransaction(Transaction tx) throws Exception {
return this.parseWithdrawTransaction(tx, null);
}
public HeterogeneousTransactionInfo parseWithdrawTransaction(String txHash) throws Exception {
Transaction tx = htgWalletApi.getTransactionByHash(txHash);
if (tx == null) {
logger().warn("交易不存在");
return null;
}
if (tx.getTo() == null) {
logger().warn("不是提现交易");
return null;
}
tx.setFrom(tx.getFrom().toLowerCase());
tx.setTo(tx.getTo().toLowerCase());
return this.parseWithdrawTransaction(tx, null);
}
/**
* 解析直接转账的方式的充值交易数据
*/
private HeterogeneousTransactionInfo parseDepositTransactionByTransferDirectly(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return null;
}
String txHash = tx.getHash();
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isDeposit = false;
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
do {
// HT充值交易的固定接收地址,金额大于0, 没有input
if (htgListener.isListeningAddress(tx.getTo()) &&
tx.getValue().compareTo(BigInteger.ZERO) > 0 &&
tx.getInput().equals(HtgConstant.HEX_PREFIX)) {
if(!this.validationEthDeposit(tx, txReceipt)) {
logger().error("[{}]不是充值交易[0]", txHash);
return null;
}
isDeposit = true;
txInfo.setDecimals(htgContext.getConfig().getDecimals());
txInfo.setAssetId(htgContext.HTG_ASSET_ID());
txInfo.setValue(tx.getValue());
txInfo.setIfContractAsset(false);
break;
}
// ERC20充值交易
if (htgERC20Helper.isERC20(tx.getTo(), txInfo)) {
if (htgERC20Helper.hasERC20WithListeningAddress(txReceipt, txInfo, address -> htgListener.isListeningAddress(address))) {
// 检查是否是NERVE资产绑定的ERC20,是则检查多签合约内是否已经注册此定制的ERC20,否则充值异常
if (htgContext.getConverterCoreApi().isBoundHeterogeneousAsset(htgContext.getConfig().getChainId(), txInfo.getAssetId())
&& !isMinterERC20(txInfo.getContractAddress())) {
logger().warn("[{}]不合法的{}网络的充值交易[6], ERC20[{}]已绑定NERVE资产,但合约内未注册", txHash, htgContext.getConfig().getSymbol(), txInfo.getContractAddress());
break;
}
isDeposit = true;
break;
}
}
} while (false);
if (!isDeposit) {
logger().error("[{}]不是充值交易[1]", txHash);
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.DEPOSIT);
return txInfo;
}
public BigInteger getTxHeight(NulsLogger logger, Transaction tx) throws Exception {
try {
if (tx == null) {
return null;
}
return tx.getBlockNumber();
} catch (Exception e) {
String txHash = tx.getHash();
logger.error("解析充值交易错误, 区块高度解析失败, 交易hash: {}, BlockNumberRaw: {}, BlockHash: {}", txHash, tx.getBlockNumberRaw(), tx.getBlockHash());
TransactionReceipt txReceipt = null;
try {
txReceipt = htgWalletApi.getTxReceipt(txHash);
return txReceipt.getBlockNumber();
} catch (Exception ex) {
if (txReceipt != null) {
logger.error("再次解析充值交易错误, 区块高度解析失败, 交易hash: {}, BlockNumberRaw: {}, BlockHash: {}", txHash, txReceipt.getBlockNumberRaw(), txReceipt.getBlockHash());
} else {
logger.error("再次解析充值交易错误, 区块高度解析失败, 交易hash: {}, empty txReceipt.", txHash);
}
throw ex;
}
}
}
public HeterogeneousTransactionInfo parseDepositTransaction(Transaction tx) throws Exception {
HtgInput htInput = this.parseInput(tx.getInput());
// 新的充值交易方式,调用多签合约的crossOut函数
if (htInput.isDepositTx()) {
HeterogeneousTransactionInfo po = new HeterogeneousTransactionInfo();
po.setTxHash(tx.getHash());
po.setBlockHeight(getTxHeight(logger(), tx).longValue());
boolean isDepositTx = this.validationEthDepositByCrossOut(tx, po);
if (!isDepositTx) {
return null;
}
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
return po;
}
// 新的充值交易方式II,调用多签合约的crossOutII函数
if (htInput.isDepositIITx()) {
HeterogeneousTransactionInfo po = new HeterogeneousTransactionInfo();
po.setTxHash(tx.getHash());
po.setBlockHeight(getTxHeight(logger(), tx).longValue());
boolean isDepositTx = this.validationEthDepositByCrossOutII(tx, null, po);
if (!isDepositTx) {
return null;
}
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
return po;
}
return this.parseDepositTransactionByTransferDirectly(tx, null);
}
public HeterogeneousTransactionInfo parseDepositTransaction(String txHash) throws Exception {
Transaction tx = htgWalletApi.getTransactionByHash(txHash);
if (tx == null) {
logger().warn("交易不存在");
return null;
}
if (tx.getTo() == null) {
logger().warn("不是充值交易");
return null;
}
tx.setFrom(tx.getFrom().toLowerCase());
tx.setTo(tx.getTo().toLowerCase());
return this.parseDepositTransaction(tx);
}
public boolean validationEthDeposit(Transaction tx) throws Exception {
return this.validationEthDeposit(tx, null);
}
private boolean validationEthDeposit(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
return false;
}
for (Log log : logs) {
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
continue;
}
String eventHash = topics.get(0);
if (!HtgConstant.EVENT_HASH_HT_DEPOSIT_FUNDS.equals(eventHash)) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_DEPOSIT_FUNDS);
if (depositEvent == null && depositEvent.size() != 2) {
return false;
}
String from = depositEvent.get(0).toString();
BigInteger amount = new BigInteger(depositEvent.get(1).toString());
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0) {
return true;
}
}
return false;
}
public boolean validationEthDepositByCrossOut(Transaction tx, HeterogeneousTransactionInfo po) throws Exception {
return this.validationEthDepositByCrossOut(tx, null, po);
}
private boolean validationEthDepositByCrossOut(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (htgContext.getConverterCoreApi().isProtocol22()) {
return newValidationEthDepositByCrossOutProtocol22(tx, txReceipt, po);
} else if (htgContext.getConverterCoreApi().isSupportProtocol13NewValidationOfERC20()) {
return newValidationEthDepositByCrossOut(tx, txReceipt, po);
} else {
return _validationEthDepositByCrossOut(tx, txReceipt, po);
}
}
private boolean _validationEthDepositByCrossOut(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
int logSize = logs.size();
if (logSize == 1) {
// HTG充值交易
Log log = logs.get(0);
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
logger().warn("交易[{}]log未知", txHash);
return false;
}
String eventHash = topics.get(0);
if (!HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
logger().warn("交易[{}]事件未知", txHash);
return false;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
}
return true;
}
} else {
// ERC20充值交易
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger actualAmount = _amount;
for (Log log : logs) {
List<String> topics = log.getTopics();
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
logger().warn("交易[{}]的ERC20地址不匹配", txHash);
return false;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
logger().warn("交易[{}]的销毁地址不匹配", txHash);
burnEvent = false;
break;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是用户地址
if (!fromAddress.equals(tx.getFrom())) {
logger().warn("交易[{}]的ERC20用户地址不匹配", txHash);
return false;
}
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
logger().warn("交易[{}]的ERC20充值地址不匹配", txHash);
return false;
}
// 是否支持转账即销毁部分的ERC20
if (htgContext.getConverterCoreApi().isSupportProtocol12ERC20OfTransferBurn()) {
if (amount.compareTo(_amount) > 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
actualAmount = amount;
} else {
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
}
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOut事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOut事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOut事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOut事件数据不合法[5]", txHash);
return false;
}
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (po != null && actualAmount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(actualAmount);
po.setNerveAddress(_to);
}
return true;
}
}
return false;
}
/**
* 解析管理员变更交易数据
*/
public HeterogeneousTransactionInfo parseManagerChangeTransaction(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return null;
}
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isChange = false;
String input, methodHash;
if (htgListener.isListeningAddress(tx.getTo()) && (input = tx.getInput()).length() >= 10) {
methodHash = input.substring(0, 10);
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNMANAGERCHANGE)) {
isChange = true;
List<Object> inputData = HtgUtil.parseInput(input, HtgConstant.INPUT_CHANGE);
List<Address> adds = (List<Address>) inputData.get(1);
List<Address> quits = (List<Address>) inputData.get(2);
if (!adds.isEmpty()) {
txInfo.setAddAddresses(HtgUtil.list2array(adds.stream().map(a -> a.getValue()).collect(Collectors.toList())));
}
if (!quits.isEmpty()) {
txInfo.setRemoveAddresses(HtgUtil.list2array(quits.stream().map(q -> q.getValue()).collect(Collectors.toList())));
}
}
}
if (!isChange) {
logger().warn("不是变更交易");
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.CHANGE);
// 解析多签列表
this.loadSigners(txReceipt, txInfo);
return txInfo;
}
/**
* 解析合约升级授权交易数据
*/
public HeterogeneousTransactionInfo parseUpgradeTransaction(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return null;
}
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isUpgrade = false;
String input, methodHash;
if (htgListener.isListeningAddress(tx.getTo()) && (input = tx.getInput()).length() >= 10) {
methodHash = input.substring(0, 10);
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNUPGRADE)) {
isUpgrade = true;
}
}
if (!isUpgrade) {
logger().warn("不是合约升级授权交易");
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.UPGRADE);
// 解析多签列表
this.loadSigners(txReceipt, txInfo);
return txInfo;
}
public List<HeterogeneousAddress> parseSigners(TransactionReceipt txReceipt, String txFrom) {
List<Object> eventResult = this.loadDataFromEvent(txReceipt);
if (eventResult == null || eventResult.isEmpty()) {
return null;
}
List<HeterogeneousAddress> signers = new ArrayList<>();
signers.add(new HeterogeneousAddress(htgContext.getConfig().getChainId(), txFrom));
return signers;
}
private void loadSigners(TransactionReceipt txReceipt, HeterogeneousTransactionInfo txInfo) {
List<Object> eventResult = this.loadDataFromEvent(txReceipt);
if (eventResult != null && !eventResult.isEmpty()) {
txInfo.setNerveTxHash(eventResult.get(eventResult.size() - 1).toString());
List<HeterogeneousAddress> signers = new ArrayList<>();
signers.add(new HeterogeneousAddress(htgContext.getConfig().getChainId(), txInfo.getFrom()));
txInfo.setSigners(signers);
}
}
private List<Object> loadDataFromEvent(TransactionReceipt txReceipt) {
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
return null;
}
Log signerLog = null;
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics != null && topics.size() > 0) {
String eventHash = topics.get(0);
if (HtgConstant.TRANSACTION_COMPLETED_TOPICS.contains(eventHash)) {
signerLog = log;
break;
}
}
}
if (signerLog == null) {
return null;
}
String eventHash = signerLog.getTopics().get(0);
//// Polygon链,存在erc20转账的合约交易中,会在末尾多出一个未知事件
//if (htgContext.getConfig().getChainId() == 106) {
// if (HtgConstant.EVENT_HASH_UNKNOWN_ON_POLYGON.equals(eventHash)) {
// log = logs.get(logs.size() - 2);
// topics = log.getTopics();
// eventHash = topics.get(0);
// }
//} else if (htgContext.getConfig().getChainId() == 122) {
// // REI链,存在erc20转账的合约交易中,会在末尾多出一个未知事件
// if (HtgConstant.EVENT_HASH_UNKNOWN_ON_REI.equals(eventHash)) {
// log = logs.get(logs.size() - 2);
// topics = log.getTopics();
// eventHash = topics.get(0);
// }
//}
// topics 解析事件名, 签名完成会触发的事件
// 解析事件数据,获得交易的成功事件数据列表
List<Object> eventResult = null;
switch (eventHash) {
case HtgConstant.EVENT_HASH_TRANSACTION_WITHDRAW_COMPLETED:
eventResult = HtgUtil.parseEvent(signerLog.getData(), HtgConstant.EVENT_TRANSACTION_WITHDRAW_COMPLETED);
break;
case HtgConstant.EVENT_HASH_TRANSACTION_MANAGER_CHANGE_COMPLETED:
eventResult = HtgUtil.parseEvent(signerLog.getData(), HtgConstant.EVENT_TRANSACTION_MANAGER_CHANGE_COMPLETED);
break;
case HtgConstant.EVENT_HASH_TRANSACTION_UPGRADE_COMPLETED:
eventResult = HtgUtil.parseEvent(signerLog.getData(), HtgConstant.EVENT_TRANSACTION_UPGRADE_COMPLETED);
break;
}
return eventResult;
}
private boolean parseWithdrawTxReceipt(TransactionReceipt txReceipt, HeterogeneousTransactionBaseInfo po) {
if (txReceipt == null || !txReceipt.isStatusOK()) {
return false;
}
List<Log> logs = txReceipt.getLogs();
if (logs != null && logs.size() > 0) {
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
// 为ERC20提现
if (topics.get(0).equals(HtgConstant.EVENT_HASH_ERC20_TRANSFER)) {
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, topics.get(1).length()).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
if (amount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(log.getAddress().toLowerCase());
po.setTo(toAddress.toLowerCase());
po.setValue(amount);
return true;
}
return false;
}
// 为HT提现
if (topics.get(0).equals(HtgConstant.EVENT_HASH_TRANSFERFUNDS)) {
String data = log.getData();
String to = HtgConstant.HEX_PREFIX + data.substring(26, 66);
String amountStr = data.substring(66, 130);
// 转账金额
BigInteger amount = new BigInteger(amountStr, 16);
if (amount.compareTo(BigInteger.ZERO) > 0) {
po.setTo(to.toLowerCase());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
return true;
}
return false;
}
}
}
return false;
}
public HtgInput parseInput(String input) {
if (input.length() < 10) {
return HtgInput.empty();
}
String methodHash;
if ((methodHash = input.substring(0, 10)).equals(HtgConstant.METHOD_HASH_CREATEORSIGNWITHDRAW)) {
return new HtgInput(true, HeterogeneousChainTxType.WITHDRAW, HtgUtil.parseInput(input, HtgConstant.INPUT_WITHDRAW).get(0).toString());
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNMANAGERCHANGE)) {
return new HtgInput(true, HeterogeneousChainTxType.CHANGE, HtgUtil.parseInput(input, HtgConstant.INPUT_CHANGE).get(0).toString());
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNUPGRADE)) {
return new HtgInput(true, HeterogeneousChainTxType.UPGRADE, HtgUtil.parseInput(input, HtgConstant.INPUT_UPGRADE).get(0).toString());
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CROSS_OUT)) {
return new HtgInput(true, HeterogeneousChainTxType.DEPOSIT);
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CROSS_OUT_II)) {
return new HtgInput(true);
}
return HtgInput.empty();
}
public HeterogeneousOneClickCrossChainData parseOneClickCrossChainData(String extend, NulsLogger logger) {
if(StringUtils.isBlank(extend)) {
return null;
}
extend = Numeric.prependHexPrefix(extend);
if(extend.length() < 10) {
return null;
}
String methodHash = extend.substring(0, 10);
if (!HtgConstant.METHOD_HASH_ONE_CLICK_CROSS_CHAIN.equals(methodHash)) {
return null;
}
extend = HtgConstant.HEX_PREFIX + extend.substring(10);
try {
List<Type> typeList = FunctionReturnDecoder.decode(extend, HtgConstant.INPUT_ONE_CLICK_CROSS_CHAIN);
if (typeList == null || typeList.isEmpty()) {
return null;
}
if (typeList.size() < 6) {
return null;
}
int index = 0;
List<Object> list = typeList.stream().map(type -> type.getValue()).collect(Collectors.toList());
BigInteger feeAmount = (BigInteger) list.get(index++);
int desChainId = ((BigInteger) list.get(index++)).intValue();
String desToAddress = (String) list.get(index++);
BigInteger tipping = (BigInteger) list.get(index++);
String tippingAddress = (String) list.get(index++);
String desExtend = Numeric.toHexString((byte[]) list.get(index++));
return new HeterogeneousOneClickCrossChainData(feeAmount, desChainId, desToAddress, tipping == null ? BigInteger.ZERO : tipping, tippingAddress, desExtend);
} catch (Exception e) {
logger.error(e);
return null;
}
}
public HeterogeneousAddFeeCrossChainData parseAddFeeCrossChainData(String extend, NulsLogger logger) {
if(StringUtils.isBlank(extend)) {
return null;
}
extend = Numeric.prependHexPrefix(extend);
if(extend.length() < 10) {
return null;
}
String methodHash = extend.substring(0, 10);
if (!HtgConstant.METHOD_HASH_ADD_FEE_CROSS_CHAIN.equals(methodHash)) {
return null;
}
extend = HtgConstant.HEX_PREFIX + extend.substring(10);
try {
List<Type> typeList = FunctionReturnDecoder.decode(extend, HtgConstant.INPUT_ADD_FEE_CROSS_CHAIN);
if (typeList == null || typeList.isEmpty()) {
return null;
}
if (typeList.size() < 2) {
return null;
}
int index = 0;
List<Object> list = typeList.stream().map(type -> type.getValue()).collect(Collectors.toList());
String nerveTxHash = (String) list.get(index++);
String subExtend = Numeric.toHexString((byte[]) list.get(index++));
return new HeterogeneousAddFeeCrossChainData(nerveTxHash, subExtend);
} catch (Exception e) {
logger.error(e);
return null;
}
}
private boolean newValidationEthDepositByCrossOutProtocol22(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (HtgConstant.ZERO_ADDRESS.equals(_erc20)) {
// 主资产充值交易
for (Log log : logs) {
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (!HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
continue;
}
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
}
return true;
}
}
logger().warn("交易[{}]的主资产[{}]充值事件不匹配", txHash, htgContext.getConfig().getSymbol());
return false;
} else {
// ERC20充值交易
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger actualAmount;
BigInteger calcAmount = BigInteger.ZERO;
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
continue;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的transfer事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
calcAmount = calcAmount.add(amount);
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOut事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOut事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOut事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOut事件数据不合法[5]", txHash);
return false;
}
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (calcAmount.compareTo(_amount) > 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
actualAmount = calcAmount;
if (actualAmount.equals(BigInteger.ZERO)) {
logger().warn("交易[{}]的ERC20充值金额为0", txHash);
return false;
}
if (po != null && actualAmount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(actualAmount);
po.setNerveAddress(_to);
}
return true;
} else {
logger().warn("交易[{}]的ERC20充值事件不匹配, transferEvent: {}, burnEvent: {}, crossOutEvent: {}",
txHash, transferEvent, burnEvent, crossOutEvent);
return false;
}
}
}
private boolean newValidationEthDepositByCrossOut(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (HtgConstant.ZERO_ADDRESS.equals(_erc20)) {
// 主资产充值交易
for (Log log : logs) {
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (!HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
continue;
}
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
}
return true;
}
}
logger().warn("交易[{}]的主资产[{}]充值事件不匹配", txHash, htgContext.getConfig().getSymbol());
return false;
} else {
// ERC20充值交易
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger actualAmount;
BigInteger calcAmount = BigInteger.ZERO;
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
continue;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的transfer事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
logger().warn("交易[{}]的销毁地址不匹配", txHash);
burnEvent = false;
break;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
calcAmount = calcAmount.add(amount);
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOut事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOut事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOut事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOut事件数据不合法[5]", txHash);
return false;
}
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (calcAmount.compareTo(_amount) > 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
actualAmount = calcAmount;
if (actualAmount.equals(BigInteger.ZERO)) {
logger().warn("交易[{}]的ERC20充值金额为0", txHash);
return false;
}
if (po != null && actualAmount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(actualAmount);
po.setNerveAddress(_to);
}
return true;
} else {
logger().warn("交易[{}]的ERC20充值事件不匹配, transferEvent: {}, burnEvent: {}, crossOutEvent: {}",
txHash, transferEvent, burnEvent, crossOutEvent);
return false;
}
}
}
private boolean newParseWithdrawTxReceipt(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionBaseInfo po) {
if (txReceipt == null || !txReceipt.isStatusOK()) {
return false;
}
String txHash = tx.getHash();
List<Object> withdrawInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_WITHDRAW);
String receive = withdrawInput.get(1).toString();
Boolean isERC20 = Boolean.parseBoolean(withdrawInput.get(3).toString());
String erc20 = withdrawInput.get(4).toString().toLowerCase();
boolean correctErc20 = false;
boolean correctMainAsset = false;
List<Log> logs = txReceipt.getLogs();
if (logs != null && logs.size() > 0) {
List<String> topics;
String eventHash;
String contract;
// 转账金额
BigInteger amount = BigInteger.ZERO;
for (Log log : logs) {
topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
eventHash = topics.get(0);
contract = log.getAddress().toLowerCase();
// 为ERC20提现
if (eventHash.equals(HtgConstant.EVENT_HASH_ERC20_TRANSFER)) {
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
if (isERC20 &&
contract.equalsIgnoreCase(erc20) &&
(fromAddress.equalsIgnoreCase(htgContext.MULTY_SIGN_ADDRESS()) || fromAddress.equalsIgnoreCase(HtgConstant.ZERO_ADDRESS))) {
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配", txHash);
return false;
}
correctErc20 = true;
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger _amount = new BigInteger(v[1], 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
// 为主资产提现
if (eventHash.equals(HtgConstant.EVENT_HASH_TRANSFERFUNDS)) {
if (isERC20 || !contract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
if (isERC20) {
logger().warn("提现交易[{}]的提现类型冲突[0]", txHash);
} else {
logger().warn("提现交易[{}]的多签合约地址不匹配", txHash);
}
return false;
}
correctMainAsset = true;
String data = log.getData();
String toAddress = HtgConstant.HEX_PREFIX + data.substring(26, 66);
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配[主资产提现]", txHash);
return false;
}
String amountStr = data.substring(66, 130);
// 转账金额
BigInteger _amount = new BigInteger(amountStr, 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
if (correctErc20 && correctMainAsset) {
logger().warn("提现交易[{}]的提现类型冲突[1]", txHash);
return false;
}
if (correctMainAsset) {
po.setTo(receive.toLowerCase());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
return true;
} else if (correctErc20) {
po.setIfContractAsset(true);
po.setContractAddress(erc20);
po.setTo(receive.toLowerCase());
po.setValue(amount);
return true;
}
}
logger().warn("提现交易[{}]解析数据缺失", txHash);
return false;
}
private boolean newParseWithdrawTxReceiptSinceProtocol21(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionBaseInfo po) {
if (txReceipt == null || !txReceipt.isStatusOK()) {
return false;
}
String txHash = tx.getHash();
List<Object> withdrawInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_WITHDRAW);
String receive = withdrawInput.get(1).toString();
Boolean isERC20 = Boolean.parseBoolean(withdrawInput.get(3).toString());
String erc20 = withdrawInput.get(4).toString().toLowerCase();
List<Log> logs = txReceipt.getLogs();
if (logs != null && logs.size() > 0) {
boolean correctErc20 = false;
boolean correctMainAsset = false;
boolean hasReceiveAddress = false;
List<String> topics;
String eventHash;
String contract;
// 转账金额
BigInteger amount = BigInteger.ZERO;
for (Log log : logs) {
topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
eventHash = topics.get(0);
contract = log.getAddress().toLowerCase();
// 为ERC20提现
if (eventHash.equals(HtgConstant.EVENT_HASH_ERC20_TRANSFER)) {
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length);
if (isERC20 &&
contract.equalsIgnoreCase(erc20) &&
(fromAddress.equalsIgnoreCase(htgContext.MULTY_SIGN_ADDRESS()) || fromAddress.equalsIgnoreCase(HtgConstant.ZERO_ADDRESS))) {
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length);
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配", txHash);
continue;
}
correctErc20 = true;
hasReceiveAddress = true;
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger _amount = new BigInteger(v[1], 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
// 为主资产提现
if (eventHash.equals(HtgConstant.EVENT_HASH_TRANSFERFUNDS)) {
if (isERC20 || !contract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
if (isERC20) {
logger().warn("提现交易[{}]的提现类型冲突[0]", txHash);
} else {
logger().warn("提现交易[{}]的多签合约地址不匹配", txHash);
}
return false;
}
String data = log.getData();
String toAddress = HtgConstant.HEX_PREFIX + data.substring(26, 66);
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配[主资产提现]", txHash);
return false;
}
correctMainAsset = true;
hasReceiveAddress = true;
String amountStr = data.substring(66, 130);
// 转账金额
BigInteger _amount = new BigInteger(amountStr, 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
if (!hasReceiveAddress) {
logger().warn("提现交易[{}]的接收地址不匹配", txHash);
return false;
}
if (correctErc20 && correctMainAsset) {
logger().warn("提现交易[{}]的提现类型冲突[1]", txHash);
return false;
}
if (correctMainAsset) {
po.setTo(receive.toLowerCase());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
return true;
} else if (correctErc20) {
po.setIfContractAsset(true);
po.setContractAddress(erc20);
po.setTo(receive.toLowerCase());
po.setValue(amount);
return true;
}
}
logger().warn("提现交易[{}]解析数据缺失", txHash);
return false;
}
public boolean validationEthDepositByCrossOutII(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT_II);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (HtgConstant.ZERO_ADDRESS.equals(_erc20)) {
// 主资产充值交易
for (Log log : logs) {
List<String> topics = log.getTopics();
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (!HtgConstant.EVENT_HASH_CROSS_OUT_II_FUNDS.equals(eventHash)) {
continue;
}
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_II_FUNDS);
if (depositEvent == null && depositEvent.size() != 6) {
logger().warn("交易[{}]CrossOutII事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
String erc20 = depositEvent.get(3).toString();
BigInteger ethAmount = new BigInteger(depositEvent.get(4).toString());
String extend = Numeric.toHexString((byte[]) depositEvent.get(5));
po.setDepositIIExtend(extend);
if (tx.getFrom().equals(from) && tx.getValue().compareTo(ethAmount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(ethAmount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
}
return true;
}
}
logger().warn("交易[{}]的主资产[{}]充值II事件不匹配", txHash, htgContext.getConfig().getSymbol());
return false;
} else {
// ERC20充值和主资产充值
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("CrossOutII: erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger erc20Amount = BigInteger.ZERO;
for (Log log : logs) {
List<String> topics = log.getTopics();
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
continue;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的transfer事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("CrossOutII: 交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
erc20Amount = erc20Amount.add(amount);
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_II_FUNDS.equals(eventHash)) {
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_II_FUNDS);
if (depositEvent == null && depositEvent.size() != 6) {
logger().warn("交易[{}]CrossOutII事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
BigInteger ethAmount = new BigInteger(depositEvent.get(4).toString());
String extend = Numeric.toHexString((byte[]) depositEvent.get(5));
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOutII事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOutII事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOutII事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOutII事件数据不合法[5]", txHash);
return false;
}
if (tx.getFrom().equals(from) && tx.getValue().compareTo(BigInteger.ZERO) > 0 && tx.getValue().compareTo(ethAmount) == 0) {
// 记录主资产充值
po.setDepositIIMainAsset(ethAmount, htgContext.getConfig().getDecimals(), htgContext.HTG_ASSET_ID());
}
po.setDepositIIExtend(extend);
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (erc20Amount.compareTo(_amount) > 0) {
logger().warn("CrossOutII: 交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
if (erc20Amount.equals(BigInteger.ZERO)) {
logger().warn("CrossOutII: 交易[{}]的ERC20充值金额为0", txHash);
return false;
}
if (po != null && erc20Amount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(erc20Amount);
po.setNerveAddress(_to);
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
}
return true;
} else {
logger().warn("交易[{}]的ERC20充值II事件不匹配, transferEvent: {}, burnEvent: {}, crossOutEvent: {}",
txHash, transferEvent, burnEvent, crossOutEvent);
return false;
}
}
}
}
|
package com.duanc.serivce.impl.web;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.duanc.api.web.ShopPageService;
import com.duanc.inner.common.BasePhoneToDTO;
import com.duanc.mapper.base.BrandMapper;
import com.duanc.mapper.base.ModelMapper;
import com.duanc.mapper.base.PhoneMapper;
import com.duanc.model.base.BaseModel;
import com.duanc.model.base.BaseModelExample;
import com.duanc.model.base.BasePhone;
import com.duanc.model.base.BasePhoneExample;
import com.duanc.model.base.BasePhoneExample.Criteria;
import com.duanc.model.dto.PhoneDTO;
@Service("shopPageService")
public class ShopPageServiceImpl implements ShopPageService {
@Autowired
private ModelMapper modelMapper;
@Autowired
private PhoneMapper phoneMapper;
@Autowired
private BrandMapper brandMapper;
@Override
public List<BaseModel> getModels() {
BaseModelExample example = new BaseModelExample();
return modelMapper.selectByExample(example);
}
@Override
public List<PhoneDTO> getPhones(Integer modelId, BigDecimal minPrice, BigDecimal maxPrice) {
BasePhoneExample example = new BasePhoneExample();
Criteria c = example.createCriteria();
if(modelId != null) {
c.andModelIdEqualTo(modelId);
}
if(minPrice != null && maxPrice != null) {
c.andPriceBetween(minPrice, maxPrice);
} else if(maxPrice != null && minPrice == null) {
c.andPriceLessThan(maxPrice);
/*c.andPriceBetween(new BigDecimal(0), maxPrice);*/
} else if(minPrice != null && maxPrice == null) {
c.andPriceGreaterThan(minPrice);
/*c.andPriceBetween(minPrice, new BigDecimal(100000000));*/
}
List<BasePhone> list = phoneMapper.selectByExample(example);
List<PhoneDTO> phones = new ArrayList<PhoneDTO>();
for (BasePhone basePhone : list) {
PhoneDTO phoneDTO = new BasePhoneToDTO().getPhoneDTO(basePhone,modelMapper,brandMapper);
phones.add(phoneDTO);
}
return phones;
}
}
|
package com.yeebar.aer;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import org.w3c.dom.Text;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegisterFragment extends Fragment {
private EditText register_edt_phone,register_edt_name,register_edt_email,register_edt_psw;
private Button register_commit_btn,register_back_btn,register_phoneVerified_btn;
private FragmentInterface mInterface;
public RegisterFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_register, container, false);
init(view);
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mInterface=(FragmentInterface)context;
}
catch (ClassCastException e)
{
throw new ClassCastException(context.toString()+" must implements FragmentInterface");
}
}
@Override
public void onDetach() {
super.onDetach();
}
public void init(View view)
{
btnOnClickListener myClickEvent=new btnOnClickListener();
// register_edt_phone=(EditText)view.findViewById(R.id.register_phone);
register_edt_name=(EditText)view.findViewById(R.id.register_name);
register_edt_email=(EditText)view.findViewById(R.id.register_email);
register_edt_psw=(EditText)view.findViewById(R.id.register_psw);
// register_back_btn=(Button)view.findViewById(R.id.register_back_btn);
register_commit_btn=(Button)view.findViewById(R.id.register_commit_btn);
// register_back_btn.setOnClickListener(myClickEvent);
register_commit_btn.setOnClickListener(myClickEvent);
}
public void commit_verified()
{
Map<String,String> map=new HashMap<String,String>();
// if(TextUtils.isEmpty(register_edt_phone.getText()))
// {
// map.put("err","手机号不能为空");
// mInterface.registerCommit(map,1);
// return;
// }
if(TextUtils.isEmpty(register_edt_name.getText()))
{
map.put("err","昵称不能为空");
mInterface.registerCommit(map,1);
return;
}
if(TextUtils.isEmpty(register_edt_email.getText()))
{
map.put("err","电子邮箱不能为空");
mInterface.registerCommit(map,1);
return;
}
if(TextUtils.isEmpty(register_edt_psw.getText()))
{
map.put("err","密码不能为空");
mInterface.registerCommit(map,1);
return;
}
// String phoneNO=register_edt_phone.getText().toString();
String email=register_edt_email.getText().toString();
String name=register_edt_name.getText().toString();
String psw=register_edt_psw.getText().toString();
String phoneNO=mInterface.getPhoneNO();
// if(!isMobileNumber(phoneNO))
// {
// map.put("err","手机号格式不正确");
// mInterface.registerCommit(map,1);
// return;
// }
if(!isEmail(email))
{
map.put("err","邮箱格式不正确");
mInterface.registerCommit(map,1);
return;
}
map.put("phoneNO",phoneNO);
map.put("email",email);
if(phoneNO!=null) {
map.put("phoneNO",phoneNO);
map.put("name",name);
map.put("psw",psw);
mInterface.registerCommit(map,0);
} else {
map.put("err","手机号码为空");
mInterface.registerCommit(map,1);
}
}
public static boolean isMobileNumber(String mobile)
{
Pattern p=Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
Matcher m=p.matcher(mobile);
return m.matches();
}
public static boolean isEmail(String email)
{
String regxString="^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern p = Pattern.compile(regxString);
Matcher m = p.matcher(email);
return m.matches();
}
class btnOnClickListener implements View.OnClickListener
{
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.register_commit_btn:
commit_verified();
break;
// case R.id.register_back_btn:
// mInterface.registerBack();
// break;
}
}
}
}
|
package com.najasoftware.fdv.model;
import java.io.Serializable;
/**
* Created by Lemoel on 09/03/2016.
* Update by Viny on 29/11/2016.
*/
@org.parceler.Parcel
public class Item implements Serializable {
private Long id;
private String nome;
private Pedido pedido;
private Produto produto;
private Double precoSugerido;
private Double desconto;
private Double qtde = Double.valueOf(1);
private Double totalComDesconto;
private Double totalSemDesconto;
private Double descontoPorcentagem;
public Pedido getPedido() {
return pedido;
}
public void setPedido(Pedido pedido) {
this.pedido = pedido;
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public Double getPrecoSugerido() {
return precoSugerido;
}
public void setPrecoSugerido(Double precoSugerido) {
this.precoSugerido = precoSugerido;
}
public Double getDesconto() {
return desconto;
}
public void setDesconto(Double desconto) {
this.desconto = desconto;
}
public Double getDescontoPorcentagem() {
return descontoPorcentagem;
}
public void setDescontoPorcentagem(Double descontoPorcentagem) {
this.descontoPorcentagem = descontoPorcentagem;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Double getQtde() {
return qtde;
}
public void setQtde(Double qtde) {
this.qtde = qtde;
}
public Double getTotalSemDesconto() {
return totalSemDesconto;
}
public void setTotalSemDesconto(Double totalSemDesconto) {
this.totalSemDesconto = totalSemDesconto;
}
public Double getTotalComDesconto() {
return totalComDesconto;
}
public void setTotalComDesconto(Double totalComDesconto) {
this.totalComDesconto = totalComDesconto;
}
}
|
package jadx.gui.ui;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import org.fife.ui.rsyntaxtextarea.LinkGenerator;
import org.fife.ui.rsyntaxtextarea.LinkGeneratorResult;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Token;
import org.fife.ui.rsyntaxtextarea.TokenTypes;
import org.fife.ui.rtextarea.SearchContext;
import org.fife.ui.rtextarea.SearchEngine;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.CodePosition;
import jadx.api.JavaNode;
import jadx.gui.settings.JadxSettings;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JNode;
import jadx.gui.utils.Position;
public final class CodeArea extends RSyntaxTextArea {
private static final Logger LOG = LoggerFactory.getLogger(CodeArea.class);
private static final long serialVersionUID = 6312736869579635796L;
private final CodePanel contentPanel;
private final JNode node;
CodeArea(CodePanel panel) {
this.contentPanel = panel;
this.node = panel.getNode();
setMarkOccurrences(true);
setEditable(false);
loadSettings();
Caret caret = getCaret();
if (caret instanceof DefaultCaret) {
((DefaultCaret) caret).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
}
caret.setVisible(true);
setSyntaxEditingStyle(node.getSyntaxName());
if (node instanceof JClass) {
setHyperlinksEnabled(true);
CodeLinkGenerator codeLinkProcessor = new CodeLinkGenerator((JClass) node);
setLinkGenerator(codeLinkProcessor);
addHyperlinkListener(codeLinkProcessor);
addMenuItems(this, (JClass) node);
}
registerWordHighlighter();
setText(node.getContent());
}
private void registerWordHighlighter() {
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() % 2 == 0 && !evt.isConsumed()) {
evt.consume();
String str = getSelectedText();
if (str != null) {
highlightAllMatches(str);
}
} else {
highlightAllMatches(null);
}
}
});
}
/**
* @param str - if null -> reset current highlights
*/
private void highlightAllMatches(@Nullable String str) {
SearchContext context = new SearchContext(str);
context.setMarkAll(true);
context.setMatchCase(true);
context.setWholeWord(true);
SearchEngine.markAll(this, context);
}
private void addMenuItems(CodeArea codeArea, JClass jCls) {
Action findUsage = new FindUsageAction(codeArea, jCls);
JPopupMenu popup = getPopupMenu();
popup.addSeparator();
popup.add(findUsage);
popup.addPopupMenuListener((PopupMenuListener) findUsage);
}
public void loadSettings() {
loadCommonSettings(contentPanel.getTabbedPane().getMainWindow(), this);
}
public static void loadCommonSettings(MainWindow mainWindow, RSyntaxTextArea area) {
area.setAntiAliasingEnabled(true);
mainWindow.getEditorTheme().apply(area);
JadxSettings settings = mainWindow.getSettings();
area.setFont(settings.getFont());
}
public static RSyntaxTextArea getDefaultArea(MainWindow mainWindow) {
RSyntaxTextArea area = new RSyntaxTextArea();
loadCommonSettings(mainWindow, area);
return area;
}
private boolean isJumpToken(Token token) {
if (token.getType() == TokenTypes.IDENTIFIER) {
// fast skip
if (token.length() == 1) {
char ch = token.getTextArray()[token.getTextOffset()];
if (ch == '.' || ch == ',' || ch == ';') {
return false;
}
}
if (node instanceof JClass) {
Position pos = getDefPosition((JClass) node, this, token.getOffset());
if (pos != null) {
// don't underline definition place
try {
int defLine = pos.getLine();
int lineOfOffset = getLineOfOffset(token.getOffset()) + 1;
if (defLine == lineOfOffset) {
return false;
}
} catch (BadLocationException e) {
return false;
}
return true;
}
}
}
return false;
}
// @Override
// public Color getForegroundForToken(Token t) {
// if (isJumpToken(t)) {
// return getHyperlinkForeground();
// }
// return super.getForegroundForToken(t);
// }
static Position getDefPosition(JClass jCls, RSyntaxTextArea textArea, int offset) {
JavaNode node = getJavaNodeAtOffset(jCls, textArea, offset);
if (node == null) {
return null;
}
CodePosition pos = jCls.getCls().getDefinitionPosition(node);
if (pos == null) {
return null;
}
return new Position(pos);
}
static JavaNode getJavaNodeAtOffset(JClass jCls, RSyntaxTextArea textArea, int offset) {
try {
int line = textArea.getLineOfOffset(offset);
int lineOffset = offset - textArea.getLineStartOffset(line);
return jCls.getCls().getJavaNodeAtPosition(line + 1, lineOffset + 1);
} catch (BadLocationException e) {
LOG.error("Can't get java node by offset", e);
}
return null;
}
public Position getCurrentPosition() {
return new Position(node, getCaretLineNumber() + 1);
}
Integer getSourceLine(int line) {
return node.getSourceLine(line);
}
void scrollToLine(int line) {
int lineNum = line - 1;
if (lineNum < 0) {
lineNum = 0;
}
setCaretAtLine(lineNum);
centerCurrentLine();
forceCurrentLineHighlightRepaint();
}
public void centerCurrentLine() {
JViewport viewport = (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, this);
if (viewport == null) {
return;
}
try {
Rectangle r = modelToView(getCaretPosition());
if (r == null) {
return;
}
int extentHeight = viewport.getExtentSize().height;
Dimension viewSize = viewport.getViewSize();
if (viewSize == null) {
return;
}
int viewHeight = viewSize.height;
int y = Math.max(0, r.y - extentHeight / 2);
y = Math.min(y, viewHeight - extentHeight);
viewport.setViewPosition(new Point(0, y));
} catch (BadLocationException e) {
LOG.debug("Can't center current line", e);
}
}
private void setCaretAtLine(int line) {
try {
setCaretPosition(getLineStartOffset(line));
} catch (BadLocationException e) {
LOG.debug("Can't scroll to {}", line, e);
}
}
private class FindUsageAction extends AbstractAction implements PopupMenuListener {
private static final long serialVersionUID = 4692546569977976384L;
private final transient CodeArea codeArea;
private final transient JClass jCls;
private transient JavaNode node;
public FindUsageAction(CodeArea codeArea, JClass jCls) {
super("Find Usage");
this.codeArea = codeArea;
this.jCls = jCls;
}
@Override
public void actionPerformed(ActionEvent e) {
if (node == null) {
return;
}
MainWindow mainWindow = contentPanel.getTabbedPane().getMainWindow();
JNode jNode = mainWindow.getCacheObject().getNodeCache().makeFrom(node);
UsageDialog usageDialog = new UsageDialog(mainWindow, jNode);
usageDialog.setVisible(true);
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
node = null;
Point pos = codeArea.getMousePosition();
if (pos != null) {
Token token = codeArea.viewToToken(pos);
if (token != null) {
node = getJavaNodeAtOffset(jCls, codeArea, token.getOffset());
}
}
setEnabled(node != null);
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
}
private class CodeLinkGenerator implements LinkGenerator, HyperlinkListener {
private final JClass jCls;
public CodeLinkGenerator(JClass cls) {
this.jCls = cls;
}
@Override
public LinkGeneratorResult isLinkAtOffset(RSyntaxTextArea textArea, int offset) {
try {
Token token = textArea.modelToToken(offset);
if (token == null) {
return null;
}
final int sourceOffset = token.getOffset();
final Position defPos = getDefPosition(jCls, textArea, sourceOffset);
if (defPos == null) {
return null;
}
return new LinkGeneratorResult() {
@Override
public HyperlinkEvent execute() {
return new HyperlinkEvent(defPos, HyperlinkEvent.EventType.ACTIVATED, null,
defPos.getNode().makeLongString());
}
@Override
public int getSourceOffset() {
return sourceOffset;
}
};
} catch (Exception e) {
LOG.error("isLinkAtOffset error", e);
return null;
}
}
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
Object obj = e.getSource();
if (obj instanceof Position) {
contentPanel.getTabbedPane().codeJump((Position) obj);
}
}
}
public static final class EditorTheme {
private final String name;
private final String path;
public EditorTheme(String name, String path) {
this.name = name;
this.path = path;
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
@Override
public String toString() {
return name;
}
}
public static EditorTheme[] getAllThemes() {
return new EditorTheme[]{
new EditorTheme("default", "/org/fife/ui/rsyntaxtextarea/themes/default.xml"),
new EditorTheme("eclipse", "/org/fife/ui/rsyntaxtextarea/themes/eclipse.xml"),
new EditorTheme("idea", "/org/fife/ui/rsyntaxtextarea/themes/idea.xml"),
new EditorTheme("vs", "/org/fife/ui/rsyntaxtextarea/themes/vs.xml"),
new EditorTheme("dark", "/org/fife/ui/rsyntaxtextarea/themes/dark.xml"),
new EditorTheme("monokai", "/org/fife/ui/rsyntaxtextarea/themes/monokai.xml")
};
}
}
|
package models;
import java.util.List;
public class Movie implements IModel{
private String name;
private String genre;
private String format;
private Integer year;
private String director;
private List<String> writers;
private List<String> stars;
public Movie(){}
public Movie(String name, String genre, String format, Integer year,
String director, List<String> writers, List<String> stars){
this.name = name;
this.genre = genre;
this.format = format;
this.year = year;
this.director = director;
this.writers = writers;
this.stars = stars;
}
public String getName() {
return name;
}
public void setName(String name) {
if(name == null) {
throw new IllegalArgumentException();
}
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
if(genre == null) {
throw new IllegalArgumentException();
}
this.genre = genre;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
if(format == null) {
throw new IllegalArgumentException();
}
this.format = format;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
if(year == null) {
throw new IllegalArgumentException();
}
this.year = year;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
if(director == null) {
throw new IllegalArgumentException();
}
this.director = director;
}
public List<String> getWriters() {
return writers;
}
public void setWriters(List<String> writers) {
if(writers == null) {
throw new IllegalArgumentException();
}
this.writers = writers;
}
public List<String> getStars() {
return stars;
}
public void setStars(List<String> stars) {
if(stars == null) {
throw new IllegalArgumentException();
}
this.stars = stars;
}
}
|
package org.gavrilov.domain;
import org.gavrilov.dto.CategoryDTO;
import org.gavrilov.dto.WorldDTO;
import org.gavrilov.mappers.CategoryMapper;
import org.gavrilov.mappers.MapperFactory;
import org.gavrilov.mappers.WorldMapper;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.persistence.Entity;
@Entity
@Table(name="world")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class World extends org.gavrilov.domain.Entity {
private final static WorldMapper mapperWorld = MapperFactory.createMapper(WorldMapper.class);
private final static CategoryMapper mapperCategory = MapperFactory.createMapper(CategoryMapper.class);
@Column(name = "value", nullable = false)
private String value;
@Column(name = "translation", nullable = false)
private String translation;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
public World() {
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getTranslation() {
return translation;
}
public void setTranslation(String translation) {
this.translation = translation;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public static WorldDTO getWorldDTO(World world) {
CategoryDTO categoryDTO = mapperCategory.asCategoryDTO(world.getCategory());
return mapperWorld.asWorldDTO(world);
}
}
|
package com.fanfte.netty.im.server.handler;
import com.fanfte.netty.im.packet.request.QuitGroupRequestPacket;
import com.fanfte.netty.im.packet.response.QuitGroupResponsePacket;
import com.fanfte.netty.im.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
/**
* Created by tianen on 2018/10/8
*
* @author fanfte
* @date 2018/10/8
**/
public class QuitGroupRequestHandler extends SimpleChannelInboundHandler<QuitGroupRequestPacket>{
@Override
protected void channelRead0(ChannelHandlerContext ctx, QuitGroupRequestPacket msg) throws Exception {
String groupId = msg.getGroupId();
ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);
channelGroup.remove(ctx.channel());
QuitGroupResponsePacket quitGroupResponsePacket = new QuitGroupResponsePacket();
quitGroupResponsePacket.setSuccess(true);
quitGroupResponsePacket.setGroupId(groupId);
ctx.channel().writeAndFlush(quitGroupResponsePacket);
}
}
|
/*Shuting Yang
* CST8110 section 340
* lab teacher name: Hubert Furey
* This program is to add, delete and get string in an array
* Assignment 4
* submission on December 2th 2018
*/
public class Assign4 {
public static void main(String[] args) {
boolean testSucceeds;
// Test that the default constructor works properly
testSucceeds=true;
SortedStringArray ssa = new SortedStringArray();
if(ssa.size()!=0)
{
System.err.println("Default constructor: initial size is wrong");
testSucceeds=false;
}
if(ssa.capacity()!=10)
{
System.err.println("Default constructor: initial capacity is wrong");
testSucceeds=false;
}
if(testSucceeds)
{
System.out.println("Default constructor: working correctly");
}
// Test that the initial constructor works properly
SortedStringArray ssa_r = new SortedStringArray(20);
if(ssa_r.size()!=0)
{
System.err.println("Default constructor: initial size is wrong");
testSucceeds=false;
}
if(ssa_r.capacity()!=20)
{
System.err.println("Default constructor: initial capacity is wrong");
testSucceeds=false;
}
if(testSucceeds)
{
System.out.println("Initial constructor: working correctly");
}
// Test that the add method works properly
ssa.add("c");
ssa.add("a");
ssa.add("b");
ssa.add("e");
ssa.add("c");
ssa.add("d");
ssa.add("d");
ssa.add("f");
ssa.add("j");
ssa.add("h");
ssa.add("g");
ssa.add("i");
String testArray[] =new String[] {"a","b","c","d","e","f","g","h","i","j"};
for(int i =0; i< ssa.size(); i++) {
if(!ssa.get(i).equals(testArray[i]) ) {
System.err.println("Add method is wrong");
testSucceeds=false;
break;
}
}
if(testSucceeds)
{
System.out.println("Add : working correctly");
}
// Test that the get method works properly
if(! ssa.get(ssa.size()).equals("ERROR") ) {
System.err.println("Get method is wrong");
}
if(!ssa.get(-1).equals("ERROR")) {
System.err.println("Get method is wrong");
}
if(testSucceeds)
{
System.out.println("Get: working correctly");
}
// Test that the getIndex method works properly
if (! (ssa.getIndex("s") == -1)) {
System.err.println("getIndex is wrong");
}
if (!(ssa.getIndex("a")==0)) {
System.err.println("getIndex is wrong");
}
if(testSucceeds)
{
System.out.println("getIndex: working correctly");
}
// Test that the delete method works properly
ssa.delete(0);
ssa.delete("b");
String testArray_r[] =new String[] {"c","d","e","f","g","h","i","j",null,null};
for(int i =0; i< ssa.size(); i++) {
if(!ssa.get(i).equals(testArray_r[i]) ) {
System.err.println("Add method is wrong");
testSucceeds=false;
break;
}
}
if(testSucceeds)
{
System.out.println("delete method: working correctly");
}
}
} |
package com.miyatu.tianshixiaobai.activities.mine.attention;
import android.view.View;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.miyatu.tianshixiaobai.R;
import com.miyatu.tianshixiaobai.activities.BaseFragment;
import com.miyatu.tianshixiaobai.adapter.AttentionServiceAdapter;
import com.miyatu.tianshixiaobai.entity.AttentionServiceEntity;
import java.util.ArrayList;
import java.util.List;
public class AttentionServiceFragment extends BaseFragment {
private RecyclerView recyclerView;
private List<AttentionServiceEntity> dataList;
private AttentionServiceAdapter adapter;
@Override
protected int getLayout() {
return R.layout.frag_attention_service;
}
@Override
protected void initView(View view) {
recyclerView = view.findViewById(R.id.recyclerView);
}
@Override
protected void initData() {
initAttentionService();
adapter = new AttentionServiceAdapter(getActivity(), dataList);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
}
@Override
protected void initEvent() {
}
@Override
protected void updateView() {
}
private void initAttentionService() {
dataList = new ArrayList<>();
AttentionServiceEntity entity = new AttentionServiceEntity();
entity.setPortrait(R.mipmap.attention_service_portrait1);
entity.setServicePhoto(R.mipmap.attention_serivce_photo1);
entity.setName("姓名1");
entity.setServiceName("服务名1");
entity.setServiceIntroduce("从业10年,熟悉流程,价格低,上门服务,上门服务!!");
entity.setPrice(1000);
entity.setSoldNumber(50);
dataList.add(entity);
entity = new AttentionServiceEntity();
entity.setPortrait(R.mipmap.attention_service_portrait2);
entity.setServicePhoto(R.mipmap.attention_service_photo2);
entity.setName("姓名2");
entity.setServiceName("服务名2");
entity.setServiceIntroduce("从业10年,熟悉流程,价格低,上门服务,上门服务!!");
entity.setPrice(2000);
entity.setSoldNumber(150);
dataList.add(entity);
entity = new AttentionServiceEntity();
entity.setPortrait(R.mipmap.attention_service_portrait1);
entity.setServicePhoto(R.mipmap.attention_serivce_photo1);
entity.setName("姓名3");
entity.setServiceName("服务名3");
entity.setServiceIntroduce("从业10年,熟悉流程,价格低,上门服务,上门服务!!");
entity.setPrice(3000);
entity.setSoldNumber(250);
dataList.add(entity);
entity = new AttentionServiceEntity();
entity.setPortrait(R.mipmap.attention_service_portrait1);
entity.setServicePhoto(R.mipmap.attention_serivce_photo1);
entity.setName("姓名4");
entity.setServiceName("服务名4");
entity.setServiceIntroduce("从业10年,熟悉流程,价格低,上门服务,上门服务!!");
entity.setPrice(4000);
entity.setSoldNumber(250);
dataList.add(entity);
entity = new AttentionServiceEntity();
entity.setPortrait(R.mipmap.attention_service_portrait1);
entity.setServicePhoto(R.mipmap.attention_serivce_photo1);
entity.setName("姓名5");
entity.setServiceName("服务名5");
entity.setServiceIntroduce("从业10年,熟悉流程,价格低,上门服务,上门服务!!");
entity.setPrice(4000);
entity.setSoldNumber(250);
dataList.add(entity);
}
}
|
import java.util.Random;
public class example32_06 {
public static void main(String[] args) {
System.out.println("Программа создает и инициализирует двумерный числовой массив, заполняет случайными числами \n"+"Из созданного массива удаляется строка и столбец, создается новый массив. \n"+"Индекс удаляемой строки и индекс удаляемого столбца определяется с помощью генератора случайных чисел.");
try {
int [][] array = new int [5][5]; //квадратная матрица
Random rnd=new Random();
int i ; // переменная задает число, необходимое для расчета количества строк
int j ; // переменная задает число, необходимое для расчета количества колонок
System.out.println("---------------------------------------------------------------");
//заполнение массива случайными числами от 0 до 200
System.out.println("Исходный массив (матрица 5 x 5), заполненный случайными числами от 0 до 200: ");
for (i = 0 ; i <array.length; ++i) {
for (j=0; j<array[i].length; ++j) {array[i][j]=rnd.nextInt(200); }
}
//вывод массива
for (i = 0 ; i <array.length; ++i) {
for (j=0; j<array[i].length; ++j) {System.out.printf("%5d", array[i][j]); }
System.out.println();
}
System.out.println("---------------------------------------------------------------");
int m=rnd.nextInt(5)+1; //индекс удаляемой строки - random от 0 до 4 работает
System.out.println("Индекс удаляемой строки: "+m);
int n=rnd.nextInt(5)+1; // индекс удаляемого столбца - random от 0 до 4 работает
System.out.println("Индекс удаляемого столбца: "+n);
System.out.println("---------------------------------------------------------------");
int [][] minor = new int [4][4]; //квадратная матрица - минор исходной
int im; //задание строк минора
int jm; //задание столбцов минора
for (i = 0, im=0 ; i <array.length; ++i) {
for (j=0, jm=0; j<array[i].length; ++j) {
if (j!=n-1 & i!=m-1) {minor[im][jm]=array[i][j]; ++jm; } //заполнение минора if удаляет столбец & контроль строки
}
if (i!=m-1) { ++im;} //if удаляет строку
}
//вывод минора
System.out.println("Преобразованный массив (матрица 4 x 4) - минор исходной матрицы: ");
for (im = 0 ; im <minor.length; ++im) {
for (jm=0; jm<minor[im].length; ++jm) {System.out.printf("%5d", minor[im][jm]); }
System.out.println();
}
}
catch (Exception error) {
System.out.println("При обработке данных произошла ошибка!"); //обработка исключения
}
}
} |
package by.htp.test02.main;
/* 2. Создйте класс Test2 двумя переменными.
*Добавьте конструктор с входными параметрами. Добавьте конструктор,
инициализирующий члены класса по умолчанию.
Добавьте set- и get- методы для полей экземпляра класса.
*/
public class Main {
public static void main(String[] args) {
Test2 t2 = new Test2(7, 3);
System.out.println(t2.getA() + " " + t2.getB());
Test2 t3 = new Test2();
System.out.println(t3.getA() + " " + t3.getB());
}
}
|
package br.com.mixfiscal.prodspedxnfe.domain.wsmix;
import java.io.Serializable;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
public class Produto implements Serializable {
private static final long serialVersionUID = -6620479549140089817L;
private String codigoProduto;
private String ean;
@SerializedName("pis_cofins")
private PisCofins pisCofins;
@SerializedName("icms_entrada")
private IcmsEntrada icmsEntrada;
@SerializedName("icms_saida")
private IcmsSaida icmsSaida;
public String getCodigoProduto() {
return codigoProduto;
}
public void setCodigoProduto(String codigoProduto) {
this.codigoProduto = codigoProduto;
}
public String getEan() {
return ean;
}
public void setEan(String ean) {
this.ean = ean;
}
public PisCofins getPisCofins() {
return pisCofins;
}
public void setPisCofins(PisCofins pisCofins) {
this.pisCofins = pisCofins;
}
public IcmsEntrada getIcmsEntrada() {
return icmsEntrada;
}
public void setIcmsEntrada(IcmsEntrada icmsEntrada) {
this.icmsEntrada = icmsEntrada;
}
public IcmsSaida getIcmsSaida() {
return icmsSaida;
}
public void setIcmsSaida(IcmsSaida icmsSaida) {
this.icmsSaida = icmsSaida;
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + Objects.hashCode(this.codigoProduto);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Produto other = (Produto) obj;
if (!Objects.equals(this.codigoProduto, other.codigoProduto)) {
return false;
}
if (!Objects.equals(this.ean, other.ean)) {
return false;
}
return true;
}
}
|
package com.accolite.au.services.impl;
import com.accolite.au.dto.BatchDTO;
import com.accolite.au.dto.CustomEntityNotFoundExceptionDTO;
import com.accolite.au.dto.SuccessResponseDTO;
import com.accolite.au.mappers.BatchMapper;
import com.accolite.au.models.Batch;
import com.accolite.au.repositories.BatchRepository;
import com.accolite.au.services.BatchService;
import com.accolite.au.utils.ObjectMergerUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BatchServiceImpl implements BatchService {
private final BatchRepository batchRepository;
private final BatchMapper batchMapper;
private final ObjectMergerUtil objectMergerUtil;
public BatchServiceImpl(BatchRepository batchRepository, BatchMapper batchMapper, ObjectMergerUtil objectMergerUtil) {
this.batchRepository = batchRepository;
this.batchMapper = batchMapper;
this.objectMergerUtil = objectMergerUtil;
}
@Override
public BatchDTO addBatch(BatchDTO batchDTO) {
Batch batch = batchMapper.toBatch(batchDTO);
return batchMapper.toBatchDTO(batchRepository.saveAndFlush(batch));
}
@Override
public List<BatchDTO> getAllBatches(){
List<Batch> batches = batchRepository.findAllByOrderByBatchName();
return batchMapper.toBatchDTOs(batches);
}
@Override
public BatchDTO getBatch(int batchId){
if(batchRepository.existsById(batchId) == false){
throw new CustomEntityNotFoundExceptionDTO("Batch with id : " + batchId + " not Found");
}
return batchMapper.toBatchDTO(batchRepository.getOne(batchId));
}
@Override
public SuccessResponseDTO deleteBatch(int batchId){
if(batchRepository.existsById(batchId)){
batchRepository.deleteById(batchId);
System.out.println("Done");
return new SuccessResponseDTO("Batch with id : " + batchId + " deleted Successfully", HttpStatus.OK);
}
throw new CustomEntityNotFoundExceptionDTO("Batch with id : " + batchId + " not Found");
}
@Override
public BatchDTO updateBatch(BatchDTO batchDTO) throws IllegalAccessException {
if(batchRepository.existsById(batchDTO.getBatchId())) {
BatchDTO updatedBatch = objectMergerUtil.merger(batchDTO, batchMapper.toBatchDTO(batchRepository.getOne(batchDTO.getBatchId())));
return batchMapper.toBatchDTO(batchRepository.saveAndFlush(batchMapper.toBatch(updatedBatch)));
}
throw new CustomEntityNotFoundExceptionDTO("Batch with id : " + batchDTO.getBatchId() + " not Found");
}
}
|
package domain;
import java.util.Collection;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Index;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.Valid;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.SafeHtml;
import org.hibernate.validator.constraints.SafeHtml.WhiteListType;
import datatype.Url;
@Entity
@Access(AccessType.PROPERTY)
@Table(indexes = {
@Index(columnList = "name")
})
public class Area extends DomainEntity {
private String name;
private Collection<Url> pictures;
@NotBlank
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
@NotEmpty
@ElementCollection(fetch = FetchType.EAGER)
@Valid
public Collection<Url> getPictures() {
return this.pictures;
}
public void setPictures(final Collection<Url> pictures) {
this.pictures = pictures;
}
//Relationships
private Chapter chapter;
@Valid
@OneToOne(optional = true)
public Chapter getChapter() {
return this.chapter;
}
public void setChapter(final Chapter chapter) {
this.chapter = chapter;
}
}
|
package com.SearchHouse.pojo;
import java.util.Set;
public class QualityRating {
private Integer qualityRatingId;// 信用编号
private String qualityRatingName;// 信用等级名称
private String qualityRatingInterval;// 信用等级区间
private Set<House> houses;
public Integer getQualityRatingId() {
return qualityRatingId;
}
public void setQualityRatingId(Integer qualityRatingId) {
this.qualityRatingId = qualityRatingId;
}
public String getQualityRatingName() {
return qualityRatingName;
}
public void setQualityRatingName(String qualityRatingName) {
this.qualityRatingName = qualityRatingName;
}
public Set<House> getHouses() {
return houses;
}
public void setHouses(Set<House> houses) {
this.houses = houses;
}
public String getQualityRatingInterval() {
return qualityRatingInterval;
}
public void setQualityRatingInterval(String qualityRatingInterval) {
this.qualityRatingInterval = qualityRatingInterval;
}
public QualityRating(Integer qualityRatingId, String qualityRatingName, Set<House> houses) {
super();
this.qualityRatingId = qualityRatingId;
this.qualityRatingName = qualityRatingName;
this.houses = houses;
}
public QualityRating(Integer qualityRatingId, String qualityRatingName, String qualityRatingInterval,
Set<House> houses) {
super();
this.qualityRatingId = qualityRatingId;
this.qualityRatingName = qualityRatingName;
this.qualityRatingInterval = qualityRatingInterval;
this.houses = houses;
}
public QualityRating() {
super();
}
@Override
public String toString() {
return "QualityRating [qualityRatingId=" + qualityRatingId + ", qualityRatingName=" + qualityRatingName
+ ", qualityRatingInterval=" + qualityRatingInterval + ", houses=" + houses + "]";
}
}
|
package egovframework.adm.cfg.mng.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import egovframework.adm.cfg.mng.dao.ManagerDAO;
import egovframework.adm.cfg.mng.service.ManagerService;
import egovframework.com.utl.fcc.service.EgovStringUtil;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
@Service("managerService")
public class ManagerServiceImpl extends EgovAbstractServiceImpl implements ManagerService{
@Resource(name="managerDAO")
private ManagerDAO managerDAO;
public List selectManagerList(Map<String, Object> commandMap) throws Exception{
return managerDAO.selectManagerList(commandMap);
}
public List selectGadminList(Map<String, Object> commandMap) throws Exception{
return managerDAO.selectGadminList(commandMap);
}
public Map selectManagerView(Map<String, Object> commandMap) throws Exception{
return managerDAO.selectManagerView(commandMap);
}
public List selectManagerViewGrcode(Map<String, Object> commandMap) throws Exception{
return managerDAO.selectManagerViewGrcode(commandMap);
}
public List selectManagerViewSubj(Map<String, Object> commandMap) throws Exception{
return managerDAO.selectManagerViewSubj(commandMap);
}
public List selectManagerViewComp(Map<String, Object> commandMap) throws Exception{
return managerDAO.selectManagerViewComp(commandMap);
}
public int updateManager(Map<String, Object> commandMap) throws Exception{
int isOk = 1;
try{
managerDAO.updateManagerInfo(commandMap);
commandMap.put("p_logmode", "U");
managerDAO.managerInsertLog(commandMap);
if(commandMap.get("p_gadminview") == null && commandMap.get("p_gadmin") != null){
commandMap.put("p_gadminview", commandMap.get("p_gadmin"));
}
if( commandMap.get("p_isneedgrcode") != null && ((String)commandMap.get("p_isneedgrcode")).equals("Y") ){
String[] v_grcode = EgovStringUtil.getStringSequence(commandMap, "p_grcode");
managerDAO.deleteGrcode(commandMap);
for( int i=0; i<v_grcode.length; i++ ){
commandMap.put("pp_grcode", v_grcode[i]);
managerDAO.insertGrcode(commandMap);
}
}
if( commandMap.get("p_isneedsubj") != null && ((String)commandMap.get("p_isneedsubj")).equals("Y") ){
String[] v_subj = EgovStringUtil.getStringSequence(commandMap, "p_subj");
managerDAO.deleteSubj(commandMap);
for( int i=0; i<v_subj.length; i++ ){
commandMap.put("pp_subj", v_subj[i]);
managerDAO.insertSubj(commandMap);
}
}
if( commandMap.get("p_isneedcomp") != null && ((String)commandMap.get("p_isneedcomp")).equals("Y") ){
String[] v_comp = EgovStringUtil.getStringSequence(commandMap, "p_comp");
managerDAO.deleteComp(commandMap);
for( int i=0; i<v_comp.length; i++ ){
commandMap.put("pp_comp", v_comp[i]);
managerDAO.insertComp(commandMap);
}
}
if( commandMap.get("p_isneeddept") != null && ((String)commandMap.get("p_isneeddept")).equals("Y") ){
String[] v_dept = EgovStringUtil.getStringSequence(commandMap, "p_dept");
managerDAO.deleteComp(commandMap);
for( int i=0; i<v_dept.length; i++ ){
commandMap.put("pp_comp", v_dept[i]);
managerDAO.insertComp(commandMap);
}
}
}catch(Exception ex){
isOk = 0;
ex.printStackTrace();
}
return isOk;
}
public List selectBranchList(Map<String, Object> commandMap) throws Exception{
return managerDAO.selectBranchList(commandMap);
}
public List getGadminSelectNop(Map<String, Object> commandMap) throws Exception{
return managerDAO.getGadminSelectNop(commandMap);
}
public int managerInsert(Map<String, Object> commandMap) throws Exception{
int isOk = 1;
try{
int cnt = managerDAO.checkManagerCount(commandMap);
if( cnt > 0 ){
isOk = -99;
}else{
managerDAO.managerInsert(commandMap);
commandMap.put("p_logmode", "I");
commandMap.put("p_gadmin", commandMap.get("p_gadminview"));
managerDAO.managerInsertLog(commandMap);
if( commandMap.get("p_isneedgrcode") != null && ((String)commandMap.get("p_isneedgrcode")).equals("Y") ){
String[] v_grcode = EgovStringUtil.getStringSequence(commandMap, "p_grcode");
for( int i=0; i<v_grcode.length; i++ ){
commandMap.put("pp_grcode", v_grcode[i]);
managerDAO.insertGrcode(commandMap);
}
}
if( commandMap.get("p_isneedsubj") != null && ((String)commandMap.get("p_isneedsubj")).equals("Y") ){
String[] v_subj = EgovStringUtil.getStringSequence(commandMap, "p_subj");
for( int i=0; i<v_subj.length; i++ ){
commandMap.put("pp_subj", v_subj[i]);
managerDAO.insertSubj(commandMap);
}
}
if( commandMap.get("p_isneedcomp") != null && ((String)commandMap.get("p_isneedcomp")).equals("Y") ){
String[] v_comp = EgovStringUtil.getStringSequence(commandMap, "p_comp");
for( int i=0; i<v_comp.length; i++ ){
commandMap.put("pp_comp", v_comp[i]);
managerDAO.insertComp(commandMap);
}
}
if( commandMap.get("p_isneeddept") != null && ((String)commandMap.get("p_isneeddept")).equals("Y") ){
String[] v_dept = EgovStringUtil.getStringSequence(commandMap, "p_dept");
for( int i=0; i<v_dept.length; i++ ){
commandMap.put("pp_comp", v_dept[i]);
managerDAO.insertComp(commandMap);
}
}
managerDAO.deleteMenuAuth(commandMap);
managerDAO.insertMenuAuth(commandMap);
}
}catch(Exception ex){
isOk = 0;
ex.printStackTrace();
}
return isOk;
}
public int managerDelete(Map<String, Object> commandMap) throws Exception{
int isOk = 1;
try{
managerDAO.deleteManager(commandMap);
managerDAO.deleteGrcode(commandMap);
managerDAO.deleteSubj(commandMap);
managerDAO.deleteComp(commandMap);
commandMap.put("p_logmode", "D");
managerDAO.managerInsertLog(commandMap);
}catch(Exception ex ){
isOk = 0;
ex.printStackTrace();
}
return isOk;
}
public int selectManagerLogTotCnt(Map<String, Object> commandMap) throws Exception{
return managerDAO.selectManagerLogTotCnt(commandMap);
}
public List selectManagerLogList(Map<String, Object> commandMap) throws Exception{
return managerDAO.selectManagerLogList(commandMap);
}
}
|
package com.luck.picture.lib.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import com.luck.picture.lib.R;
/**
* 来自 伍玉南 的装逼小尾巴 on 17/12/23.
* 用在图片编辑画笔颜色选择那里
*/
public class ColorDotView extends View{
private int width = 0;
private int height = 0;
private int radius = 0;
private int maxRadius = 0; //选中状态的半径
private int color = 0;
private Rect mRect;
private Paint mPaint;
public ColorDotView(Context context) {
this(context, null);
}
public ColorDotView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ColorDotView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
Drawable d = getBackground();
if(d instanceof ColorDrawable){
color = ((ColorDrawable) d).getColor();
}else{
color = context.getResources().getColor(R.color.color_4d);
}
setBackgroundColor(0);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
if(isSelected()){
mPaint.setColor(Color.parseColor("#ffffff"));
canvas.drawCircle(width / 2, width / 2, maxRadius, mPaint);
mPaint.setColor(color);
canvas.drawCircle(width / 2, width / 2, maxRadius - 5, mPaint);
}else{
mPaint.setColor(Color.parseColor("#ffffff"));
canvas.drawCircle(width / 2, width / 2, radius, mPaint);
mPaint.setColor(color);
canvas.drawCircle(width / 2, width / 2, radius - 5, mPaint);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
maxRadius = Math.min(width, height) / 2;
radius = maxRadius - 5;
if(mRect == null){
mRect = new Rect(0, 0, radius, radius);
}
}
public int getColor() {
return color;
}
}
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static void almostSorted(int[] arr) {
if(isSorted(arr))
{
System.out.println("yes");
}
int swap = -1;
for(int i = 0; i < arr.length - 1; i++)
{
if(arr[i] > arr[i + 1] && swap == -1)
{
if(i - 1 < 0 || arr[i + 1] > arr[i - 1])
{
swap = i;
}
else
{
swap = i + 1;
}
break;
}
}
int swap2;
for(swap2 = arr.length - 1; arr[swap2] > arr[swap]; swap2--);
int temp = arr[swap2];
arr[swap2] = arr[swap];
arr[swap] = temp;
if(!isSorted(arr))
{
temp = arr[swap2];
arr[swap2] = arr[swap];
arr[swap] = temp;
for(int i = 0; i <= (swap2 - swap)/2; i++)
{
temp = arr[swap2 - i];
arr[swap2 - i] = arr[swap + i];
arr[swap + i] = temp;
}
if(isSorted(arr))
{
System.out.println("yes");
System.out.println("reverse "+(swap + 1)+" "+(swap2 + 1));
}
else
{
System.out.println("no");
}
}
else
{
System.out.println("yes");
System.out.println("swap "+(swap + 1)+" "+(swap2 + 1));
}
}
static boolean isSorted(int[] arr)
{
for(int i = 0; i < arr.length - 1; i++)
{
if(arr[i] > arr[i + 1])
{
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int arr_i = 0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
almostSorted(arr);
in.close();
}
}
|
package com.gsccs.sme.plat.svg.dao;
import com.gsccs.sme.plat.svg.model.SvorgT;
import com.gsccs.sme.plat.svg.model.SvorgTExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface SvorgTMapper {
int countByExample(SvorgTExample example);
int deleteByExample(SvorgTExample example);
int deleteByPrimaryKey(Long id);
int insert(SvorgT record);
List<SvorgT> selectPageByExample(SvorgTExample example);
List<SvorgT> querySvgByItem(SvorgTExample example);
SvorgT selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") SvorgT record,
@Param("example") SvorgTExample example);
int updateByExampleWithBLOBs(@Param("record") SvorgT record,
@Param("example") SvorgTExample example);
int updateByExample(@Param("record") SvorgT record,
@Param("example") SvorgTExample example);
int updateByPrimaryKeySelective(SvorgT record);
int updateByPrimaryKeyWithBLOBs(SvorgT record);
int updateByPrimaryKey(SvorgT record);
} |
package com.bayestree.assesment.model;
import java.util.List;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class ItemsModel {
private List<Item> items;
}
|
package com.contus.keerthi.myapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import com.contus.keerthi.myapp.Pojo.Gallery;
import com.contus.keerthi.myapp.Custom.CustomGalleryAdapter;
import com.contus.keerthi.myapp.Custom.GetImages;
import java.util.ArrayList;
/**Fragment with recyclerview to show images
* Created by Keerthivasan on 20/2/17.
*/
public class GalleryFragment extends Fragment {
RecyclerView recyclerView;
ArrayList<Gallery> galleryArrayList;
GetImages getImages;
CustomGalleryAdapter customGalleryAdapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.gallery, container, false);
galleryArrayList = new ArrayList<Gallery>();
recyclerView = (RecyclerView) view.findViewById(R.id.gallery_recycler_view);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(layoutManager);
getImages = new GetImages(getActivity());
galleryArrayList = getImages.getImages();
customGalleryAdapter = new CustomGalleryAdapter(galleryArrayList, getActivity(), adapterInterface);
recyclerView.setAdapter(customGalleryAdapter);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
}
CustomGalleryAdapter.AdapterInterface adapterInterface = new CustomGalleryAdapter.AdapterInterface() {
@Override
public void fetchData(View view, int position) {
Gallery gallery = galleryArrayList.get(position);
Intent intent = new Intent(view.getContext(), ImageViewerActivity.class);
intent.putExtra("imgUrl", gallery.getImageUrl());
startActivity(intent);
}
};
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
}
} |
package com.syl.gateway.controller;
import com.syl.gateway.service.GatewayRouteService;
import com.syl.gateway.service.Impl.GatewayDynamicRouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/gateway")
public class GatewayRouteController {
@Autowired
private GatewayRouteService mGatewayRouteService;
@Autowired
private GatewayDynamicRouteService gatewayDynamicRouteService;
@PostMapping("add")
public String create(@RequestBody RouteDefinition entity){
int add = gatewayDynamicRouteService.add(entity);
return String.valueOf(add+"");
}
@PostMapping("/update")
public String update(@RequestBody RouteDefinition entity){
int result = gatewayDynamicRouteService.update(entity);
return String.valueOf(result);
}
@GetMapping("/delete")
public Mono<ResponseEntity<Object>> delete(String id){
return gatewayDynamicRouteService.delete(id);
}
@GetMapping("addGoods")
public String addGoods(){
RouteDefinition entity = new RouteDefinition();
entity.setId("goods");
entity.setUri(URI.create("lb://goods"));
entity.setOrder(0);
List<PredicateDefinition> predicates = new ArrayList<>();
PredicateDefinition pre = new PredicateDefinition();
pre.setName("Path");
Map map = new HashMap();
map.put("_genkey_0","/goods/*");
pre.setArgs(map);
predicates.add(pre);
entity.setPredicates(predicates);
List<FilterDefinition> filters = new ArrayList<>();
entity.setFilters(filters);
int add = gatewayDynamicRouteService.add(entity);
return String.valueOf(add+"");
}
@GetMapping("refresh")
public String RefreshRoute(){
mGatewayRouteService.RefreshRoute();
return "成功";
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.client;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* @author Arjen Poutsma
*/
public class ExtractingResponseErrorHandlerTests {
private ExtractingResponseErrorHandler errorHandler;
private final ClientHttpResponse response = mock();
@BeforeEach
public void setup() {
HttpMessageConverter<Object> converter = new MappingJackson2HttpMessageConverter();
this.errorHandler = new ExtractingResponseErrorHandler(
Collections.singletonList(converter));
this.errorHandler.setStatusMapping(
Collections.singletonMap(HttpStatus.I_AM_A_TEAPOT, MyRestClientException.class));
this.errorHandler.setSeriesMapping(Collections
.singletonMap(HttpStatus.Series.SERVER_ERROR, MyRestClientException.class));
}
@Test
public void hasError() throws Exception {
given(this.response.getStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT);
assertThat(this.errorHandler.hasError(this.response)).isTrue();
given(this.response.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(this.errorHandler.hasError(this.response)).isTrue();
given(this.response.getStatusCode()).willReturn(HttpStatus.OK);
assertThat(this.errorHandler.hasError(this.response)).isFalse();
}
@Test
public void hasErrorOverride() throws Exception {
this.errorHandler.setSeriesMapping(Collections
.singletonMap(HttpStatus.Series.CLIENT_ERROR, null));
given(this.response.getStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT);
assertThat(this.errorHandler.hasError(this.response)).isTrue();
given(this.response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND);
assertThat(this.errorHandler.hasError(this.response)).isFalse();
given(this.response.getStatusCode()).willReturn(HttpStatus.OK);
assertThat(this.errorHandler.hasError(this.response)).isFalse();
}
@Test
public void handleErrorStatusMatch() throws Exception {
given(this.response.getStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
assertThatExceptionOfType(MyRestClientException.class).isThrownBy(() ->
this.errorHandler.handleError(this.response))
.satisfies(ex -> assertThat(ex.getFoo()).isEqualTo("bar"));
}
@Test
public void handleErrorSeriesMatch() throws Exception {
given(this.response.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
assertThatExceptionOfType(MyRestClientException.class).isThrownBy(() ->
this.errorHandler.handleError(this.response))
.satisfies(ex -> assertThat(ex.getFoo()).isEqualTo("bar"));
}
@Test
public void handleNoMatch() throws Exception {
given(this.response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() ->
this.errorHandler.handleError(this.response))
.satisfies(ex -> {
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(ex.getResponseBodyAsByteArray()).isEqualTo(body);
});
}
@Test
public void handleNoMatchOverride() throws Exception {
this.errorHandler.setSeriesMapping(Collections
.singletonMap(HttpStatus.Series.CLIENT_ERROR, null));
given(this.response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
this.errorHandler.handleError(this.response);
}
@SuppressWarnings("serial")
private static class MyRestClientException extends RestClientException {
private String foo;
public MyRestClientException(String msg) {
super(msg);
}
public MyRestClientException(String msg, Throwable ex) {
super(msg, ex);
}
public String getFoo() {
return this.foo;
}
}
}
|
package com.tyj.venus.dao;
import com.tyj.venus.entity.Gadmin;
public interface GadminRepository extends BaseRepository<Gadmin,Integer> {
}
|
package com.fmi.decorator;
public class DecoratorDemo {
public static void main(final String[] args) {
final IShape shape = new Circle();
shape.draw();
final AShapeDecorator decorator = new RedShapeDecorator(shape);
decorator.draw();
}
}
|
package configuration;
public class FinalGrade {
public String finalGrade(String grade) {
String equi = "";
if(grade.equals("") || grade.equals("Not S"))
equi = "Not S";
else if(grade.equals("0"))
equi = "";
else if(grade.equals("I"))
equi = "INC";
else if(grade.equals("5.00"))
equi = "F";
else if(grade.equals("D"))
equi = "F";
else
equi = "P";
return equi;
}
}
|
package ac.yedam.prod;
import java.util.List;
public interface InOutService { // 입출고관리
// 입고
public void insertIOV(InOutVo iov);
// 출고
public void insertIOV1(InOutVo iov);
// 전체재고
public List<InOutVo> getIOVList();
}
|
package com.cheese.radio.ui.user.profile;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.binding.model.util.FileUtil;
import com.cheese.radio.base.cycle.BaseActivity;
import static com.cheese.radio.inject.component.ActivityComponent.Router.profile;
import static com.cheese.radio.ui.Constant.REQUEST_CAMERA;
import static com.cheese.radio.ui.Constant.REQUEST_PHOTO;
/**
* Created by 29283 on 2018/3/9.
*/
@Route(path = profile)
public class ProfileActivity extends BaseActivity<ProfileModel> {
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_CAMERA && resultCode == -1) {
vm.processePictures(null);
}
else if (requestCode ==REQUEST_PHOTO && resultCode == -1){
Uri uri = intent.getData();
String path = FileUtil.getRealPathFromURI(this, uri);
if (TextUtils.isEmpty(path)) path = FileUtil.getImageAbsolutePath(this, uri);
if (TextUtils.isEmpty(path)) return;
vm.processePictures(path);
}
if (intent == null) return;
}
public String getFileUriParent() {
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/test";
}
}
|
package jp.ac.kyushu_u.csce.modeltool.spec.preference;
import static jp.ac.kyushu_u.csce.modeltool.spec.constant.SpecPreferenceConstants.*;
import jp.ac.kyushu_u.csce.modeltool.dictionary.dialog.DictionaryViewerFilter;
import jp.ac.kyushu_u.csce.modeltool.spec.Messages;
import jp.ac.kyushu_u.csce.modeltool.spec.ModelToolSpecPlugin;
import jp.ac.kyushu_u.csce.modeltool.spec.constant.SpecConstants;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.ColorSelector;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
/**
* プリファレンスページ(仕様書エディタ設定)
*
* @author KBK yoshimura
*/
public class SpecPreferencePage
extends PreferencePage
implements IWorkbenchPreferencePage {
// 登録辞書
/** 既定辞書 ラジオボタン */
private Button rdoFixedDictionary;
/** 登録時選択 ラジオボタン */
private Button rdoSelectedDictionary;
/** アクティブ辞書 ラジオボタン */
private Button rdoActiveDictionary;
/** 既定辞書 入力フィールド */
private Text txtFixedDictionary;
/** 既定辞書 参照ボタン */
private Button btnFixedDictionary;
/** 折り返し */
private Button btnWordwrap;
/** 辞書ビューとのリンク */
private Button btnLink;
/** 辞書ビューとのリンク 背景色 */
private ColorSelector cslBackColor;
/** 辞書ビューとのリンク 前景色 */
private ColorSelector cslForeColor;
/** 辞書ビューとのリンク 背景色(副キーワード) */
private ColorSelector cslSubBackColor;
/** 辞書ビューとのリンク 前景色(副キーワード) */
private ColorSelector cslSubForeColor;
/** 辞書ビューとのリンク 背景色(活用形) */
private ColorSelector cslConjBackColor;
/** 辞書ビューとのリンク 前景色(活用形) */
private ColorSelector cslConjForeColor;
/**
* コンストラクタ
*/
public SpecPreferencePage() {
setPreferenceStore(ModelToolSpecPlugin.getDefault().getPreferenceStore());
setDescription(Messages.SpecPreferencePage_0);
}
/**
* コンテンツの作成
* @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns = 1;
composite.setLayout(layout);
GridData gd = new GridData(GridData.FILL_BOTH);
composite.setLayoutData(gd);
// 正規表現設定
btnWordwrap = new Button(composite, SWT.CHECK | SWT.LEFT);
btnWordwrap.setFont(parent.getFont());
btnWordwrap.setText(Messages.SpecPreferencePage_1);
// 辞書登録設定エリアの作成
createRegistrationArea(composite);
// 辞書ビューとのリンク
// btnLink = new Button(composite, SWT.CHECK | SWT.LEFT);
// btnLink.setFont(parent.getFont());
// btnLink.setText("辞書ビューで選択したキーワードを強調表示する。");
createLinkArea(composite);
// リスナーの設定
setListener();
// 初期値の設定
setInitialValue();
return composite;
}
/**
* 辞書登録設定エリアの作成
* @param control
* @return
*/
protected Control createRegistrationArea(Composite parent) {
// ラジオボタングループ(登録辞書の指定方法)
Group group = new Group(parent, SWT.NONE);
group.setText(Messages.SpecPreferencePage_2);
group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
GridLayout layout= new GridLayout();
layout = new GridLayout();
layout.numColumns = 3;
layout.verticalSpacing = 0;
group.setLayout(layout);
// ラジオボタン(既定辞書)
rdoFixedDictionary = new Button(group, SWT.RADIO);
rdoFixedDictionary.setText(Messages.SpecPreferencePage_3);
rdoFixedDictionary.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
// テキストボックス(既定辞書)
txtFixedDictionary = new Text(group, SWT.BORDER | SWT.READ_ONLY);
txtFixedDictionary.setBackground(Display.getCurrent().getSystemColor(
SWT.COLOR_LIST_BACKGROUND));
txtFixedDictionary.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
// ボタン(既定辞書 参照)
btnFixedDictionary = new Button(group, SWT.NONE);
btnFixedDictionary.setText(Messages.SpecPreferencePage_4);
btnFixedDictionary.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
Point buttonSize = btnFixedDictionary.computeSize(SWT.DEFAULT, SWT.DEFAULT);
// ラジオボタン(登録時指定)
rdoSelectedDictionary = new Button(group, SWT.RADIO);
rdoSelectedDictionary.setText(Messages.SpecPreferencePage_5);
GridData gd1 = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
gd1.heightHint = buttonSize.y;
rdoSelectedDictionary.setLayoutData(gd1);
// ラジオボタン(アクティブな辞書に登録)
rdoActiveDictionary = new Button(group, SWT.RADIO);
rdoActiveDictionary.setText(Messages.SpecPreferencePage_6);
GridData gd2 = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
gd2.heightHint = buttonSize.y;
rdoActiveDictionary.setLayoutData(gd2);
return group;
}
/**
* 辞書ビューリンク設定エリアの作成
* @param control
* @return
*/
protected Control createLinkArea(Composite parent) {
// ラジオボタングループ
Group group = new Group(parent, SWT.NONE);
group.setText(Messages.SpecPreferencePage_9);
group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
GridLayout layout= new GridLayout();
layout = new GridLayout();
layout.numColumns = 3;
layout.verticalSpacing = 0;
group.setLayout(layout);
// 辞書ビューとのリンク
btnLink = new Button(group, SWT.CHECK | SWT.LEFT);
btnLink.setFont(parent.getFont());
btnLink.setText(Messages.SpecPreferencePage_10);
GridData gdLink = new GridData();
gdLink.horizontalSpan = 3;
btnLink.setLayoutData(gdLink);
new Label(group, SWT.NONE).setText(""); //$NON-NLS-1$
new Label(group, SWT.NONE).setText(Messages.SpecPreferencePage_11);
new Label(group, SWT.NONE).setText(Messages.SpecPreferencePage_13);
// キーワード
Label lblBackColor = new Label(group, SWT.NONE);
lblBackColor.setText(Messages.SpecPreferencePage_14);
cslBackColor = new ColorSelector(group);
cslForeColor = new ColorSelector(group);
// 副キーワード
Label lblSubBackColor = new Label(group, SWT.NONE);
lblSubBackColor.setText(Messages.SpecPreferencePage_15);
cslSubBackColor = new ColorSelector(group);
cslSubForeColor = new ColorSelector(group);
// 活用形
Label lblConjBackColor = new Label(group, SWT.NONE);
lblConjBackColor.setText(Messages.SpecPreferencePage_16);
cslConjBackColor = new ColorSelector(group);
cslConjForeColor = new ColorSelector(group);
return group;
}
/**
* リスナー設定
*/
protected void setListener() {
// 既定辞書 参照ボタン
btnFixedDictionary.addSelectionListener(new DictionaryButtonListener());
// ラジオボタン
SelectionAdapter radioButtonListener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
txtFixedDictionary.setEnabled(rdoFixedDictionary.getSelection());
btnFixedDictionary.setEnabled(rdoFixedDictionary.getSelection());
// 妥当性チェック
checkState();
}
};
rdoFixedDictionary.addSelectionListener(radioButtonListener);
rdoSelectedDictionary.addSelectionListener(radioButtonListener);
rdoActiveDictionary.addSelectionListener(radioButtonListener);
}
/**
* 辞書選択ボタンリスナー
*
* @author KBK yoshimura
*/
private class DictionaryButtonListener extends SelectionAdapter {
/**
* コントロールが選択されたときの処理
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent e) {
// 辞書選択ダイアログ
ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
dialog.setTitle(Messages.SpecPreferencePage_7);
dialog.setMessage(Messages.SpecPreferencePage_8);
// フィルターの設定
dialog.addFilter(new DictionaryViewerFilter());
// 複数選択不可
dialog.setAllowMultiple(false);
// ヘルプ非表示
dialog.setHelpAvailable(false);
// ワークスペースのルートの配下を表示
dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
// 初期フォーカスの設定
if (txtFixedDictionary.getText().isEmpty() == false) {
IPath path = new Path(txtFixedDictionary.getText());
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
// IFile file = root.getFileForLocation(path);
IFile file = root.getFile(path);
dialog.setInitialSelection(file);
}
// バリデータの設定
dialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] selection) {
if (selection.length > 0 && selection[0] instanceof IFile) {
return new Status(IStatus.OK, ModelToolSpecPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
} else {
return new Status(IStatus.ERROR, ModelToolSpecPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
}
}
});
// ダイアログを開く
if (dialog.open() == Dialog.OK) {
// 結果をテキストボックスにセット
// txtFixedDictionary.setText(((IResource)dialog.getFirstResult()).getLocation().toString());
txtFixedDictionary.setText(((IResource)dialog.getFirstResult()).getFullPath().toString());
}
// 妥当性チェック
checkState();
}
}
/**
* 初期値の設定
*/
protected void setInitialValue() {
IPreferenceStore store = getPreferenceStore();
// プリファレンスの値より初期状態を設定
// 折り返し設定
btnWordwrap.setSelection(store.getBoolean(PK_SPECEDITOR_WORDWRAP));
// 登録辞書の指定方法
boolean fixed = false;
switch (store.getInt(PK_REGISTER_DICTIONARY)) {
case PV_REGISTER_FIXED:
fixed = true;
rdoFixedDictionary.setSelection(true);
txtFixedDictionary.setText(store.getString(PK_REGISTER_FIXED_PATH));
break;
case PV_REGISTER_SELECT:
rdoSelectedDictionary.setSelection(true);
break;
case PV_REGISTER_ACTIVE:
rdoActiveDictionary.setSelection(true);
break;
default:
break;
}
txtFixedDictionary.setEnabled(fixed);
btnFixedDictionary.setEnabled(fixed);
// 辞書ビューとのリンク
btnLink.setSelection(store.getBoolean(PK_LINK_DICTIONARY));
cslBackColor.setColorValue(
PreferenceConverter.getColor(store, PK_SPEC_HIGHLIGHT_BACKCOLOR));
cslForeColor.setColorValue(
PreferenceConverter.getColor(store, PK_SPEC_HIGHLIGHT_FORECOLOR));
cslSubBackColor.setColorValue(
PreferenceConverter.getColor(store, PK_SPEC_SUB_HIGHLIGHT_BACKCOLOR));
cslSubForeColor.setColorValue(
PreferenceConverter.getColor(store, PK_SPEC_SUB_HIGHLIGHT_FORECOLOR));
cslConjBackColor.setColorValue(
PreferenceConverter.getColor(store, PK_SPEC_CONJ_HIGHLIGHT_BACKCOLOR));
cslConjForeColor.setColorValue(
PreferenceConverter.getColor(store, PK_SPEC_CONJ_HIGHLIGHT_FORECOLOR));
// 妥当性チェック
checkState();
}
/**
* 妥当性チェック
*/
protected void checkState() {
boolean valid = true;
String msg = null;
if (rdoFixedDictionary.getSelection()) {
if ("".equals(txtFixedDictionary.getText())) { //$NON-NLS-1$
msg = Messages.SpecPreferencePage_12;
valid = false;
}
}
setErrorMessage(msg);
setValid(valid);
}
/**
* 初期化
*/
public void init(IWorkbench workbench) {
// プリファレンスストアのセット
setPreferenceStore(ModelToolSpecPlugin.getDefault().getPreferenceStore());
}
/**
* デフォルトボタン押下時の処理
* @see org.eclipse.jface.preference.PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore store = getPreferenceStore();
// プリファレンスの値より初期状態を設定
// 登録辞書の指定方法
switch (store.getDefaultInt(PK_REGISTER_DICTIONARY)) {
case PV_REGISTER_FIXED:
rdoFixedDictionary.setSelection(true);
txtFixedDictionary.setText(store.getDefaultString(PK_REGISTER_FIXED_PATH));
rdoSelectedDictionary.setSelection(false);
rdoActiveDictionary.setSelection(false);
break;
case PV_REGISTER_SELECT:
rdoSelectedDictionary.setSelection(true);
rdoFixedDictionary.setSelection(false);
rdoActiveDictionary.setSelection(false);
break;
case PV_REGISTER_ACTIVE:
rdoActiveDictionary.setSelection(true);
rdoFixedDictionary.setSelection(false);
rdoSelectedDictionary.setSelection(false);
break;
default:
break;
}
// コントロールの制御
txtFixedDictionary.setEnabled(rdoFixedDictionary.getSelection());
btnFixedDictionary.setEnabled(rdoFixedDictionary.getSelection());
// 辞書ビューとのリンク
btnLink.setSelection(store.getDefaultBoolean(PK_LINK_DICTIONARY));
cslBackColor.setColorValue(PreferenceConverter.getDefaultColor(store, PK_SPEC_HIGHLIGHT_BACKCOLOR));
cslForeColor.setColorValue(PreferenceConverter.getDefaultColor(store, PK_SPEC_HIGHLIGHT_FORECOLOR));
cslSubBackColor.setColorValue(PreferenceConverter.getDefaultColor(store, PK_SPEC_SUB_HIGHLIGHT_BACKCOLOR));
cslSubForeColor.setColorValue(PreferenceConverter.getDefaultColor(store, PK_SPEC_SUB_HIGHLIGHT_FORECOLOR));
cslConjBackColor.setColorValue(PreferenceConverter.getDefaultColor(store, PK_SPEC_CONJ_HIGHLIGHT_BACKCOLOR));
cslConjForeColor.setColorValue(PreferenceConverter.getDefaultColor(store, PK_SPEC_CONJ_HIGHLIGHT_FORECOLOR));
}
/**
* OKボタン押下時の処理
*/
public boolean performOk() {
IPreferenceStore store = getPreferenceStore();
// 折り返し設定
store.setValue(PK_SPECEDITOR_WORDWRAP, btnWordwrap.getSelection());
// 折り返しトグルボタンへの設定値の反映
ModelToolSpecPlugin.getHandlerActivationManager().changeToggleState(SpecConstants.COMMAND_ID_FOLDING,
btnWordwrap.getSelection());
// 登録辞書の指定方法
if (rdoFixedDictionary.getSelection()) {
store.setValue(PK_REGISTER_DICTIONARY, PV_REGISTER_FIXED);
store.setValue(PK_REGISTER_FIXED_PATH, txtFixedDictionary.getText());
} else if (rdoSelectedDictionary.getSelection()) {
store.setValue(PK_REGISTER_DICTIONARY, PV_REGISTER_SELECT);
store.setToDefault(PK_REGISTER_FIXED_PATH);
} else if (rdoActiveDictionary.getSelection()) {
store.setValue(PK_REGISTER_DICTIONARY, PV_REGISTER_ACTIVE);
store.setToDefault(PK_REGISTER_FIXED_PATH);
}
// 辞書ビューとのリンク
store.setValue(PK_LINK_DICTIONARY, btnLink.getSelection());
ModelToolSpecPlugin.getHandlerActivationManager().changeToggleState(SpecConstants.COMMAND_ID_LINK,
btnLink.getSelection());
PreferenceConverter.setValue(store, PK_SPEC_HIGHLIGHT_BACKCOLOR, cslBackColor.getColorValue());
PreferenceConverter.setValue(store, PK_SPEC_HIGHLIGHT_FORECOLOR, cslForeColor.getColorValue());
PreferenceConverter.setValue(store, PK_SPEC_SUB_HIGHLIGHT_BACKCOLOR, cslSubBackColor.getColorValue());
PreferenceConverter.setValue(store, PK_SPEC_SUB_HIGHLIGHT_FORECOLOR, cslSubForeColor.getColorValue());
PreferenceConverter.setValue(store, PK_SPEC_CONJ_HIGHLIGHT_BACKCOLOR, cslConjBackColor.getColorValue());
PreferenceConverter.setValue(store, PK_SPEC_CONJ_HIGHLIGHT_FORECOLOR, cslConjForeColor.getColorValue());
return true;
}
} |
package com.spreadtrum.android.eng;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MMCReceiver extends BroadcastReceiver {
private final String TAG = "MMCReceiver";
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
int i;
MmcInfo.setLastValueWhenBootComplete();
Log.i("TAG", MmcInfo.lastcrc.toString());
Log.i("TAG", MmcInfo.lastTimeout.toString());
for (i = 0; i < 8; i += 2) {
Log.i("MMCReceiver", ((Integer) MmcInfo.lastcrc.get(i / 2)).toString());
}
for (i = 1; i < 8; i += 2) {
Log.i("MMCReceiver", ((Integer) MmcInfo.lastTimeout.get(i / 2)).toString());
}
}
if (intent.getAction().equals("android.intent.action.ACTION_SHUTDOWN")) {
MmcInfo.getLastValue();
MmcInfo.saveValue();
}
}
}
|
package racingcar.domain;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CarTest {
private String carName = "pobi";
@Test
public void 자동차_생성_후_이름_확인() {
// when
Car car = new Car(carName);
// then
assertThat(car.getName()).isEqualTo(carName);
}
@Test
public void 전진_성공() {
// given
Car car = new Car(carName);
int value = Car.MOVE_THRESHOLD + 1;
// when
car.goWhenGreaterThanThreshold(value);
// then
assertThat(car.getMovedDistance()).isEqualTo(1);
}
@Test
public void 전진_실패() {
// given
Car car = new Car(carName);
int value = Car.MOVE_THRESHOLD;
// when
car.goWhenGreaterThanThreshold(value);
// then
assertThat(car.getMovedDistance()).isEqualTo(0);
}
@Test
public void copy_생성() {
// given
Car car = new Car(carName);
car.go();
// when
Car copy = car.copy();
// then
assertThat(copy.getName()).isEqualTo(carName);
assertThat(copy.getMovedDistance()).isEqualTo(1);
car.go();
assertThat(copy.getMovedDistance()).isEqualTo(1);
}
@Test
public void 초기화() {
// given
Car car = new Car(carName);
car.go();
// when
car.initialize();
// then
assertThat(car.getMovedDistance()).isEqualTo(0);
}
} |
package in.msmartpay.agent.dmr2Moneytrasfer;
public class BankListModel {
private String BankName;
private String BankCode;
public String getBankName() {
return BankName;
}
public void setBankName(String bankName) {
BankName = bankName;
}
public String getBankCode() {
return BankCode;
}
public void setBankCode(String bankCode) {
BankCode = bankCode;
}
} |
package com.scalefocus.java.dbconfig;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "sqliteEntityManagerFactory",
basePackages = {"com.scalefocus.java.repository.remote"},
transactionManagerRef = "sqliteTransactionManager"
)
public class RemoteConfig {
@Autowired
private Environment env;
@Autowired
@Qualifier("routerDb")
private DataSource dataSource;
@Bean(name = "sqliteEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em
= new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan(
"com.scalefocus.java.domain.remote");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect",
env.getProperty("remote.hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
@Bean(name = "sqliteTransactionManager")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
entityManagerFactory().getObject());
return transactionManager;
}
}
|
package ua.epam.provider.servlet.tariff;
import ua.epam.provider.dao.ServiceDao;
import ua.epam.provider.dao.TariffDao;
import ua.epam.provider.entity.Tariff;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/admin/update-tariff.do")
public class UpdateTariffAdminServlet extends HttpServlet {
private static final String FILE_DIR = "files";
private static final long serialVersionUID = 1L;
private ServiceDao serviceDao = new ServiceDao();
private TariffDao tariffDao = new TariffDao();
private Tariff oldTariff;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String title = request.getParameter("title");
Double priceByDay = Double.valueOf(request.getParameter("priceByDay"));
oldTariff = new TariffDao().getTariff(title);
request.getSession().setAttribute("title", title);
request.getSession().setAttribute("priceByDay", priceByDay);
request.getSession().setAttribute("oldTariff", oldTariff);
request.getRequestDispatcher("/WEB-INF/views/admin/update-tariff.jsp").forward(
request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String title = request.getParameter("newTitle");
Double priceByDay = Double.valueOf(request.getParameter("newPriceByDay"));
Tariff newTariff = new Tariff(priceByDay, title);
String oldTitle = (String) request.getSession().getAttribute("title");
if (!new TariffDao().isExistTariff(title)||(oldTitle.equals(title))) {
oldTariff = new TariffDao().getTariff(oldTitle);
tariffDao.updateTariff(oldTariff, newTariff);
request.getSession().removeAttribute("tariff");
response.sendRedirect("/admin/tariff-admin.do");
} else {
request.setAttribute("errorMessage", "Tariff with title " + title + " is already exists");
request.getRequestDispatcher("/WEB-INF/views/admin/update-tariff.jsp").forward(
request, response);
}
}
}
|
public class Validate {
public boolean passed() {
return true;
}
public boolean failed() {
return false;
}
}
|
package com.infnet.at.client;
import com.infnet.at.models.Produto;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class ProdutoClient {
public Produto buscarProdutoPorId(Long id) {
RestTemplate template = new RestTemplate();
return template.getForObject("http://localhost:8081/produtos/{id}", Produto.class, id);
}
}
|
package com.dev.darrell.musicfinder.activity;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.dev.darrell.musicfinder.R;
import com.dev.darrell.musicfinder.model.Track;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.picasso.Picasso;
import java.io.IOException;
public class TrackPlayer extends AppCompatActivity implements MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {
public static final String TRACK_EXTRA = "com.dev.darrell.musicfinder.activity.TrackPlayer";
private static final String TAG = "TrackPlayer";
private String mtrackTitle;
private String mArtistName;
private String mAlbumCover;
private String mTrackAudio;
private TextView mTvTrackName;
private ImageView mIvAlbumArt;
private SeekBar mSeekBar;
private FloatingActionButton mPauseNdPlay;
private FloatingActionButton mLoop;
private FloatingActionButton mStopPlayback;
private MediaPlayer mMediaPlayer = null;
private boolean mMediaPlayerPrepped;
private TextView mCurrentPosition;
private TextView mTrackDuration;
private int mFileDuration;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track_player);
Intent intent = getIntent();
Track currentTrack = intent.getParcelableExtra(TRACK_EXTRA);
mtrackTitle = currentTrack.getTitle();
mArtistName = currentTrack.getArtist();
mAlbumCover = currentTrack.getAlbumCover();
mTrackAudio = currentTrack.getPreviewLink().toString();
mTvTrackName = findViewById(R.id.tv_track_playing);
mIvAlbumArt = findViewById(R.id.img_album_playing);
mSeekBar = findViewById(R.id.duration_seekbar);
mPauseNdPlay = findViewById(R.id.fab_pause_play);
mLoop = findViewById(R.id.fab_loop);
mStopPlayback = findViewById(R.id.fab_stop_playback);
mCurrentPosition = findViewById(R.id.track_current_position);
mTrackDuration = findViewById(R.id.track_duration);
LoadLayoutItems();
}
private void LoadLayoutItems() {
Log.d(TAG, "LoadLayoutItems: Loading track name and cover");
mTvTrackName.setText(mtrackTitle);
Picasso.get().load(mAlbumCover)
.fit()
.placeholder(R.drawable.sharp_headset_black_18dp)
.error(R.drawable.sharp_headset_black_18dp)
.into(mIvAlbumArt);
createMediaPlayer();
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mMediaPlayer != null && fromUser) {
mMediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
// mMediaPlayer.seekTo(seekBar.getProgress());
// }
}
});
}
private void createMediaPlayer() {
// TODO: Set seekbar up to show playback progress and seek through songs.
Log.d(TAG, "createMediaPlayer: creating media player instance");
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
try {
mMediaPlayer.setDataSource(mTrackAudio);
} catch (IOException e) {
Log.d(TAG, "createMediaPlayer: Data source error =" + e.toString());
e.printStackTrace();
}
mMediaPlayer.setOnErrorListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.prepareAsync();
}
@Override
public void onPrepared(final MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared: Media player in prepared state");
Toast toast = Toast.makeText(this, "MediaPlayer Kullanima Hazir", Toast.LENGTH_LONG);
toast.show();
mMediaPlayerPrepped = true;
mFileDuration = mMediaPlayer.getDuration();
getDurationTimer();
mSeekBar.setMax(mFileDuration);
mediaPlayer.start();
mPauseNdPlay.setImageResource(R.drawable.ic_pause_media);
mHandler = new Handler();
this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mMediaPlayer != null) {
int currentPosition = mMediaPlayer.getCurrentPosition();
mSeekBar.setProgress(currentPosition);
final long minutes = (currentPosition / 1000) / 60;
final int seconds = (int) ((currentPosition / 1000) % 60);
mCurrentPosition.setText(minutes + ":" + seconds);
}
mHandler.postDelayed(this, 1000);
}
});
mPauseNdPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
mPauseNdPlay.setImageResource(R.drawable.ic_play_media);
} else if (mMediaPlayer == null) {
createMediaPlayer();
} else {
mediaPlayer.start();
mPauseNdPlay.setImageResource(R.drawable.ic_pause_media);
}
}
});
mLoop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!mediaPlayer.isLooping()) {
mediaPlayer.setLooping(true);
mLoop.setFocusable(true);
} else {
mediaPlayer.setLooping(false);
mLoop.setSelected(false);
}
}
});
mStopPlayback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPauseNdPlay.setImageResource(R.drawable.ic_play_media);
mediaPlayer.stop();
}
});
}
// end of onPrepare method
public void getDurationTimer() {
final long minutes = (mFileDuration / 1000) / 60;
final int seconds = (int) ((mFileDuration / 1000) % 60);
mTrackDuration.setText(minutes + ":" + seconds);
}
// public void getCurrentTimer(){
//
// }
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mPauseNdPlay.setImageResource(R.drawable.ic_play_media);
}
@Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
@Override
public void onBackPressed() {
mMediaPlayer.release();
mMediaPlayer = null;
super.onBackPressed();
}
} |
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Create a Scanner
Scanner input = new Scanner(System.in);
//user enters 3 numbers
System.out.print("Enter 3 numbers: ");
// JA: These numbers are supposed to be generated randomly
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
//asks user the sum of their numbers
System.out.print("What is " + num1 + " + " + num2 + " + " + num3 + "? ");
int answer = input.nextInt();
//says if their answer is true or false
System.out.print(num1 + " + " + num2 + " + " + num3 + " = " + answer
+ " is " + (num1 + num2 + num3 == answer));
}
}
|
import exceptions.NoSuchAgeException;
import javafx.beans.property.SimpleBooleanProperty;
/**
* Class represents a person
* @author Duc Minh Le (s3651764)
*/
public class Person {
public final String name;
public final String photo;
public final String status;
public final boolean gender;
public final int age;
public final String state;
// Field for JavaFX to determine if the person is currently selected
public final SimpleBooleanProperty selected = new SimpleBooleanProperty(false);
public Person(String name, String photo, String status, boolean gender, int age, String state) {
if (age < 0 || age > 150) {
throw new NoSuchAgeException("Age must be a positive number up to 150");
}
this.name = name;
this.photo = photo;
this.status = status;
this.gender = gender;
this.age = age;
this.state = state;
}
public boolean isAdult() {
return age > 16;
}
public boolean isChild() {
return age >= 3 && age <= 16;
}
public boolean isYoungChild() {
return age < 3;
}
public String getGenderText() {
return gender? "Female" : "Male";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return name.equals(person.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", photo='" + photo + '\'' +
", status='" + status + '\'' +
", genderToggleGroup=" + gender +
", age=" + age +
", state='" + state + '\'' +
'}';
}
}
|
package pl.dkiszka.bank.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author Dominik Kiszka {dominikk19}
* @project bank-application
* @date 21.04.2021
*/
@AllArgsConstructor
@Getter
public class BaseResponse {
private String message;
}
|
package algo3.fiuba.modelo.cartas.efectos;
import algo3.fiuba.modelo.Juego;
import algo3.fiuba.modelo.cartas.Carta;
public class EfectoNulo extends EfectoCarta {
@Override
public void activar(Carta carta) {
}
}
|
/**
* Copyright 2014 Bill McDowell
*
* This file is part of theMess (https://github.com/forkunited/theMess)
*
* 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 ark.data.annotation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import ark.data.annotation.nlp.ConstituencyParse;
import ark.data.annotation.nlp.DependencyParse;
import ark.data.annotation.nlp.PoSTag;
import ark.model.annotator.nlp.NLPAnnotator;
/**
* DocumentInMemory represents a text document with various
* NLP annotations (e.g. PoS tags, parses, etc) kept in
* memory.
*
* @author Bill McDowell
*
*/
public class DocumentInMemory extends Document {
protected String[][] tokens;
protected PoSTag[][] posTags;
protected DependencyParse[] dependencyParses;
protected ConstituencyParse[] constituencyParses;
public DocumentInMemory() {
}
public DocumentInMemory(JSONObject json) {
super(json);
}
public DocumentInMemory(String jsonPath) {
super(jsonPath);
}
public DocumentInMemory(String name, String text, Language language, NLPAnnotator annotator) {
this.name = name;
this.language = language;
this.nlpAnnotator = annotator.toString();
annotator.setLanguage(language);
annotator.setText(text);
this.tokens = annotator.makeTokens();
this.dependencyParses = annotator.makeDependencyParses(this, 0);
this.constituencyParses = annotator.makeConstituencyParses(this, 0);
this.posTags = annotator.makePoSTags();
}
public DocumentInMemory(String name, String[] sentences, Language language, NLPAnnotator annotator) {
this.name = name;
this.language = language;
this.nlpAnnotator = annotator.toString();
this.dependencyParses = new DependencyParse[sentences.length];
this.constituencyParses = new ConstituencyParse[sentences.length];
this.tokens = new String[sentences.length][];
this.posTags = new PoSTag[sentences.length][];
annotator.setLanguage(language);
for (int i = 0; i < sentences.length; i++) {
annotator.setText(sentences[i]);
String[][] sentenceTokens = annotator.makeTokens();
if (sentenceTokens.length > 1)
throw new IllegalArgumentException("Input sentences are not actually sentences according to annotator...");
else if (sentenceTokens.length == 0) {
this.tokens[i] = new String[0];
this.dependencyParses[i] = new DependencyParse(this, i);
this.constituencyParses[i] = new ConstituencyParse(this, i);
this.posTags[i] = new PoSTag[0];
continue;
}
this.tokens[i] = new String[sentenceTokens[0].length];
for (int j = 0; j < sentenceTokens[0].length; j++)
this.tokens[i][j] = sentenceTokens[0][j];
this.dependencyParses[i] = annotator.makeDependencyParses(this, i)[0];
this.constituencyParses[i] = annotator.makeConstituencyParses(this, i)[0];
PoSTag[][] sentencePoSTags = annotator.makePoSTags();
this.posTags[i] = new PoSTag[sentencePoSTags[0].length];
for (int j = 0; j < sentencePoSTags[0].length; j++)
this.posTags[i][j] = sentencePoSTags[0][j];
}
}
public int getSentenceCount() {
return this.tokens.length;
}
public int getSentenceTokenCount(int sentenceIndex) {
return this.tokens[sentenceIndex].length;
}
public String getText() {
StringBuilder text = new StringBuilder();
for (int i = 0; i < getSentenceCount(); i++)
text = text.append(getSentence(i)).append(" ");
return text.toString().trim();
}
public String getSentence(int sentenceIndex) {
StringBuilder sentenceStr = new StringBuilder();
for (int i = 0; i < this.tokens[sentenceIndex].length; i++) {
sentenceStr = sentenceStr.append(this.tokens[sentenceIndex][i]).append(" ");
}
return sentenceStr.toString().trim();
}
public String getToken(int sentenceIndex, int tokenIndex) {
if (tokenIndex < 0)
return "ROOT";
else
return this.tokens[sentenceIndex][tokenIndex];
}
public PoSTag getPoSTag(int sentenceIndex, int tokenIndex) {
return this.posTags[sentenceIndex][tokenIndex];
}
@Override
public ConstituencyParse getConstituencyParse(int sentenceIndex) {
return this.constituencyParses[sentenceIndex];
}
@Override
public DependencyParse getDependencyParse(int sentenceIndex) {
return this.dependencyParses[sentenceIndex];
}
public boolean setPoSTags(PoSTag[][] posTags) {
if (this.tokens.length != posTags.length)
return false;
this.posTags = new PoSTag[this.tokens.length][];
for (int i = 0; i < posTags.length; i++) {
if (this.tokens[i].length != posTags[i].length)
return false;
this.posTags[i] = new PoSTag[posTags[i].length];
for (int j = 0; j < posTags[i].length; j++) {
this.posTags[i][j] = posTags[i][j];
}
}
return true;
}
public boolean setDependencyParses(DependencyParse[] dependencyParses) {
this.dependencyParses = new DependencyParse[this.tokens.length];
for (int i = 0; i < this.dependencyParses.length; i++)
this.dependencyParses[i] = dependencyParses[i].clone(this);
return true;
}
public boolean setConstituencyParses(ConstituencyParse[] constituencyParses) {
this.constituencyParses = new ConstituencyParse[this.tokens.length];
for (int i = 0; i < this.constituencyParses.length; i++)
this.constituencyParses[i] = constituencyParses[i].clone(this);
return true;
}
@Override
public JSONObject toJSON() {
JSONObject json = new JSONObject();
JSONArray sentencesJson = new JSONArray();
json.put("name", this.name);
json.put("language", this.language.toString());
json.put("nlpAnnotator", this.nlpAnnotator);
int sentenceCount = getSentenceCount();
for (int i = 0; i < sentenceCount; i++) {
int tokenCount = getSentenceTokenCount(i);
JSONObject sentenceJson = new JSONObject();
sentenceJson.put("sentence", getSentence(i));
JSONArray tokensJson = new JSONArray();
JSONArray posTagsJson = new JSONArray();
for (int j = 0; j < tokenCount; j++) {
tokensJson.add(getToken(i, j));
if (this.posTags.length > 0) {
PoSTag posTag = getPoSTag(i, j);
if (posTag != null)
posTagsJson.add(posTag.toString());
}
}
sentenceJson.put("tokens", tokensJson);
if (this.posTags.length > 0)
sentenceJson.put("posTags", posTagsJson);
if (this.dependencyParses.length > 0)
sentenceJson.put("dependencyParse", getDependencyParse(i).toString());
if (this.constituencyParses.length > 0)
sentenceJson.put("constituencyParse", getConstituencyParse(i).toString());
sentencesJson.add(sentenceJson);
}
json.put("sentences", sentencesJson);
return json;
}
@Override
protected boolean fromJSON(JSONObject json) {
this.name = json.getString("name");
this.language = Language.valueOf(json.getString("language"));
if (json.has("nlpAnnotator"))
this.nlpAnnotator = json.getString("nlpAnnotator");
JSONArray sentences = json.getJSONArray("sentences");
this.tokens = new String[sentences.size()][];
this.posTags = new PoSTag[sentences.size()][];
this.dependencyParses = new DependencyParse[sentences.size()];
this.constituencyParses = new ConstituencyParse[sentences.size()];
for (int i = 0; i < sentences.size(); i++) {
JSONObject sentenceJson = sentences.getJSONObject(i);
JSONArray tokensJson = sentenceJson.getJSONArray("tokens");
JSONArray posTagsJson = (sentenceJson.has("posTags")) ? sentenceJson.getJSONArray("posTags") : null;
this.tokens[i] = new String[tokensJson.size()];
for (int j = 0; j < tokensJson.size(); j++)
this.tokens[i][j] = tokensJson.getString(j);
if (posTagsJson != null) {
this.posTags[i] = new PoSTag[posTagsJson.size()];
for (int j = 0; j < posTagsJson.size(); j++)
this.posTags[i][j] = PoSTag.valueOf(posTagsJson.getString(j));
}
if (sentenceJson.has("dependencyParse"))
this.dependencyParses[i] = DependencyParse.fromString(sentenceJson.getString("dependencyParse"), this, i);
if (sentenceJson.has("constituencyParse"))
this.constituencyParses[i] = ConstituencyParse.fromString(sentenceJson.getString("constituencyParse"), this, i);
}
return true;
}
@Override
public Document makeInstanceFromJSONFile(String path) {
return new DocumentInMemory(path);
}
}
|
package com.lenovohit.hcp.base.web.rest;
import org.apache.shiro.authz.UnauthenticatedException;
import com.lenovohit.bdrp.authority.model.AuthPrincipal;
import com.lenovohit.bdrp.authority.web.rest.AuthorityRestController;
import com.lenovohit.hcp.base.model.HcpUser;
public class HcpBaseRestController extends AuthorityRestController{
protected HcpUser getCurrentUser(){
AuthPrincipal user = this.getCurrentPrincipal();
if(null == user){
throw new UnauthenticatedException("当前无登录用户");
}
if(!(user instanceof HcpUser)){
HcpUser hcpUser = new HcpUser();
hcpUser.setId(user.getId());
hcpUser.setName(user.getName());
return hcpUser;
}
return (HcpUser)user;
}
}
|
/*
* This file is part of bytebin, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.lucko.bytebin.http;
import me.lucko.bytebin.content.ContentLoader;
import me.lucko.bytebin.content.ContentStorageHandler;
import me.lucko.bytebin.util.ContentEncoding;
import me.lucko.bytebin.util.ExpiryHandler;
import me.lucko.bytebin.util.Gzip;
import me.lucko.bytebin.util.RateLimitHandler;
import me.lucko.bytebin.util.RateLimiter;
import me.lucko.bytebin.util.TokenGenerator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.jooby.Context;
import io.jooby.Route;
import io.jooby.StatusCode;
import io.jooby.exception.StatusCodeException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nonnull;
public final class PutHandler implements Route.Handler {
/** Logger instance */
private static final Logger LOGGER = LogManager.getLogger(PutHandler.class);
private final BytebinServer server;
private final RateLimiter rateLimiter;
private final RateLimitHandler rateLimitHandler;
private final ContentStorageHandler storageHandler;
private final ContentLoader contentLoader;
private final long maxContentLength;
private final ExpiryHandler expiryHandler;
public PutHandler(BytebinServer server, RateLimiter rateLimiter, RateLimitHandler rateLimitHandler, ContentStorageHandler storageHandler, ContentLoader contentLoader, long maxContentLength, ExpiryHandler expiryHandler) {
this.server = server;
this.rateLimiter = rateLimiter;
this.rateLimitHandler = rateLimitHandler;
this.storageHandler = storageHandler;
this.contentLoader = contentLoader;
this.maxContentLength = maxContentLength;
this.expiryHandler = expiryHandler;
}
@Override
public CompletableFuture<Void> apply(@Nonnull Context ctx) {
// get the requested path
String path = ctx.path("id").value();
if (path.trim().isEmpty() || path.contains(".") || TokenGenerator.INVALID_TOKEN_PATTERN.matcher(path).find()) {
throw new StatusCodeException(StatusCode.NOT_FOUND, "Invalid path");
}
AtomicReference<byte[]> newContent = new AtomicReference<>(ctx.body().bytes());
// ensure something was actually posted
if (newContent.get().length == 0) {
throw new StatusCodeException(StatusCode.BAD_REQUEST, "Missing content");
}
// check rate limits
String ipAddress = this.rateLimitHandler.getIpAddressAndCheckRateLimit(ctx, this.rateLimiter);
String authHeader = ctx.header("Authorization").valueOrNull();
if (authHeader == null) {
throw new StatusCodeException(StatusCode.UNAUTHORIZED, "Authorization header not present");
}
if (!authHeader.startsWith("Bearer ")) {
throw new StatusCodeException(StatusCode.UNAUTHORIZED, "Invalid Authorization scheme");
}
String authKey = authHeader.substring("Bearer ".length());
return this.contentLoader.get(path).handleAsync((oldContent, throwable) -> {
if (throwable != null || oldContent == null || oldContent.getKey() == null || oldContent.getContent().length == 0) {
// use a generic response to prevent use of this endpoint to search for valid content
throw new StatusCodeException(StatusCode.FORBIDDEN, "Incorrect modification key");
}
// ok so the old content does exist, check that it is modifiable & that the key matches
if (!oldContent.isModifiable() || !oldContent.getAuthKey().equals(authKey)) {
// use a generic response to prevent use of this endpoint to search for valid content
throw new StatusCodeException(StatusCode.FORBIDDEN, "Incorrect modification key");
}
// determine the new content type
String newContentType = ctx.header("Content-Type").value(oldContent.getContentType());
// determine new encoding
List<String> newEncodings = ContentEncoding.getContentEncoding(ctx.header("Content-Encoding").valueOrNull());
// compress if necessary
if (newEncodings.isEmpty()) {
newContent.set(Gzip.compress(newContent.get()));
newEncodings.add(ContentEncoding.GZIP);
}
// check max content length
if (newContent.get().length > this.maxContentLength) {
throw new StatusCodeException(StatusCode.REQUEST_ENTITY_TOO_LARGE, "Content too large");
}
// get the user agent & origin headers
String userAgent = ctx.header("User-Agent").value("null");
String origin = ctx.header("Origin").value("null");
String host = ctx.getHostAndPort();
Date newExpiry = this.expiryHandler.getExpiry(userAgent, origin, host);
LOGGER.info("[PUT]\n" +
" key = " + path + "\n" +
" new type = " + new String(newContentType.getBytes()) + "\n" +
" new encoding = " + newEncodings.toString() + "\n" +
" user agent = " + userAgent + "\n" +
" ip = " + ipAddress + "\n" +
(origin.equals("null") ? "" : " origin = " + origin + "\n") +
" old content size = " + String.format("%,d", oldContent.getContent().length / 1024) + " KB" + "\n" +
" new content size = " + String.format("%,d", newContent.get().length / 1024) + " KB" + "\n"
);
// metrics
BytebinServer.recordRequest("PUT", ctx);
// update the content instance with the new data
oldContent.setContentType(newContentType);
oldContent.setEncoding(String.join(",", newEncodings));
oldContent.setExpiry(newExpiry);
oldContent.setLastModified(System.currentTimeMillis());
oldContent.setContent(newContent.get());
// make the http response
ctx.setResponseCode(StatusCode.OK);
ctx.send();
// save to disk
this.storageHandler.save(oldContent);
return null;
}, this.storageHandler.getExecutor());
}
}
|
package ru.orbot90.guestbook.model;
/**
* @author Iurii Plevako orbot90@gmail.com
**/
public enum PostApproval {
APPROVED, ALL
}
|
package hu.lamsoft.hms.regimen.contoller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import hu.lamsoft.hms.regimen.service.regimen.RegimenService;
import hu.lamsoft.hms.regimen.service.regimen.dto.RegimenDTO;
import hu.lamsoft.hms.regimen.service.regimen.vo.RegimenSearchVO;
@RestController
public class RegimenController {
@Autowired
private RegimenService regimenService;
@RequestMapping(value = "/regimens", method = RequestMethod.GET)
public Page<RegimenDTO> getFoods(@RequestParam(name = "page", required = false, defaultValue = "0") int page,
@RequestParam(name = "size", required = false, defaultValue = "10") int size) {
return regimenService.searchRegimen(new RegimenSearchVO(page, size));
}
@RequestMapping(value = "/regimens", method = RequestMethod.POST)
public Page<RegimenDTO> getFoods(@RequestBody RegimenSearchVO foodSearchVO) {
return regimenService.searchRegimen(foodSearchVO);
}
}
|
package com.library.network.interfaces;
import android.os.Handler;
import java.util.HashMap;
import java.util.Map;
/**
* Created by admin on 2016/6/14.
*/
public abstract class IHttpParams {
//请求地址
private String httpUrl;
public String getHttpUrl() {
return httpUrl;
}
public void setHttpUrl(String httpUrl) {
this.httpUrl = httpUrl;
}
//Http请求参数
private Map<String, Object> param = new HashMap<>();
public Map<String, Object> getParam() {
return param;
}
public void setParam(Map<String, Object> param) {
this.param = param;
}
public void addParam(String name, Object value) {
if (null == value) {
return;
}
param.put(name, value.toString());
}
public String getParamString() {
StringBuffer stringBuffer = new StringBuffer();
if (null != param && param.size() > 0) {
for (Map.Entry<String, Object> entry : param.entrySet()) {
if (stringBuffer.length() > 0) {
stringBuffer.append("&");
}
if (null == entry) {
continue;
}
stringBuffer.append(entry.getKey()).append("=").append(entry.getValue().toString());
}
}
return stringBuffer.toString();
}
//请求Tag
private Object tag;
public Object getTag() {
return tag;
}
public void setTag(Object tag) {
this.tag = tag;
}
//是否主线程回调(默认主线程回调)
private boolean asyncBack;
public boolean isAsyncBack() {
return asyncBack;
}
public void setAsyncBack(boolean asyncBack) {
this.asyncBack = asyncBack;
}
//保存文件路径
private String saveFilePath;
public String getSaveFilePath() {
return saveFilePath;
}
public void setSaveFilePath(String saveFilePath) {
this.saveFilePath = saveFilePath;
}
//保存文件名称
private String saveFileName;
public String getSaveFileName() {
return saveFileName;
}
public void setSaveFileName(String saveFileName) {
this.saveFileName = saveFileName;
}
//Handler
private Handler handler;
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
}
|
package old.Data20180427;
import old.DataType.TreeNode;
import java.util.LinkedList;
public class SubTree {
public static void main(String[] args){
TreeNode root = new TreeNode(8);
root.left = new TreeNode(8);
root.left.right = new TreeNode(9);
root.left.left = new TreeNode(7);
TreeNode root2 = new TreeNode(8);
root2.left = new TreeNode(7);
root2.right = new TreeNode(9);
new SubTree().HasSubtree(root, root2);
}
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
if(root2 == null || root1 == null)
return false;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root1);
while(!queue.isEmpty()){
int size = queue.size();
while(size-- > 0){
TreeNode node = queue.poll();
if(subTree(node, root2))
return true;
if(node.left != null)
queue.offer(node.left);
if(node.right != null)
queue.offer(node.right);
}
}
return false;
}
public boolean subTree(TreeNode root1, TreeNode root2){
if(root2 == null)
return true;
if(root1 == null && root2 != null)
return false;
if(root1.val != root2.val)
return false;
return subTree(root1.left, root2.left) && subTree(root1.right, root2.right);
}
}
|
package com.yc.education.service.sale;
import com.yc.education.model.sale.SaleReturnGoodsProduct;
import com.yc.education.service.IService;
import java.util.List;
/**
* @author BlueSky
* @Description:
* @Date 15:23 2018-09-26
*/
public interface ISaleReturnGoodsProductService extends IService<SaleReturnGoodsProduct> {
/**
* @Description 修改入库数量
* @Author BlueSky
* @param orderNo 订单号
* @param productNo 产品编号
* @param num 数量
* @Date 16:39 2019/4/23
**/
int updateSaleReturnGoodsProductInboundNum( String orderNo, String productNo, String num);
/**
* @Description 通过销售退货单订单号和产品编号获取销售退货单产品详情
* @Author BlueSky
* @param orderNo 订单号
* @param productNo 产品编号
* @Date 19:42 2019/4/23
**/
SaleReturnGoodsProduct getSaleReturnGoodsProductBySaleNum( String orderNo, String productNo);
/**
* 时间条件查询
* @param state 1:已开票、0:未开票
* @param ben
* @param end
* @param customerNo 客户编号
* @return
*/
List<SaleReturnGoodsProduct> listTimeWhere(String state,String ben,String end,String customerNo);
/**
* 根据销售退货单id查询销退产品
* @param orderid
* @return
*/
List<SaleReturnGoodsProduct> listReturnGoodsProduct(String orderid);
/**
* 分页
* 根据销售退货单id查询销退产品
* @param orderid
* @return
*/
List<SaleReturnGoodsProduct> listReturnGoodsProduct(String orderid, int page, int rows);
/**
* 根据外键id删除销退产品
* @param orderid
* @return
*/
int deleteSaleReturnGoodsProductByParentId( String orderid);
/**
* 查询销退单
* @param productNum
* @param startTime
* @param endTime
* @return
*/
List<SaleReturnGoodsProduct> selectSaleReturnGoodsProductdByProductNameAndStartTimeAndEndTime(String productNum,
String startTime,
String endTime);
}
|
package ru.jft.first;
import org.testng.Assert;
import org.testng.annotations.Test;
public class EquationTests {
@Test
public void test0() {
Equation e = new Equation(0, 1, 1);
Assert.assertEquals(e.rootNumber(), 0);
}
@Test
public void test1() {
Equation e = new Equation(1, 0, 1);
Assert.assertEquals(e.rootNumber(), 1);
}
@Test
public void test2() {
Equation e = new Equation(1, 5, 0);
Assert.assertEquals(e.rootNumber(), 2);
}
} |
/**
* Write a description of class ICommand here.
*
* @author (your name)
* @version (a version number or a date)
*/
public interface ICommand
{
//public void setReceiverScreen(IReceiver receiver);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.