text stringlengths 10 2.72M |
|---|
import java.util.Scanner;
class YoungerAgeException extends RuntimeException // inheriting properties from parent exception class
{
YoungerAgeException(String msg) // parameterized constructor
{
super(msg);
}
}
public class Voting
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in); // taking input from user
System.out.println("Enter the age: ");
int age=s.nextInt();
try
{
if(age<18)
{
throw new YoungerAgeException("You are not eligible to vote."); //user creating object of exception class
}
else
{
System.out.println("You can vote.");
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Exception handled");
}
}
|
/**
*/
package featureModel.impl;
import featureModel.FeatureModelPackage;
import featureModel.Group;
import featureModel.GroupedFeature;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Group</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link featureModel.impl.GroupImpl#getGroupedFeatures <em>Grouped Features</em>}</li>
* <li>{@link featureModel.impl.GroupImpl#isInclusive <em>Inclusive</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class GroupImpl extends MinimalEObjectImpl.Container implements Group {
/**
* The cached value of the '{@link #getGroupedFeatures() <em>Grouped Features</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getGroupedFeatures()
* @generated
* @ordered
*/
protected EList<GroupedFeature> groupedFeatures;
/**
* The default value of the '{@link #isInclusive() <em>Inclusive</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isInclusive()
* @generated
* @ordered
*/
protected static final boolean INCLUSIVE_EDEFAULT = false;
/**
* The cached value of the '{@link #isInclusive() <em>Inclusive</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isInclusive()
* @generated
* @ordered
*/
protected boolean inclusive = INCLUSIVE_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected GroupImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return FeatureModelPackage.Literals.GROUP;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<GroupedFeature> getGroupedFeatures() {
if (groupedFeatures == null) {
groupedFeatures = new EObjectContainmentEList<GroupedFeature>(GroupedFeature.class, this, FeatureModelPackage.GROUP__GROUPED_FEATURES);
}
return groupedFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isInclusive() {
return inclusive;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setInclusive(boolean newInclusive) {
boolean oldInclusive = inclusive;
inclusive = newInclusive;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FeatureModelPackage.GROUP__INCLUSIVE, oldInclusive, inclusive));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case FeatureModelPackage.GROUP__GROUPED_FEATURES:
return ((InternalEList<?>)getGroupedFeatures()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case FeatureModelPackage.GROUP__GROUPED_FEATURES:
return getGroupedFeatures();
case FeatureModelPackage.GROUP__INCLUSIVE:
return isInclusive();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case FeatureModelPackage.GROUP__GROUPED_FEATURES:
getGroupedFeatures().clear();
getGroupedFeatures().addAll((Collection<? extends GroupedFeature>)newValue);
return;
case FeatureModelPackage.GROUP__INCLUSIVE:
setInclusive((Boolean)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case FeatureModelPackage.GROUP__GROUPED_FEATURES:
getGroupedFeatures().clear();
return;
case FeatureModelPackage.GROUP__INCLUSIVE:
setInclusive(INCLUSIVE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case FeatureModelPackage.GROUP__GROUPED_FEATURES:
return groupedFeatures != null && !groupedFeatures.isEmpty();
case FeatureModelPackage.GROUP__INCLUSIVE:
return inclusive != INCLUSIVE_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (inclusive: ");
result.append(inclusive);
result.append(')');
return result.toString();
}
} //GroupImpl
|
package me.d2o.statemachine.config;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import me.d2o.statemachine.annotations.EnterMachineState;
import me.d2o.statemachine.annotations.ExitMachineState;
import me.d2o.statemachine.exceptions.MachineEventHandlerConfigurationException;
import me.d2o.statemachine.exceptions.StateMachineConfigurationException;
@Component
public class ConfigValidator implements BeanPostProcessor {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
private StateMachineConfigurable smc;
@Autowired
ConfigValidator(StateMachineConfigurable smc){
this.smc = smc;
}
private void validate(String state){
try {
smc.checkIfStateIsValid(state);
} catch (StateMachineConfigurationException ex){
MachineEventHandlerConfigurationException e = new MachineEventHandlerConfigurationException("Could not construct the MachineEventHandler ["+this.getClass()+"] because the 'State' method returns an invalid String",ex);
logger.error("Bad configuration",e);
throw e;
}
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
//Check for method annotations Enter/Exit
for(Method method: bean.getClass().getMethods()){
if(method.isAnnotationPresent(EnterMachineState.class)){
validate(method.getAnnotation(EnterMachineState.class).value());
}
if(method.isAnnotationPresent(ExitMachineState.class)){
validate(method.getAnnotation(ExitMachineState.class).value());
}
}
return bean;
}
}
|
package org.springframework.samples.petclinic.admin.model;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ScannerRepository extends JpaRepository<Alert, Integer>{
// List<Alert> findByLastName(String lastName);
}
|
package com.allmsi.test.model;
import java.util.List;
public class MethodVo {
private String url;
private String type;
private String className;
private String method;
private List<String> parameters;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public List<String> getParameters() {
return parameters;
}
public void setParameters(List<String> parameters) {
this.parameters = parameters;
}
}
|
import java.util.*;
class message
{
public static void main(String args[])
{
Scanner x=new Scanner(System.in);
System.out.println("Enter User Name::");
String uname=x.nextLine();
System.out.println("GET WELL SOON::"+uname);
}//close of main
}//close of class |
package com.ecommerce.engineerk;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EngineerkApplication {
public static void main(String[] args) {
SpringApplication.run(EngineerkApplication.class, args);
}
}
|
package cn.bjfu.hotiems;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Properties;
/**
* Created by jxy on 2021/4/15 0015 18:06
*/
public class KafkaProducerUtil {
public static void main(String[] args)throws Exception {
writeToKafka("hostitems");
}
//包装写一个kafka的方法
public static void writeToKafka(String topic)throws Exception{
Properties props = new Properties();
props.put("bootstrap.servers", "Master:9092,Worker1:9092,Worker3:9092,Worker4:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
//定义一个Kafka Producer
KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(props);
BufferedReader bufferedReader = new BufferedReader(new FileReader("F:\\\\wsy\\\\1.csv"));
String line;
while ((line = bufferedReader.readLine())!=null){
ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, line);
kafkaProducer.send(producerRecord);
}
kafkaProducer.close();
}
}
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.types.authn;
import pl.edu.icm.unity.types.DescribedObjectImpl;
/**
* Authentication realm definition.
* @author K. Benedyczak
*/
public class AuthenticationRealm extends DescribedObjectImpl
{
private int blockAfterUnsuccessfulLogins;
private int blockFor;
private int allowForRememberMeDays;
private int maxInactivity;
public AuthenticationRealm()
{
}
public AuthenticationRealm(String name, String description, int blockAfterUnsuccessfulLogins, int blockFor,
int allowForRememberMeDays, int maxInactivity)
{
super(name, description);
this.blockAfterUnsuccessfulLogins = blockAfterUnsuccessfulLogins;
this.blockFor = blockFor;
this.allowForRememberMeDays = allowForRememberMeDays;
this.maxInactivity = maxInactivity;
}
public int getBlockAfterUnsuccessfulLogins()
{
return blockAfterUnsuccessfulLogins;
}
public void setBlockAfterUnsuccessfulLogins(int blockAfterUnsuccessfulLogins)
{
this.blockAfterUnsuccessfulLogins = blockAfterUnsuccessfulLogins;
}
public int getBlockFor()
{
return blockFor;
}
public void setBlockFor(int blockFor)
{
this.blockFor = blockFor;
}
public int getAllowForRememberMeDays()
{
return allowForRememberMeDays;
}
public void setAllowForRememberMeDays(int allowForRememberMeDays)
{
this.allowForRememberMeDays = allowForRememberMeDays;
}
public int getMaxInactivity()
{
return maxInactivity;
}
public void setMaxInactivity(int maxInactivity)
{
this.maxInactivity = maxInactivity;
}
}
|
package com.bruce.factory.simplefactory.pizzastore.improve.order;
import com.bruce.factory.simplefactory.pizzastore.improve.pizza.Pizza;
import com.bruce.factory.simplefactory.pizzastore.improve.pizza.CheesPizza;
import com.bruce.factory.simplefactory.pizzastore.improve.pizza.GreekPizza;
import com.bruce.factory.simplefactory.pizzastore.improve.pizza.JapanPizza;
public class OrderFactory {
static Pizza pizza = null;
public Pizza createPizza(String orderType) {
if (orderType.equals("greek")) {
pizza = new GreekPizza();
} else if (orderType.equals("cheese")) {
pizza = new CheesPizza();
} else if (orderType.equals("japan")) {
pizza = new JapanPizza();
}
return pizza;
}
}
|
// Frank Kepler 4/16/2013 Heroes & MONSTERS!!
// All extra credit attempted
import java.util.*;
public abstract class Hero extends DungeonCharacter
{
protected double c2b;
protected int turns;
public Hero(String name, int hp, int attackSpeed, int damageLow, int damageHigh, double strikeChance, double c2b, int turns)
{
super(name, hp, attackSpeed, damageLow, damageHigh, strikeChance);
this.name = setName();
this.c2b = c2b;
this.turns = turns;
}
public abstract String setName();
public void setC2B(double c2b)
{
this.c2b = c2b;
}
public double getC2B()
{
return c2b;
}
public void setTurns(int turns)
{
this.turns = turns;
}
public int getTurns()
{
return turns;
}
public void randomBlock(int points)
{
double rand = new Random().nextDouble();
if(rand < this.c2b)
System.out.println(this.getName() + " blocked the attack and still has " + this.getHP() + " health points total.");
else
{
this.setHP(this.getHP() - points);
System.out.println(this.getName() + " has " + this.getHP() + " health points left.");
}
}
public int attack()
{
double rd = randomDouble();
if(rd < this.strikeChance)
{
int rand = randomInt();
System.out.println(successAttack(rand));
return rand;
}
System.out.println(failedAttack());
return 0;
}
} |
package com.pichincha.prueba.enums;
public enum FormatoFecha {
YYYY_MM_DD("yyyy-MM-dd"),
YYYY_MM_DD_HH_MM_SS("YYYY-MM-DD hh:mm:ss");
private String name;
FormatoFecha(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
|
package com.nanyin.repository;
import com.nanyin.entity.Role;
import com.nanyin.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface UserRepository extends JpaRepository<User,Integer>, QuerydslPredicateExecutor<User> {
/**
* 根据名称查询用户
* @Author nanyin
* @Date 20:28 2019-07-24
* @param name
* @return com.nanyin.entity.User
**/
@Query(nativeQuery = true,value = "select u.* from user u where u.name=:name limit 1")
User findUserByName(String name);
@Override
User saveAndFlush(User user);
@Query(nativeQuery = true,value = "select u.name from user u where u.id:id limit 1")
String getUserNameById(Integer id);
}
//
|
package Level1;
import java.util.Scanner;
public class Test7 {
public static void main(String[] args) {
/*
흔한 수학 문제 중 하나는 주어진 점이 어느 사분면에 속하는지 알아내는 것이다. 사분면은 아래 그림처럼 1부터 4까지 번호를 갖는다. "Quadrant n"은 "제n사분면"이라는 뜻이다.
예를 들어, 좌표가 (12, 5)인 점 A는 x좌표와 y좌표가 모두 양수이므로 제1사분면에 속한다. 점 B는 x좌표가 음수이고 y좌표가 양수이므로 제2사분면에 속한다.
점의 좌표를 입력받아 그 점이 어느 사분면에 속하는지 알아내는 프로그램을 작성하시오. 단, x좌표와 y좌표는 모두 양수나 음수라고 가정한다.
*/
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
int result = 0;
if( x > 0 && y > 0) {
result = 1 ;
}else if( x > 0 && y < 0) {
result = 4;
}else if(x < 0 && y > 0) {
result = 2;
}else {
result = 3;
}
System.out.println(result);
}
}
|
package com.alibaba.druid.bvt.sql.odps;
import com.alibaba.druid.sql.SQLUtils;
import junit.framework.TestCase;
public class OdpsLoadTest extends TestCase {
public void test_load_0() throws Exception {
String sql = "LOAD OVERWRITE TABLE tsv_load_tbl \n" +
"FROM\n" +
"LOCATION 'oss://accessId:accesssKey@oss-cn-hangzhou-zmf.aliyuncs.com/my_bucket_id/my_location/'\n" +
"STORED BY 'com.aliyun.odps.TsvStorageHandler'\n" +
"WITH SERDEPROPERTIES ('odps.text.option.delimiter'='\\t');";
assertEquals("LOAD OVERWRITE INTO TABLE tsv_load_tbl\n" +
"LOCATION 'oss://accessId:accesssKey@oss-cn-hangzhou-zmf.aliyuncs.com/my_bucket_id/my_location/'\n" +
"STORED BY 'com.aliyun.odps.TsvStorageHandler'\n" +
"WITH SERDEPROPERTIES (\n" +
"\t'odps.text.option.delimiter' = '\t'\n" +
");", SQLUtils.formatOdps(sql));
}
public void test_load_1() throws Exception {
String sql = "LOAD OVERWRITE TABLE oss_load_static_part PARTITION(ds='20190101')\n" +
"FROM\n" +
"LOCATION 'oss://<yourAccessKeyId>:<yourAccessKeySecret>@oss-cn-hangzhou-zmf.aliyuncs.com/my_bucket_id/my_location/'\n" +
"STORED AS PARQUET;";
assertEquals("LOAD OVERWRITE INTO TABLE oss_load_static_part PARTITION (ds = '20190101')\n" +
"LOCATION 'oss://<yourAccessKeyId>:<yourAccessKeySecret>@oss-cn-hangzhou-zmf.aliyuncs.com/my_bucket_id/my_location/'\n" +
"STORED AS PARQUET;", SQLUtils.formatOdps(sql));
}
public void test_load_2() throws Exception {
String sql = "LOAD OVERWRITE TABLE oss_load_dyn_part PARTITION(ds)\n" +
"FROM\n" +
"LOCATION 'oss://accessId:accesssKey@oss-cn-hangzhou-zmf.aliyuncs.com/bucket/text_data/'\n" +
"ROW FORMAT serde 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'\n" +
"WITH SERDEPROPERTIES(\n" +
" 'Fields terminator'='\\001',\n" +
" 'Escape delimitor'='\\\\',\n" +
" 'Collection items terminator'='\\002',\n" +
" 'Map keys terminator'='\\003',\n" +
" 'Lines terminator'='\\n',\n" +
" 'Null defination'='\\\\N')\n" +
"STORED AS TEXTFILE ;";
assertEquals("LOAD OVERWRITE INTO TABLE oss_load_dyn_part PARTITION (ds)\n" +
"LOCATION 'oss://accessId:accesssKey@oss-cn-hangzhou-zmf.aliyuncs.com/bucket/text_data/'\n" +
"ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'\n" +
"WITH SERDEPROPERTIES (\n" +
"\t'Fields terminator' = '\\001',\n" +
"\t'Escape delimitor' = '\\\\',\n" +
"\t'Collection items terminator' = '\\002',\n" +
"\t'Map keys terminator' = '\\003',\n" +
"\t'Lines terminator' = '\\n',\n" +
"\t'Null defination' = '\\\\N'\n" +
")\n" +
"STORED AS TEXTFILE;", SQLUtils.formatOdps(sql));
}
}
|
package com.annotation.day01;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Day01 {
/**
* 1720. 解码异或后的数组
*
* 异或运算具有如下性质:
*
* 异或运算满足交换律和结合律;
*
* 任意整数和自身做异或运算的结果都等于 00,即 x \oplus x = 0x⊕x=0;
*
* 任意整数和 00 做异或运算的结果都等于其自身,即 x \oplus 0 = 0 \oplus x = xx⊕0=0⊕x=x。
*/
public static void main(String[] args) {
int[] a = {6,2,7,3};
int[] b = new int[a.length + 1];
b[0]=4;
for (int i = 1; i < b.length; i++) {
b[i]=b[i-1]^a[i-1];
}
System.out.println(Arrays.toString(b));
int [] c={2,7,2,3,6,4};
int target=9;
for (int i = 0; i < c.length-1; i++) {
if (target==c[i]+c[i+1]){
System.out.println(i+" "+(i+1));
return;
}
}
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.event;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
/**
* {@code TestExecutionListener} that publishes test execution events to the
* {@link org.springframework.context.ApplicationContext ApplicationContext}
* for the currently executing test.
*
* <h3>Supported Events</h3>
* <ul>
* <li>{@link BeforeTestClassEvent}</li>
* <li>{@link PrepareTestInstanceEvent}</li>
* <li>{@link BeforeTestMethodEvent}</li>
* <li>{@link BeforeTestExecutionEvent}</li>
* <li>{@link AfterTestExecutionEvent}</li>
* <li>{@link AfterTestMethodEvent}</li>
* <li>{@link AfterTestClassEvent}</li>
* </ul>
*
* <p>These events may be consumed for various reasons, such as resetting <em>mock</em>
* beans or tracing test execution. One advantage of consuming test events rather
* than implementing a custom {@link org.springframework.test.context.TestExecutionListener
* TestExecutionListener} is that test events may be consumed by any Spring bean
* registered in the test {@code ApplicationContext}, and such beans may benefit
* directly from dependency injection and other features of the {@code ApplicationContext}.
* In contrast, a {@code TestExecutionListener} is not a bean in the {@code ApplicationContext}.
*
* <p>Note that the {@code EventPublishingTestExecutionListener} is registered by
* default; however, it only publishes events if the {@code ApplicationContext}
* {@linkplain TestContext#hasApplicationContext() has already been loaded}. This
* prevents the {@code ApplicationContext} from being loaded unnecessarily or too
* early. Consequently, a {@code BeforeTestClassEvent} will not be published until
* after the {@code ApplicationContext} has been loaded by another
* {@code TestExecutionListener}. For example, with the default set of
* {@code TestExecutionListeners} registered, a {@code BeforeTestClassEvent} will
* not be published for the first test class that uses a particular test
* {@code ApplicationContext}, but a {@code BeforeTestClassEvent} will be published
* for any subsequent test class in the same test suite that uses the same test
* {@code ApplicationContext} since the context will already have been loaded
* when subsequent test classes run (as long as the context has not been removed
* from the {@link org.springframework.test.context.cache.ContextCache ContextCache}
* via {@link org.springframework.test.annotation.DirtiesContext @DirtiesContext}
* or the max-size eviction policy). If you wish to ensure that a
* {@code BeforeTestClassEvent} is published for every test class, you need to
* register a {@code TestExecutionListener} that loads the {@code ApplicationContext}
* in the {@link org.springframework.test.context.TestExecutionListener#beforeTestClass
* beforeTestClass} callback, and that {@code TestExecutionListener} must be registered
* before the {@code EventPublishingTestExecutionListener}. Similarly, if
* {@code @DirtiesContext} is used to remove the {@code ApplicationContext} from
* the context cache after the last test method in a given test class, the
* {@code AfterTestClassEvent} will not be published for that test class.
*
* <h3>Exception Handling</h3>
* <p>By default, if a test event listener throws an exception while consuming
* a test event, that exception will propagate to the underlying testing framework
* in use. For example, if the consumption of a {@code BeforeTestMethodEvent}
* results in an exception, the corresponding test method will fail as a result
* of the exception. In contrast, if an asynchronous test event listener throws
* an exception, the exception will not propagate to the underlying testing framework.
* For further details on asynchronous exception handling, consult the class-level
* Javadoc for {@link org.springframework.context.event.EventListener @EventListener}.
*
* <h3>Asynchronous Listeners</h3>
* <p>If you want a particular test event listener to process events asynchronously,
* you can use Spring's {@link org.springframework.scheduling.annotation.Async @Async}
* support. For further details, consult the class-level Javadoc for
* {@link org.springframework.context.event.EventListener @EventListener}.
*
* @author Sam Brannen
* @author Frank Scheffler
* @since 5.2
* @see org.springframework.test.context.event.annotation.BeforeTestClass @BeforeTestClass
* @see org.springframework.test.context.event.annotation.PrepareTestInstance @PrepareTestInstance
* @see org.springframework.test.context.event.annotation.BeforeTestMethod @BeforeTestMethod
* @see org.springframework.test.context.event.annotation.BeforeTestExecution @BeforeTestExecution
* @see org.springframework.test.context.event.annotation.AfterTestExecution @AfterTestExecution
* @see org.springframework.test.context.event.annotation.AfterTestMethod @AfterTestMethod
* @see org.springframework.test.context.event.annotation.AfterTestClass @AfterTestClass
*/
public class EventPublishingTestExecutionListener extends AbstractTestExecutionListener {
/**
* Returns {@code 10000}.
*/
@Override
public final int getOrder() {
return 10_000;
}
/**
* Publish a {@link BeforeTestClassEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void beforeTestClass(TestContext testContext) {
testContext.publishEvent(BeforeTestClassEvent::new);
}
/**
* Publish a {@link PrepareTestInstanceEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void prepareTestInstance(TestContext testContext) {
testContext.publishEvent(PrepareTestInstanceEvent::new);
}
/**
* Publish a {@link BeforeTestMethodEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void beforeTestMethod(TestContext testContext) {
testContext.publishEvent(BeforeTestMethodEvent::new);
}
/**
* Publish a {@link BeforeTestExecutionEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void beforeTestExecution(TestContext testContext) {
testContext.publishEvent(BeforeTestExecutionEvent::new);
}
/**
* Publish an {@link AfterTestExecutionEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void afterTestExecution(TestContext testContext) {
testContext.publishEvent(AfterTestExecutionEvent::new);
}
/**
* Publish an {@link AfterTestMethodEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void afterTestMethod(TestContext testContext) {
testContext.publishEvent(AfterTestMethodEvent::new);
}
/**
* Publish an {@link AfterTestClassEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void afterTestClass(TestContext testContext) {
testContext.publishEvent(AfterTestClassEvent::new);
}
}
|
/*Kane G
* April 19
* door choice
*/
package gameZone;
import java.util.Scanner;
public class DoorChoice
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int door;
int choice;
Scanner input = new Scanner(System.in);
do{
System.out.println(" Welocome to the game show of doom. doom. doom. Here you have a choice between 3 doors, pick the "
+ " right door and win a pirze");
System.out.println("Please enter the door you choose. Door 1 2 or 3");
door = input.nextInt();
if(door == 1)
{
System.out.println("You have won nothing but disappointment");
}
if(door == 2)
{
System.out.println("You have won congratulations you have just won a brand new taco truck!!");
}
if(door == 3)
{
System.out.println("Dude just go home.. Like that's is just sad, you just won a trip to the inLaws");
}
else
{
System.out.println("Common silly goose there is only 3 doors, pick one of them");
}
System.out.println("Would you like to enter another door? 1 for Yes or 2 for no");
choice = input.nextInt();
}while(choice == 1);
}
}
|
package de.mq.vaadin.util;
import java.util.Collection;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import com.vaadin.navigator.Navigator;
import com.vaadin.navigator.View;
@Component
@Scope("session")
public class SimpleViewNavImpl implements ViewNav {
private Navigator navigator;
/* (non-Javadoc)
* @see de.mq.vaadin.util.ViewNav#create(com.vaadin.navigator.View, java.util.Collection)
*/
@Override
public final void create(final View root, final Collection<View> views, final VaadinOperations vaadinOperations) {
navigator = vaadinOperations.newNavigator();
navigator.addView("", root);
for (final View view : views) {
//call @PostConstruct now ...
view.toString();
navigator.addView(viewNameFor(view), view);
}
}
/* (non-Javadoc)
* @see de.mq.vaadin.util.ViewNav#navigateTo(java.lang.Class)
*/
@Override
public final void navigateTo(Class<? extends View> clazz, String ... params ) {
Assert.isTrue(!ClassUtils.isCglibProxyClass(clazz) , "Class should not be a CglibProxyClass." ) ;
String parameter = "" ;
if( params.length > 0 ) {
parameter += "/";
parameter += StringUtils.arrayToDelimitedString(params, "/");
}
navigator.navigateTo(StringUtils.uncapitalize(clazz.getSimpleName() ) + parameter );
}
private String viewNameFor(final View view) {
if (AopUtils.isCglibProxy(view)) {
return StringUtils.uncapitalize(AopUtils.getTargetClass(view).getSimpleName());
}
return StringUtils.uncapitalize(view.getClass().getSimpleName());
}
}
|
package com.infoworks.lab.cryptor.impl;
import com.infoworks.lab.cryptor.definition.Cryptor;
import com.infoworks.lab.cryptor.util.CryptoAlgorithm;
import com.infoworks.lab.cryptor.util.HashKey;
import com.infoworks.lab.cryptor.util.Transformation;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
public class AESCryptor implements Cryptor {
private Cipher cipher;
private Cipher decipher;
private MessageDigest sha;
private final HashKey hashKey;
private final Transformation transformation;
private final CryptoAlgorithm cryptoAlgorithm;
public AESCryptor() {
this(HashKey.SHA_256, Transformation.AES_ECB_PKCS5Padding, CryptoAlgorithm.AES);
}
public AESCryptor(HashKey hashKey, Transformation transformation, CryptoAlgorithm cryptoAlgorithm) {
this.hashKey = hashKey;
this.transformation = transformation;
this.cryptoAlgorithm = cryptoAlgorithm;
}
public CryptoAlgorithm getAlgorithm() {return cryptoAlgorithm;}
public Transformation getTransformation() {return transformation;}
public HashKey getHashKey() {return hashKey;}
private Cipher getCipher(String secret) throws Exception{
if (cipher == null){
Key secretKey = getKey(secret);
cipher = Cipher.getInstance(getTransformation().value());
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
}
return cipher;
}
private Cipher getDecipher(String secret) throws Exception{
if (decipher == null){
Key secretKey = getKey(secret);
decipher = Cipher.getInstance(getTransformation().value());
decipher.init(Cipher.DECRYPT_MODE, secretKey);
}
return decipher;
}
@Override
public Key getKey(String mykey)
throws UnsupportedEncodingException, NoSuchAlgorithmException {
//
if (mykey == null || mykey.isEmpty())
throw new UnsupportedEncodingException("SecretKey is null or empty!");
//
if (transformation == Transformation.AES_ECB_PKCS5Padding){
byte[] key = mykey.getBytes("UTF-8");
key = getSha(getHashKey()).digest(key);
key = Arrays.copyOf(key, 16);
SecretKeySpec secretKey = new SecretKeySpec(key, getAlgorithm().name());
return secretKey;
}
else if (transformation == Transformation.AES_CBC_PKCS7Padding){
throw new NoSuchAlgorithmException(getTransformation().value() + " not supported yet");
}
else if (transformation == Transformation.AES_GCM_NoPadding){
throw new NoSuchAlgorithmException(getTransformation().value() + " not supported yet");
}
else {
throw new NoSuchAlgorithmException(getTransformation().value() + " not supported yet");
}
}
private MessageDigest getSha(HashKey hashKey) throws NoSuchAlgorithmException {
if (sha == null){
sha = MessageDigest.getInstance(hashKey.value());
}
return sha;
}
@Override
public String encrypt(String secret, String strToEncrypt) {
try {
Cipher cipher = getCipher(secret);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
@Override
public String decrypt(String secret, String strToDecrypt) {
try {
Cipher cipher = getDecipher(secret);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
}
|
package annotations;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
public @interface WithIntArg {
int val() default 1;
}
|
public enum PoisonousMushrooms {
AMANITA_MUSCARIA(false),
AMANITA_PANTHERINA(true),
CHLOROPHYLLUM_MOLYBDITES(false),
ENTOLOMA(true),
INOCYBE(true),
WHITE_CLITOCYBE(true),
TRICHOLOMA_PARDINUM(true),
TRICHOLOMA_EQUESTRE(true),
HYPHOLOMA_FASCICULARE(false),
PAXILLUS_INVOLUTUS(true),
RUBROBOLETUS_SATANAS(true),
HEBELOMA_CRUSTULINIFORME(false),
AGARICUS_CALIFORNICUS(true),
LACTIFLUUS_PIPERATUS(true),
LACTARIUS_VINACEORUFESCENS(true),
RAMARIA_GELATINOSA(false),
GOMPHUS_FLOCCOSUS(true);
private boolean deadly;
PoisonousMushrooms(boolean deadly) {
this.deadly = deadly;
}
public boolean isDeadly() {
return deadly;
}
public void setDeadly(boolean deadly) {
this.deadly = deadly;
}
}
|
package com.xiaomi.view.exception;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
/**
* @author hekun
*/
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
@ExceptionHandler(value = Exception.class)
public String defaultExceptionHandler(Exception e, HttpServletRequest request, Model m){
m.addAttribute("error",e.getMessage());
m.addAttribute("url",request.getRequestURI().toString());
return "error";
}
}
|
/*
* 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.reactive;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.reactive.accept.HeaderContentTypeResolver;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.resource.ResourceWebHandler;
import org.springframework.web.reactive.result.SimpleHandlerAdapter;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.reactive.result.method.annotation.ResponseBodyResultHandler;
import org.springframework.web.reactive.result.method.annotation.ResponseEntityExceptionHandler;
import org.springframework.web.reactive.result.method.annotation.ResponseEntityResultHandler;
import org.springframework.web.server.NotAcceptableStatusException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import org.springframework.web.server.WebHandler;
import org.springframework.web.server.handler.ExceptionHandlingWebHandler;
import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse;
import org.springframework.web.testfixture.server.MockServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.MediaType.APPLICATION_JSON;
/**
* Test the effect of exceptions at different stages of request processing by
* checking the error signals on the completion publisher.
*
* @author Rossen Stoyanchev
*/
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "ThrowableInstanceNeverThrown"})
public class DispatcherHandlerErrorTests {
private static final IllegalStateException EXCEPTION = new IllegalStateException("boo");
private DispatcherHandler dispatcherHandler;
@BeforeEach
public void setup() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(TestConfig.class);
context.refresh();
this.dispatcherHandler = new DispatcherHandler(context);
}
@Test
public void noHandler() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/does-not-exist"));
Mono<Void> mono = this.dispatcherHandler.handle(exchange);
StepVerifier.create(mono)
.consumeErrorWith(ex -> {
assertThat(ex).isInstanceOf(ResponseStatusException.class);
assertThat(ex.getMessage()).isEqualTo("404 NOT_FOUND");
})
.verify();
// SPR-17475
AtomicReference<Throwable> exceptionRef = new AtomicReference<>();
StepVerifier.create(mono).consumeErrorWith(exceptionRef::set).verify();
StepVerifier.create(mono).consumeErrorWith(ex -> assertThat(ex).isNotSameAs(exceptionRef.get())).verify();
}
@Test
public void noStaticResource() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(StaticResourceConfig.class);
context.refresh();
MockServerHttpRequest request = MockServerHttpRequest.get("/resources/non-existing").build();
MockServerWebExchange exchange = MockServerWebExchange.from(request);
new DispatcherHandler(context).handle(exchange).block();
MockServerHttpResponse response = exchange.getResponse();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
assertThat(response.getBodyAsString().block()).isEqualTo("""
{"type":"about:blank",\
"title":"Not Found",\
"status":404,\
"detail":"No static resource non-existing.",\
"instance":"/resources/non-existing"}\
""");
}
@Test
public void controllerReturnsMonoError() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/error-signal"));
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error -> assertThat(error).isSameAs(EXCEPTION))
.verify();
}
@Test
public void controllerThrowsException() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/raise-exception"));
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error -> assertThat(error).isSameAs(EXCEPTION))
.verify();
}
@Test
public void unknownReturnType() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/unknown-return-type"));
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error ->
assertThat(error)
.isInstanceOf(IllegalStateException.class)
.hasMessageStartingWith("No HandlerResultHandler"))
.verify();
}
@Test
public void responseBodyMessageConversionError() {
ServerWebExchange exchange = MockServerWebExchange.from(
MockServerHttpRequest.post("/request-body").accept(APPLICATION_JSON).body("body"));
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error -> assertThat(error).isInstanceOf(NotAcceptableStatusException.class))
.verify();
}
@Test
public void requestBodyError() {
ServerWebExchange exchange = MockServerWebExchange.from(
MockServerHttpRequest.post("/request-body").body(Mono.error(EXCEPTION)));
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error -> assertThat(error).isSameAs(EXCEPTION))
.verify();
}
@Test
public void webExceptionHandler() {
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/unknown-argument-type"));
List<WebExceptionHandler> handlers = Collections.singletonList(new ServerError500ExceptionHandler());
WebHandler webHandler = new ExceptionHandlingWebHandler(this.dispatcherHandler, handlers);
webHandler.handle(exchange).block(Duration.ofSeconds(5));
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}
@Configuration
@SuppressWarnings({"unused", "WeakerAccess"})
static class TestConfig {
@Bean
public RequestMappingHandlerMapping handlerMapping() {
return new RequestMappingHandlerMapping();
}
@Bean
public RequestMappingHandlerAdapter handlerAdapter() {
return new RequestMappingHandlerAdapter();
}
@Bean
public ResponseBodyResultHandler resultHandler() {
return new ResponseBodyResultHandler(Collections.singletonList(
new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly())),
new HeaderContentTypeResolver());
}
@Bean
public TestController testController() {
return new TestController();
}
}
@Controller
@SuppressWarnings("unused")
private static class TestController {
@RequestMapping("/error-signal")
@ResponseBody
public Publisher<String> errorSignal() {
return Mono.error(EXCEPTION);
}
@RequestMapping("/raise-exception")
public void raiseException() {
throw EXCEPTION;
}
@RequestMapping("/unknown-return-type")
public Foo unknownReturnType() {
return new Foo();
}
@RequestMapping("/request-body")
@ResponseBody
public Publisher<String> requestBody(@RequestBody Publisher<String> body) {
return Mono.from(body).map(s -> "hello " + s);
}
}
private static class Foo {
}
@Configuration
@SuppressWarnings({"unused", "WeakerAccess"})
static class StaticResourceConfig {
@Bean
public SimpleUrlHandlerMapping resourceMapping(ResourceWebHandler resourceWebHandler) {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setUrlMap(Map.of("/resources/**", resourceWebHandler));
return mapping;
}
@Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
return new RequestMappingHandlerAdapter();
}
@Bean
public SimpleHandlerAdapter simpleHandlerAdapter() {
return new SimpleHandlerAdapter();
}
@Bean
public ResourceWebHandler resourceWebHandler() {
return new ResourceWebHandler();
}
@Bean
public ResponseEntityResultHandler responseEntityResultHandler() {
ServerCodecConfigurer configurer = ServerCodecConfigurer.create();
return new ResponseEntityResultHandler(configurer.getWriters(), new HeaderContentTypeResolver());
}
@Bean
GlobalExceptionHandler globalExceptionHandler() {
return new GlobalExceptionHandler();
}
}
@ControllerAdvice
private static class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
}
private static class ServerError500ExceptionHandler implements WebExceptionHandler {
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
return Mono.empty();
}
}
}
|
package domain;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class Price
{
private static final SimpleDateFormat inputDf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
private Pricelist priceList;
private Date validFrom;
private BigDecimal value;
private OrganizationalUnit organizationalUnit;
public Price(final Pricelist priceList, final Date validFrom, final BigDecimal value,
final OrganizationalUnit organizationalUnit)
{
super();
this.priceList = priceList;
this.validFrom = validFrom;
this.value = value;
this.organizationalUnit = organizationalUnit;
}
/**
* old contructor
*
* @param priceList
* @param validFrom
* @param value
*/
public Price(final Pricelist priceList, final Date validFrom, final BigDecimal value)
{
super();
this.priceList = priceList;
this.validFrom = validFrom;
this.value = value;
}
public JSONObject toJSON()
{
final JSONObject obj = new JSONObject();
try
{
obj.put("priceList", priceList.getUuid());
obj.put("validFrom", inputDf.format(validFrom));
obj.put("value", value);
if (organizationalUnit != null)
obj.put("organizationalUnit", organizationalUnit.getUuid());
return obj;
}
catch (final JSONException e)
{
e.printStackTrace();
return null;
}
}
public Pricelist getPriceList()
{
return priceList;
}
public void setPriceList(final Pricelist priceList)
{
this.priceList = priceList;
}
public BigDecimal getValue()
{
return value;
}
public OrganizationalUnit getOrganizationalUnit()
{
return organizationalUnit;
}
public void setValue(final BigDecimal value)
{
this.value = value;
}
public void setOrganizationalUnit(final OrganizationalUnit organizationalUnit)
{
this.organizationalUnit = organizationalUnit;
}
public Date getValidFrom()
{
return validFrom;
}
public void setValidFrom(final Date validFrom)
{
this.validFrom = validFrom;
}
@Override
public boolean equals(final Object obj)
{
return obj.hashCode() == this.hashCode();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((this.priceList == null) ? 0 : this.priceList.hashCode());
result = prime * result + ((this.validFrom == null) ? 0 : this.validFrom.hashCode());
result = prime * result + ((this.value == null) ? 0 : this.value.hashCode());
return result;
}
}
|
public class Nest{
public static void main(String[] args){
int x, y;
x = 0;
y = 0;
while (x < 11){
while (y < 5){
System.out.print(" * ");
y++;
}
x ++;
System.out.println("");
y = 0;
}
}
} |
package com.codeaches.activmq.embedded;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
@Service
public class JmsConsumer {
Logger log = LoggerFactory.getLogger(JmsConsumer.class);
@JmsListener(destination = "${activemq.queue.name}")
public void receive(String message) {
log.info("Received message='{}'", message);
}
}
|
/**
* Course: Development for mobile applications.
* Umeå University
* Summer 2019
* @author Alex Norrman
*/
package se.umu.cs.alno0025.fjallstugan;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.android.gms.maps.model.LatLng;
public class Fjallstation implements Parcelable{
private String name;
private String adress;
private String email;
private String phoneNr;
private String url;
private String imgUrl;
private double lat;
private double lng;
/**
* Constructor for the Fjallstation-model.
* @param name Name of the station.
* @param adress The adress for the station.
* @param email Email for the station.
* @param phoneNr Phone number to the station.
* @param url Website for the station.
* @param imgUrl URL for the image of the station.
* @param lat Latitude of the stations position.
* @param lng Longitude of the stations position.
*/
public Fjallstation(String name, String adress, String email, String phoneNr,
String url, String imgUrl, double lat, double lng){
this.name = name;
this.adress = adress;
this.email = email;
this.phoneNr = phoneNr;
this.url = url;
this.imgUrl = imgUrl;
this.lat = lat;
this.lng = lng;
}
/**
* Returns the coordinates, in LatLng, for the position of the station.
* @return latitude and longitude.
*/
public com.google.android.gms.maps.model.LatLng getLatLng() {
return new LatLng(lat, lng);
}
/**
* Returns the adress for the station.
* @return adress.
*/
public String getAdress() {
return adress;
}
/**
* Returns the email for the station.
* @return email.
*/
public String getEmail() {
return email;
}
/**
* Returns the name for the station.
* @return name.
*/
public String getName() {
return name;
}
/**
* Returns the phone number for the station.
* @return phone number.
*/
public String getPhoneNr() {
return phoneNr;
}
/**
* Returns the website for the station.
* @return url.
*/
public String getUrl() {
return url;
}
/**
* Returns the URL for the stations image.
* @return image-url.
*/
public String getImgUrl(){
return imgUrl;
}
/** Method for Parcelable.
* @return int = 0.
*/
public int describeContents() {
return 0;
}
/**
* Flatten this fjallstation in to a Parcel
* @param out The Parcel in which the object should be written.
* @param flags Additional flags about how the object should be written
*/
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(name);
out.writeString(adress);
out.writeString(email);
out.writeString(phoneNr);
out.writeString(url);
out.writeString(imgUrl);
out.writeDouble(lat);
out.writeDouble(lng);
}
/**
* Constructor used to initialize the fjallstation
* again after recreation.
* @param in Parcel with the fjallstation to recreate
*/
private Fjallstation(Parcel in){
name = in.readString();
adress = in.readString();
email = in.readString();
phoneNr = in.readString();
url = in.readString();
imgUrl = in.readString();
lat = in.readDouble();
lng = in.readDouble();
}
/**
* Interface that must be implemented and provided as a public CREATOR field
* that generates instances of the Parcelable fjallstation class from a Parcel.
*/
public static final Creator<Fjallstation> CREATOR = new Creator<Fjallstation>() {
// Create a new instance of the Parcelable class.
@Override
public Fjallstation createFromParcel(Parcel in) {
return new Fjallstation(in);
}
// Create a new array of the Parcelable class.
@Override
public Fjallstation[] newArray(int size) {
return new Fjallstation[size];
}
};
}
|
package com.vpt.pw.demo.dtos.crf5bDTO;
import com.vpt.pw.demo.dtos.PregnantWomanDTO;
import com.vpt.pw.demo.dtos.StudiesDTO;
import com.vpt.pw.demo.model.Team;
import java.util.List;
public class FormCrf5bDTO {
private Integer id;
private Team team;
private StudiesDTO studiesDTO;
private Integer followupNumber = -1;
private PregnantWomanDTO pregnantWoman;
private String q02;
private String q03;
private String refusedReason;
private String q18;
private String q19;
private String q20;
private String q21;
private String q46;
private String q47;
private String q48;
private String q49;
private String q50;
private String q51;
private String q52;
private String q53;
private String q54;
private String q55;
private String q56;
private List<FormCrf5bDetailsDTO> details;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
public StudiesDTO getStudiesDTO() {
return studiesDTO;
}
public void setStudiesDTO(StudiesDTO studiesDTO) {
this.studiesDTO = studiesDTO;
}
public Integer getFollowupNumber() {
return followupNumber;
}
public void setFollowupNumber(Integer followupNumber) {
this.followupNumber = followupNumber;
}
public PregnantWomanDTO getPregnantWoman() {
return pregnantWoman;
}
public void setPregnantWoman(PregnantWomanDTO pregnantWoman) {
this.pregnantWoman = pregnantWoman;
}
public String getQ02() {
return q02;
}
public void setQ02(String q02) {
this.q02 = q02;
}
public String getQ03() {
return q03;
}
public void setQ03(String q03) {
this.q03 = q03;
}
public String getRefusedReason() {
return refusedReason;
}
public void setRefusedReason(String refusedReason) {
this.refusedReason = refusedReason;
}
public String getQ18() {
return q18;
}
public void setQ18(String q18) {
this.q18 = q18;
}
public String getQ19() {
return q19;
}
public void setQ19(String q19) {
this.q19 = q19;
}
public String getQ20() {
return q20;
}
public void setQ20(String q20) {
this.q20 = q20;
}
public String getQ21() {
return q21;
}
public void setQ21(String q21) {
this.q21 = q21;
}
public String getQ46() {
return q46;
}
public void setQ46(String q46) {
this.q46 = q46;
}
public String getQ47() {
return q47;
}
public void setQ47(String q47) {
this.q47 = q47;
}
public String getQ48() {
return q48;
}
public void setQ48(String q48) {
this.q48 = q48;
}
public String getQ49() {
return q49;
}
public void setQ49(String q49) {
this.q49 = q49;
}
public String getQ50() {
return q50;
}
public void setQ50(String q50) {
this.q50 = q50;
}
public String getQ51() {
return q51;
}
public void setQ51(String q51) {
this.q51 = q51;
}
public String getQ52() {
return q52;
}
public void setQ52(String q52) {
this.q52 = q52;
}
public String getQ53() {
return q53;
}
public void setQ53(String q53) {
this.q53 = q53;
}
public String getQ54() {
return q54;
}
public void setQ54(String q54) {
this.q54 = q54;
}
public String getQ55() {
return q55;
}
public void setQ55(String q55) {
this.q55 = q55;
}
public String getQ56() {
return q56;
}
public void setQ56(String q56) {
this.q56 = q56;
}
public List<FormCrf5bDetailsDTO> getDetails() {
return details;
}
public void setDetails(List<FormCrf5bDetailsDTO> details) {
this.details = details;
}
}
|
//Name: Adham Elarabawy
public class WordSearch {
private String[][] oMatrix;
private int rows;
private int columns;
public WordSearch(int size, String str) {
oMatrix = new String[size][size];
int index = 1;
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
oMatrix[i][j] = str.substring(index - 1, index);
index++;
}
}
rows = oMatrix.length;
columns = oMatrix[0].length;
}
public boolean isFound(String word) {
for(int i = 0; i < oMatrix.length; i++) {
for(int j = 0; j < oMatrix[i].length; j++) {
if(checkRight(word, i, j) || checkLeft(word, i, j) ||
checkUp(word, i, j) || checkDown(word, i, j) ||
checkDiagUpRight(word, i, j) ||
checkDiagUpLeft(word, i, j) ||
checkDiagDownRight(word, i, j) ||
checkDiagDownLeft(word, i, j)) {
return true;
}
}
}
return false;
}
public boolean checkRight(String w, int r, int c) {
String test = "";
for(int i = 0; i < w.length(); i++) {
String check = getInBounds(r + i, c);
if(check.equals(""))
return false;
test += check;
}
if(test.equals(w))
return true;
return false;
}
public boolean checkLeft(String w, int r, int c) {
String test = "";
for(int i = 0; i < w.length(); i++) {
String check = getInBounds(r - i, c);
if(check.equals(""))
return false;
test += check;
}
if(test.equals(w))
return true;
return false;
}
public boolean checkUp(String w, int r, int c) {
String test = "";
for(int i = 0; i < w.length(); i++) {
String check = getInBounds(r, c - i);
if(check.equals(""))
return false;
test += check;
}
if(test.equals(w))
return true;
return false;
}
public boolean checkDown(String w, int r, int c) {
String test = "";
for(int i = 0; i < w.length(); i++) {
String check = getInBounds(r, c + i);
if(check.equals(""))
return false;
test += check;
}
if(test.equals(w))
return true;
return false;
}
public boolean checkDiagUpRight(String w, int r, int c) {
String test = "";
for(int i = 0; i < w.length(); i++) {
String check = getInBounds(r + i, c - i);
if(check.equals(""))
return false;
test += check;
}
if(test.equals(w))
return true;
return false;
}
public boolean checkDiagUpLeft(String w, int r, int c) {
String test = "";
for(int i = 0; i < w.length(); i++) {
String check = getInBounds(r - i, c - i);
if(check.equals(""))
return false;
test += check;
}
if(test.equals(w))
return true;
return false;
}
public boolean checkDiagDownLeft(String w, int r, int c) {
String test = "";
for(int i = 0; i < w.length(); i++) {
String check = getInBounds(r - i, c + i);
if(check.equals(""))
return false;
test += check;
}
if(test.equals(w))
return true;
return false;
}
public boolean checkDiagDownRight(String w, int r, int c) {
String test = "";
for(int i = 0; i < w.length(); i++) {
String check = getInBounds(r + i, c + i);
if(check.equals(""))
return false;
test += check;
}
if(test.equals(w))
return true;
return false;
}
private String getInBounds(int r, int c) {
if(c >= 0 && c < rows) {
if(r >= 0 && r < columns) {
return oMatrix[c][r];
}
}
return "";
}
public String toString() {
String matrix = "";
for(String[] i : oMatrix) {
for(String j : i) {
matrix += j + " ";
}
matrix += "\n";
}
return matrix;
}
}
|
package com.atlassian.theplugin.idea.jira.tree;
import com.atlassian.theplugin.commons.remoteapi.ServerData;
import com.atlassian.theplugin.commons.util.MiscUtil;
import com.atlassian.theplugin.idea.ui.Entry;
import com.atlassian.theplugin.idea.ui.tree.paneltree.AbstractTreeNode;
import com.atlassian.theplugin.jira.model.JiraCustomFilter;
import com.intellij.openapi.util.IconLoader;
import org.apache.commons.lang.StringUtils;
import javax.swing.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
/**
* User: pmaruszak
*/
public class JIRAFilterTreeRenderer extends DefaultTreeCellRenderer {
private static final Icon JIRA_FILTER_ICON = IconLoader.getIcon("/icons/jira/nodes/ico_jira_filter.png");
private static final Icon JIRA_RECENTLY_OPEN_ISSUES_ICON =
IconLoader.getIcon("/icons/jira/nodes/ico_jira_recent_issues.png");
private static final String TOOLTIP_FOOTER_HTML = "<hr style=\"height: '1'; text-align: 'left'; "
+ "color: 'black'; width: '100%'\">"
+ "<p style=\"font-size:'90%'; color:'grey'\">right click on filter node to edit</p>";
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
JComponent c = (JComponent) super.getTreeCellRendererComponent(
tree, value, selected, expanded, leaf, row, hasFocus);
setToolTipText(null);
if (value instanceof JiraPresetFilterTreeNode && c instanceof JLabel) {
((JLabel) c).setIcon(JIRA_FILTER_ICON);
return c;
}
if (value instanceof JIRAManualFilterTreeNode && c instanceof JLabel) {
final JIRAManualFilterTreeNode filterTreeNode = (JIRAManualFilterTreeNode) value;
setToolTipText(createManualFilterToolTipText(filterTreeNode.getManualFilter(),
filterTreeNode.getJiraServerCfg()));
((JLabel) c).setIcon(JIRA_FILTER_ICON);
JiraCustomFilter filter = ((JIRAManualFilterTreeNode) value).getManualFilter();
if (filter != null && filter.isEmpty()) {
JLabel label = ((JLabel) c);
label.setText(label.getText() + " (not defined)");
}
return c;
//return ((JIRAManualFilterTreeNode) value).getRenderer(c, selected, expanded, hasFocus);
}
if (value instanceof JIRASavedFilterTreeNode && c instanceof JLabel) {
((JLabel) c).setIcon(JIRA_FILTER_ICON);
return c;
}
if (value instanceof AbstractJiraFilterGroupTreeNode) {
((JLabel) c).setIcon(((AbstractJiraFilterGroupTreeNode) value).getIcon());
return c;
}
if (value instanceof JiraRecentlyOpenTreeNode && c instanceof JLabel) {
((JLabel) c).setIcon(JIRA_RECENTLY_OPEN_ISSUES_ICON);
return c;
}
if (value instanceof JIRAServerTreeNode && c instanceof JLabel) {
((JLabel) c).setIcon(JIRAServerTreeNode.JIRA_SERVER_ENABLED_ICON);
((JLabel) c).setDisabledIcon(JIRAServerTreeNode.JIRA_SERVER_DISABLED_ICON);
c.setBorder(BorderFactory.createEmptyBorder());
return c;
}
if (value instanceof AbstractTreeNode) {
return ((AbstractTreeNode) value).getRenderer(c, selected, expanded, hasFocus);
}
return c;
}
private String createManualFilterToolTipText(JiraCustomFilter manualFilter, ServerData server) {
Collection<Entry> entries = MiscUtil.buildArrayList();
Map<JiraCustomFilter.QueryElement, ArrayList<String>> map = manualFilter.groupBy(true);
for (JiraCustomFilter.QueryElement element : map.keySet()) {
entries.add(new Entry(element.getName(), StringUtils.join(map.get(element), ", ")));
}
if (entries.size() == 0) {
// get also 'any' values
map = manualFilter.groupBy(false);
for (JiraCustomFilter.QueryElement element : map.keySet()) {
entries.add(new Entry(element.getName(), StringUtils.join(map.get(element), ", ")));
}
}
StringBuffer sb = new StringBuffer();
sb.append("<html>");
if (entries.size() == 0) {
sb.append("No Custom Filter Defined");
} else {
sb.append("<html><table>");
sb.append("<tr><td><font color=blue><b>").append(server.getName()).append("</b></td><td></td>");
for (Entry entry : entries) {
sb.append("<tr><td><b>").append(entry.getLabel()).append(":")
.append("</b></td><td>");
if (entry.isError()) {
sb.append("<font color=red>");
}
sb.append(entry.getValue()).append("</td></tr>");
}
sb.append("</table>");
}
sb.append(TOOLTIP_FOOTER_HTML);
sb.append("</html>");
return sb.toString();
}
}
|
package com.codingchili.instance.model.skills;
import com.codingchili.core.storage.Storable;
/**
* Configuration used for harvesting resources.
*/
public class HarvestConfig implements Storable {
private String id;
// skill required to harvest the resource.
private SkillType skill;
// amount of experience granted to player on completion.
private int experience;
// chance of successfully harvesting, either per resource or per action.
private float success;
// base chance of failing to harvest the resource, resulting in
// a consequence to the player.
private float fail;
// the time required to harvest the resource.
private int time;
@Override
public String getId() {
return id;
}
public SkillType getSkill() {
return skill;
}
public void setSkill(SkillType skill) {
this.skill = skill;
}
public int getExperience() {
return experience;
}
public void setExperience(int experience) {
this.experience = experience;
}
public float getSuccess() {
return success;
}
public void setSuccess(float success) {
this.success = success;
}
public float getFail() {
return fail;
}
public void setFail(float fail) {
this.fail = fail;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
} |
package pers.mine.scratchpad.other;
import java.util.concurrent.atomic.AtomicInteger;
public class SafepointTest {
public static AtomicInteger num = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
// Runnable runnable = () -> {
// for (int i = 0; i < 1000000000; i++) {
// num.getAndAdd(1);
// }
// };
//
// Thread t1 = new Thread(runnable);
// Thread t2 = new Thread(runnable);
// t1.start();
// t2.start();
// Thread.sleep(1000);
// System.out.println("num = " + num);
Class<? extends Object> aClass = new Object() {
}.getClass();
System.out.println(aClass == Object.class);
}
}
|
package com.spring.testable.mock;
import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
/**
* @author caiie
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
ParameterBuilder signParam = new ParameterBuilder();
ParameterBuilder timeParam = new ParameterBuilder();
ParameterBuilder tokenParam = new ParameterBuilder();
ArrayList<Parameter> pars = new ArrayList<>();
signParam.name("sign").description("user sign").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
//header中的sign参数非必填,传空也可以
timeParam.name("timestamp").description("request timestamp mills").modelRef(new ModelRef("string"))
.parameterType("header").required(false).build();
tokenParam.name("token").description("login token").modelRef(new ModelRef("string")).parameterType("header")
.required(false).build();
pars.add(signParam.build());
pars.add(timeParam.build());
pars.add(tokenParam.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build().globalOperationParameters(pars);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("testable mock demo")
.description("testable mock demo")
.termsOfServiceUrl("http://xx.io/")
.version("1.0")
.build();
}
} |
/*
* 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 Ex;
/**
*
* @author YNZ
*/
class UnReached {
public static void main(String[] args) {
try {
amethod();
System.out.println("try");
} catch (Exception e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
System.out.println("out");
}
public static void amethod() throws Exception {
}
}
|
package org.patsimas.mongo.domain;
import lombok.*;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.FieldType;
import org.springframework.data.mongodb.core.mapping.MongoId;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(collection = "movies")
public class Movie {
@MongoId(FieldType.OBJECT_ID) // or @Id
private Integer id;
private String title;
private List<String> genre;
private String director;
private Integer year;
private Double revenue;
}
|
package test.nested;
import test.other.Imported;
import static test.other.Static.method;
import static test.other.StaticAll.alpha;
import static test.other.StaticAll.beta;
public class Src {
Imported imported;
public void test() {
method(imported);
alpha();
beta();
}
}
|
package com.example.trialattemptone;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.trialattemptone.Creators.Course;
import com.example.trialattemptone.Creators.CourseStatus;
import com.example.trialattemptone.Creators.Mentor;
import com.example.trialattemptone.Creators.Term;
import com.example.trialattemptone.database.DataSource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class EditCourseScreen extends AppCompatActivity {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
DataSource mDataSource;
public static int selectedCourseForEdit;
public static Term currentTerm;
public static Course selectedEditCourse;
public static String courseTitle;
public int startOrEnd;
CalendarView calView;
public static String startingDate;
public static String endingDate = "";
Button selectDateButton;
Date termStart;
Date termEnd;
public static int termIDSelection;
public static int statusIDSelection;
public static int mentorIDSelection;
public static int selectedTermSpinnerItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_course_screen);
selectedCourseForEdit = CourseDetailsScreen.selCourseID;
mDataSource = new DataSource(this);
mDataSource.open();
selectedEditCourse = mDataSource.getCourseByID(selectedCourseForEdit);
EditText ecTitle = findViewById(R.id.eCourseTitleET);
EditText ecStartDate = findViewById(R.id.eStartDateET);
EditText ecEndDate = findViewById(R.id.eEndDateET);
ecTitle.setText(selectedEditCourse.getCourseTitle());
ecStartDate.setText(selectedEditCourse.getCourseStart());
ecEndDate.setText(selectedEditCourse.getCourseEnd());
Spinner ectSpinner = findViewById(R.id.eTermSpinner);
Spinner ecsSpinner = findViewById(R.id.eStatusSpinner);
Spinner ecmSpinner = findViewById(R.id.eMentorSpinner);
setupSpinners();
getSupportActionBar().setTitle("Edit " + selectedEditCourse.getCourseTitle());
}
// Methods for the addcourse_layout
public void startDatePickPressed(View view)
{
currentTerm = mDataSource.getTermByTermID(termIDSelection);
try
{
termStart = sdf.parse(currentTerm.getStartDate());
termEnd = sdf.parse(currentTerm.getEndDate());
}catch (ParseException ex)
{
System.out.println(ex.getLocalizedMessage());
}
EditText titleEditT = findViewById(R.id.eCourseTitleET);
if (titleEditT.getText().toString().isEmpty() == false)
{
courseTitle = titleEditT.getText().toString();
}
startOrEnd =0;
setContentView(R.layout.activity_date_picker);
getSupportActionBar().setTitle("Pick a Starting Date");
calView = findViewById(R.id.calendarView);
long date = calView.getDate();
// Setup the starting date
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date);
calendar.setTime(new Date(calView.getDate()));
startingDate = sdf.format(new Date(calendar.getTime().getTime()));
selectDateButton = findViewById(R.id.selectButton);
calView = findViewById(R.id.calendarView);
calView.setMinDate(termStart.getTime());
calView.setMaxDate(termEnd.getTime());
calView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
String selMonth = String.valueOf(month + 1);
String selYear = String.valueOf(year);
String selDay = String.valueOf(dayOfMonth);
String newMonth = selMonth;
String newDay = selDay;
String newYear = selYear;
if (month < 10)
{
newMonth = "0" + selMonth;
}
if (dayOfMonth < 10)
{
newDay = "0" + selDay;
}
startingDate = newMonth + "/" + newDay + "/" + newYear;
System.out.println(startingDate);
}
});
}
public void endDatePickPressed(View view)
{
currentTerm = mDataSource.getTermByTermID(termIDSelection);
try
{
termStart = sdf.parse(currentTerm.getStartDate());
termEnd = sdf.parse(currentTerm.getEndDate());
}catch (ParseException ex)
{
System.out.println(ex.getLocalizedMessage());
}
EditText titleEditT = findViewById(R.id.eCourseTitleET);
if (titleEditT.getText().toString().isEmpty() == false)
{
courseTitle = titleEditT.getText().toString();
}
startOrEnd = 1;
setContentView(R.layout.activity_date_picker);
getSupportActionBar().setTitle("Pick a Ending Date");
selectDateButton = findViewById(R.id.selectButton);
calView = findViewById(R.id.calendarView);
calView.setMinDate(termStart.getTime());
calView.setMaxDate(termEnd.getTime());
calView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
String selMonth = String.valueOf(month + 1);
String selYear = String.valueOf(year);
String selDay = String.valueOf(dayOfMonth);
String newMonth = selMonth;
String newDay = selDay;
String newYear = selYear;
if (month < 10)
{
newMonth = "0" + selMonth;
}
if (dayOfMonth < 10)
{
newDay = "0" + selDay;
}
endingDate = newMonth + "/" + newDay + "/" + newYear;
System.out.println(endingDate);
}
});
}
public void createMentorButtonPressed(View view)
{
setContentView(R.layout.addmentor_layout);
}
public void cancelButtonPressed(View view)
{
finish();
Intent intent = new Intent(this, CourseDetailsScreen.class);
startActivity(intent);
}
public void saveButtonPressed(View view)
{
EditText titleEditT = findViewById(R.id.eCourseTitleET);
EditText esdET = findViewById(R.id.eStartDateET);
EditText eedET = findViewById(R.id.eEndDateET);
String editStartDate = esdET.getText().toString();
String editEndDate = eedET.getText().toString();
String courseTitle = titleEditT.getText().toString();
Course course = new Course(courseTitle, editStartDate, editEndDate, termIDSelection, statusIDSelection, mentorIDSelection);
mDataSource.updateCourse(course, selectedCourseForEdit);
Toast.makeText(this, "Course Edited", Toast.LENGTH_SHORT).show();
this.finish();
Intent intent = new Intent(this, CourseDetailsScreen.class);
startActivity(intent);
}
// Create methods for date selection layout
public void selectButtonPressed(View view)
{
if (startOrEnd == 0)
{
setContentView(R.layout.activity_edit_course_screen);
EditText startEdit = findViewById(R.id.eStartDateET);
startEdit.setText(startingDate);
EditText tTitle = findViewById(R.id.eCourseTitleET);
tTitle.setText(courseTitle);
setupSpinners();
Spinner spinnerTerm = findViewById(R.id.eTermSpinner);
spinnerTerm.setSelection(selectedTermSpinnerItem);
}
else if (startOrEnd == 1)
{
setContentView(R.layout.activity_edit_course_screen);
EditText startEdit = findViewById(R.id.eStartDateET);
startEdit.setText(endingDate);
EditText tTitle = findViewById(R.id.eCourseTitleET);
tTitle.setText(courseTitle);
setupSpinners();
Spinner spinnerTerm = findViewById(R.id.eTermSpinner);
spinnerTerm.setSelection(selectedTermSpinnerItem);
}
if (startingDate.isEmpty() == false && endingDate.isEmpty() == false)
{
setContentView(R.layout.activity_edit_course_screen);
EditText startEditText = findViewById(R.id.eStartDateET);
EditText endEditText = findViewById(R.id.eEndDateET);
startEditText.setText(startingDate);
endEditText.setText(endingDate);
EditText tTitle = findViewById(R.id.eCourseTitleET);
tTitle.setText(courseTitle);
setupSpinners();
Spinner spinnerTerm = findViewById(R.id.eTermSpinner);
spinnerTerm.setSelection(selectedTermSpinnerItem);
}
}
public void cancelDatePick(View view)
{
setContentView(R.layout.addcourse_layout);
setupSpinners();
}
// methods for addmentor_layout
public void cancelMentorButton(View view)
{
setContentView(R.layout.activity_edit_course_screen);
setupSpinners();
}
public void saveMentorButtonPressed(View view)
{
EditText firstNameET = findViewById(R.id.fNameET);
String first = firstNameET.getText().toString();
EditText lastNameET = findViewById(R.id.lNameET);
String last = lastNameET.getText().toString();
EditText phoneNumberET = findViewById(R.id.phoneET);
String phone = phoneNumberET.getText().toString();
EditText emailAddressET = findViewById(R.id.emailET);
String mail = emailAddressET.getText().toString();
Mentor mentor = new Mentor(first, last, phone, mail);
mDataSource.addMentor(mentor);
Toast.makeText(this, "Mentor Added", Toast.LENGTH_SHORT).show();
setContentView(R.layout.addcourse_layout);
setupSpinners();
EditText startEditText = findViewById(R.id.startDateET);
EditText endEditText = findViewById(R.id.endDateET);
startEditText.setText(startingDate);
endEditText.setText(endingDate);
EditText tTitle = findViewById(R.id.courseTitleET);
tTitle.setText(courseTitle);
}
// Other methods to avoid repetition
public void setupSpinners() {
List<CourseStatus> courseStatusList = mDataSource.getAllCourseStatus();
List<Mentor> mentorsList = mDataSource.getAllMentors();
List<String> courseStatusNames = new ArrayList<>();
List<String> mentorNames = new ArrayList<>();
for (CourseStatus courseStatus : courseStatusList) {
courseStatusNames.add(courseStatus.getCourseStatus());
}
for (Mentor mentor : mentorsList) {
mentorNames.add(mentor.getLastName() + ", " + mentor.getFirstName());
}
// Create and setup the spinner for terms
List<Term> termsList = mDataSource.getAllTerms();
List<String> termNamesList = new ArrayList<>();
for (Term term : termsList) {
termNamesList.add(term.getTermName());
}
Spinner spinnerTerm = findViewById(R.id.eTermSpinner);
ArrayAdapter<String> termAdapter = new ArrayAdapter<>(
this, android.R.layout.simple_spinner_item, termNamesList
);
spinnerTerm.setAdapter(termAdapter);
for (int i = 0; i < termsList.size(); i++)
{
if (selectedEditCourse.getCourseTermId() == termsList.get(i).getTermID())
{
spinnerTerm.setSelection(i);
}
}
spinnerTerm.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.getItemAtPosition(position);
selectedTermSpinnerItem = position;
System.out.println(parent.getItemAtPosition(position).toString());
System.out.println(mDataSource.getTermId(parent.getItemAtPosition(position).toString()));
termIDSelection = mDataSource.getTermId((String) parent.getItemAtPosition(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Create and setup the course status spinner
Spinner spinnerStatus = findViewById(R.id.eStatusSpinner);
ArrayAdapter<String> statusAdapter = new ArrayAdapter<>(
this, android.R.layout.simple_spinner_item, courseStatusNames
);
spinnerStatus.setAdapter(statusAdapter);
for (int i = 0; i < courseStatusList.size(); i++)
{
if (selectedEditCourse.getCourseStatusId() == courseStatusList.get(i).getCourseStatusID())
{
spinnerStatus.setSelection(i);
}
}
spinnerStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.getItemAtPosition(position);
System.out.println(parent.getItemAtPosition(position).toString());
System.out.println(mDataSource.getCourseStatusId(parent.getItemAtPosition(position).toString()));
statusIDSelection = mDataSource.getCourseStatusId((String) parent.getItemAtPosition(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Create and setup the mentor spinner
Spinner spinMentor = findViewById(R.id.eMentorSpinner);
ArrayAdapter<String> mentorAdapter = new ArrayAdapter<>(
this, android.R.layout.simple_spinner_item, mentorNames
);
spinMentor.setAdapter(mentorAdapter);
for (int i = 0; i < mentorsList.size(); i++)
{
if (selectedEditCourse.getMentorId() == mentorsList.get(i).getMentorId())
{
spinMentor.setSelection(i);
}
}
spinMentor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.getItemAtPosition(position);
String mentorFullName = parent.getItemAtPosition(position).toString().replace(",", " ");
String[] fullName = mentorFullName.split("\\s+");
mentorIDSelection = mDataSource.getMentorID(fullName[0], fullName[1]);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
|
/** Esto es un comentario para probar javadoc
* Esta clase mostrará el mensaje Mi segundo programa y bien comentado!!
* <strong> realizado en Septiembre de 2014 </strong>
*
* @author Javi
* @version 1.2
*/
public class HolaMundo2
{
/** Este metodo contiene el ccdigo ejecutable de la clase
*
* @param args Lista de argumentos de la linea de comandos
* @return Como no devuelve nada, no seria necesaria esta etiqueta
*/
public static void main (String [] args)
{
System.out.println("Mi primer programa y bien comentado!!");
//Muestra por pantalla el mensaje entre comillas
// Este comentario no sale en el Javadoc, es solo para el programador
}
} |
package at.fhv.itm14.fhvgis.persistence.exceptions;
/**
* Author: Philip Heimböck
* Date: 18.12.15.
*/
public class PersistenceException extends Exception {
public PersistenceException() {
}
public PersistenceException(String message) {
super(message);
}
public PersistenceException(String message, Throwable cause) {
super(message, cause);
}
public PersistenceException(Throwable cause) {
super(cause);
}
public PersistenceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
package at.fhv.itm14.fhvgis.persistence.dao.interfaces;
import java.util.Date;
import java.util.List;
import at.fhv.itm14.fhvgis.persistence.exceptions.PersistenceException;
import com.vividsolutions.jts.geom.Geometry;
import at.fhv.itm14.fhvgis.domain.POI;
import at.fhv.itm14.fhvgis.domain.Schedule;
import at.fhv.itm14.fhvgis.domain.TransportationRoute;
public interface IScheduleDao extends IGenericDao<Schedule> {
List<Schedule> findScheduleByPositionAndTime(Geometry position, Date date) throws PersistenceException;
List<Schedule> findSchedulesOfTransportationRoute(TransportationRoute route) throws PersistenceException;
void deleteSchedulesOfTransportationRoute(TransportationRoute transportationRoute) throws PersistenceException;
void deleteSchedulesOfPoi(POI poi) throws PersistenceException;
//void deleteSchedulesOfScheduleDay(ScheduleDay scheduleDay);
}
|
package com.openclassrooms.apisafetynet.repository;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.springframework.data.jdbc.repository.query.Modifying;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.openclassrooms.apisafetynet.constants.DBConstants;
import com.openclassrooms.apisafetynet.model.FireStation;
import com.openclassrooms.apisafetynet.model.Person;
import com.openclassrooms.apisafetynet.projection.FireAlert;
import com.openclassrooms.apisafetynet.projection.People;
@Repository
public interface FireStationsRepository extends CrudRepository<FireStation, Integer> {
@org.springframework.data.jpa.repository.Query(value = DBConstants.ADDRESSES_BY_STATION, nativeQuery = true)
//@Query(value="SELECT person.first_name, person.last_name, person.address, person.phone FROM person WHERE firestation.station = ?1 firestation.address = person.address")
List<Person> findAllByStationNumber(int station);
//@org.springframework.data.jpa.repository.Query(value = "SELECT p.last_name, p.phone, mr.birthdate, mr.allergies, mr.medications FROM Firestations f JOIN persons p JOIN medicalrecords mr", nativeQuery = true)
//@org.springframework.data.jpa.repository.Query(value = "SELECT last_name FROM persons f WHERE address = :address")
//Iterable<FireAlert> getFireAlert(@Param("address")String address);
Optional<FireStation> findByAddress(String address);
} |
package com.st.common.util;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtil {
public static final String DEFAULT_CHARTSET = "UTF-8";
/**
* 判断字符串是否为空
*
* @param str
* @return
*/
public static boolean isBlank(String str) {
int strLen;
if (str != null && (strLen = str.length()) != 0) {
for (int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
/**
* 判断字符串是否不为空
*
* @param str
* @return
*/
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
/**
* 转换为下划线
*/
public static String underscoreName(String camelCaseName) {
StringBuilder result = new StringBuilder();
if (camelCaseName != null && camelCaseName.length() > 0) {
result.append(camelCaseName.substring(0, 1).toLowerCase());
for (int i = 1; i < camelCaseName.length(); i++) {
char ch = camelCaseName.charAt(i);
if (Character.isUpperCase(ch)) {
result.append("_");
result.append(Character.toLowerCase(ch));
} else {
result.append(ch);
}
}
}
return result.toString();
}
/**
* 转换为驼峰
*/
public static String camelCaseName(String underscoreName) {
StringBuilder result = new StringBuilder();
if (underscoreName != null && underscoreName.length() > 0) {
boolean flag = false;
for (int i = 0; i < underscoreName.length(); i++) {
char ch = underscoreName.charAt(i);
if ("_".charAt(0) == ch) {
flag = true;
} else {
if (flag) {
result.append(Character.toUpperCase(ch));
flag = false;
} else {
result.append(ch);
}
}
}
}
return result.toString();
}
/**
* 根据模板生成生成字符串
*
* @param template
* @param params
* @return
*/
public static String processTemplate(String template, HashMap<Object, Object> params) {
StringBuffer sb = new StringBuffer();
Matcher m = Pattern.compile("\\$\\{ {0,1}\\w+ {0,1}\\}").matcher(template);
while (m.find()) {
String param = m.group();
Object value = params.get(param.substring(2, param.length() - 1).trim());
m.appendReplacement(sb, value == null ? "" : value.toString());
}
return sb.toString();
}
/**
* 简单判断text是否为json
*
* @param text
* @return
*/
public static boolean isJson(String text) {
text = text.trim();
if (text.startsWith("{") && text.endsWith("}")) {
return true;
} else {
return false;
}
}
/**
* 简单判断text是否为xml
*
* @param text
* @return
*/
public static boolean isXml(String text) {
text = text.trim();
if (text.startsWith("<") && text.endsWith(">")) {
return true;
} else {
return false;
}
}
public static boolean isMatches(String str, String regular) {
boolean flag = false;
Pattern p = Pattern.compile(regular);
Matcher m = p.matcher(str);
if (m.matches()) {
flag = true;
}
return flag;
}
} |
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations;
import org.giddap.dreamfactory.leetcode.onlinejudge.WordBreak;
import java.util.Set;
/**
* one-dimension DP
*/
public class WordBreakImpl implements WordBreak {
public boolean wordBreak(String s, Set<String> dict) {
final int len = s.length();
if (len == 0) {
return false;
}
boolean[] memo = new boolean[len + 1];
memo[0] = true;
for (int i = 1; i <= len; i++) {
for (int j = 0; j <= i; j++) {
if (memo[j] && dict.contains(s.substring(j, i))) {
memo[i] = true;
break;
}
}
}
return memo[len];
}
}
|
package io.devchaos.comm.domain;
import lombok.Data;
import javax.validation.constraints.NotBlank;
/**
* @author Paulo Jesus
*/
@Data
public class PlayerEvent {
@NotBlank
private String playerId;
}
|
package ru.avokin.highlighting.impl;
import ru.avokin.highlighting.CodeHighlighter;
import ru.avokin.highlighting.CodeHighlighterManager;
import ru.avokin.utils.FileUtils;
import java.io.File;
import java.util.Map;
/**
* User: Andrey Vokin
* Date: 06.10.2010
*/
public class CodeHighlighterManagerImpl implements CodeHighlighterManager {
private final Map<String, CodeHighlighter> fileExtensionToHighlightersMap;
private final CodeHighlighter defaultCodeHighlighter;
public CodeHighlighterManagerImpl(Map<String, CodeHighlighter> fileExtensionToHighlightersMap,
CodeHighlighter defaultCodeHighlighter) {
this.fileExtensionToHighlightersMap = fileExtensionToHighlightersMap;
this.defaultCodeHighlighter = defaultCodeHighlighter;
}
public CodeHighlighter getCodeHighlighter(File file) {
String fileExtension = FileUtils.getExtension(file);
CodeHighlighter result = fileExtensionToHighlightersMap.get(fileExtension);
if (result == null) {
result = defaultCodeHighlighter;
}
return result;
}
}
|
package com.zkdemo;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
public class XMLMemRead {
public static void main(String[] args) throws Exception {
File f = new File("pom.xml");
BufferedInputStream bins = new BufferedInputStream(new FileInputStream(f));
byte[] file = new byte[bins.read()];
}
}
|
package com.example.springmvc.controller;
import com.example.springmvc.model.User;
import com.example.springmvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@RequestMapping(value = "/hotel-it/users")
@CrossOrigin(origins = "*",allowedHeaders = "*")
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public ResponseEntity<String> createUser(@RequestBody User user) {
user = userService.createNewUser(user);
return ResponseEntity.ok("User " + user.getName() + " " + user.getLastName() + " " + user.getMiddleName() + " successfully created!");
}
@DeleteMapping("/{id}")
@ResponseBody
public ResponseEntity<String> deleteUser(@PathVariable("id") long id) {
try {
userService.deleteUser(id);
return ResponseEntity.ok("User " + id + " was deleted successfully");
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/*@GetMapping
@ResponseBody
public List<User> getAllUsers(@RequestParam String... sort) {
return userService.getAllUsersList(sort);
}*/
@GetMapping
@ResponseBody
public List<User> getAllUsers(@RequestParam String sort, @RequestParam boolean isAsc, @RequestParam int limit, @RequestParam int page) {
return userService.getAllUsersForTable(sort, isAsc, limit, page);
}
@GetMapping("/{id}")
@ResponseBody
public User getUser(@PathVariable long id) {
return userService.getUserById(id);
}
@PutMapping("/{id}")
public void update(@PathVariable("id") long id, String name, String lastName, String middleName, Date date, String address, String phone, String email) {
userService.updateUser(id, name, lastName, middleName, date, address, phone, email);
}
}
|
package com.xingzy.viewmodels;
import com.xingzy.data.Plant;
import com.xingzy.data.PlantRepository;
import java.util.List;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
/**
* @author roy.xing
* @date 2018/12/6
*/
public class PlantListViewModel extends ViewModel {
private static final int NO_GROW_ZONE = -1;
private MutableLiveData<Integer> growZoneNumber;
private MediatorLiveData<List<Plant>> plantList;
public PlantListViewModel(PlantRepository plantRepository) {
growZoneNumber = new MutableLiveData<>();
plantList = new MediatorLiveData<>();
growZoneNumber.setValue(NO_GROW_ZONE);
LiveData<List<Plant>> livePlantList = Transformations.switchMap(growZoneNumber, it -> {
if (it == NO_GROW_ZONE) {
return plantRepository.getPlants();
} else {
return plantRepository.getPlantsWithGrowZoneNumber(it);
}
});
plantList.addSource(livePlantList, plantList::setValue);
}
public LiveData<List<Plant>> plantList() {
return plantList;
}
public void setGrowZoneNumber(int number) {
growZoneNumber.setValue(number);
}
public void clearGrowZoneNumber() {
growZoneNumber.setValue(NO_GROW_ZONE);
}
public boolean isFiltered() {
return NO_GROW_ZONE != growZoneNumber.getValue();
}
}
|
package com.oa.dictionary.dao;
import java.util.List;
import com.oa.dictionary.form.Dictionary;
import com.oa.page.form.Page;
public interface DictionaryDao {
public void addDictionary(Dictionary dictionary);
public void updateDictionary(Dictionary dictionary);
public void deleteDictionary(Integer dictionaryId);
public List<Dictionary> findAllDictionaryByPage(Page page);
public List<Dictionary> findAllDictionarys();
public Dictionary findDictionaryById(Integer id);
public Dictionary findDictionaryByDictionaryTitle(String dictionaryTitle);
}
|
public class precisionAtR {
}
|
package com.android.gestiondesbiens.model;
public class Personnel {
private int personnelId;
public int getPersonnelId() {
return personnelId;
}
public String getPersonnelName() {
return personnelName;
}
public void setPersonnelId(int personnelId) {
this.personnelId = personnelId;
}
public void setPersonnelName(String personnelName) {
this.personnelName = personnelName;
}
private String personnelName;
}
|
package pro.likada.dao;
import pro.likada.model.Agreement;
import pro.likada.model.AgreementStatus;
import pro.likada.model.AgreementType;
import pro.likada.model.Contractor;
import java.util.List;
/**
* Created by Yusupov on 1/25/2017.
*/
public interface AgreementDAO {
Agreement findById(long id);
List<Agreement> findByAgreementNumber(String agreementNumber);
void save(Agreement agreement);
void deleteById(long id);
void deleteByAgreementNumber(String agreementNumber);
List<Agreement> findAllAgreements(String searchString);
List<Agreement> findAllAgreementsBasedOnCompanyAndContractor(Contractor company, Contractor contractor, String agreementType);
AgreementType findAgreementTypeById(long id);
List<AgreementType> findAllAgreementTypes();
AgreementStatus findAgreementStatusById(long id);
List<AgreementStatus> findAllAgreementStatuses();
}
|
package com.codigo.smartstore.sdk.core.money;
import java.io.IOException;
import java.io.InputStream;
import java.util.Comparator;
import java.util.Properties;
import java.util.function.LongFunction;
import java.util.function.LongUnaryOperator;
import java.util.stream.IntStream;
import com.codigo.smartstore.sdk.core.opearte.StringOperator;
import com.codigo.smartstore.sdk.core.sequence.Divider;
@FunctionalInterface
interface IConvertable<T, R> {
R convert(T instance);
}
@FunctionalInterface
interface INumberConvertable<T extends Number>
extends IConvertable<T, String> {
@Override
String convert(T instance);
}
/**
* Operator realizuje zamianę/konwersję wartości monetarnej na wartość słowną
*
* @author andrzej.radziszewski
* @version 1.0.0.0
* @since 2018
* @category model
*/
public final class MoneyInWordsModel
implements IConvertable<Double, String> {
private static final String MONEY_WORDS_FILE = "moneyinwords_pl.properties";
private static final Properties moneyInWords;
static {
moneyInWords = new Properties();
try (InputStream input = MoneyInWordsModel.class.getClassLoader()
.getResourceAsStream(MONEY_WORDS_FILE)) {
if (input == null)
throw new NullPointerException("Sorry, unable to find moneyinwords_pl.properties");
moneyInWords.loadFromXML(input);
} catch (final IOException ex) {
ex.printStackTrace();
}
}
/**
* Oprator wyznacznia setek z wartości liczby
*/
private static LongUnaryOperator hasHunds = item -> ((item / 100) % 100) != 0 ? (item / 100) : 0;
/**
* Operator wyznacznia jednostek z wartości liczby
*/
private static LongUnaryOperator hasOnes = item -> (1 == ((item / 10) % 10)) ? 0 : item % 10;
/**
* Operator wyznacznia nastek z wartości liczby
*/
private static final LongUnaryOperator hasTeens = item -> (1 == ((item % 100) / 10)) && ((0 != ((item % 100) % 10)))
? (item % 10)
: 0;
/**
* Oprator wyznacznia dziesiątek z wartości liczby
*/
private static LongUnaryOperator hasTens = item -> (((item / 10) % 10) != 1)
|| ((((item / 10) % 10) == 1) && (((item) % 10) == 0)) ? ((item / 10) % 10) : 0;
public static void main(final String[] args) {
final var iterator = IntStream.iterate(1, item -> item + 1)
.iterator();
final LongFunction<String> func = tyt -> {
final var sb = new StringBuilder();
Divider.compute(tyt, 1_000)
.mapToObj(item -> MoneyInWordsModel.builder()
.setValue((int) item)
.setSector(iterator.next())
.setUnitsCount((int) hasOnes.applyAsLong(item))
.setTeensCount((int) hasTeens.applyAsLong(item))
.setTensCount((int) hasTens.applyAsLong(item))
.setHundsCount((int) hasHunds.applyAsLong(item))
.build())
.map(item -> item)
.sorted(Comparator.comparingLong(MoneyInWordsModel::getSector)
.reversed())
.forEach(obj -> {
final var units = moneyInWords.get("0" + "."
+ obj.countOfUnit())
.toString()
.trim();
final var teens = moneyInWords.get("1" + "."
+ obj.countOfTeens())
.toString()
.trim();
final var tens = moneyInWords.get("2" + "."
+ obj.countOfTens())
.toString()
.trim();
final var hunds = moneyInWords.get("3" + "."
+ obj.countOfHundred())
.toString()
.trim();
final var v3 = moneyInWords.get("v." + (obj.getSector() - 1)
+ ".1")
.toString()
.trim();
sb.append(StringOperator.isNullOrEmpty(hunds) ? "" : hunds + " ");
sb.append(StringOperator.isNullOrEmpty(tens) ? "" : tens + " ");
sb.append(StringOperator.isNullOrEmpty(teens) ? "" : teens + " ");
sb.append(StringOperator.isNullOrEmpty(units) ? "" : units + " ");
sb.append(v3 + " ");
});
return sb.toString();
};
System.out.println(func.apply(1_452_114L));
System.out.println(func.apply(1_200_500L));
System.out.println(func.apply(19_500L));
}
private final int value;
/**
* Pola określa numer sekcji tysięcznej wartości monetarnej
*/
private final int sector;
/**
* Pola określa ilość jedności w sekcji tysięcznej wartości monetarnej
*/
private final int unitsCount;
/**
* Pola określa ilość nastek w sekcji tysięcznej wartości monetarnej
*/
private final int teensCount;
/**
* Pola określa ilość dziesiątek w sekcji tysięcznej wartości monetarnej
*/
private final int tensCount;
/**
* Pola określa ilość setek w sekcji tysięcznej wartości monetarnej
*/
private final int hundsCount;
public static MoneyPartBuilder builder() {
return new MoneyPartBuilder(
);
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:2px;border-style:
* solid;font-size:1.1em'>
* Podstawowy konstruktor obiektu klasy
* </p>
*
* @param partBuilder Budowniczy struktury przechowującej sektory liczby.
*/
public MoneyInWordsModel(final MoneyPartBuilder partBuilder) {
this.value = partBuilder.value;
this.sector = partBuilder.sector;
this.unitsCount = partBuilder.unitsCount;
this.tensCount = partBuilder.tensCount;
this.teensCount = partBuilder.teensCount;
this.hundsCount = partBuilder.hundsCount;
}
public int getValue() {
return this.value;
}
public int getSector() {
return this.sector;
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:1px;border-style:
* thin;'>
* Właściwość określa ilość jedności w danym segmencie wartości montetarnej.
* </p>
*
* @return Wartość numeryczna całkowita.
*/
public int countOfUnit() {
return this.unitsCount;
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:2px;border-style:
* solid;'>
* Właściwość określa ilość nastek w danym segmencie wartości montetarnej.
* </p>
*
* @return Wartość numeryczna całkowita.
*/
public int countOfTeens() {
return this.teensCount;
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:1px;border-style:
* thin;'>
* Właściwość określa ilość dziesiątek w danym segmencie wartości montetarnej.
* </p>
*
* @return Wartość numeryczna całkowita.
*/
public int countOfTens() {
return this.tensCount;
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:4px;border-style:
* solid;'>
* Właściwość określa ilość setek w danym segmencie wartości montetarnej.
* </p>
*
* @return Wartość numeryczna całkowita.
*/
public int countOfHundred() {
return this.hundsCount;
}
@Override
public String toString() {
final StringBuilder myBuilder = new StringBuilder();
myBuilder.append("{");
myBuilder.append(String.format("sector:'%03d'", this.getSector()));
myBuilder.append(String.format("value:'%03d'", this.getValue()));
myBuilder.append(String.format(",hundreds:'%03d'", this.countOfHundred()));
myBuilder.append(String.format(",tens:'%03d'", this.countOfTens()));
myBuilder.append(String.format(",teens:'%03d'", this.countOfTeens()));
myBuilder.append(String.format(",units:'%03d'", this.countOfUnit()));
myBuilder.append("}");
return myBuilder.toString();
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:1px;border-style:
* solid;font-size:1.1em'>
* Klasa realizuje mechanizm przechowywania wartości ilości jednostek danego
* sektora liczby<br>
* Store file : MoneyInWords.java</br>
* Create date: 24.01.2017
* </p>
*
* @author andrzej.radziszewski *
* @version 1.0.0.0
*/
public static class MoneyPartBuilder {
private int value;
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:4px;border-style:
* solid;'>
* Numer sektora w liczbie.
* </p>
*/
private int sector;
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:4px;border-style:
* solid;'>
* Ilość jednostek w sektorze liczby.
* </p>
*/
private int unitsCount;
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:4px;border-style:
* solid;'>
* Ilość nastek w sektorze liczby.
* </p>
*/
private int teensCount;
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:4px;border-style:
* solid;'>
* Ilość dziesiątek w sektorze liczby.
* </p>
*/
private int tensCount;
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:2px;border-style:
* solid;border-width:1px'>
* Ilość setek w sektorze liczby
* </p>
*/
private int hundsCount;
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:2px;border-style:
* solid;border-width:1px'>
* Metoda weryfikuje wartość ilości jednostek przypisywanych do danego sektora
* liczby.</br>
* Wykonywana jest walidacja czy przypisywana wartość jest z zakresu [0-9].
* </p>
*
* @param assignValue Wartość ilości przypisywanej do sektora liczby.
*
* @throws IllegalArgumentException
* <p style=
* 'color:red;background:rgba(255,230,230,0.9);padding:12px;border-radius:2px;'>
* Wyjątek powstaje w przypadku gdy wartości <code>assignValue</code> jest poza
* zakresem dozwolonych wartości [0-9]
* </p>
*/
private void checkAssignValue(final int assignValue) {
if ((assignValue < 0) || (assignValue > 999))
throw new IllegalArgumentException(
"\nBłędna wartość parametru {assignValue}."
+ " \nDozwolone wartości to liczby z zakresu [0-999]");
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:2px;border-style:
* solid;'>
* Podstawowy konstruktor obiektu klasy.
* </p>
*
* @param sector Numer sektora w liczbie. Numer sektora należy rozumieć jako
* kolejny tysięczny blok składowy liczby.
*/
private MoneyPartBuilder() {
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:4px;border-style:
* solid;'>
* Właściwość ustawia atrybut <code>this.unitCount</code> określający ilość
* jednostek w danym sektorze liczby.
* </p>
*
* @param count Ilość jednostek w danym sektorze liczby.
*
* @return Obiekt typu <code>WordsMoneyPartBuilder</code>.
*/
public MoneyPartBuilder setValue(final int value) {
this.checkAssignValue(value);
this.value = value;
return this;
}
public MoneyPartBuilder setSector(final int sector) {
this.checkAssignValue(sector);
this.sector = sector;
return this;
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:4px;border-style:
* solid;'>
* Właściwość ustawia atrybut <code>this.unitCount</code> określający ilość
* jednostek w danym sektorze liczby.
* </p>
*
* @param count Ilość jednostek w danym sektorze liczby.
*
* @return Obiekt typu <code>WordsMoneyPartBuilder</code>.
*/
public MoneyPartBuilder setUnitsCount(final int count) {
this.checkAssignValue(count);
this.unitsCount = count;
return this;
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:4px;border-style:
* solid;'>
* Właściwość ustawia atrybut <code>this.teenCount</code> określający ilość
* nastek w danym sektorze liczby.
* </p>
*
* @param count : Ilość nastek w danym sektorze liczby.
*
* @return Obiekt typu <code>WordsMoneyPartBuilder</code>.
*/
public MoneyPartBuilder setTeensCount(final int count) {
this.checkAssignValue(count);
this.teensCount = count;
return this;
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:1px;border-style:
* solid;'>
* Właściwość ustawia atrybut <code>this.tenCount</code> określający ilość
* dziesiątek w danym sektorze liczby.
* </p>
*
* @param count Ilość dziesiątek w danym sektorze liczby.
*
* @return Obiekt typu <code>WordsMoneyPartBuilder</code>.
*/
public MoneyPartBuilder setTensCount(final int count) {
this.checkAssignValue(count);
this.tensCount = count;
return this;
}
/**
* <p style=
* 'color:white;background:rgba(1,113,113,0.5);padding:12px;border-radius:4px;border-style:solid;'>
* Właściwość ustawia atrybut <code>this.hundCount</code> określający ilość
* setek w danym sektorze liczby.
* </p>
*
* @param count Ilość setek w danym sektorze liczby.
*
* @return Obiekt typu <code>WordsMoneyPartBuilder</code>.
*/
public MoneyPartBuilder setHundsCount(final int count) {
this.checkAssignValue(count);
this.hundsCount = count;
return this;
}
public MoneyInWordsModel build() {
return new MoneyInWordsModel(this);
}
}
@Override
public String convert(final Double instance) {
return "";
}
}
|
/*
* #%L
* Diana UI Core
* %%
* Copyright (C) 2014 Diana UI
* %%
* 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.
* #L%
*/
package com.dianaui.universal.core.client.ui;
import com.dianaui.universal.core.client.ui.base.ComplexWidget;
import com.dianaui.universal.core.client.ui.base.HasType;
import com.dianaui.universal.core.client.ui.base.helper.StyleHelper;
import com.dianaui.universal.core.client.ui.constants.ElementTags;
import com.dianaui.universal.core.client.ui.constants.GlyphiconType;
import com.dianaui.universal.core.client.ui.constants.Styles;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.uibinder.client.UiConstructor;
/**
* Simple put, an icon.
*
* @author <a href='mailto:donbeave@gmail.com'>Alexey Zhokhov</a>
* @see com.dianaui.universal.core.client.ui.constants.IconType
*/
public class Glyphicon extends ComplexWidget implements HasType<GlyphiconType> {
public Glyphicon() {
this(Document.get().createElement(ElementTags.I));
}
protected Glyphicon(Element element) {
setElement(element);
addStyleName(Styles.GLYPHICON_BASE);
}
@UiConstructor
public Glyphicon(final GlyphiconType type) {
this();
setType(type);
}
@Override
public GlyphiconType getType() {
return GlyphiconType.fromStyleName(getStyleName());
}
@Override
public void setType(final GlyphiconType type) {
StyleHelper.addUniqueEnumStyleName(this, GlyphiconType.class, type);
}
}
|
/** #kmp #binary-search */
import java.util.Scanner;
class TextEditor {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.nextLine();
String B = sc.nextLine();
int n = Integer.parseInt(sc.nextLine());
// calculate prefix
int[] prefix = new int[B.length()];
calculatePrefix(B, prefix);
//
int right = B.length();
int left = 0;
int ret, result = -1;
while (left < right) {
int mid = left + (right - left) / 2;
ret = kmpSearch(A, B, prefix, mid + 1);
if (ret >= n) {
result = mid + 1;
left = mid + 1;
} else {
right = mid;
}
}
System.out.println((result == -1) ? "IMPOSSIBLE" : B.substring(0, result));
}
public static int kmpSearch(String s, String p, int[] prefix, int m) {
int n = s.length();
int i = 0, j = 0;
int count = 0;
while (i < n) {
if (s.charAt(i) == p.charAt(j)) {
i++;
j++;
}
if (j == m) {
count++;
j = prefix[j - 1];
} else if (i < n && s.charAt(i) != p.charAt(j)) {
if (j != 0) {
j = prefix[j - 1];
} else {
i++;
}
}
}
return count;
}
public static void calculatePrefix(String p, int[] prefix) {
prefix[0] = 0;
int j = 0, i = 1;
while (i < p.length()) {
if (p.charAt(i) == p.charAt(j)) {
j++;
prefix[i] = j;
i++;
} else {
if (j != 0) {
j = prefix[j - 1];
} else {
prefix[i] = 0;
i++;
}
}
}
}
}
|
package com.eappcat.base.query;
public class BadQueryException extends RuntimeException {
public BadQueryException(Exception e) {
super(e);
}
public BadQueryException(String e) {
super(e);
}
}
|
package alg;
import alg.rerank.Reranker;
import profile.Profile;
import alg.Recommender;
import util.reader.DatasetReader;
import java.util.List;
/**
* Re-ranks a baseline set of recommended items according to a criteria other than predicted rating
* i.e. recommendation set diversity
*/
public class RerankingRecommender implements RecAlg {
private DatasetReader reader;
private Reranker reranker;
private Recommender baselineRecommender;
/**
* Constructor
* @param reader - the data set reader
* @param baselineRecommender - a recommender algorithm
* @param reranker - the algorithm that re-ranks the recommended set of items
*/
public RerankingRecommender(DatasetReader reader, Recommender baselineRecommender, Reranker reranker) {
this.reader = reader;
this.reranker = reranker;
this.baselineRecommender = baselineRecommender;
}
/**
* Get recommendations using the re-ranking algorithm
* @param userId - a user's id
* @return a list of recommended items ordered by the baseline recommender and re-ranker algorithm
*/
public List<Integer> getRecommendations(final Integer userId) {
Profile userProfile = reader.getUserProfiles().get(userId);
return reranker.rerank(userProfile, baselineRecommender.getRecommendationScores(userId));
}
}
|
package de.mq.phone.domain.person;
import java.util.Collection;
import de.mq.phone.domain.person.support.BankingAccount;
public interface Person extends PersonStringAware {
String id();
String firstname();
String name();
Collection<Contact> contacts();
void assign(final Contact contact);
Address address();
void assign(final Address address);
void assign(BankingAccount bankingAccount);
BankingAccount bankingAccount();
String alias();
boolean hasGeoCoordinates();
boolean hasAddress();
}
|
package com.norg.worldofwaste;
import com.norg.worldofwaste.gameobjects.Subject;
import com.norg.worldofwaste.gameobjects.Valuable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ObjectProcessor {
public static Logger LOGGER = LoggerFactory.getLogger(ObjectProcessor.class);
private List<Subject> subjects = new ArrayList<>();
private List<Valuable> valuables = new ArrayList<>();
public void add(Object object) {
LOGGER.info("Add object {}", object);
if (object instanceof Subject) {
Subject subject = (Subject) object;
subjects.add(subject);
for (Subject earlier : subjects) {
earlier.modify(Collections.singletonList(subject), false);
}
subject.modify(subjects, false);
subject.change(valuables, true, false);
}
if (object instanceof Valuable) {
valuables.add((Valuable) object);
}
}
public void remove(Object object) {
if (object instanceof Subject) {
Subject subject = (Subject) object;
subjects.remove(subject);
subject.modify(subjects, true);
}
}
public void turn() {
LOGGER.trace("Turn");
for (Subject subject : subjects) {
subject.change(valuables, false, false);
}
}
public StateReport getStateReport() {
return getStateReport(0);
}
private StateReport getStateReport(int turns) {
StateReport stateReport = new StateReport();
for (Valuable valuable : valuables) {
stateReport.with(valuable);
}
return stateReport;
}
} |
package com.ruslangilazov.sp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* A simple {@link Fragment} subclass.
*/
public class ListFragment extends Fragment {
public RecyclerView listView;//здесь был Grid/ListView
public AdapterPLace adapterPlace;
public StaggeredGridLayoutManager mLayoutManager;
public LinkedList<Place> dataBase ;
public ListFragment() {
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view,savedInstanceState);
try {
dataBase = new Data(getActivity()).getAllPlaces();
adapterPlace = new AdapterPLace(getActivity(),dataBase, getActivity().getLayoutInflater());
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//listView.setBackgroundColor(getResources().getColor(R.color.cardview_dark_background));
listView.setAdapter(adapterPlace);
listView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(getActivity(), PlaceInfoActivity.class);
//Integer i = Integer.parseInt(view.getTag().toString());
intent.putExtra("PlaceObject", dataBase.get(position));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(intent);
}
}));
EditText searchEditText = (EditText)getView().findViewWithTag("EditTextSearch1");
searchEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
adapterPlace.getFilter().filter(s.toString());
}
});
//listView.setOnScrollListener(onScroll);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER);
EditText searchEdit = new EditText(getActivity());
searchEdit.setTag("EditTextSearch1");
searchEdit.setVisibility(View.GONE);
linearLayout.addView(searchEdit);
listView = new RecyclerView(getActivity());
listView.setTag("RecycleView1");
listView.setHasFixedSize(true);
mLayoutManager = new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL);
//можно задать горизонтальную ориентацию. Будет свежо и необычно. Наверное
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
linearLayout.addView(listView);
return linearLayout;
}
}
|
package com.epion_t3.log.command.model;
import com.epion_t3.log.command.runner.LogExtractDuringTimeRunner;
import com.epion_t3.core.common.annotation.CommandDefinition;
import com.epion_t3.core.common.bean.scenario.Command;
import lombok.Getter;
import lombok.Setter;
import org.apache.bval.constraints.NotEmpty;
/**
*
*/
@Getter
@Setter
@CommandDefinition(id = "LogExtractDuringTime", runner = LogExtractDuringTimeRunner.class)
public class LogExtractDuringTime extends Command {
@NotEmpty
private String targetFlow;
@NotEmpty
private String extractPattern;
private Integer group = 1;
private String datePattern = "yyyy-MM-ddTHH:mm:ss";
/**
* 前後バッファ数.
*/
private Integer roundBuffer = 0;
/**
* 前後バッファ時間ユニット.
*/
private String roundBufferTimeUnit = "seconds";
/**
* ファイルエンコーディング.
*/
private String encoding = "UTF-8";
}
|
package com.minhvu.proandroid.sqlite.database.models.DAO;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import com.minhvu.proandroid.sqlite.database.models.data.ImageContract;
import com.minhvu.proandroid.sqlite.database.models.data.NoteContract;
import com.minhvu.proandroid.sqlite.database.models.data.NoteDeletedContract;
import com.minhvu.proandroid.sqlite.database.models.entity.Image;
import java.util.ArrayList;
import java.util.List;
/**
* Created by vomin on 1/13/2018.
*/
public class ImageDAO extends BaseDAO {
public ImageDAO(Context context) {
super(context);
}
public List<Image> loadData(){
SQLiteDatabase db = getReadDB();
Cursor c = db.query(ImageContract.ImageEntry.DATABASE_TABLE,
null, null, null, null, null, null);
if(c != null && c.moveToFirst()){
List<Image> imageList = new ArrayList<>();
do{
String path = c.getString(c.getColumnIndex(ImageContract.ImageEntry.COL_NAME_PATH));
long noteID = c.getLong(c.getColumnIndex(ImageContract.ImageEntry.COL_NOTE_ID));
int state = c.getInt(c.getColumnIndex(ImageContract.ImageEntry.COL_SYNC));
imageList.add(new Image(path, state, noteID));
}while (c.moveToNext());
c.close();
return imageList;
}
return null;
}
public List<String> loadImagePathListOfNote(long noteID) {
SQLiteDatabase db = getReadDB();
String selection = ImageContract.ImageEntry.COL_NOTE_ID + "=?";
Cursor c = db.query(ImageContract.ImageEntry.DATABASE_TABLE,
null,
selection,
new String[]{String.valueOf(noteID)},
null,
null,
null);
if (c != null && c.moveToFirst()) {
List<String> imageList = new ArrayList<>();
int pathIndex = c.getColumnIndex(ImageContract.ImageEntry.COL_NAME_PATH);
int deletedIndex = c.getColumnIndex(ImageContract.ImageEntry.COL_SYNC);
do {
String path = c.getString(pathIndex);
int deleted = c.getInt(deletedIndex);
if (deleted != -1) {
imageList.add(path);
}
} while (c.moveToNext());
c.close();
return imageList;
}
return null;
}
public boolean insertItem(Image image) {
SQLiteDatabase db = getWriteDB();
ContentValues cv = new ContentValues();
cv.put(ImageContract.ImageEntry.COL_NAME_PATH, image.getPath());
cv.put(ImageContract.ImageEntry.COL_NOTE_ID, image.getNoteID());
cv.put(ImageContract.ImageEntry.COL_SYNC, image.getSync());
try {
long insertOrThrow = db.insertOrThrow(ImageContract.ImageEntry.DATABASE_TABLE, null, cv);
return insertOrThrow > 0;
} catch (SQLException e) {
return false;
}
}
public boolean updateByPath(Image image) {
SQLiteDatabase db = getWriteDB();
String selection = ImageContract.ImageEntry.COL_NAME_PATH + "=?";
ContentValues cv = new ContentValues();
if (!TextUtils.isEmpty(image.getPath()))
cv.put(ImageContract.ImageEntry.COL_NAME_PATH, image.getPath());
if (image.getNoteID() != -1)
cv.put(ImageContract.ImageEntry.COL_NOTE_ID, image.getNoteID());
cv.put(ImageContract.ImageEntry.COL_SYNC, image.getSync());
int success = db.update(
ImageContract.ImageEntry.DATABASE_TABLE,
cv,
selection,
new String[]{image.getPath()});
return success > 0;
}
public void updatesByPath(List<Image> imageList) {
SQLiteDatabase db = getWriteDB();
String selection = ImageContract.ImageEntry.COL_NAME_PATH + "=?";
ContentValues cv = new ContentValues();
for(Image image: imageList){
if (!TextUtils.isEmpty(image.getPath()))
cv.put(ImageContract.ImageEntry.COL_NAME_PATH, image.getPath());
if (image.getNoteID() != -1)
cv.put(ImageContract.ImageEntry.COL_NOTE_ID, image.getNoteID());
cv.put(ImageContract.ImageEntry.COL_SYNC, image.getSync());
int success = db.update(
ImageContract.ImageEntry.DATABASE_TABLE,
cv,
selection,
new String[]{image.getPath()});
}
}
public boolean updateByNoteID(Image image) {
SQLiteDatabase db = getWriteDB();
String selection = ImageContract.ImageEntry.COL_NOTE_ID + "=?";
ContentValues cv = new ContentValues();
if (!TextUtils.isEmpty(image.getPath()))
cv.put(ImageContract.ImageEntry.COL_NAME_PATH, image.getPath());
if (image.getNoteID() != -1)
cv.put(ImageContract.ImageEntry.COL_NOTE_ID, image.getNoteID());
cv.put(ImageContract.ImageEntry.COL_SYNC, image.getSync());
int success = db.update(
ImageContract.ImageEntry.DATABASE_TABLE,
cv,
selection,
new String[]{String.valueOf(image.getNoteID())});
return success > 0;
}
public void deleteAllItems(){
SQLiteDatabase db = getWriteDB();
db.execSQL("delete from " + ImageContract.ImageEntry.DATABASE_TABLE);
}
public void deleteAllItemsBySyncState(int SYNC_STATE){
SQLiteDatabase db = getWriteDB();
db.delete(
ImageContract.ImageEntry.DATABASE_TABLE,
ImageContract.ImageEntry.COL_SYNC + "=?",
new String[]{SYNC_STATE + ""});
}
public long getCountOfNote(long noteID){
SQLiteDatabase db = getReadDB();
String sql = "SELECT * FROM " +
ImageContract.ImageEntry.DATABASE_TABLE + " WHERE " + ImageContract.ImageEntry.COL_NOTE_ID + "=" + noteID;
Cursor cursor = db.rawQuery(sql, null);
if(cursor != null && cursor.moveToFirst()){
return cursor.getCount();
}
return 0;
}
public boolean updateAllBySyncState(int STATE){
ContentValues cv = new ContentValues();
cv.put(ImageContract.ImageEntry.COL_SYNC, STATE);
SQLiteDatabase db = getWriteDB();
long success = db.update(ImageContract.ImageEntry.DATABASE_TABLE, cv, null, null);
return success > 0;
}
}
|
package com.metoo.foundation.domain;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.Version;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import com.metoo.core.annotation.Lock;
import com.metoo.core.constant.Globals;
import com.metoo.core.domain.IdEntity;
/**
*
* <p>
* Title: User.java
* </p>
*
* <p>
* Description: 用户类,所有用户均使用该类进行管理,包括普通用户、管理员、商家等 补充:Spring
* Security框架提供了一个基础用户接口UserDetails,该接口提供了基本的用户相关的操作,
* 比如获取用户名/密码、用户账号是否过期和用户认证是否过期等,我们定义自己的User类时需要实现该接口。
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company:
* </p>
*
* @author erikzhang、hezeng
*
* @date 2014-4-25
*
*
* @version koala_b2b2c v2.0 2015版
*/
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Entity
@Table(name = Globals.DEFAULT_TABLE_SUFFIX + "user")
public class User extends IdEntity implements UserDetails {
private static final long serialVersionUID = 8026813053768023527L;
@Lock
@Column(unique = true)
private String userName;// 用户名
private String nickName;// 昵称
private String trueName;// 真实姓名
public String code;// 个人邀请码
public String pointName;// 邀请人姓名
public Long pointId;// 邀请人id
@Column(columnDefinition = "int default 0")
public int pointNum;// 邀请人数
@Lock
private String password;// 密码
private String pwd;// 未加密密码
private String userRole;// 用户角色,登录时根据不同用户角色导向不同的管理页面ADMIN、BUYER、SELLER
private Date birthday;// 出生日期
private String telephone;// 电话号码
private String QQ;// 用户QQ
private String WW;// 用户阿里旺旺
@Column(columnDefinition = "int default 0")
private int years;// 用户年龄
private String MSN;// 用户MSN
private int sex;// 性别 1为男、0为女、-1为保密
private String email;// 邮箱地址
private String mobile;// 手机号码
private String card; // 身份证号
private String sdeptcode;// 电信组织机构
private int status;// 用户状态,-1表示已经删除,删除时在用户前增加下划线
@ManyToMany(targetEntity = Role.class, fetch = FetchType.LAZY)
@JoinTable(name = Globals.DEFAULT_TABLE_SUFFIX
+ "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new TreeSet<Role>();
@Transient
private Map<String, List<Res>> roleResources;
private Date lastLoginDate;// 上次登陆时间
private Date loginDate;// 登陆时间
private String lastLoginIp;// 上次登录IP
private String loginIp;// 登陆Ip
private int loginCount;// 登录次数
private int report;// 是否允许举报商品,0为允许,-1为不允许
@Lock
@Column(precision = 12, scale = 2)
private BigDecimal availableBalance;// 可用余额
@Lock
@Column(precision = 12, scale = 2)
private BigDecimal freezeBlance;// 冻结余额
@Lock
private int integral;// 用户积分
@Lock
private int freezeIntegral;// 用户冻结积分 用户完成收货,并在无退货情况下解冻该积分为用户正常使用积分; 一周期为14天
@Lock
private int gold;// 用户金币
@OneToOne(mappedBy = "user")
private UserConfig config;
@OneToMany(mappedBy = "user")
private List<Accessory> files = new ArrayList<Accessory>();// 用户上传的文件
@OneToMany(mappedBy = "user")
private List<GoodsCart> goodscarts = new ArrayList<GoodsCart>();// 用户对应的购物车
@OneToOne(cascade = CascadeType.REMOVE)
private Store store;// 用户对应的店铺
@ManyToOne(fetch = FetchType.LAZY)
private User parent;// 上级用户,通过哪个用户分享的
@OneToMany(mappedBy = "parent") // 下级用户,分享给了哪些用户
private List<User> childs = new ArrayList<User>();
@Transient
private GrantedAuthority[] authorities = new GrantedAuthority[] {};
private String qq_openid;// qq互联
private String sina_openid;// 新浪微博id
@Column(columnDefinition = "int default 0")
private int user_type;// 用户类别,默认为0个人用户,1为企业用户,3为电信员工, 4:游客身份
private int user_country; // 0: 代表阿联酋 1:沙特
private int language;// 0:英语 1:阿语
// @Column(columnDefinition = "int default 0")
private int store_apply_step;// 店铺申请进行的步骤,默认为0,总共分为0、1、2、3、4、5、6、7、8
@OneToMany(mappedBy = "pd_user", cascade = CascadeType.REMOVE)
private List<Predeposit> posits = new ArrayList<Predeposit>();// 用户的的预存款充值记录
@OneToMany(mappedBy = "pd_log_user", cascade = CascadeType.REMOVE)
private List<PredepositLog> user_predepositlogs = new ArrayList<PredepositLog>();// 用户的预存款日志
@OneToMany(mappedBy = "pd_log_admin", cascade = CascadeType.REMOVE)
private List<PredepositLog> admin_predepositlogs = new ArrayList<PredepositLog>();// 管理的预存款操作f日志
@OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE)
private List<Address> addrs = new ArrayList<Address>();// 用户的配送地址信息
@OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE)
private List<Album> albums = new ArrayList<Album>();// 用户的相册
@OneToMany(mappedBy = "fromUser", cascade = CascadeType.REMOVE)
private List<Message> from_msgs = new ArrayList<Message>();// 用户发送的邮件
@OneToMany(mappedBy = "toUser", cascade = CascadeType.REMOVE)
private List<Message> to_msgs = new ArrayList<Message>();// 用户收到的邮件
@OneToMany(mappedBy = "gold_user", cascade = CascadeType.REMOVE)
private List<GoldRecord> gold_record = new ArrayList<GoldRecord>();// 用户的金币记录
@OneToMany(mappedBy = "gold_admin", cascade = CascadeType.REMOVE)
private List<GoldRecord> gold_record_admin = new ArrayList<GoldRecord>();// 管理员操作的金币记录
@OneToMany(mappedBy = "integral_user", cascade = CascadeType.REMOVE)
private List<IntegralLog> integral_logs = new ArrayList<IntegralLog>();// 用户积分日志
@OneToMany(mappedBy = "operate_user", cascade = CascadeType.REMOVE)
private List<IntegralLog> integral_admin_logs = new ArrayList<IntegralLog>();// 管理员操作积分日志
@OneToMany(mappedBy = "evaluate_user", cascade = CascadeType.REMOVE)
private List<Evaluate> user_evaluate = new ArrayList<Evaluate>();// 买家评价
@OneToMany(mappedBy = "log_user", cascade = CascadeType.REMOVE)
private List<OrderFormLog> ofls = new ArrayList<OrderFormLog>();// 订单日志
@OneToMany(mappedBy = "refund_user", cascade = CascadeType.REMOVE)
private List<RefundLog> rls = new ArrayList<RefundLog>();// 订单退款日志
@OneToMany(mappedBy = "igo_user", cascade = CascadeType.REMOVE)
private List<IntegralGoodsOrder> integralorders = new ArrayList<IntegralGoodsOrder>();// 用户对应的积分商品订单
@OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE)
private List<GroupLifeGoods> grouplifegoods = new ArrayList<GroupLifeGoods>();// 用户发放的生活类团购
@OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE)
private List<CouponInfo> couponinfos = new ArrayList<CouponInfo>();// 用户发放的生活类团购
@OneToMany(mappedBy = "seller", cascade = CascadeType.REMOVE)
private List<PayoffLog> paylogs = new ArrayList<PayoffLog>();// 商家对应的结算日志
@Column(precision = 12, scale = 2)
private BigDecimal user_goods_fee;// 该用户总商品消费金额,1、用于计算用户等级,消费越高,等级越高。2、平台发放优惠券时(如:限制人数100人),按照用户消费金额排序,前100人可以得到该优惠券
@OneToOne(mappedBy = "user", fetch = FetchType.LAZY)
private StorePoint admin_sp;// 管理员评价统计类
@Column(columnDefinition = "LongText")
private String staple_gc;// 用户店铺常用分类,使用json管理[{"id",1"name":"女装"},{"id",3"name":"男装"}]这里只记录最底层分类的id
private String app_login_token;// 用户手机app登录产生的token
private String app_seller_login_token;// 商家手机app登录产生的token
private String user_form;// 用户类型,分为pc,android,ios,
private String mobile_pay_password;// 手机支付密码,用户手机端使用预存款支付时需要输入支付密码,如果用户没有设置支付密码需要输入登录密码
private String invoice;// 用户发票信息
@Column(columnDefinition = "int default 0")
private int invoiceType;// 发票类型
private Long delivery_id;// 用户所申请的自提点id
@Column(columnDefinition = "int default 1")
private int whether_attention;// 是否允许关注 关闭后其他人无法访问您的个人主页 且无法对您进行关注
// 0为不允许,1为允许
@Column(columnDefinition = "LongText")
private String circle_create_info;// 用户所创建圈子id,可以多个,使用json管理[{"id":1,"name":"搞笑一家人"},{"id":1,"name":"搞笑一家人"},{"id":1,"name":"搞笑一家人"}]
@Column(columnDefinition = "LongText")
private String circle_attention_info;// 用户关注的圈子信息,使用json管理[{"id":1,"name":"搞笑一家人"},{"id":1,"name":"搞笑一家人"},{"id":1,"name":"搞笑一家人"}]
private String openId;// 微信公众平台使用的openid
@Column(columnDefinition = "LongText")
private String userMark; // 用户保密
@Version
private int user_version;// User数据版本控制,不允许多线程同时修改User
private String employee_no;// 员工号
private Date ControlDate;// 控制每天错误登陆时间
private Long ControlNumber;// 记录每天错误登陆次数
private int raffle;// 抽奖次数
// 国家
private String country;
// 省份
private String province;
// 城市
private String city;
// 用户头像链接
private String headImgUrl;
// 用户是否关注公众号 值为0时则没有关注
private String subscribe;
// 用户关注时间 时间戳
private String subscribe_time;
private String imei;
private String automatic;// 是否为自动注册用户
@OneToOne(mappedBy = "user", fetch = FetchType.LAZY)
private Sign sign;// 签到类
@OneToOne(mappedBy = "user")
private PlantingTrees planting_trees;// 用户正在种植的树
@ManyToMany
@JoinTable(name = Globals.DEFAULT_TABLE_SUFFIX
+ "user_trees", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "tree_id"))
private List<Tree> trees = new ArrayList<Tree>();
@Column(columnDefinition = "int default 0")
private int water_drops_unused;// 用户未使用水滴数量
@Column(columnDefinition = "int default 0")
private int water_drop_used;// 用户已使用水滴数量
@OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE)
private List<GameUserTask> guts = new ArrayList<GameUserTask>() ;// 用户是否领取任务
@OneToMany(mappedBy = "friend", cascade = CascadeType.REMOVE)
private List<Friend> friends = new ArrayList<Friend>();// 用户好友列表
@OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE)
private List<Friend> users = new ArrayList<Friend>();// 用户好友列表
private String firebase_token;// 用户当前设备应用token
public String getAutomatic() {
return automatic;
}
public void setAutomatic(String automatic) {
this.automatic = automatic;
}
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
public int getPointNum() {
return pointNum;
}
public void setPointNum(int pointNum) {
this.pointNum = pointNum;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getPointName() {
return pointName;
}
public void setPointName(String pointName) {
this.pointName = pointName;
}
public Long getPointId() {
return pointId;
}
public void setPointId(Long pointId) {
this.pointId = pointId;
}
public int getUser_country() {
return user_country;
}
public void setUser_country(int user_country) {
this.user_country = user_country;
}
public int getLanguage() {
return language;
}
public void setLanguage(int language) {
this.language = language;
}
public Date getControlDate() {
return ControlDate;
}
public void setControlDate(Date controlDate) {
ControlDate = controlDate;
}
public Long getControlNumber() {
return ControlNumber;
}
public void setControlNumber(Long controlNumber) {
ControlNumber = controlNumber;
}
public String getApp_seller_login_token() {
return app_seller_login_token;
}
public void setApp_seller_login_token(String app_seller_login_token) {
this.app_seller_login_token = app_seller_login_token;
}
public int getUser_version() {
return user_version;
}
public void setUser_version(int user_version) {
this.user_version = user_version;
}
public String getUserMark() {
return userMark;
}
public void setUserMark(String userMark) {
this.userMark = userMark;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getCircle_create_info() {
return circle_create_info;
}
public void setCircle_create_info(String circle_create_info) {
this.circle_create_info = circle_create_info;
}
public int getRaffle() {
return raffle;
}
public void setRaffle(int raffle) {
this.raffle = raffle;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(Long id, Date addTime) {
super(id, addTime);
// TODO Auto-generated constructor stub
}
public User(String app_login_token) {
super();
this.app_login_token = app_login_token;
}
public User(String userName, String email, String mobile) {
super();
this.userName = userName;
this.email = email;
this.mobile = mobile;
}
public User(Long id, Date addTime, String userName, String trueName, String email, String mobile, String QQ,
String WW, String MSN, BigDecimal availableBalance, BigDecimal freezeBlance, int integral, int gold,
int loginCount, Date lastLoginDate, String lastLoginIp) {
super(id, addTime);
super.setAddTime(addTime);
this.userName = userName;
this.trueName = trueName;
this.email = email;
this.mobile = mobile;
this.QQ = QQ;
this.WW = WW;
this.MSN = MSN;
this.availableBalance = availableBalance;
this.freezeBlance = freezeBlance;
this.integral = integral;
this.gold = gold;
this.loginCount = loginCount;
this.lastLoginDate = lastLoginDate;
this.lastLoginIp = lastLoginIp;
// TODO Auto-generated constructor stub
}
public User(Long id, Date addTime, String userName, String trueName, String email, String mobile, String QQ,
String WW, String MSN, BigDecimal availableBalance, BigDecimal freezeBlance, int integral, int gold,
int loginCount, Date lastLoginDate, String lastLoginIp, String employee_no) {
super(id, addTime);
super.setAddTime(addTime);
this.userName = userName;
this.trueName = trueName;
this.email = email;
this.mobile = mobile;
this.QQ = QQ;
this.WW = WW;
this.MSN = MSN;
this.availableBalance = availableBalance;
this.freezeBlance = freezeBlance;
this.integral = integral;
this.gold = gold;
this.loginCount = loginCount;
this.lastLoginDate = lastLoginDate;
this.lastLoginIp = lastLoginIp;
this.employee_no = employee_no;
// TODO Auto-generated constructor stub
}
public String getCircle_attention_info() {
return circle_attention_info;
}
public void setCircle_attention_info(String circle_attention_info) {
this.circle_attention_info = circle_attention_info;
}
public int getWhether_attention() {
return whether_attention;
}
public void setWhether_attention(int whether_attention) {
this.whether_attention = whether_attention;
}
public Long getDelivery_id() {
return delivery_id;
}
public void setDelivery_id(Long delivery_id) {
this.delivery_id = delivery_id;
}
public int getInvoiceType() {
return invoiceType;
}
public void setInvoiceType(int invoiceType) {
this.invoiceType = invoiceType;
}
public String getInvoice() {
return invoice;
}
public void setInvoice(String invoice) {
this.invoice = invoice;
}
public String getMobile_pay_password() {
return mobile_pay_password;
}
public void setMobile_pay_password(String mobile_pay_password) {
this.mobile_pay_password = mobile_pay_password;
}
public String getUser_form() {
return user_form;
}
public void setUser_form(String user_form) {
this.user_form = user_form;
}
public String getApp_login_token() {
return app_login_token;
}
public void setApp_login_token(String app_login_token) {
this.app_login_token = app_login_token;
}
public List<PayoffLog> getPaylogs() {
return paylogs;
}
public void setPaylogs(List<PayoffLog> paylogs) {
this.paylogs = paylogs;
}
public List<CouponInfo> getCouponinfos() {
return couponinfos;
}
public void setCouponinfos(List<CouponInfo> couponinfos) {
this.couponinfos = couponinfos;
}
public List<GroupLifeGoods> getGrouplifegoods() {
return grouplifegoods;
}
public void setGrouplifegoods(List<GroupLifeGoods> grouplifegoods) {
this.grouplifegoods = grouplifegoods;
}
public List<IntegralGoodsOrder> getIntegralorders() {
return integralorders;
}
public void setIntegralorders(List<IntegralGoodsOrder> integralorders) {
this.integralorders = integralorders;
}
public List<GoodsCart> getGoodscarts() {
return goodscarts;
}
public void setGoodscarts(List<GoodsCart> goodscarts) {
this.goodscarts = goodscarts;
}
public BigDecimal getUser_goods_fee() {
return user_goods_fee;
}
public void setUser_goods_fee(BigDecimal user_goods_fee) {
this.user_goods_fee = user_goods_fee;
}
public String getStaple_gc() {
return staple_gc;
}
public void setStaple_gc(String staple_gc) {
this.staple_gc = staple_gc;
}
public StorePoint getAdmin_sp() {
return admin_sp;
}
public void setAdmin_sp(StorePoint admin_sp) {
this.admin_sp = admin_sp;
}
public int getStore_apply_step() {
return store_apply_step;
}
public void setStore_apply_step(int store_apply_step) {
this.store_apply_step = store_apply_step;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getCard() {
return card;
}
public void setCard(String card) {
this.card = card;
}
public int getUser_type() {
return user_type;
}
public void setUser_type(int user_type) {
this.user_type = user_type;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public List<OrderFormLog> getOfls() {
return ofls;
}
public void setOfls(List<OrderFormLog> ofls) {
this.ofls = ofls;
}
public List<RefundLog> getRls() {
return rls;
}
public void setRls(List<RefundLog> rls) {
this.rls = rls;
}
public List<Evaluate> getUser_evaluate() {
return user_evaluate;
}
public void setUser_evaluate(List<Evaluate> user_evaluate) {
this.user_evaluate = user_evaluate;
}
public List<IntegralLog> getIntegral_logs() {
return integral_logs;
}
public void setIntegral_logs(List<IntegralLog> integral_logs) {
this.integral_logs = integral_logs;
}
public List<IntegralLog> getIntegral_admin_logs() {
return integral_admin_logs;
}
public void setIntegral_admin_logs(List<IntegralLog> integral_admin_logs) {
this.integral_admin_logs = integral_admin_logs;
}
public List<GoldRecord> getGold_record() {
return gold_record;
}
public void setGold_record(List<GoldRecord> gold_record) {
this.gold_record = gold_record;
}
public List<GoldRecord> getGold_record_admin() {
return gold_record_admin;
}
public void setGold_record_admin(List<GoldRecord> gold_record_admin) {
this.gold_record_admin = gold_record_admin;
}
public List<Message> getFrom_msgs() {
return from_msgs;
}
public void setFrom_msgs(List<Message> from_msgs) {
this.from_msgs = from_msgs;
}
public List<Message> getTo_msgs() {
return to_msgs;
}
public void setTo_msgs(List<Message> to_msgs) {
this.to_msgs = to_msgs;
}
public List<Album> getAlbums() {
return albums;
}
public void setAlbums(List<Album> albums) {
this.albums = albums;
}
public List<Address> getAddrs() {
return addrs;
}
public void setAddrs(List<Address> addrs) {
this.addrs = addrs;
}
public List<Predeposit> getPosits() {
return posits;
}
public void setPosits(List<Predeposit> posits) {
this.posits = posits;
}
public String getSina_openid() {
return sina_openid;
}
public void setSina_openid(String sina_openid) {
this.sina_openid = sina_openid;
}
public String getQq_openid() {
return qq_openid;
}
public void setQq_openid(String qq_openid) {
this.qq_openid = qq_openid;
}
public void setStore(Store store) {
this.store = store;
}
public Date getLoginDate() {
return loginDate;
}
public void setLoginDate(Date loginDate) {
this.loginDate = loginDate;
}
public String getLastLoginIp() {
return lastLoginIp;
}
public void setLastLoginIp(String lastLoginIp) {
this.lastLoginIp = lastLoginIp;
}
public String getLoginIp() {
return loginIp;
}
public void setLoginIp(String loginIp) {
this.loginIp = loginIp;
}
public Date getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(Date lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public GrantedAuthority[] get_all_Authorities() {
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());
for (Role role : roles) {
grantedAuthorities.add(new GrantedAuthorityImpl(role.getRoleCode()));
}
return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);
}
public GrantedAuthority[] get_common_Authorities() {
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());
for (Role role : roles) {
if (!role.getType().equals("ADMIN"))
grantedAuthorities.add(new GrantedAuthorityImpl(role.getRoleCode()));
}
return grantedAuthorities.toArray(new GrantedAuthority[grantedAuthorities.size()]);
}
public String getAuthoritiesString() {
List<String> authorities = new ArrayList<String>();
for (GrantedAuthority authority : this.getAuthorities()) {
authorities.add(authority.getAuthority());
}
return StringUtils.join(authorities.toArray(), ",");
}
public User(String userName, String mobile) {
super();
this.userName = userName;
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public String getUsername() {
return userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public boolean isAccountNonExpired() {
return true;
}
public boolean isAccountNonLocked() {
return true;
}
public boolean isCredentialsNonExpired() {
return true;
}
public Map<String, List<Res>> getRoleResources() {
// init roleResources for the first time
if (this.roleResources == null) {
this.roleResources = new HashMap<String, List<Res>>();
for (Role role : this.roles) {
String roleCode = role.getRoleCode();
List<Res> ress = role.getReses();
for (Res res : ress) {
String key = roleCode + "_" + res.getType();
if (!this.roleResources.containsKey(key)) {
this.roleResources.put(key, new ArrayList<Res>());
}
this.roleResources.get(key).add(res);
}
}
}
return this.roleResources;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public void setRoleResources(Map<String, List<Res>> roleResources) {
this.roleResources = roleResources;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
public String getTrueName() {
return trueName;
}
public void setTrueName(String trueName) {
this.trueName = trueName;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getQQ() {
return QQ;
}
public void setQQ(String qq) {
QQ = qq;
}
public String getMSN() {
return MSN;
}
public void setMSN(String msn) {
MSN = msn;
}
public BigDecimal getAvailableBalance() {
return availableBalance;
}
public void setAvailableBalance(BigDecimal availableBalance) {
this.availableBalance = availableBalance;
}
public BigDecimal getFreezeBlance() {
return freezeBlance;
}
public void setFreezeBlance(BigDecimal freezeBlance) {
this.freezeBlance = freezeBlance;
}
public UserConfig getConfig() {
return config;
}
public void setConfig(UserConfig config) {
this.config = config;
}
public List<Accessory> getFiles() {
return files;
}
public void setFiles(List<Accessory> files) {
this.files = files;
}
public int getIntegral() {
return integral;
}
public void setIntegral(int integral) {
this.integral = integral;
}
public int getLoginCount() {
return loginCount;
}
public void setLoginCount(int loginCount) {
this.loginCount = loginCount;
}
public String getWW() {
return WW;
}
public void setWW(String ww) {
WW = ww;
}
public GrantedAuthority[] getAuthorities() {
return authorities;
}
public void setAuthorities(GrantedAuthority[] authorities) {
this.authorities = authorities;
}
public int getGold() {
return gold;
}
public void setGold(int gold) {
this.gold = gold;
}
public int getReport() {
return report;
}
public void setReport(int report) {
this.report = report;
}
public List<PredepositLog> getUser_predepositlogs() {
return user_predepositlogs;
}
public void setUser_predepositlogs(List<PredepositLog> user_predepositlogs) {
this.user_predepositlogs = user_predepositlogs;
}
public List<PredepositLog> getAdmin_predepositlogs() {
return admin_predepositlogs;
}
public void setAdmin_predepositlogs(List<PredepositLog> admin_predepositlogs) {
this.admin_predepositlogs = admin_predepositlogs;
}
public void setParent(User parent) {
this.parent = parent;
}
public List<User> getChilds() {
return childs;
}
public void setChilds(List<User> childs) {
this.childs = childs;
}
public Store getStore() {
if (this.getParent() == null) {
return store;
} else {
return this.getParent().getStore();
}
}
public User getParent() {
return parent;
}
public String getEmployee_no() {
return employee_no;
}
public void setEmployee_no(String employee_no) {
this.employee_no = employee_no;
}
public String getSdeptcode() {
return sdeptcode;
}
public void setSdeptcode(String sdeptcode) {
this.sdeptcode = sdeptcode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getHeadImgUrl() {
return headImgUrl;
}
public void setHeadImgUrl(String headImgUrl) {
this.headImgUrl = headImgUrl;
}
public String getSubscribe() {
return subscribe;
}
public void setSubscribe(String subscribe) {
this.subscribe = subscribe;
}
public String getSubscribe_time() {
return subscribe_time;
}
public void setSubscribe_time(String subscribe_time) {
this.subscribe_time = subscribe_time;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public int getFreezeIntegral() {
return freezeIntegral;
}
public void setFreezeIntegral(int freezeIntegral) {
this.freezeIntegral = freezeIntegral;
}
public Sign getSign() {
return sign;
}
public void setSign(Sign sign) {
this.sign = sign;
}
public PlantingTrees getPlanting_trees() {
return planting_trees;
}
public void setPlanting_trees(PlantingTrees planting_trees) {
this.planting_trees = planting_trees;
}
public List<Tree> getTrees() {
return trees;
}
public void setTrees(List<Tree> trees) {
this.trees = trees;
}
public int getWater_drops_unused() {
return water_drops_unused;
}
public void setWater_drops_unused(int water_drops_unused) {
this.water_drops_unused = water_drops_unused;
}
public int getWater_drop_used() {
return water_drop_used;
}
public void setWater_drop_used(int water_drop_used) {
this.water_drop_used = water_drop_used;
}
public List<GameUserTask> getGuts() {
return guts;
}
public void setGuts(List<GameUserTask> guts) {
this.guts = guts;
}
public List<Friend> getFriends() {
return friends;
}
public void setFriends(List<Friend> friends) {
this.friends = friends;
}
public String getFirebase_token() {
return firebase_token;
}
public void setFirebase_token(String firebase_token) {
this.firebase_token = firebase_token;
}
@Override
public String toString() {
return "User [userName=" + userName + ", nickName=" + nickName + ", trueName=" + trueName + ", pointName="
+ pointName + ", pointId=" + pointId + ", code=" + code + ", pointNum=" + pointNum + ", password="
+ password + ", pwd=" + pwd + ", userRole=" + userRole + ", birthday=" + birthday + ", telephone="
+ telephone + ", QQ=" + QQ + ", WW=" + WW + ", years=" + years + ", MSN=" + MSN + ", sex=" + sex
+ ", email=" + email + ", mobile=" + mobile + ", card=" + card + ", sdeptcode=" + sdeptcode
+ ", status=" + status + ", roles=" + roles + ", roleResources=" + roleResources + ", lastLoginDate="
+ lastLoginDate + ", loginDate=" + loginDate + ", lastLoginIp=" + lastLoginIp + ", loginIp=" + loginIp
+ ", loginCount=" + loginCount + ", report=" + report + ", availableBalance=" + availableBalance
+ ", freezeBlance=" + freezeBlance + ", integral=" + integral + ", freezeIntegral=" + freezeIntegral
+ ", gold=" + gold + ", config=" + config + ", files=" + files + ", goodscarts=" + goodscarts
+ ", store=" + store + ", parent=" + parent + ", childs=" + childs + ", authorities="
+ Arrays.toString(authorities) + ", qq_openid=" + qq_openid + ", sina_openid=" + sina_openid
+ ", user_type=" + user_type + ", user_country=" + user_country + ", language=" + language
+ ", store_apply_step=" + store_apply_step + ", posits=" + posits + ", user_predepositlogs="
+ user_predepositlogs + ", admin_predepositlogs=" + admin_predepositlogs + ", addrs=" + addrs
+ ", albums=" + albums + ", from_msgs=" + from_msgs + ", to_msgs=" + to_msgs + ", gold_record="
+ gold_record + ", gold_record_admin=" + gold_record_admin + ", integral_logs=" + integral_logs
+ ", integral_admin_logs=" + integral_admin_logs + ", user_evaluate=" + user_evaluate + ", ofls=" + ofls
+ ", rls=" + rls + ", integralorders=" + integralorders + ", grouplifegoods=" + grouplifegoods
+ ", couponinfos=" + couponinfos + ", paylogs=" + paylogs + ", user_goods_fee=" + user_goods_fee
+ ", admin_sp=" + admin_sp + ", staple_gc=" + staple_gc + ", app_login_token=" + app_login_token
+ ", app_seller_login_token=" + app_seller_login_token + ", user_form=" + user_form
+ ", mobile_pay_password=" + mobile_pay_password + ", invoice=" + invoice + ", invoiceType="
+ invoiceType + ", delivery_id=" + delivery_id + ", whether_attention=" + whether_attention
+ ", circle_create_info=" + circle_create_info + ", circle_attention_info=" + circle_attention_info
+ ", openId=" + openId + ", userMark=" + userMark + ", user_version=" + user_version + ", employee_no="
+ employee_no + ", ControlDate=" + ControlDate + ", ControlNumber=" + ControlNumber + ", raffle="
+ raffle + ", country=" + country + ", province=" + province + ", city=" + city + ", headImgUrl="
+ headImgUrl + ", subscribe=" + subscribe + ", subscribe_time=" + subscribe_time + ", imei=" + imei
+ ", automatic=" + automatic + ", sign=" + sign + ", planting_trees=" + planting_trees + ", trees="
+ trees + ", water_drops_unused=" + water_drops_unused + ", water_drop_used=" + water_drop_used
+ ", guts=" + guts + ", friends=" + friends + ", firebase_token=" + firebase_token + "]";
}
}
|
package com.lmlnemesis.minesweeper.dto;
import lombok.Data;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@Data
public class SizeDto {
@NotNull(message = "rows amount can not be null")
@Min(value=1, message = "Row should be grater than 0")
private Integer rows;
@NotNull(message = "columns amount can not be null")
@Min(value=1, message = "Row should be grater than 0")
private Integer columns;
}
|
package com.stk123.model.strategy;
public interface Sortable {
double getValue();
void setOrder(int order);
void setPercentile(double percentile);
double getPercentile();
static int compare(boolean asc, Sortable o1, Sortable o2){
//return (int) (asc ? o1.getValue() - o2.getValue() : o2.getValue() - o1.getValue());
return asc ? (o1.getValue() > o2.getValue() ? 1:-1) : (o2.getValue() > o1.getValue() ? 1:-1);
}
}
|
/*
* 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 morpion;
import java.util.ArrayList;
/**
*
* @author vinotco
*/
public class Morpion {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Controleur controleur = new Controleur();
VueInitialisation VI = new VueInitialisation(controleur.listeJoueursToString(controleur.getListeJoueurs()));
VI.afficher();
VI.addObserver(controleur);
}
}
|
package com.alibaba.dubbo.remoting.http;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//HTTP处理器接口
public interface HttpHandler {
/**
* invoke.
*
* 处理器请求
*
* @param request request. 请求
* @param response response. 响应
* @throws IOException 当 IO 发生异常
* @throws ServletException 当 Servlet 发生异常
*/
void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;
} |
package cn.swsk.rgyxtqapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
import java.util.Map;
import cn.swsk.rgyxtqapp.adapter.AnquanItemsAdapter;
import cn.swsk.rgyxtqapp.bean.TEquip;
import cn.swsk.rgyxtqapp.utils.CommonUtils;
import cn.swsk.rgyxtqapp.utils.HttpUtils;
import cn.swsk.rgyxtqapp.utils.JsonTools;
import cn.swsk.rgyxtqapp.utils.PushUtils;
/**
* Created by Administrator on 2016/3/4.
*/
public abstract class AnquanQRBaseActivity extends AnquanguanliBaseActivity {
public ListView lv;
public AnquanItemsAdapter dapter;
public Button scan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv = (ListView)findViewById(R.id.lv);
if(dapter==null)
lv.setAdapter(dapter=new AnquanItemsAdapter(this));
else lv.setAdapter(dapter);
scan = (Button)findViewById(R.id.scan);
scan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(AnquanQRBaseActivity.this, ScanQRCode.class);
intent.putExtra("title", "扫描二维码");
startActivityForResult(intent,1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==1&&resultCode==1){
final String result = data.getStringExtra("result");
HttpUtils.commonRequest2(PushUtils.getServerIP(this) +
"rgyx/AppManageSystem/parseCode?code=" + result, this, new HttpUtils
.RequestCB() {
@Override
public void cb(Map<String, Object> map, String resp, int type) {
List<TEquip> list = null;
if (resp != null && resp.startsWith("["))
list = JsonTools.getTEquips(resp);
if (list != null && list.size() > 0) {
CommonUtils.log("=====================" + list.size());
dapter.addInfos(list);
} else {
CommonUtils.log("=====================");
CommonUtils.toast("获取数据失败", AnquanQRBaseActivity.this);
}
}
});
}
}
protected void save(String path){
String data= JsonTools.getJsonStr(dapter.getCheckedInfos());
if(data==null||data.length()<8){
CommonUtils.toast("无提交的数据",this);
return ;
}
HttpUtils.commonRequest3(path, this, data, new HttpUtils.RequestCB() {
@Override
public void cb(Map<String, Object> map, String resp,int type) {
if(type==0){
dapter.removeCheckedInfos();
CommonUtils.toast("保存成功",AnquanQRBaseActivity.this);
}else{
CommonUtils.log(map.toString());
if("-2".equals(map.get("status")+"")){
if((map.get("code")+"").length()>1)
dapter.changeState (((String)map.get("code")).split("\\|"));
}
}
}
});
}
}
|
package com.yuneec.uartcontroller;
import com.yuneec.uartcontroller.UARTInfoMessage.CalibrationRawData;
public class UartInterface {
static native int Recv(byte[] bArr, int i);
public static native UARTInfoMessage RecvMsg();
static native int Send(byte[] bArr, int i);
static native void UpdateRfVersionCompleted();
static native void UpdateTxVersionCompleted();
static native boolean acquireTxResourceInfo();
static native boolean bind(int i);
static native void clearRecvBuf();
static native boolean closeDevice();
static native boolean enterBind();
static native boolean enterFactoryCalibration();
static native boolean enterRun();
static native boolean enterSim();
static native boolean enterTestRF(int i, int i2);
static native boolean enterTransmitTest();
static native boolean exitBind();
static native boolean exitFactoryCalibration();
static native boolean exitRun();
static native boolean exitSim();
static native boolean exitTransmitTest();
static native boolean finishBind();
static native boolean finishCalibration();
static native CalibrationRawData getCalibrationRawData(boolean z);
static native boolean getRfVersion();
static native byte[] getRxResInfo(int i);
static native boolean getSignal(int i);
static native boolean getSubTrim(int[] iArr, boolean z);
static native int getTrimStep(boolean z);
static native boolean getTxBLVersion();
static native boolean getTxVersion();
static native boolean isOpenDevice();
static native void nativeDestory();
static native void nativeInit();
static native String openDevice();
static native UARTInfoMessage parseMsg(byte[] bArr, int i);
static native boolean queryBindState();
static native boolean querySwitchState(int i);
static native int readTransmitRate();
static native void readyForUpdateRfVersion();
static native void readyForUpdateTxVersion();
static native boolean receiveBothChannel();
static native boolean receiveMixedChannelOnly();
static native boolean receiveRawChannelOnly();
static native boolean sendMissionRequest(int i, int i2, int i3);
static native boolean sendMissionResponse(int i, int i2, int i3);
static native boolean sendMissionSettingCccWaypoint(WaypointData waypointData);
static native boolean sendMissionSettingRoiCenter(RoiData roiData);
static native boolean sendRxResInfo(byte[] bArr);
static native boolean setBindKeyFunction(int i);
static native boolean setChannelConfig(int i, int i2);
static native boolean setFmodeKey(int i);
static native boolean setSubTrim(int[] iArr);
static native boolean setTTBstate(int i, boolean z);
static native boolean setTrimStep(int i);
static native boolean shutDown();
static native boolean sonarSwitch(boolean z);
static native boolean startBind();
static native boolean startCalibration();
static native boolean syncMixingData(MixedData mixedData, int i);
static native boolean syncMixingDataDeleteAll();
public static native boolean testBit();
static native boolean unbind();
static native boolean updateCompass(float f);
static native boolean updateGPS(float f, float f2, float f3, float f4, float f5, float f6, int i);
static native String updateRfVersion(String str);
static native String updateTxVersion(String str);
static native boolean writeTransmitRate(int i);
static {
System.loadLibrary("flycontroljni");
}
}
|
import java.io.*;
public class SequenceInputOutputStream {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
FileInputStream fis1 = new FileInputStream("C:/Users/RAKESH/Desktop/Tutorial.txt");
FileInputStream fis2 = new FileInputStream("C:/Users/RAKESH/Desktop/Tutorial2.txt");
SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
FileOutputStream fos = new FileOutputStream("C:/Users/RAKESH/Desktop/Tutorial5.txt");
//available() of SequenceInputStream Determines only number of bytes available in first Stream.
int size = fis1.available() + fis2.available();
int k;
System.out.println("Size: " + size);
for(int i = 0; i < size; i ++){
k = sis.read();
fos.write(k);
}
System.out.println("Copy Paste Completed");
}
}
|
package DAO;
import model.Serviços;
import java.util.ArrayList;
import java.util.List;
public class ServiçosRepositorio {
private static ServiçosRepositorio serviçosRepositorio;
private List<Serviços> serviços = new ArrayList<>();
public static ServiçosRepositorio getInstance() {
if (serviçosRepositorio == null) {
serviçosRepositorio = new ServiçosRepositorio();
}
return serviçosRepositorio;
}
public void addServiço(Serviços serviço){
int ultimoID = 1;
for(int i=0; i<serviços.size(); i++){
ultimoID++;
}
serviço.setId(ultimoID);
serviços.add(serviço);
}
public boolean removerServiço(int id){
Serviços removerServiço = VerificarServiço(id);
if(removerServiço != null){
serviços.remove(removerServiço);
return true;
}
return false;
}
public void atualizarServiço(Serviços serviço, int id){
Serviços atualizarServiço = VerificarServiço(id);
if(atualizarServiço != null){
atualizarServiço.setNomeServiço(serviço.getNomeServiço());
atualizarServiço.setPreço(serviço.getPreço());
}
}
public List<Serviços> mostrarServiços(){
return serviços;
}
public Serviços VerificarServiço(int id){
for (Serviços serviço: serviços ) {
if(serviço.getId() == id){
return serviço;
}
}
return null;
}
public List<Serviços> getServiços() {
return serviços;
}
public void setServiços(List<Serviços> serviços) {
this.serviços = serviços;
}
}
|
import java.util.Scanner;
public class Principal {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
do {
Scanner teclado = new Scanner(System.in);
System.out.print("\n** MENU **");
System.out.print("\n\n -1: Jogar");
System.out.print("\n -2: Sair");
System.out.print("\n Escolha: ");
int aux = 0;
aux = teclado.nextInt();
switch (aux){
case 1: {
//do{
int verif = 1;
do{
System.out.print("\nQual o tamanho do mapa? Informe a quntidade de linhas e colunas (máx.: 5x5): ");
int linhas = teclado.nextInt();
int colunas = teclado.nextInt();
if (linhas>5 || colunas>5 || linhas<0 || colunas<0){
System.out.println("Entrada Inválida!");
//verif = 0;
break;
}
CampoMinado m1 = new CampoMinado(linhas,colunas);
m1.imprimeMapa();
System.out.println("\n\n");
do{
System.out.println("Quantas bombas deseja colocar no mapa? (máx. " + ((linhas*colunas)-1) + "):");
int bombas = teclado.nextInt();
if (bombas<=0 || bombas>((linhas*colunas)-1)){
System.out.println("Entrada Inválida!");
verif = 0;
break;
}
m1.preencheComBombas(bombas);
} while (verif == 0);
do{
System.out.print("\nEscolha uma posição (linha e coluna): ");
int l = teclado.nextInt();
int c = teclado.nextInt();
m1.resolveMapa(l-1,c-1);
verif = m1.getVerif();
if (verif == 0)
m1.imprimeMapa2();
} while (verif == 0);
} while (verif == 0);
//} while(true);
} break;
case 2: System.exit(0);
default: System.out.println("Entrada inválida!"); break;
}
} while (true);
}
}
|
package net.dvinfosys.alertdialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
public class MyAlertDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
builder.setTitle("My Dialog !");
builder.setCancelable(false);
builder.setMessage("Your Are Close The Dialog").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
Toast.makeText(getActivity(),"Yes Clicked",Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(),"No Clicked",Toast.LENGTH_SHORT).show();
}
});
// builder.setNegativeButton(R.);
Dialog dialog=builder.create();
return dialog;
}
}
|
package com.example.fisso.morpiontest.model;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.example.fisso.morpiontest.R;
import com.example.fisso.morpiontest.model.Joueur;
public class Matrice {
private ImageView image;
private ImageButton a1,a2,a3,b1,b2,b3,c1,c2,c3;
private boolean estFinie;
private int forme;
private ImageButton[][] tableau= { {a1, a2, a3}, {b1, b2, b3},{ c1, c2, c3} };
public Matrice () {
this.estFinie = false;
this.image = null;
}
public ImageButton[][] getMatrice(){
return this.tableau;
}
public int verificationVictoire(Joueur joueur){
int compteuregalite = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (tableau[i][0].getTag() == joueur.getPseudo() &&
tableau[i][1].getTag() == joueur.getPseudo() && tableau[i][2].getTag() == joueur.getPseudo()){
estFinie = true;
forme = joueur.getFormeTrans();
return 1;
}
if(tableau[0][i].getTag() == joueur.getPseudo() &&
tableau[1][i].getTag() == joueur.getPseudo() && tableau[2][i].getTag() == joueur.getPseudo())
{
estFinie = true;
forme = joueur.getFormeTrans();
return 1;
}
if(tableau[0][0].getTag() == joueur.getPseudo() &&
tableau[1][1].getTag() == joueur.getPseudo() && tableau[2][2].getTag() == joueur.getPseudo()) {
estFinie = true;
forme = joueur.getFormeTrans();
return 1;
}
if(tableau[2][0].getTag() == joueur.getPseudo() &&
tableau[1][1].getTag() == joueur.getPseudo() && tableau[0][2].getTag() == joueur.getPseudo()){
estFinie = true;
forme = joueur.getFormeTrans();
return 1;
}
if(tableau[i][j].getTag() != null){
compteuregalite++;
}
}
}
if(compteuregalite == 9){
this.estFinie = true;
this.forme = R.drawable.egalite;
return 1;
}
return 0;
}
public int coupSuivant(ImageButton b){
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if(b == tableau[i][j]){
return 3*i+j;
}
}
}
return 9;
}
public void activerMatrice(){
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if(tableau[i][j].getTag()==null && this.estFinie==false) {
tableau[i][j].setBackgroundResource(R.drawable.carreauselec);
tableau[i][j].setEnabled(true);
}
}
}
}
public void desactiverMatrice(){
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
tableau[i][j].setEnabled(false);
if(tableau[i][j].getTag()==null) {
tableau[i][j].setBackgroundResource(R.drawable.carreau);
}
}
}
}
public void reinitialiserMatrice(){
this.estFinie = false;
this.forme = 0;
this.image.setVisibility(View.GONE);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
tableau[i][j].setTag(null);
}
}
}
public boolean getEstFinie(){
return this.estFinie;
}
public int getForme(){
return this.forme;
}
public ImageView getImage (){
return this.image;
}
public void setImage(ImageView image){
this.image = image;
}
}
|
package com.wangcheng.concurrent.thread;
/**
* description:
* 不能调用两次start()方法,会抛出议程
* threadStatus初始值为0
* if (threadStatus != 0)
* throw new IllegalThreadStateException();
*
* @author WangCheng
* create in 2019-11-10 21:50
*/
public class StartTwiceThread {
public static void main(String[] args) {
Thread thread = new Thread();
//第一次调用后线程threadStatus会变化
thread.start();
//第二次在调用threadStatus != 0
thread.start();
}
}
|
/**
*/
package featureModel;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Group</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link featureModel.Group#getGroupedFeatures <em>Grouped Features</em>}</li>
* <li>{@link featureModel.Group#isInclusive <em>Inclusive</em>}</li>
* </ul>
* </p>
*
* @see featureModel.FeatureModelPackage#getGroup()
* @model
* @generated
*/
public interface Group extends EObject {
/**
* Returns the value of the '<em><b>Grouped Features</b></em>' containment reference list.
* The list contents are of type {@link featureModel.GroupedFeature}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Grouped Features</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Grouped Features</em>' containment reference list.
* @see featureModel.FeatureModelPackage#getGroup_GroupedFeatures()
* @model containment="true" lower="2"
* @generated
*/
EList<GroupedFeature> getGroupedFeatures();
/**
* Returns the value of the '<em><b>Inclusive</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Inclusive</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Inclusive</em>' attribute.
* @see #setInclusive(boolean)
* @see featureModel.FeatureModelPackage#getGroup_Inclusive()
* @model required="true"
* @generated
*/
boolean isInclusive();
/**
* Sets the value of the '{@link featureModel.Group#isInclusive <em>Inclusive</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Inclusive</em>' attribute.
* @see #isInclusive()
* @generated
*/
void setInclusive(boolean value);
} // Group
|
package business.implementation.Interfaces;
import business.model.gameProfile;
import javax.swing.table.TableModel;
import java.sql.SQLException;
public interface AchievementsManagerInterface {
/* Check if achievements have been unlocked */
void checkAchievement(gameProfile gameProfile) throws SQLException;
/* Add an achievement to a profile */
boolean insertAchievementToProfile(int user_id, int achievement_id) throws SQLException;
/* Get the available achievements */
TableModel getAchievement() throws SQLException;
/* Get the achievements list of a user */
TableModel getUserAchievementsList(int userId) throws SQLException;
/* Check if an achievement has been found on the profile */
boolean AchievementFoundOnProfile(int achievement_id, int user_id) throws SQLException;
}
|
package com.ahuo.personapp.ui.activity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import com.ahuo.personapp.R;
import com.ahuo.personapp.base.BaseActivity;
import com.ahuo.tools.util.ToastUtils;
/**
* Created on 2017-6-16
*
* @author LiuHuiJie
*/
public class MyWebViewActivity extends BaseActivity {
private WebView webview;
private WebSettings settings;
private SwipeRefreshLayout swipe_refresh;
private String mUrl = null;
private final static String INTENT_URL="intent_url";
public static void startActivity(Activity activity, String url){
Intent intent=new Intent(activity,MyWebViewActivity.class);
intent.putExtra(INTENT_URL,url);
activity.startActivity(intent);
}
@Override
protected int getLayoutId() {
return R.layout.activity_my_web;
}
@Override
protected void initData() {
super.initData();
swipe_refresh = (SwipeRefreshLayout) this.findViewById(R.id.swipe_refresh);
webview = new WebView(getApplicationContext());
webview.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
swipe_refresh.addView(webview);
settings = webview.getSettings();
webview.setWebViewClient(new MyWebViewClient());
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
webview.loadUrl(webview.getUrl());
}
});
//设置进度条
webview.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
//隐藏进度条
swipe_refresh.setRefreshing(false);
} else {
if (!swipe_refresh.isRefreshing())
swipe_refresh.setRefreshing(true);
}
super.onProgressChanged(view, newProgress);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
}
);
if(getIntent()!=null){
mUrl = getIntent().getStringExtra(INTENT_URL);
}
if (TextUtils.isEmpty(mUrl)) {
ToastUtils.showToast("网络异常");
finish();
}
}
@Override
protected void onResume() {
super.onResume();
settings.setJavaScriptEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.loadUrl(mUrl);
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
});
}
@Override
protected void onPause() {
super.onPause();
settings.setJavaScriptEnabled(false);
}
@Override
protected void onDestroy() {
swipe_refresh.removeAllViews();
webview.stopLoading();
webview.removeAllViews();
webview.destroy();
webview = null;
swipe_refresh = null;
super.onDestroy();
}
private final class MyWebViewClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url2) {
view.loadUrl(url2);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//view.loadUrl(url);
// pb_loading.setVisibility(IView.GONE);
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
}
|
package com.nexlesoft.tenwordsaday_chiforeng.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.TouchDelegate;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.nexlesoft.tenwordsaday_chiforeng.R;
/**
* @author annqd
*
*/
public class SwitchButton extends FrameLayout implements OnClickListener {
@SuppressWarnings("unused")
private static final String TAG = SwitchButton.class.getSimpleName();
private LinearLayout mRootView;
private FontableTextView mTxtOn, mTxtOff;
@SuppressWarnings("unused")
private ImageView mToggle;
private Status mStatus;
public Status getStatus() {
return mStatus;
}
public enum Status {
ON, OFF
}
public interface OnSwitchListener {
public void OnSwitchChanged(Status status);
}
private OnSwitchListener mOnSwitchListener;
public void setOnSwitchListener(OnSwitchListener mOnSwitchListener) {
this.mOnSwitchListener = mOnSwitchListener;
}
public SwitchButton(Context context) {
super(context);
}
public SwitchButton(Context context, AttributeSet attrs) {
super(context, attrs);
Init(attrs);
}
public SwitchButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Init(attrs);
}
private void Init(AttributeSet attrs) {
mRootView = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.switch_button, null);
mTxtOn = (FontableTextView) mRootView.findViewById(R.id.text_on);
mTxtOff = (FontableTextView) mRootView.findViewById(R.id.text_off);
mToggle = (ImageView) mRootView.findViewById(R.id.iv_toggle);
mRootView.post(new Runnable() {
@Override
public void run() {
Rect delegateArea = new Rect();
mTxtOn.getHitRect(delegateArea);
mTxtOff.getHitRect(delegateArea);
delegateArea.top -= 100;
delegateArea.bottom += 100;
delegateArea.left -= 100;
delegateArea.right += 100;
TouchDelegate mTxtOnExpandArea = new TouchDelegate(delegateArea, mTxtOn);
TouchDelegate mTxtOffExpandArea = new TouchDelegate(delegateArea, mTxtOff);
if (View.class.isInstance(mTxtOn.getParent())) {
((View) mTxtOn.getParent()).setTouchDelegate(mTxtOnExpandArea);
}
if (View.class.isInstance(mTxtOn.getParent())) {
((View) mTxtOn.getParent()).setTouchDelegate(mTxtOffExpandArea);
}
}
});
mTxtOn.setOnClickListener(this);
mTxtOff.setOnClickListener(this);
if (attrs != null) {
TypedArray styled = getContext().obtainStyledAttributes(attrs, R.styleable.SwitchButton);
String textOn = styled.getString(R.styleable.SwitchButton_text_on);
String textOff = styled.getString(R.styleable.SwitchButton_text_off);
mStatus = Status.values()[styled.getInt(R.styleable.SwitchButton_init_status, 0)];
mTxtOn.setText(textOn);
mTxtOff.setText(textOff);
SwitchState(mStatus);
}
this.addView(mRootView);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.text_on:
SwitchState(Status.OFF);
break;
case R.id.text_off:
SwitchState(Status.ON);
break;
default:
break;
}
}
public void SwitchState(Status status) {
mStatus = status;
switch (status) {
case ON:
mTxtOn.setVisibility(View.VISIBLE);
mTxtOff.setVisibility(View.GONE);
break;
case OFF:
mTxtOn.setVisibility(View.GONE);
mTxtOff.setVisibility(View.VISIBLE);
break;
default:
break;
}
if (mOnSwitchListener != null)
mOnSwitchListener.OnSwitchChanged(mStatus);
}
}
|
package com.tyj.venus.controller.home;
import com.tyj.venus.controller.BaseController;
import com.tyj.venus.entity.Systems;
import com.tyj.venus.entity.User;
import com.tyj.venus.entity.UserInfo;
import com.tyj.venus.service.MenuService;
import com.tyj.venus.service.SystemService;
import com.tyj.venus.service.UserInfoService;
import com.tyj.venus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping(value = "")
public class AuthController extends BaseController {
@Autowired
private UserInfoService userInfoService;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private MenuService menuService;
@Autowired
private SystemService systemService;
@GetMapping("/login")
public String login(Model model) {
Systems system = systemService.get(1);//系统设置
model.addAttribute("sys", system);
return "home/login";
}
@PostMapping("/login")
@ResponseBody
public String loginAt(HttpServletRequest request) {
String username = request.getParameter("username");
String password = request.getParameter("password");
String remember = "-1";
UserInfo user = userInfoService.login(username, password);
if (user == null) {
return this.outPutErr("用户名或密码不正确");
}
// 记住密码session永不失效
if (remember == "-1") {
request.getSession().setMaxInactiveInterval(Integer.parseInt(remember));
}
request.getSession().setAttribute("user", user);
return this.outPutData("登录成功");
}
@GetMapping("/logout")
public String logout(HttpServletRequest request) {
request.getSession().removeAttribute("user");
String path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
return "redirect:"+path+"/login";
}
}
|
package cc.lau.http;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by cc on 18/3/16
*/
public class HttpUtil {
/**
* get请求
*
* @param uri
* @return
*/
public static String get(String uri) {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet(uri);
CloseableHttpResponse response = null;
try {
response = client.execute(get);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
String result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != response) {
response.close();
}
if (null != client) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* post请求(用于key-value格式的参数)
*
* @param uri
* @param params
* @return
*/
public static String post(String uri, Map<String, Object> params) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(uri);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
nameValuePairList.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
CloseableHttpResponse response = null;
try {
post.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != response) {
response.close();
}
if (null != client) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* post请求(用于JSON参数)
*
* @param uri
* @param params
* @return
*/
public static String post(String uri, String params) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(uri);
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(params, "UTF-8"));
CloseableHttpResponse response = null;
try {
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != response) {
response.close();
}
if (null != client) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
|
package com.example.a.book_recommend;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.example.a.book_recommend.Adapter.AdapterRecyclerView;
import com.example.a.book_recommend.Adapter.Book;
import com.example.a.book_recommend.Adapter.Bookobject;
import com.example.a.book_recommend.Async_and_BackEnd.CosineVectorSimilarity;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class DisplaySimilarActivity extends AppCompatActivity {
private static final String TAG = "DisplaySimilarActivity";
DatabaseReference addatabasereference = FirebaseDatabase.getInstance().getReference().child("library_db");
ArrayList<Bookobject> booklists;
ArrayList<Book> bookobjects;
String[] tokenstring;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
booklists = new ArrayList<>();
setContentView(R.layout.activity_display_similar);
final Intent intent = getIntent();
ArrayList<String> token = intent.getStringArrayListExtra("token");
tokenstring = token.toArray(new String[0]);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
bookobjects = new ArrayList<>();
loaddatafromfirebase();
}
private void loaddatafromfirebase() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
addatabasereference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
booklists.clear();
for (DataSnapshot bookdatasnapshot : dataSnapshot.getChildren()) {
Book book = bookdatasnapshot.getValue(Book.class);
Bookobject bookobject = new Bookobject();
bookobject.bookname = book.getBook_name();
bookobject.bookauthor = book.getBook_author();
bookobject.bookdate = book.getBook_date();
bookobject.bookdetail = book.getBook_detail();
bookobject.bookisbn = book.getBook_isbn();
bookobject.booktoken = book.getBook_token();
bookobject.Uris = book.getURIs();
bookobject.cosadd = book.getCos_add();
bookobject.likecount = book.getLike_count();
bookobject.dislikecount = book.getDislike_count();
bookobject.requestcount = book.getRequest_count();
bookobject.bookgenre = book.getBook_Genre();
bookobject.available=book.getBook_Available();
Log.d(TAG, "BOOK TOKEN=" + bookobject.booktoken);
String[] tokenstring3 = new String[bookobject.booktoken.size()];
for (int i = 0; i < bookobject.booktoken.size(); i++) {
tokenstring3[i] = bookobject.booktoken.get(i);
Log.d(TAG, bookobject.booktoken.size() + "size of book token");
}
bookobject.cosine = CosineVectorSimilarity.consineTextSimilarity(tokenstring, tokenstring3);
booklists.add(bookobject);
}
adapter = new AdapterRecyclerView(booklists, true, getApplicationContext());
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
Log.d(TAG, "RUNNING SORTER");
sortarray();//ascending
Collections.reverse(booklists);//DESCENDNG
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("DisplaySimilarActivity", "ERROR LOADING DATA");
}
});
}
private void sortarray() {
Collections.sort(booklists, new Comparator<Bookobject>() {
@Override
public int compare(Bookobject t1, Bookobject bookobject) {
return Double.compare(t1.getCosine(), bookobject.getCosine());
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(DisplaySimilarActivity.this, LibraryActivity.class));
}
}
|
//Figure 3-2b
import Semaphore;
public class SomeClass extends Object {
// Shared objects
// Proctect resource One
public static Semaphore resource_1 = new Semaphore(1);
// Proctect resource Two
public static Semaphore resource_2 = new Semaphore(1);
class User1 extends Thread {
public void process_A(){
resource_1.down();
resource_2.down();
use_both_resources();
resource_2.up();
resource_1.up();
}
}
class User2 extends Thread {
public void process_B(){
resource_2.down();
resource_1.down();
use_both_resources();
resource_1.up();
resource_2.up();
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mypack.listmapping;
import java.util.List;
/**
*
* @author mnagdev
*/
public class Question {
private int id;
private String qname;
private List<String> answers;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQname() {
return qname;
}
public void setQname(String qname) {
this.qname = qname;
}
public List getAnswers(){
return this.answers;
}
public void setAnswers(List<String> answers)
{
this.answers=answers;
}
}//class
|
/*
* $Header: /home/cvsroot/HelpDesk/src/com/aof/util/Constants.java,v 1.1 2004/11/10 01:39:03 nicebean Exp $
* $Revision: 1.1 $
* $Date: 2004/11/10 01:39:03 $
*
* ====================================================================
*
* Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved.
*
* ====================================================================
*/
package com.aof.util;
/**
* 维持用户登陆系统后运行信息
*
* @author Xingping Xu
* @version $Revision: 1.1 $ $Date: 2004/11/10 01:39:03 $
*/
public final class Constants {
/**
* The package name for this application.
*/
public static final String Package = "com.aof";
/**
* 缓存数据库记录
*/
public static final String DATABASE_KEY = "DATABASE_KEY";
/**
* 缓存HibernateSession连结
*/
public static final String HIBERNATE_SESSION_KEY = "AOFSESSION";
/**
* Catch the SecurityHandler
*/
public static final String SECURITY_HANDLER_KEY = "AOFSECURITY";
/**
* 缓存用户信息记录
*/
public static final String USERLOGIN_KEY = "USERLOGIN_KEY";
public static final String USERID_KEY = "USERID_KEY";
public static final String USERNAME_KEY = "USERNAME_KEY";
public static final String MODELS_KEY = "MODEL_KEY";
public static final String SECURITY_KEY = "SECURITY_KEY";
public static final String USER_ROLE_KEY="USER_ROLE_KEY";
public static final String PARTY_KEY = "PARTY_KEY";
public static final String TRUE_PARTY_KEY = "TRUE_PARTY_KEY";
public static final String ERROR_KEY = "ERROR_KEY";
public static final String USERLOGIN_ROLE_KEY = "USERLOGIN_ROLE_KEY";
public static final String SUB_PARTY_KEY = "SUB_PARTY_KEY";
//Transaction Category defination
public final static String TRANSACATION_CATEGORY_EXPENSE = "Expense";
public final static String TRANSACATION_CATEGORY_CAF = "CAF";
public final static String TRANSACATION_CATEGORY_ALLOWANCE = "Allowance";
public final static String TRANSACATION_CATEGORY_BILLING_ACCEPTANCE = "ProjBill";
public final static String TRANSACATION_CATEGORY_PAYMENT_ACCEPTANCE = "ProjPayment";
public final static String TRANSACATION_CATEGORY_OTHER_COST = "OtherCost";
public final static String TRANSACATION_CATEGORY_DOWN_PAYMENT = "Down-Payment";
public final static String TRANSACATION_CATEGORY_CREDIT_DOWN_PAYMENT = "Credit-Down-Payment";
//Billing Status defination
public final static String BILLING_STATUS_DRAFT = "Draft";
public final static String BILLING_STATUS_WIP = "WIP";
public final static String BILLING_STATUS_COMPLETED = "Completed";
//PAYMENT Status defination
public final static String PAYMENT_STATUS_DRAFT = "Draft";
public final static String PAYMENT_STATUS_WIP = "WIP";
public final static String PAYMENT_STATUS_COMPLETED = "Completed";
//PAYMENT SETTLEMENT TRANSACTION STATUS
public final static String POST_PAYMENT_TRANSACTION_STATUS_DRAFT = "Draft";
public final static String POST_PAYMENT_TRANSACTION_STATUS_POST = "Post";
public final static String POST_PAYMENT_TRANSACTION_STATUS_PAID = "Paid";
public final static String POST_PAYMENT_TRANSACTION_STATUS_REJECTED = "Rejected";
//POST PAYMENT Status defination
public final static String POST_PAYMENT_STATUS_DRAFT = "Draft";
public final static String POST_PAYMENT_STATUS_WIP = "WIP";
public final static String POST_PAYMENT_STATUS_COMPLETED = "Completed";
//PAYMENT confirm Status defination
public final static String PAYMENT_CONFIRM_STATUS_DRAFT = "Draft";
public final static String PAYMENT_CONFIRM_STATUS_COMPLETED = "Completed";
//Billing Type defination
public final static String BILLING_TYPE_DOWN_PAYMENT = "Down Payment";
public final static String BILLING_TYPE_NORMAL = "Normal";
// payment Type defination
public final static String PAYMENT_TYPE_DOWN_PAYMENT = "Down Payment";
public final static String PAYMENT_TYPE_NORMAL = "Normal";
//Invoice Status defination
public final static String INVOICE_STATUS_UNDELIVERED = "Undelivered";
public final static String INVOICE_STATUS_DELIVERED = "Delivered";
public final static String INVOICE_STATUS_CONFIRMED = "Confirmed";
public final static String INVOICE_STATUS_CANCELED = "Cancelled";
public final static String INVOICE_STATUS_INPROSESS = "In Process";
public final static String INVOICE_STATUS_COMPLETED = "Completed";
//Invoice Type defination
public final static String INVOICE_TYPE_NORMAL = "Normal";
public final static String INVOICE_TYPE_LOST_RECORD = "Lost Record";
//EMS deliver type defination
public final static String EMS_TYPE_EMS_DELIVER = "EMS Deliver";
public final static String EMS_TYPE_OTHER_DELIVER = "Other Deliver";
public final static String ONLINE_USER_KEY = "ONLINE_USER_KEY";
public final static String ONLINE_USER_LISTENER = "ONLINE_USER_LISTENER";
public final static String ONLINE_USER_IP_ADDRESS = "ONLINE_USER_IP_ADDRESS";
//Payment Status defination
public final static String PAYMENT_INVOICE_STATUS_DRAFT = "Draft";
public final static String PAYMENT_INVOICE_STATUS_CONFIRMED = "Confirmed";
public final static String PAYMENT_INVOICE_STATUS_CANCELED = "Cancelled";
//Receipt Status defination
public final static String RECEIPT_STATUS_DRAFT = "Draft";
public final static String RECEIPT_STATUS_WIP = "WIP";
public final static String RECEIPT_STATUS_COMPLETED = "Completed";
//Supplier Invoice Status defination
public final static String SUPPLIER_INVOICE_PAY_STATUS_DRAFT = "Draft";
public final static String SUPPLIER_INVOICE_PAY_STATUS_WIP = "WIP";
public final static String SUPPLIER_INVOICE_PAY_STATUS_COMPLETED = "Completed";
public final static String SUPPLIER_INVOICE_SETTLE_STATUS_DRAFT = "Draft";
public final static String SUPPLIER_INVOICE_SETTLE_STATUS_WIP = "WIP";
public final static String SUPPLIER_INVOICE_SETTLE_STATUS_COMPLETED = "Completed";
//Payment Type defination
public final static String PAYMENT_INVOICE_TYPE_NORMAL = "Normal";
public final static String PAYMENT_INVOICE_TYPE_LOST_RECORD = "Lost Record";
public final static String CONTRACT_PROFILE_STATUS_UNSIGNED ="Unsigned";
public final static String CONTRACT_PROFILE_STATUS_SIGNED ="Signed";
public final static String CONTRACT_PROFILE_STATUS_CANCEL ="Cancel";
public final static String CONTRACT_PROFILE_STATUS_CLOSED ="Closed";
//StepGroup Disable Flag Status defination
public final static String STEP_GROUP_DISABLE_FLAG_STATUS_YES = "Y";
public final static String STEP_GROUP_DISABLE_FLAG_STATUS_NO = "N";
//StepActivity Critical Flag Status defination
public final static String STEP_ACTIVITY_CRITICAL_FLAG_STATUS_YES = "Y";
public final static String STEP_ACTIVITY_CRITICAL_FLAG_STATUS_NO = "N";
//BidMaster Status defination
public final static String BID_MASTER_STATUS_WIP = "WIP";
public final static String BID_MASTER_STATUS_WIN = "Win";
public final static String BID_MASTER_STATUS_WON = "Won";
public final static String BID_MASTER_STATUS_WITHDRAWED = "Withdrawed";
public final static String BID_MASTER_STATUS_PENDING = "Pending";
public final static String BID_MASTER_STATUS_LOST = "Lost";
}
|
package net.sf.throughglass.timeline.testcase;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import net.sf.throughglass.timeline.model.Timeline.TimelineCacheItem;
import net.sf.throughglass.timeline.model.Timeline.TimelineListCache;
import net.sf.throughglass.timeline.model.TimelineModelMgr;
/**
* Created by guang_hik on 14-8-10.
*/
public class TestCaseData {
private Context mContext;
public TestCaseData(Context context) {
mContext = context;
}
public void testResetTimelineData() {
// TODO:
TimelineListCache.Builder builder = TimelineListCache.newBuilder();
for (int i = 0; i < 30; i++) {
TimelineCacheItem.Builder b = TimelineCacheItem.newBuilder();
b.addThumbs("bitmap://path/to/your/file#400x200");
b.setCreateUnixTime((int) (System.currentTimeMillis() / 1000L));
b.setId(i);
builder.addList(b);
}
try {
FileOutputStream fos = mContext.openFileOutput(TimelineModelMgr.CACHE_FILE, Context.MODE_PRIVATE);
builder.build().writeTo(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package cn.com.signheart.common.util;
import org.apache.commons.io.IOUtils;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
public class FileUtil {
public static String separator = System.getProperty("file.separator");
public static String[] IMG_FIX = new String[]{"jpg", "bmp", "gif", "jpeg", "png"};
public static int WRITE_MODE_OVERWRITE = 0;
public static int WRITE_MODE_APPEND = 1;
public FileUtil() {
}
public static File creatFile(String _file) throws Exception {
String path = null;
if(_file.lastIndexOf(separator) >= 0) {
path = _file.substring(0, _file.lastIndexOf(separator));
} else {
path = _file;
}
File jarFile;
if(path.length() > 2 && _file.lastIndexOf(separator) >= 0) {
jarFile = new File(path);
if(!jarFile.exists()) {
jarFile.mkdirs();
}
}
jarFile = new File(_file);
if(!jarFile.exists()) {
jarFile.createNewFile();
}
return jarFile;
}
public static File copy(String _sourceFile, String _newFile, boolean _overWrite) throws Exception {
File outFile = new File(_newFile);
File inFile = new File(_sourceFile);
return copy(inFile, outFile, _overWrite);
}
public static File copy(File _sourceFile, String _newFile, boolean _overWrite) throws Exception {
File outFile = new File(_newFile);
return copy(_sourceFile, outFile, _overWrite);
}
public static File copy(String _sourceFile, File _newFile, boolean _overWrite) throws Exception {
File inFile = new File(_sourceFile);
return copy(inFile, _newFile, _overWrite);
}
public static File copy(File _sourceFile, File _newFile, boolean _overWrite) throws Exception {
FileOutputStream is = null;
FileInputStream rd = null;
try {
if(_newFile.isFile() && _overWrite && _newFile.exists()) {
_newFile.delete();
}
if(_sourceFile.isFile() && !_overWrite && _newFile.exists()) {
File var13 = _newFile;
return var13;
}
is = new FileOutputStream(_newFile);
rd = new FileInputStream(_sourceFile);
byte[] fnfe = new byte[16384];
for(int var14 = rd.read(fnfe); var14 != -1; var14 = rd.read(fnfe)) {
is.write(fnfe, 0, var14);
}
} catch (FileNotFoundException var11) {
if(!_sourceFile.isDirectory()) {
throw var11;
}
File[] files = _sourceFile.listFiles();
for(int i = 0; i < files.length; ++i) {
if((new File(_sourceFile + File.separator + files[i].getName())).isDirectory() && !(new File(_newFile + File.separator + files[i].getName())).exists()) {
(new File(_newFile + File.separator + files[i].getName())).mkdirs();
}
copy(_sourceFile + File.separator + files[i].getName(), _newFile + File.separator + files[i].getName(), _overWrite);
}
} finally {
IOUtils.closeQuietly(rd);
IOUtils.closeQuietly(is);
}
return _newFile;
}
public static File writeFile(String _path, String _content, int _writeMode, String _encode) throws FileNotFoundException, UnsupportedEncodingException, IOException {
File outFile = new File(_path);
return writeFile(outFile, _content, _writeMode, _encode);
}
public static File writeFile(File _file, String _content, int _writeMode, String _encode) throws FileNotFoundException, UnsupportedEncodingException, IOException {
return writeFile(_file, _content.getBytes(_encode), _writeMode);
}
public static File writeFile(File _file, byte[] _fileByte, int _writeMode) throws FileNotFoundException, UnsupportedEncodingException, IOException {
if(_writeMode <= WRITE_MODE_APPEND && _writeMode >= WRITE_MODE_OVERWRITE) {
FileOutputStream is = null;
try {
if(!_file.getParentFile().exists()) {
_file.getParentFile().mkdirs();
}
is = new FileOutputStream(_file.getPath(), WRITE_MODE_APPEND == _writeMode);
IOUtils.write(_fileByte, is);
} finally {
IOUtils.closeQuietly(is);
}
return _file;
} else {
throw new IOException("错误的文件写入方式:" + _writeMode);
}
}
public static File openFile(String _file) throws Exception {
return openFile(_file, true);
}
public static File openFile(String _file, boolean _create) throws Exception {
String path = null;
if(_file.lastIndexOf(separator) >= 0) {
path = _file.substring(0, _file.lastIndexOf(separator));
} else {
path = _file;
}
File newFile;
if(path.length() > 2 && _file.lastIndexOf(separator) >= 0) {
newFile = new File(path);
if(!newFile.exists()) {
newFile.mkdirs();
}
}
newFile = new File(_file);
if(_create && !newFile.exists()) {
newFile.createNewFile();
}
return newFile;
}
public static File ChooseDir(Component _cp, String _title, String _currPath) throws Exception {
JFileChooser choose = FileChooser(_currPath, _title, 1);
return getFile(_cp, choose);
}
public static File ChooseOpenFile(Component _cp, String _title, String _currPath) throws Exception {
JFileChooser choose = FileChooser(_currPath, _title, 0);
return getFile(_cp, choose);
}
public static File ChooseSaveFile(Component _cp, String _title, String _currPath) throws Exception {
JFileChooser choose = FileChooser(_currPath, _title, 1);
return getFile(_cp, choose);
}
public static File[] ChooseDirs(Component _cp, String _title, String _currPath) throws Exception {
JFileChooser choose = mulitFileChooser(_currPath, _title, 1);
return getFiles(_cp, choose);
}
public static File[] ChooseOpenFiles(Component _cp, String _title, String _currPath) throws Exception {
JFileChooser choose = mulitFileChooser(_currPath, _title, 0);
return getFiles(_cp, choose);
}
public static File[] ChooseSaveFiles(Component _cp, String _title, String _currPath) throws Exception {
JFileChooser choose = mulitFileChooser(_currPath, _title, 1);
return getFiles(_cp, choose);
}
public static JFileChooser FileChooser(String _currPath, String _title, int _Mod) {
JFileChooser choose = null;
if(AssertUtil.isEmpty(_currPath)) {
choose = new JFileChooser();
} else {
choose = new JFileChooser(_currPath);
}
choose.setFileSelectionMode(_Mod);
choose.setMultiSelectionEnabled(false);
choose.setDialogTitle(_title);
return choose;
}
public static JFileChooser mulitFileChooser(String _currPath, String _title, int _Mod) {
JFileChooser choose = null;
if(AssertUtil.isEmpty(_currPath)) {
choose = new JFileChooser();
} else {
choose = new JFileChooser(_currPath);
}
choose.setFileSelectionMode(_Mod);
choose.setMultiSelectionEnabled(true);
choose.setDialogTitle(_title);
return choose;
}
public static File getFile(Component _cp, JFileChooser _choose) {
int n = _choose.showOpenDialog(_cp);
return n == 0?_choose.getSelectedFile():null;
}
public static File[] getFiles(Component _cp, JFileChooser _choose) {
int n = _choose.showOpenDialog(_cp);
return n == 0?_choose.getSelectedFiles():null;
}
public static boolean isImage(String _fileName) throws Exception {
if(AssertUtil.isEmpty(_fileName)) {
throw new Exception("传入的参数错误:为空");
} else {
int startPoint = _fileName.lastIndexOf(".");
if(startPoint >= 0) {
String fix = _fileName.substring(startPoint + 1, _fileName.length());
if(StringUtil.isInContainer(IMG_FIX, fix)) {
return true;
}
}
return false;
}
}
public static boolean isImage(File _file) throws Exception {
return isImage(_file.getPath());
}
public static String[] getContentListFromTxt(String _fileName) {
return getContentListFromTxt(new File(_fileName));
}
public static String[] getContentListFromTxt(File _file) {
BufferedReader fr = null;
ArrayList strList = new ArrayList();
try {
fr = new BufferedReader(new FileReader(_file));
String e = "";
while((e = fr.readLine()) != null) {
strList.add(e);
}
} catch (IOException var7) {
var7.printStackTrace();
} finally {
IOUtils.closeQuietly(fr);
}
return strList.isEmpty()?new String[0]:(String[])strList.toArray(new String[strList.size()]);
}
public static void main(String[] args) {
try {
copy("d:\\test.txt", "d:\\test_test\\test.txt", true);
} catch (Exception var2) {
var2.printStackTrace();
}
}
public static String readFileContext(String file) throws IOException {
return readFileContext(file, "utf-8");
}
public static String readFileContext(String file, String encode) throws IOException {
File f = new File(file);
if(f.exists() && f.isFile()) {
FileInputStream reader = new FileInputStream(file);
String var4;
try {
var4 = IOUtils.toString(reader, encode);
} finally {
IOUtils.closeQuietly(reader);
}
return var4;
} else {
return "读取文件异常";
}
}
public static String buildFilePath(String... path) {
StringBuilder rsb = new StringBuilder();
String[] arr$ = path;
int len$ = path.length;
for(int i$ = 0; i$ < len$; ++i$) {
String midlePath = arr$[i$];
if(rsb.length() > 0) {
rsb.append(separator);
}
rsb.append(midlePath);
}
return rsb.toString();
}
}
|
package Programmieraufgabe14;
import java.util.Scanner;
public class Program {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Player player = new Player();
Field field = new Field();
do {
field.erasePreviousPlayer(player.getCoordinateX(), player.getCoordinateY());
player.updatePlayerStatus(askForNextAction(), '^');
player.updatePlayerPosition(askForNextAction());
field.createField(player.getCoordinateX(),player.getCoordinateY(), player.getPlayerStatusAtPosition());
field.displayField();
System.out.println("Willst du nochmal spielen?");
}
while (scanner.next().contains("Ja"));
}
public static char askForNextAction() {
System.out.println("Führen Sie eine Aktion (g = vorwärts gehen, l = links drehen, r = rechts drehen, q = beenden) aus:");
char action = scanner.next().charAt(0);
return action;
}
}
|
package io.codex.cryptogram.encoding;
/**
* 原样编码器
*
* @author 杨昌沛 646742615@qq.com
* 2018/10/18
*/
public class PlainEncoder implements Encoder {
public String algorithm() {
return "Plain";
}
public String encode(byte[] data) {
return new String(data);
}
}
|
package com.su.dao.api;
import com.su.domain.User;
/**
* Created by Андрей on 25.10.2016.
*/
public interface UserDao extends GenericDao<User> {
}
|
package com.oa.user.dao;
import java.util.List;
import com.oa.user.form.UserInfo;
public interface UserInfoDao {
public void addUser(UserInfo userInfo);
public List<UserInfo> selectAllUser();
public UserInfo selectUserByName(String userName)
;
public UserInfo selectUserByNameAndPassword(String userName,String password);
public UserInfo selectUserById(int id);
public void removeUser(int id);
public void updateUser(UserInfo userInfo);
public void deleteUser(Integer id);
}
|
package com.selfspring.gimi.json.keyUp;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date;
/**
* Created by ckyang on 2019/10/14.
*/
public class UserSynInfo {
/**
* 用户Id
*
* 作为更新表的主键使用
*/
@JSONField(name="UserId")
private Long userId;
/**
* 用户昵称
*/
@JSONField(name="NickName")
private String nickName;
/**
* 用户的NetId
*/
@JSONField(name="NetId")
private Integer netId;
/**
* 用户加入家庭时间,时间格式为标准时间戳格式,如2016-03-23 11:43:07
*/
@JSONField(name="CreateTime",format="yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 全同步不需要,单条同步需要
*/
@JSONField(name="SN")
private String sN;
/**
* 更新时间,时间格式为标准时间戳格式,如2016-03-23 11:43:07
*/
@JSONField(name="UpdateTime",format="yyyy-MM-dd HH:mm:ss")
private String updateTime;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Integer getNetId() {
return netId;
}
public void setNetId(Integer netId) {
this.netId = netId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getsN() {
return sN;
}
public void setsN(String sN) {
this.sN = sN;
}
}
|
package com.example.prova;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AccActivity extends AppCompatActivity implements SensorEventListener{
private static final String TAG = "AccActivity";
private TextView txtX, txtY, txtZ;
private Button btnEsci;
private SensorManager sensorManager;
private Sensor accelerometro;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acc);
//BIND
txtX = findViewById(R.id.txtX);
txtY = findViewById(R.id.txtY);
txtZ = findViewById(R.id.txtZ);
btnEsci = findViewById(R.id.btnEsciAcc);
//Listener
btnEsci.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AccActivity.this.finish();
}
});
//attivazione e collegamento sensore
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); // init del Gestore dei sensori
accelerometro = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // specifico che l'oggetto sensore andrà a gestire il sensore Accelerometro
// Registrazione Listener per sensore specifico
sensorManager.registerListener((SensorEventListener) this, accelerometro, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
Log.d(TAG, "X: "+ event.values[0]+
" Y: " + event.values[1]+
" Z: "+ event.values[2]);
txtX.setText((int) event.values[0]);
txtY.setText((int) event.values[1]);
txtZ.setText((int) event.values[2]);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
|
package tn.esprit.spring.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tn.esprit.spring.entity.Contrat;
import tn.esprit.spring.repository.ContratRepository;
@Transactional
@Service
public class ContratServiceImpl implements IContratService {
@Autowired
ContratRepository contratRepository;
@Override
public Contrat ajouterContrat(Contrat contrat) {
contratRepository.save(contrat);
return contrat;
}
@Override
public void deleteContratById(int ContratId) {
Contrat contratManagedentity = contratRepository.findById(ContratId).get();
contratRepository.delete(contratManagedentity);
}
}
|
package com.gsccs.sme.plat.svg.model;
import com.gsccs.sme.api.domain.DeclareItem;
/**
* 项目申报
* @author x.d zhang
*
*/
public class DeclareItemT extends DeclareItem{
} |
package com.fanfte.netty.im.console;
import com.fanfte.netty.im.packet.request.GroupMessageRequestPacket;
import io.netty.channel.Channel;
import java.util.Scanner;
/**
* Created by tianen on 2018/10/9
*
* @author fanfte
* @date 2018/10/9
**/
public class SendToGroupConsoleCommand implements ConsoleCommand {
@Override
public void exec(Scanner scanner, Channel channel) {
System.out.println("输入groupId和消息内容,用空格隔开,发送消息到群组:");
String groupId = scanner.next();
String message = scanner.next();
GroupMessageRequestPacket groupMessageRequestPacket = new GroupMessageRequestPacket();
groupMessageRequestPacket.setToGroupId(groupId);
groupMessageRequestPacket.setMessage(message);
channel.writeAndFlush(groupMessageRequestPacket);
}
}
|
package com.dalong;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.function.Consumer;
@RestController
@SpringBootApplication(scanBasePackages ={"${scan.packages}","${scan.thirdpackages}"})
public class AppdemoApplication {
@Autowired
List<UserLogin> userLogins ;
@Value(value = "${scan.packages}")
private String packages;
@Value(value = "${scan.thirdpackages:null}")
private String thirdpackage;
public static void main(String[] args) {
SpringApplication.run(AppdemoApplication.class, args);
}
@GetMapping(value = {"/demo"})
public String result(){
userLogins.forEach(new Consumer<UserLogin>() {
@Override
public void accept(UserLogin userLogin) {
System.out.println(userLogin.login("dalobg",111));
}
});
return String.format("%s,%s",packages,thirdpackage);
}
}
|
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MessageController {
@GetMapping("/messages")
public String messages(Model model) {
return "messages";
}
} |
package com.sen.myshop.web.admin.web.controller;
import com.sen.myshop.commons.dto.BaseResult;
import com.sen.myshop.domain.TbUser;
import com.sen.myshop.web.admin.abstracts.AbstractBaseController;
import com.sen.myshop.web.admin.service.TbUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("user")
public class UserController extends AbstractBaseController<TbUser,TbUserService> {
/**
* 用于user_list展示所有的用户信息
* @return
*/
@Override
@RequestMapping(value = "list", method = RequestMethod.GET)
public String list() {
return "user_list";
}
/**
* 跳转表单页面
* @return
*/
@Override
@RequestMapping(value = "form", method = RequestMethod.GET)
public String form() {
return "user_form";
}
/**
* 提供对象返回页面模型给form标签使用
* @param id
* @return
*/
@ModelAttribute
public TbUser getTbUserByID(Long id) {
TbUser tbUser = null;
if (id != null) {
tbUser = service.getById(id);
} else {
tbUser = new TbUser();//spring自动注入
}
return tbUser;
}
/**
* 保存或者修改用户的相关处理
* @param tbUser
* @param redirectAttributes
* @param model
* @return
*/
@Override
@RequestMapping(value = "save", method = RequestMethod.POST)
public String save(TbUser tbUser, RedirectAttributes redirectAttributes, Model model) {
BaseResult baseResult = service.save(tbUser);
if (baseResult.getStatus() == BaseResult.STATUS_SUCCESS) {
redirectAttributes.addFlashAttribute("baseResult", baseResult);//把保存成功的信息重定向到用户列表页面
return "redirect:/user/list";
}
model.addAttribute("failedmessage", baseResult);
return "user_form";
}
/**
* 查看用户详情
* @return
*/
@Override
@RequestMapping(value = "detail", method = RequestMethod.GET)
public String detail() {
return "user_detail";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.