blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
85d8ba4167589e2aea25c244312ca8e342ebc7e5 | Java | dwerle/Palladio-Addons-Indirections | /bundles/org.palladiosimulator.indirections.simulizar/src/org/palladiosimulator/indirections/simulizar/rdseffswitch/IndirectionsAwareRDSeffSwitch.java | UTF-8 | 12,676 | 1.539063 | 2 | [] | no_license | package org.palladiosimulator.indirections.simulizar.rdseffswitch;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.apache.log4j.Logger;
import org.eclipse.emf.common.util.EList;
import org.palladiosimulator.indirections.actions.ConsumeDataAction;
import org.palladiosimulator.indirections.actions.EmitDataAction;
import org.palladiosimulator.indirections.actions.util.ActionsSwitch;
import org.palladiosimulator.indirections.composition.DataChannelSinkConnector;
import org.palladiosimulator.indirections.composition.DataChannelSourceConnector;
import org.palladiosimulator.indirections.interfaces.IDataChannelResource;
import org.palladiosimulator.indirections.scheduler.IndirectionUtil;
import org.palladiosimulator.indirections.system.DataChannel;
import org.palladiosimulator.pcm.allocation.Allocation;
import org.palladiosimulator.pcm.allocation.AllocationContext;
import org.palladiosimulator.pcm.core.PCMRandomVariable;
import org.palladiosimulator.pcm.core.composition.AssemblyContext;
import org.palladiosimulator.pcm.core.composition.Connector;
import org.palladiosimulator.pcm.core.composition.EventChannel;
import org.palladiosimulator.pcm.parameter.VariableCharacterisation;
import org.palladiosimulator.pcm.parameter.VariableUsage;
import org.palladiosimulator.pcm.repository.SinkRole;
import org.palladiosimulator.pcm.repository.SourceRole;
import org.palladiosimulator.simulizar.exceptions.PCMModelAccessException;
import org.palladiosimulator.simulizar.exceptions.PCMModelInterpreterException;
import org.palladiosimulator.simulizar.interpreter.ExplicitDispatchComposedSwitch;
import org.palladiosimulator.simulizar.interpreter.InterpreterDefaultContext;
import org.palladiosimulator.simulizar.runtimestate.SimulatedBasicComponentInstance;
import org.palladiosimulator.simulizar.utils.SimulatedStackHelper;
import de.uka.ipd.sdq.simucomframework.resources.SimulatedResourceContainer;
import de.uka.ipd.sdq.simucomframework.variables.EvaluationProxy;
import de.uka.ipd.sdq.simucomframework.variables.StackContext;
import de.uka.ipd.sdq.simucomframework.variables.exceptions.ValueNotInFrameException;
import de.uka.ipd.sdq.simucomframework.variables.stackframe.SimulatedStackframe;
import de.uka.ipd.sdq.stoex.AbstractNamedReference;
import de.uka.ipd.sdq.stoex.analyser.visitors.StoExPrettyPrintVisitor;
public class IndirectionsAwareRDSeffSwitch extends ActionsSwitch<Object> {
private static final Logger LOGGER = Logger.getLogger(IndirectionsAwareRDSeffSwitch.class);
private InterpreterDefaultContext context;
private SimulatedBasicComponentInstance basicComponentInstance;
private ExplicitDispatchComposedSwitch<Object> parentSwitch;
private Allocation allocation;
private SimulatedStackframe<Object> resultStackFrame;
private DataChannelRegistry dataChannelRegistry;
/**
* copied from
* {@link org.palladiosimulator.simulizar.interpreter.RDSeffSwitch#RDSeffSwitch(InterpreterDefaultContext, SimulatedBasicComponentInstance)}
*
* @param context
* @param basicComponentInstance
*/
public IndirectionsAwareRDSeffSwitch(final InterpreterDefaultContext context,
final SimulatedBasicComponentInstance basicComponentInstance) {
super();
this.context = context;
this.allocation = context.getLocalPCMModelAtContextCreation().getAllocation();
this.resultStackFrame = new SimulatedStackframe<Object>();
this.basicComponentInstance = basicComponentInstance;
this.dataChannelRegistry = DataChannelRegistry.getInstanceFor(context);
}
public IndirectionsAwareRDSeffSwitch(InterpreterDefaultContext context,
SimulatedBasicComponentInstance basicComponentInstance,
ExplicitDispatchComposedSwitch<Object> parentSwitch) {
this(context, basicComponentInstance);
this.parentSwitch = parentSwitch;
}
/**
* Same as
* {@link SimulatedStackHelper#addParameterToStackFrame(SimulatedStackframe, EList, SimulatedStackframe)}
* but defaults for the parameters.
*
* @param parameterName
*/
private static final void addParameterToStackFrameWithCopying(final SimulatedStackframe<Object> contextStackFrame,
final EList<VariableUsage> parameter, String parameterName,
final SimulatedStackframe<Object> targetStackFrame) {
for (final VariableUsage variableUsage : parameter) {
if (variableUsage.getVariableCharacterisation_VariableUsage().isEmpty()) {
final AbstractNamedReference namedReference = variableUsage.getNamedReference__VariableUsage();
// TODO: move from convention quick hack to better solution
String[] split = namedReference.getReferenceName().split("->");
if (split.length != 2) {
throw new PCMModelInterpreterException(
"If no variable chacterisations are present, name must be of form 'input->output'. Name is: "
+ namedReference.getReferenceName());
}
String inputPrefix = split[0] + ".";
String outputPrefix = split[1] + ".";
List<Entry<String, Object>> inputs = contextStackFrame.getContents().stream()
.filter(it -> it.getKey().startsWith(inputPrefix)).collect(Collectors.toList());
if (inputs.size() == 0) {
throw new PCMModelInterpreterException("Nothing found on stack frame for prefix '" + inputPrefix
+ "'. Available: " + contextStackFrame.getContents().stream().map(it -> it.getKey())
.collect(Collectors.joining(", ")));
}
inputs.forEach(it -> targetStackFrame
.addValue(outputPrefix + it.getKey().substring(inputPrefix.length()), it.getValue()));
continue;
}
for (final VariableCharacterisation variableCharacterisation : variableUsage
.getVariableCharacterisation_VariableUsage()) {
final PCMRandomVariable randomVariable = variableCharacterisation
.getSpecification_VariableCharacterisation();
final AbstractNamedReference namedReference = variableCharacterisation
.getVariableUsage_VariableCharacterisation().getNamedReference__VariableUsage();
final String id = new StoExPrettyPrintVisitor().doSwitch(namedReference).toString() + "."
+ variableCharacterisation.getType().getLiteral();
;
if (SimulatedStackHelper.isInnerReference(namedReference)) {
targetStackFrame.addValue(id,
new EvaluationProxy(randomVariable.getSpecification(), contextStackFrame.copyFrame()));
} else {
targetStackFrame.addValue(id,
StackContext.evaluateStatic(randomVariable.getSpecification(), contextStackFrame));
}
if (LOGGER.isDebugEnabled()) {
try {
LOGGER.debug("Added value " + targetStackFrame.getValue(id) + " for id " + id
+ " to stackframe " + targetStackFrame);
} catch (final ValueNotInFrameException e) {
throw new RuntimeException(e);
}
}
}
}
}
// TODO move to helper
private <K,V> Map<K,V> toMap(List<Entry<K,V>> entryList) {
return entryList.stream()
.collect(Collectors.toMap(it -> it.getKey(), it -> it.getValue()));
}
@Override
public Object caseEmitDataAction(EmitDataAction action) {
// System.out.println("Emit event action: " + action.getEntityName());
IDataChannelResource dataChannelResource = getDataChannelResource(action);
SimulatedStackframe<Object> eventStackframe = new SimulatedStackframe<Object>();
String parameterName = IndirectionUtil
.claimOne(
action.getSourceRole().getEventGroup__SourceRole().getEventTypes__EventGroup())
.getParameter__EventType().getParameterName();
addParameterToStackFrameWithCopying(this.context.getStack().currentStackFrame(),
action.getInputVariableUsages__CallAction(), parameterName, eventStackframe);
// TODO: check cases in which getContents does not work
dataChannelResource.put(this.context.getThread(), toMap(eventStackframe.getContents()));
return true;
}
@Override
public Object caseConsumeDataAction(ConsumeDataAction action) {
IDataChannelResource dataChannelResource = getDataChannelResource(action);
String randomUUID = Thread.currentThread().getName();
// System.out.println("Trying to get (" + randomUUID + ")");
boolean result = dataChannelResource.get(this.context.getThread(), (eventMap) -> {
SimulatedStackframe<Object> contextStackframe = SimulatedStackHelper.createFromMap(eventMap);
String parameterName = IndirectionUtil
.claimOne(action.getSinkRole().getEventGroup__SinkRole().getEventTypes__EventGroup())
.getParameter__EventType().getParameterName();
// System.out.println("Parameter name: " + parameterName + " (" + randomUUID + ")");
addParameterToStackFrameWithCopying(contextStackframe, action.getReturnVariableUsage__CallReturnAction(),
parameterName, this.context.getStack().currentStackFrame());
// System.out.println(this.context.getStack().currentStackFrame());
});
// System.out.println("Continuing with " + this.context.getStack().currentStackFrame() + " (" + randomUUID + ")");
return result;
}
private IDataChannelResource getDataChannelResource(EmitDataAction action) {
AssemblyContext assemblyContext = this.context.getAssemblyContextStack().peek();
SourceRole sourceRole = action.getSourceRole();
DataChannel dataChannel = getConnectedSinkDataChannel(assemblyContext, sourceRole);
AllocationContext eventChannelAllocationContext = getAllocationContext(dataChannel);
SimulatedResourceContainer resourceContainer = getSimulatedResourceContainer(dataChannel,
eventChannelAllocationContext);
IDataChannelResource dataChannelResource = dataChannelRegistry.getOrCreateDataChannelResource(dataChannel);
return dataChannelResource;
}
private IDataChannelResource getDataChannelResource(ConsumeDataAction action) {
AssemblyContext assemblyContext = this.context.getAssemblyContextStack().peek();
SinkRole sinkRole = action.getSinkRole();
DataChannel dataChannel = getConnectedSourceDataChannel(assemblyContext, sinkRole);
AllocationContext eventChannelAllocationContext = getAllocationContext(dataChannel);
SimulatedResourceContainer resourceContainer = getSimulatedResourceContainer(dataChannel,
eventChannelAllocationContext);
IDataChannelResource dataChannelResource = dataChannelRegistry.getOrCreateDataChannelResource(dataChannel);
return dataChannelResource;
}
private SimulatedResourceContainer getSimulatedResourceContainer(EventChannel eventChannel,
AllocationContext eventChannelAllocationContext) {
List<SimulatedResourceContainer> simulatedResourceContainers = this.context.getModel().getResourceRegistry()
.getSimulatedResourceContainers();
return simulatedResourceContainers.stream()
.filter(it -> it.getResourceContainerID()
.equals(eventChannelAllocationContext.getResourceContainer_AllocationContext().getId()))
.findAny().orElseThrow(() -> new PCMModelAccessException(
"Could not find resource container for event channel " + eventChannel));
}
private AllocationContext getAllocationContext(EventChannel eventChannel) {
return this.allocation.getAllocationContexts_Allocation().stream()
.filter(it -> it.getEventChannel__AllocationContext() == eventChannel).findAny()
.orElseThrow(() -> new PCMModelAccessException(
"Could not find allocation context for event channel " + eventChannel));
}
private DataChannel getConnectedSinkDataChannel(AssemblyContext assemblyContext, SourceRole sourceRole) {
EList<Connector> connectors = assemblyContext.getParentStructure__AssemblyContext()
.getConnectors__ComposedStructure();
List<DataChannelSourceConnector> dataChannelSourceConnectors = connectors.stream()
.filter(DataChannelSourceConnector.class::isInstance).map(DataChannelSourceConnector.class::cast)
.collect(Collectors.toList());
return dataChannelSourceConnectors.stream().filter(it -> it.getSourceRole().equals(sourceRole)).findAny()
.orElseThrow(
() -> new PCMModelAccessException("Could not find data channel for source role " + sourceRole))
.getDataChannel();
}
private DataChannel getConnectedSourceDataChannel(AssemblyContext assemblyContext, SinkRole sinkRole) {
EList<Connector> connectors = assemblyContext.getParentStructure__AssemblyContext()
.getConnectors__ComposedStructure();
List<DataChannelSinkConnector> dataChannelSinkConnectors = connectors.stream()
.filter(DataChannelSinkConnector.class::isInstance).map(DataChannelSinkConnector.class::cast)
.collect(Collectors.toList());
DataChannelSinkConnector sinkConnectorForRole = dataChannelSinkConnectors.stream()
.filter(it -> it.getSinkRole().equals(sinkRole)).findAny().orElseThrow(
() -> new PCMModelAccessException("Could not find data channel for sink role " + sinkRole));
return sinkConnectorForRole.getDataChannel();
}
}
| true |
e34c40103adf2cea6259397e4328ff85d70cab90 | Java | aniolm/WeatherAppFX | /src/main/java/pl/wroclaw/asma/controller/services/CityListLoaderService.java | UTF-8 | 1,419 | 2.6875 | 3 | [] | no_license | package pl.wroclaw.asma.controller.services;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import pl.wroclaw.asma.Config;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
public class CityListLoaderService extends Service<HashMap<String, String>> {
@Override
protected Task<HashMap<String, String>> createTask() {
return new Task<HashMap<String, String>>() {
@Override
protected HashMap<String, String> call() throws Exception {
return loadCityList();
}
};
}
private HashMap<String, String> loadCityList() {
String fileName = Config.getCitiesFileName();
HashMap cityList = new HashMap<String, String>();
try {
Reader in = new FileReader( fileName );
CSVParser parser = new CSVParser( in, CSVFormat.DEFAULT.withDelimiter(';') );
List<CSVRecord> csvCityList = parser.getRecords();
for( CSVRecord row : csvCityList ){
cityList.put(row.get(0) + " / "+ row.get(3),row.get(1) + ", "+ row.get(2));
}
} catch (IOException e) {
e.printStackTrace();
}
return cityList;
}
}
| true |
c3e203fd6427124fa480d2fd743028297fec8fb8 | Java | kuzsergey/x5school | /src/main/java/homeWork_8/AccountService.java | UTF-8 | 2,392 | 3.390625 | 3 | [] | no_license | package homeWork_8;
import java.sql.Connection;
public class AccountService {
private Connection connection;
public AccountService(Connection connection) {
this.connection = connection;
}
public void balance(int accountId) throws UnknownAccountException {
Account account = DBAccounts.read(connection, accountId);
if (account.getId() == 0) {
throw new UnknownAccountException("Неизвестный счет");
}
System.out.println(account.getAmount());
}
public void withdraw(int accountId, int amount) throws NotEnoughMoneyException, UnknownAccountException {
Account account = DBAccounts.read(connection, accountId);
if (account.getId() == 0) {
throw new UnknownAccountException("Неизвестный счет");
}
if (account.getAmount() < amount) {
throw new NotEnoughMoneyException("На счету не достаточно средств.");
}
int currentAmount = account.getAmount();
account.setAmount(currentAmount - amount);
DBAccounts.write(connection, account);
}
public void deposit(int accountId, int amount) throws UnknownAccountException {
Account account = DBAccounts.read(connection, accountId);
if (account.getId() == 0) {
throw new UnknownAccountException("Неизвестный счет");
}
int currentAmount = account.getAmount();
account.setAmount(currentAmount + amount);
DBAccounts.write(connection, account);
}
public void transfer(int from, int to, int amount) throws UnknownAccountException, NotEnoughMoneyException {
Account fromAccount = DBAccounts.read(connection, from);
Account toAccount = DBAccounts.read(connection, to);
if (fromAccount.getId() == 0) {
throw new UnknownAccountException("Неизвестный счет отправителя.");
}
if (toAccount.getId() == 0) {
throw new UnknownAccountException("Неизвестный счет получателя.");
}
if (fromAccount.getAmount() < amount) {
throw new NotEnoughMoneyException("На счету отправителя не достаточно средств.");
}
withdraw(from, amount);
deposit(to, amount);
}
}
| true |
1a7c50c5253a512d77ac86b5b6d2f70075b52e49 | Java | XiaoPingZilsp/crms | /src/main/java/com/gdupt/mapper/ServiceUserAllotMapper.java | UTF-8 | 1,136 | 1.539063 | 2 | [] | no_license | package com.gdupt.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gdupt.entity.BasicData;
import com.gdupt.entity.ServiceManagement;
import com.gdupt.entity.ServiceUserAllot;
import com.gdupt.entity.vo.ServiceDeal;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @since 2018-11-22
*/
public interface ServiceUserAllotMapper extends BaseMapper<ServiceUserAllot> {
List<BasicData> findServiceHandle();
boolean addAllot(ServiceUserAllot serviceUserAllot);
boolean addDeal(ServiceUserAllot serviceUserAllot);
List<ServiceDeal> findAll(Page page,@Param("name") String name);
List<ServiceDeal> findFile(Page page,@Param("customer") String customer,@Param("outline") String outline,@Param("serviceType") String serviceType);
List<ServiceDeal> findFeedBack(Page page,@Param("name") String name);
boolean addResult(ServiceUserAllot serviceUserAllot);
List<BasicData> findSatisfaction();
boolean updateStatuss(ServiceManagement serviceManagement);
}
| true |
86d335602121fa2a13611ffe59ab1905047948f4 | Java | yyanan/AndroidDemo | /demoutils/src/main/java/com/example/demoutils/moudle/ZhihuModule.java | UTF-8 | 895 | 2.140625 | 2 | [] | no_license | package com.example.demoutils.moudle;
import com.example.demoutils.base.moudle.HttpFinishCallback;
import com.example.demoutils.beans.zhihu.DailyListBean;
import com.example.demoutils.http.BaseObserver;
import com.example.demoutils.http.ZhuhuManager;
import com.example.demoutils.utils.RxUtils;
public class ZhihuModule {
public interface ZHihuCallBack extends HttpFinishCallback{
void setDailyListBean(DailyListBean data);
}
public void getDailyListBean(final ZHihuCallBack zHihuCallBack){
zHihuCallBack.setShowProgressbar();
ZhuhuManager.getZhuhuServer().getDailyList().compose(RxUtils.<DailyListBean>rxObserableSchedulerHelper()).subscribe(new BaseObserver<DailyListBean>(zHihuCallBack) {
@Override
public void onNext(DailyListBean value) {
zHihuCallBack.setDailyListBean(value);
}
});
}
}
| true |
f8707cd95affe5029dff41aaa997381839175699 | Java | HL7-DaVinci/PDex-Patient-Import-UI | /api/src/main/java/org/hl7/davinci/refimpl/patientui/dto/socket/RequestStatus.java | UTF-8 | 198 | 1.71875 | 2 | [] | no_license | package org.hl7.davinci.refimpl.patientui.dto.socket;
/**
* Represents an HTTP request status.
*
* @author Taras Vuyiv
*/
public enum RequestStatus {
UNDEFINED,
PENDING,
COMPLETED,
FAILED
}
| true |
43ab81328927c3640c5446f678f45e352ecbb30e | Java | nourmat/Advanced_Mobile_Assignments | /Assignment 3/app/src/main/java/com/example/assignment3/model/room/CountryRoomDatabase.java | UTF-8 | 2,358 | 2.75 | 3 | [] | no_license | package com.example.assignment3.model.room;
import android.content.Context;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
@Database(entities = {Country.class}, version = 1, exportSchema = false)
public abstract class CountryRoomDatabase extends RoomDatabase{
public abstract CountryDao countryDao();
private static CountryRoomDatabase INSTANCE;
public static CountryRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (CountryRoomDatabase.class) {
if (INSTANCE == null) { //create database if doesn't exist
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
CountryRoomDatabase.class, "country_database")
// Wipes and rebuilds instead of migrating
// if no Migration object.
// Migration is not part of this practical.
.fallbackToDestructiveMigration()
.addCallback(sRoomDatabaseCallback)
.build();
}
}
}
return INSTANCE;
}
private static RoomDatabase.Callback sRoomDatabaseCallback =
new RoomDatabase.Callback() {
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
new PopulateDbAsync(INSTANCE).execute();
}
};
/**
* Populate the database in the background.
*/
private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {
private final CountryDao mDao;
// Country country = new Country("Cairo", 20, 12, 25, 54, 56);
PopulateDbAsync(CountryRoomDatabase db) { mDao = db.countryDao(); }
@Override
protected Void doInBackground(final Void... params) {
// Start the app with a clean database every time.
// Not needed if you only populate the database
// when it is first created
// mDao.deleteAllData();
// mDao.insertData(country);
return null;
}
}
}
| true |
db8126dbdc5d4075c9e5050f423986e8df5fc19a | Java | zhaoziyun21/platform | /platform-admin/src/main/java/com/platform/service/impl/TblClientLoanRecordServiceImpl.java | UTF-8 | 2,685 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | package com.platform.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.dao.TblClientDao;
import com.platform.entity.TblClient;
import com.platform.entity.TblClientLoanRecord;
import com.platform.dao.TblClientLoanRecordDao;
import com.platform.service.TblClientLoanRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.utils.PageUtilsPlus;
import com.platform.utils.QueryPlus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.Map;
/**
* <p>
* 客户贷款记录 服务实现类
* </p>
*
* @author zhaoziyun
* @since 2019-07-14
*/
@Service
public class TblClientLoanRecordServiceImpl implements TblClientLoanRecordService {
@Autowired
private TblClientLoanRecordDao tblClientLoanRecordDao;
@Autowired
private TblClientDao tblClientDao;
@Override
public PageUtilsPlus queryPage(Map<String, Object> params) {
//排序
params.put("sidx", "createTime");
params.put("asc", false);
Page<TblClientLoanRecord> page = new QueryPlus<TblClientLoanRecord>(params).getPage();
return new PageUtilsPlus(page.setRecords(tblClientLoanRecordDao.selectTblClientLoanRecordPage(page, params)));
}
@Override
public TblClientLoanRecord queryObject(long id) {
return tblClientLoanRecordDao.queryObject(id);
}
@Override
@Transactional
public void saveClientLoanRecord(TblClientLoanRecord tblClientLoanRecord) {
TblClient tblClient = tblClientDao.queryObject(tblClientLoanRecord.getClientId());
tblClient.setClientManagerId(tblClientLoanRecord.getClientManagerId());
tblClient.setUpdateUser(tblClientLoanRecord.getClientManagerName());
tblClient.setFollowTime(new Date());
tblClientDao.update(tblClient);
tblClientLoanRecordDao.save(tblClientLoanRecord);
}
@Override
@Transactional
public void updateClientLoanRecord(TblClientLoanRecord tblClientLoanRecord) {
TblClient tblClient = tblClientDao.queryObject(tblClientLoanRecord.getClientId());
//有客户记录 更新跟单时间
if(tblClient != null){
tblClient.setClientManagerId(tblClientLoanRecord.getClientManagerId());
tblClient.setUpdateUser(tblClientLoanRecord.getClientManagerName());
tblClient.setFollowTime(new Date());
tblClientDao.update(tblClient);
tblClientLoanRecordDao.update(tblClientLoanRecord);
}
}
}
| true |
55e9de4d4f73e0d1b05f8e2ae67057b217003701 | Java | nablarch/nablarch-fw-batch | /src/test/java/nablarch/fw/action/TinyFileBatchAction2.java | UTF-8 | 778 | 2.4375 | 2 | [
"Apache-2.0"
] | permissive | package nablarch.fw.action;
import java.math.BigDecimal;
import nablarch.core.dataformat.DataRecord;
import nablarch.fw.ExecutionContext;
import nablarch.fw.Result;
/**
* データ部の読み込み中に例外をスローするAction。
* @author Masato Inoue
*/
public class TinyFileBatchAction2 extends TinyFileBatchAction {
// エラー値
public static int errorValue = 0;
public Result doData(DataRecord record, ExecutionContext ctx) {
if(errorValue == 0) { throw new IllegalStateException("エラーとする値を設定してください。");};
if(new BigDecimal(errorValue).equals(record.get("amount"))) {
throw new RuntimeException("error");
}
return new Result.Success(record.getString("type"));
}
} | true |
6e0b788e990f3f31ba50de27d0bf45b06620a14a | Java | iceleeyo/concurrency | /java/src/concurrencies/fundamentals/basic/beginner1/HelloActor.java | UTF-8 | 1,449 | 3.21875 | 3 | [] | no_license | package basic.beginner1;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedAbstractActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
/**
* <p>Actor框架入门示例-HelloWorld的角色</p>
*
* @author hanchao 2018/4/16 21:07
**/
public class HelloActor extends UntypedAbstractActor {
//定义日志,很重要
LoggingAdapter log = Logging.getLogger(getContext().getSystem(),this);
/**
* <p>重写接收方法</p>
* @author hanchao 2018/4/16 21:31
**/
@Override
public void onReceive(Object message){
log.info("HelloActor receive message : " + message);
//如果消息类型是HelloMessage,则进行处理
if (message instanceof HelloMessage){
log.info("Hello " + ((HelloMessage) message).getName() + "!");
}
}
/**
* <p>Actor入门示例</p>
* @author hanchao 2018/4/16 21:37
**/
public static void main(String[] args) {
//创建actor系统
ActorSystem system = ActorSystem.create("hello-system");
//定义Actor引用
ActorRef helloActor = system.actorOf(Props.create(HelloActor.class),"hello-actor");
//向HelloActor发送消息
helloActor.tell(new HelloMessage("World"),null);
helloActor.tell(new HelloMessage("Akka Actor"),null);
//终止Actor系统
system.terminate();
}
}
| true |
94d8b6a4ddc666d01600b24aa3d79e707d1e9952 | Java | pranayak/spring-hotel-booking | /hotelbooking/src/test/java/com/project/hotel/test/BookingServiceTest.java | UTF-8 | 1,177 | 2.09375 | 2 | [] | no_license | /**
*
*/
package com.project.hotel.test;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.project.hotel.ApplicationConfig;
import com.project.hotel.exception.DataNotFoundException;
import com.project.hotel.model.dto.CityVO;
import com.project.hotel.service.IBookingService;
/**
* @author prakashnayak
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfig.class,loader = AnnotationConfigContextLoader.class)
public class BookingServiceTest {
@Autowired
private IBookingService bookingService;
@Test
public void testFindAllCities()
{
List<CityVO> cities = null;
try {
cities = bookingService.findAllCities();
} catch (DataNotFoundException e) {
fail("Fetching All Cities failed");
}
assertTrue("Cities fetched successfully", cities.size()>0);
}
}
| true |
6521f55bfc8716c60681b200e5713c4972749f29 | Java | gityalvarez/tecnobedelias-backend | /tecnobedelias/src/main/java/com/proyecto/tecnobedelias/service/UsuarioService.java | UTF-8 | 1,355 | 1.828125 | 2 | [] | no_license | package com.proyecto.tecnobedelias.service;
import java.util.List;
import java.util.Optional;
import com.proyecto.tecnobedelias.persistence.model.Actividad;
import com.proyecto.tecnobedelias.persistence.model.Rol;
import com.proyecto.tecnobedelias.persistence.model.Usuario;
public interface UsuarioService {
//Usuario loadUsuarioByUsername(String username);
public List<Usuario> listarUsuarios();
public boolean existeUsuario(String username);
public boolean existeCedula(String cedula);
public boolean existeEmail(String username);
public void altaUsuario(Usuario usuario);
public void altaBienUsuario(Usuario usuario);
public List<Rol> listarRoles();
public void asignarRolUsuario(String rolName, Usuario usuario);
public List<Usuario> filtrarEstudiantes();
public void bajaUsuario(Usuario usuario);
public Optional<Usuario> findUsuarioByResetToken(String resetToken);
public Optional<Usuario> findUsuarioByUsername(String username);
public Optional<Usuario> obtenerUsuarioCedula(String cedula);
public Optional<Usuario> obtenerUsuarioEmail(String email);
public Optional<Usuario> obtenerUsuario(long usuarioId);
public void inicializar();
public void modificacionUsuario(Usuario usuario);
public List<Actividad> escolaridad(Usuario usuario);
}
| true |
f66de21025ee93acf1961989c322ea158aeed8a7 | Java | saipraveen-a/Spring-Security-Java-Demo | /src/main/java/com/training/WebSecurityConfig.java | UTF-8 | 1,226 | 2.125 | 2 | [] | no_license | package com.training;
import org.springframework.context.annotation.*;
//import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.*;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableWebSecurity
@ComponentScan("com.training")
public class WebSecurityConfig implements WebMvcConfigurer {
@Bean
public UserDetailsService userDetailsService() throws Exception {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withDefaultPasswordEncoder().username("admin").
password("1234").roles("USER").build());
return manager;
}
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/")
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
| true |
bd644a5810e0e31db0e333bb572bab079c2ea246 | Java | EliteTC/epractices | /practice6.3/src/main/java/main/Main.java | UTF-8 | 1,042 | 2.890625 | 3 | [] | no_license | package main;
import entity.UnaryOperation;
import reflect_util.ReflectionUtil;
import java.lang.reflect.InvocationTargetException;
public class Main {
public static void main(String [] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
UnaryOperation reflectionObject = ReflectionUtil.createReflection();
System.out.println(reflectionObject.toString());
ReflectionUtil.dynamicInvokation(reflectionObject);
System.out.println(reflectionObject.toString());
System.out.println(ReflectionUtil.getObjectInfo(reflectionObject));
UnaryOperation reflectionObjectWithParameters = ReflectionUtil.createReflection(3.4);
System.out.println(reflectionObjectWithParameters.toString());
ReflectionUtil.dynamicInvokation(reflectionObjectWithParameters);
System.out.println(reflectionObjectWithParameters.toString());
System.out.println(ReflectionUtil.getObjectInfo(reflectionObjectWithParameters));
}
}
| true |
54cbf04e74137947514bf937c13d4317430a1f4b | Java | ryanleyva/OOD-Patterns | /SEAssignment/source/FlowerBed.java | UTF-8 | 2,927 | 3 | 3 | [] | no_license | import java.util.ArrayList;
import javafx.geometry.Point2D;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import java.io.Serializable;
public class FlowerBed implements GardenEntity {
Point2D point;
Color color;
boolean movable;
Rectangle rect;
final double width;
final double height;
GardenEntity parent;
public ArrayList<GardenEntity> children;
public FlowerBed(Point2D point, Color color, double width, double height)
{
this.width = width;
this.height = height;
this.point = point;
this.color = color;
children = new ArrayList<GardenEntity>();
initFlowerBed();
}
public void initFlowerBed()
{
rect = new Rectangle(point.getX(),point.getY(),height,width);
rect.setFill(color);
rect.toBack();
}
@Override
public void move(double dx, double dy) {
rect.setX(rect.getX() + dx);
rect.setY(rect.getY() + dy);
System.out.println("moving flowerbed");
for (GardenEntity child : children)
{
child.move(dx, dy);
}
}
@Override
public Shape getShape() {
return rect;
}
@Override
public boolean clicked(Point2D clickpoint) {
double a = rect.getX();
double b = rect.getY();
if ((clickpoint.getX() >= a && clickpoint.getX() <= (a + width))
&& (clickpoint.getY() >= b && clickpoint.getY() <= (b + height)))
return true;
else
return false;
}
@Override
public GardenEntity deepCopy() {
GardenEntity tmp = new FlowerBed(new Point2D(rect.getX(), rect.getY()), color, width, height);
return tmp;
}
@Override
public GardenEntity getClickedEntity(Point2D clickPoint) {
if (clicked(clickPoint))
{
System.out.println("parent = flowerbed");
return this;
}
else
{
return null;
}
/*
for (GardenEntity child : children)
{
GardenEntity g = child.getClickedEntity(clickPoint);
if (g != null)
{
return g;
}
}
return this;
}
else
{
return null;
}*/
}
@Override
public void add(GardenEntity g) {
if (g != this)
children.add(g);
}
@Override
public void remove(GardenEntity g) {
System.out.println("remove(gardenItem)");
children.remove(g);
}
@Override
public GardenEntity getNode(Point2D clickPoint) {
GardenEntity gardenItem = null;
for (GardenEntity g : children)
{
if (g.clicked(clickPoint))
{
gardenItem = g.getNode(clickPoint);
if (gardenItem != null)
{
return gardenItem;
}
}
}
return this;
}
@Override
public void setParent(GardenEntity node) {
if (this != node)
this.parent = node;
}
@Override
public GardenEntity getParent() {
return parent;
}
@Override
public GardenEntitySerializable serialize() {
return new FlowerBedSerializable (point.getX(), point.getY(), height, width, color.toString(), children);
}
}
| true |
d6f0f5b9af24ed2f42033f5f2254679566bd4db0 | Java | igallego8/android_imtio | /app/src/main/java/com/agora/app/AppContext.java | UTF-8 | 3,585 | 1.875 | 2 | [] | no_license | package com.agora.app;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.multidex.MultiDex;
import com.agora.R;
import com.agora.db.FactoryDBHelper;
import com.agora.entity.Bid;
import com.agora.entity.Need;
import com.agora.entity.User;
import com.agora.util.listadapter.Item;
import com.facebook.drawee.backends.pipeline.Fresco;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ivan on 25/09/15.
*/
public class AppContext extends Application {
private static Context mContext;
private List<Bitmap> attachedImages= new ArrayList<>();
private List<Bitmap> thumbnailImages= new ArrayList<>();
private List<String> imageURIs= new ArrayList<>();
private boolean attachedImagesConfirmed=false;
private static List<Need> needs= new ArrayList<>();
private List<Bid> bids= new ArrayList<>();
public static FactoryDBHelper dbHelper;
public static final Item[] BID_ITEM_OPTIONS = new Item[2];
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public static Context getmContext() {
return mContext;
}
public static void setmContext(Context mContext) {
AppContext.mContext = mContext;
}
public List<Bitmap> getAttachedImages() {
return attachedImages;
}
public void setAttachedImages(List<Bitmap> attachedImages) {
this.attachedImages = attachedImages;
}
public List<Bitmap> getThumbnailImages() {
return thumbnailImages;
}
public void setThumbnailImages(List<Bitmap> thumbnailImages) {
this.thumbnailImages = thumbnailImages;
}
public List<String> getImageURIs() {
return imageURIs;
}
public void setImageURIs(List<String> imageURIs) {
this.imageURIs = imageURIs;
}
public boolean isAttachedImagesConfirmed() {
return attachedImagesConfirmed;
}
public void setAttachedImagesConfirmed(boolean attachedImagesConfirmed) {
this.attachedImagesConfirmed = attachedImagesConfirmed;
}
public static List<Need> getNeeds() {
return needs;
}
public void setNeeds(List<Need> needs) {
this.needs = needs;
}
public List<Bid> getBids() {
return bids;
}
public void setBids(List<Bid> bids) {
this.bids = bids;
}
public FactoryDBHelper getDbHelper() {
return dbHelper;
}
public void setDbHelper(FactoryDBHelper dbHelper) {
this.dbHelper = dbHelper;
}
@Override
public void onCreate() {
super.onCreate();
mContext = this;
Fresco.initialize(mContext);
dbHelper= new FactoryDBHelper( mContext,AppConfig.DATABASE_NAME,null,AppConfig.DATABASE_VERSION);
BID_ITEM_OPTIONS[0]= new Item(AppContext.mContext.getResources().getString(R.string.inappropriate_content),
AppContext.mContext.getResources().getString(R.string.report_inappropriate_content),R.drawable.ic_control_point_black_24dp);
BID_ITEM_OPTIONS[1]= new Item(AppContext.mContext.getResources().getString(R.string.hide_bid),
AppContext.mContext.getResources().getString(R.string.hide_bid_from_list),R.drawable.ic_control_point_black_24dp);
}
public static Context getContext(){
return mContext;
}
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
| true |
5a2bd67f6ec4f73d7e082759b4484ac6f70e13bb | Java | kimdaehyeok/SpringBoot | /SpringBootBatch/src/main/java/com/example/demo/reader/MybatisPagingItemReaderConfiguration.java | UTF-8 | 2,947 | 2.15625 | 2 | [] | no_license | package com.example.demo.reader;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.batch.MyBatisPagingItemReader;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
@Configuration
public class MybatisPagingItemReaderConfiguration
{
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private DataSource dataSource;
private final int chunk_size = 10;
public SqlSessionFactory getSqlSessionFactory() throws Exception
{
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/example/demo/xml/*.xml"));
return (SqlSessionFactory) sqlSessionFactory.getObject();
}
@Bean
public Job mybatisPagingItemReaderJob() throws Exception
{
return jobBuilderFactory.get("mybatisPagingItemReader")
.start(mybatisPagingItemReaderStep())
.build();
}
@Bean
public Step mybatisPagingItemReaderStep() throws Exception
{
return stepBuilderFactory.get("mybatisPagingItemReaderStep")
.<PayForMybatis, PayForMybatis>chunk(chunk_size) // <InputType, OutputType>
.reader(mybatisPagingItemReader())
.writer(myBatisPagingItemWriter())
.build();
}
@Bean
// public ItemReader<InputType>
public MyBatisPagingItemReader<PayForMybatis> mybatisPagingItemReader() throws Exception
{
Map<String, Object> parameterValues = new HashMap();
parameterValues.put("amount", "2000");
MyBatisPagingItemReader<PayForMybatis> MyBatisPagingItemReader = new MyBatisPagingItemReader<PayForMybatis>();
MyBatisPagingItemReader.setSqlSessionFactory(getSqlSessionFactory());
MyBatisPagingItemReader.setPageSize(chunk_size);
MyBatisPagingItemReader.setParameterValues(parameterValues);
MyBatisPagingItemReader.setQueryId("selectAmount");
return MyBatisPagingItemReader;
}
@Bean
//public ItemWriter<OutputType>
public ItemWriter<PayForMybatis> myBatisPagingItemWriter()
{
return list -> {
for (PayForMybatis pay : list) {
System.out.println("Mybatis Current Pay = " + pay.getTxName() + " / " + pay.getAmount() + " / " + pay.getId() + " / " + pay.getTxDateTime());
}
};
}
}
| true |
9315fc56faefc910f05a8c768be27fcbcc6776c3 | Java | oleksandrm-in6k/CarShop | /out/artifacts/CarShop_war_exploded/WEB-INF/src/main/java/game2048/Run.java | UTF-8 | 503 | 1.984375 | 2 | [] | no_license | package game2048;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by anri on 18.10.15.
*/
public class Run {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("xmlConfig.xml");
GameController gameController = (GameController)applicationContext.getBean("gameController");
gameController.startGame();
}
}
| true |
823ef50a9048bf29e381e896a7605ceac991d439 | Java | SiyangZhang/SimpleCompiler | /src/MyQueue.java | UTF-8 | 215 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | import java.util.LinkedList;
public class MyQueue<T> extends LinkedList<T> {
public T pop(){
return super.removeFirst();
}
public void push(T element){
super.addLast(element);
}
}
| true |
f104d66b1844e57c0adde16900a02fcce010ea4a | Java | avinashporwal2607/Manthan-ELF-16th-October-Avinash-Porwal | /WORKSPACE/Student/src/com/testyantra/student/qspider/Selenium.java | UTF-8 | 154 | 2.015625 | 2 | [] | no_license | package com.testyantra.student.qspider;
public class Selenium {
public void teachSelenium() {
System.out.println("I am teachSelenium method()");
}
}
| true |
6b363ffb05af987744e760e5f3b2763c0e96f41c | Java | lightning95/lesson6 | /app/src/main/java/ru/ifmo/md/lesson6/MyContentObserver.java | UTF-8 | 724 | 2.25 | 2 | [] | no_license | package ru.ifmo.md.lesson6;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
/**
* Created by lightning95 on 12/20/14.
*/
public class MyContentObserver extends ContentObserver {
Handler handler;
Callbacks callbacks;
public interface Callbacks {
public void onChannelsObserverFired();
}
public MyContentObserver(Callbacks callback) {
super(null);
handler = new Handler();
callbacks = callback;
}
@Override
public void onChange(boolean selfChange) {
callbacks.onChannelsObserverFired();
}
@Override
public void onChange(boolean selfChange, Uri uri) {
onChange(selfChange);
}
}
| true |
53a99357d31d87000cb47255554190e801058aa2 | Java | sumaq/cfdi-files-ws | /src/com/aje/download/ws/FileTextImpl.java | UTF-8 | 501 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | package com.aje.download.ws;
import javax.jws.WebService;
import javax.xml.ws.soap.MTOM;
//Service Implementation Bean
@MTOM
@WebService(endpointInterface = "com.aje.download.ws.FileText")
public class FileTextImpl implements FileText {
@Override
public int createFileText(String[] query) {
String _query = query[0];
int result = 0;
ArchivoPlano ap = new ArchivoPlano(_query);
result = ap.generateFile();
//System.out.println("Ejecutando: " + _query);
return result;
}
}
| true |
a6b18145050d495fc709bbda42235873b9923313 | Java | Geka000/sample-webview | /app/src/main/java/com/snc/zero/permission/RPermission.java | UTF-8 | 1,868 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package com.snc.zero.permission;
import android.content.Context;
import com.gun0912.tedpermission.TedPermission;
import java.util.List;
import androidx.annotation.NonNull;
public class RPermission {
public static RPermission with(Context context) {
return new RPermission(context);
}
private final Context context;
private String[] permissions;
private RPermissionListener listener;
public RPermission(Context context) {
this.context = context;
}
public RPermission setPermissionListener(RPermissionListener listener) {
this.listener = listener;
return this;
}
public RPermission setPermissions(List<String> permissions) {
this.permissions = permissions.toArray(new String[] {});
return this;
}
public RPermission setPermissions(String[] permissions) {
this.permissions = permissions;
return this;
}
public void check() {
TedPermission.with(context)
.setPermissionListener(new com.gun0912.tedpermission.PermissionListener() {
@Override
public void onPermissionGranted() {
if (null != listener) {
listener.onPermissionGranted();
}
}
@Override
public void onPermissionDenied(List<String> deniedPermissions) {
if (null != listener) {
listener.onPermissionDenied(deniedPermissions);
}
}
})
.setPermissions(permissions)
.check();
}
public static boolean isGranted(Context context, @NonNull String... permissions) {
return TedPermission.isGranted(context, permissions);
}
}
| true |
08930e89606bf115b62d72e3b6bfb0f95a91ee26 | Java | ye13jian/fm-templates | /fm-templates/web-spring-security-hibernate-hbm-0-0-2/src/main/java/com/fm/template/manager/impl/UserManagerImpl.java | UTF-8 | 2,148 | 2.46875 | 2 | [] | no_license | package com.fm.template.manager.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.fm.template.dao.UserDAO;
import com.fm.template.exception.UserAlreadyExistingException;
import com.fm.template.exception.UserNotFoundException;
import com.fm.template.manager.UserManager;
import com.fm.template.model.User;
public class UserManagerImpl implements UserManager, UserDetailsService {
private Logger log = Logger.getLogger(UserManagerImpl.class);
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
User user = userDAO.getUserByUsername(username);
if (user != null) {
return user;
} else {
throw new UsernameNotFoundException("User with username [" + username + "] not found.");
}
}
@Override
public List<User> getUsers() {
return userDAO.getUsers();
}
@Override
public User getUserById(Integer id) throws UserNotFoundException {
User user = userDAO.getUserById(id);
if (user != null) {
return user;
} else {
throw new UserNotFoundException("User with user id [" + id + "] not found");
}
}
@Override
public Integer saveUser(User user) throws UserAlreadyExistingException {
try {
Integer id = userDAO.saveUser(user);
return id;
} catch (DataAccessException e) {
log.warn("User duplicated. Username [" + user.getUsername() + "] Email [" + user.getEmail() + "]");
throw new UserAlreadyExistingException(e);
}
}
@Override
public void updateUser(User user) throws UserAlreadyExistingException {
try {
userDAO.updateUser(user);
} catch (DataAccessException e) {
log.warn("User duplicated. Username [" + user.getUsername() + "] Email [" + user.getEmail() + "]");
throw new UserAlreadyExistingException(e);
}
}
} | true |
c455e3c5a3c50c8b15579417ef52c6acc54b0fb2 | Java | GauravT-optimus/AutoEase-Automation-Framework | /src/test/java/com/autoease/framework/WebDriverGenerator.java | UTF-8 | 8,345 | 2.328125 | 2 | [] | no_license | package com.autoease.framework;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.autoease.framework.SeleniumCore;
import com.autoease.framework.utilities.HostUtils;
import cucumber.api.Scenario;
import cucumber.api.java.After;
/**
* WebDriverGenerator class. It is a core of framework, implements a private constructor which provides current driver object
* to each step definition class, always make an instance of this class whenever you create a customized step definition
*
*
*
*
* @author Gaurav Tiwari
*
* @todo It is not tested yet
*
* Copyright [2015] [Gaurav Tiwari]
*
*
*/
public class WebDriverGenerator {
static WebDriver driver =null;
static WebDriverWait wait=null;
public static Properties OR=null;
public static Properties CONFIG=null;
Logger APP_LOGS=Logger.getLogger("devpinoyLogger");
public WebDriverGenerator() {
//This constructor does not implement anything as of now
}
public static WebDriverWait getWaitObject(){
wait=new WebDriverWait(driver,30);
return wait;
}
/**
* returns a new driver object, if driver is already initialized
* then returns the existing object for using this method make an object of current class and call.
*
*
*/
public static WebDriver getWebDriver(){
if (driver==null){
//Initialize the OR
OR=new Properties();
//Initialize the Config
CONFIG=new Properties();
try{
FileInputStream fs=new FileInputStream(System.getProperty("user.dir")+"\\test-configs\\or.properties");
//System.out.println(System.getProperty("user.dir"));
OR.load(fs);
fs=new FileInputStream(System.getProperty("user.dir")+"\\test-configs\\config.properties");
CONFIG.load(fs);
}
catch(Exception e){
System.out.println("Error in initiatilizing property file");
}
//logger.info("browser is :"+browsername+",proxy is :"+proxy);
//logger.info("browser is :"+browsername+",proxy is :"+proxy);
DesiredCapabilities capability=new DesiredCapabilities();
SeleniumCore.browserCommonSettings(capability);
//code for selecting the preferred browser and launching it with preferred capabilities
if(CONFIG.getProperty("browserType").equalsIgnoreCase("Mozilla")){
try{
try {
SeleniumCore.browserFirefoxSettings(capability);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver = new FirefoxDriver(capability);
}catch(WebDriverException e){
if(e.getMessage().contains("Cannot find firefox binary in PATH")){
System.out.println("Current execution host:"+HostUtils.getFQDN()+" not installed Firefox Browser ,please install it firstly!");
}else{
System.out.println("Firefox Driver met unexpected error:"+e);
}
System.exit(1);
}
}
else if(CONFIG.getProperty("browserType").equalsIgnoreCase("Chrome")){
SeleniumCore.browserChromeSettings(capability);
try{
driver=new ChromeDriver(capability);
}catch(WebDriverException exception){
if(exception.getMessage().contains("unknown error: cannot find Chrome binary")){
System.out.println("Current execution host:"+HostUtils.getFQDN()+" not installed Chrome Browser ,please install it firstly!");
}else{
System.out.println("Chrome Driver met unexpected error:"+exception);
}
System.exit(1);
}
}
else if(CONFIG.getProperty("browserType").equalsIgnoreCase("IE")){
SeleniumCore.browserIESettings(capability);
driver=new InternetExplorerDriver(capability);
}
else if(CONFIG.getProperty("browserType").trim().equalsIgnoreCase("safari")){
SeleniumCore.browserSafariSettings(capability);
try{
driver=new SafariDriver(capability);
}catch(IllegalStateException exception){
if(exception.getMessage().contains("The expected Safari data directory does not exist")){
System.out
.println("Current execution host:"+HostUtils.getFQDN()+" not installed Safari Browser ,please install it firstly!");
}else{
System.out
.println("Safari Driver met unexpected error:"+exception);
}
System.exit(1);
}catch(WebDriverException exception){
System.out
.println("Current execution host:"+HostUtils.getFQDN()+" not installed safari Browser ,please install it firstly!");
System.exit(1);
}
}
}
//set the implicit wait, visit the selenium manager method implementation
SeleniumCore.seleniumManager(driver);
return driver;
}
/**
* @Title: catchAnyExceptions
* @Description: TODO
* @author GAURAV TIWARI [gauravtiwari91@yahoo.com]
* @param @param result
* @param @param context
* @param @throws Exception
* @return void return type
* @throws
*/
/*
@AfterMethod(description="this method will capture any Exception when the testing is running")
public void catchAnyExceptions(ITestResult result, ITestContext context)throws Exception {
final Throwable t = result.getThrowable();
if(t instanceof IOException){
}
}
/**
* returns a new driver object, if driver is already initialized
* then returns the existing object for using this method make an object of current class and call.
*
* @param WebDriver The driver object to be used
* @param By selector to find the element
* @param String Value attribute of the option tag of drop down
*
*/
public By getIdentifierAt(String propertyValue){
By objectValue = null;
String lowercasepropertyValue =propertyValue.toLowerCase();
System.out.println(propertyValue);
try{
if(lowercasepropertyValue.endsWith(GlobalConstants.CSS)){
objectValue=By.cssSelector(OR.getProperty(propertyValue));
}
else if(lowercasepropertyValue.endsWith(GlobalConstants.ID)){
objectValue=By.id(OR.getProperty(propertyValue));
}
else if(lowercasepropertyValue.endsWith(GlobalConstants.NAME)){
objectValue=By.name(OR.getProperty(propertyValue));
}
else if(lowercasepropertyValue.endsWith(GlobalConstants.TAG_NAME)){
objectValue=By.tagName(OR.getProperty(propertyValue));
}
else if(lowercasepropertyValue.endsWith(GlobalConstants.CLASS_NAME)){
objectValue=By.className(OR.getProperty(propertyValue));
}
else if(lowercasepropertyValue.endsWith(GlobalConstants.LINK_TEXT)){
objectValue=By.linkText(OR.getProperty(propertyValue));
}
else if(lowercasepropertyValue.endsWith(GlobalConstants.PARTIAL_LINK_TEXT)){
objectValue=By.partialLinkText(OR.getProperty(propertyValue));
}
else if(lowercasepropertyValue.endsWith(GlobalConstants.XPATH)){
objectValue=By.xpath(OR.getProperty(propertyValue));
}
else
{
System.out.println("Object identifier is not named properly, Please append one of the following text for each identifer in OR properties file accordingly");
System.out.println("---css, id, name, tagname, classname, linktxt, prtlinktxt or xpath---");
}
}
catch(Exception e){
System.out.println("error in getting the object"+e.getMessage());
}
return objectValue;
}
}
| true |
0376530f35ad78ca8b0ad1b38cdd8623c4a06246 | Java | KindRoach/LearnSpring | /src/main/java/data/datareader/DevDataBaseReader.java | UTF-8 | 171 | 2.109375 | 2 | [] | no_license | package data.datareader;
public class DevDataBaseReader implements DataReader {
public void readData() {
System.out.println("Read dev data base...");
}
}
| true |
55b112f0ac9e0dd7a60329a88dc281915ea91d53 | Java | kitiya/beaver | /src/main/java/com/kitiya/beaver/business/service/ActivityDomainService.java | UTF-8 | 2,616 | 2.453125 | 2 | [] | no_license | package com.kitiya.beaver.business.service;
import com.kitiya.beaver.business.domain.ActivityDomain;
import com.kitiya.beaver.data.entity.Activity;
import com.kitiya.beaver.data.repository.ActivityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
@Service
public class ActivityDomainService {
private ActivityRepository activityRepository;
@Autowired
public ActivityDomainService(ActivityRepository activityRepository) {
this.activityRepository = activityRepository;
}
public List<ActivityDomain> getAllActivitiesWithProviders() {
Iterable<Activity> activities = this.activityRepository.findAll();
List<ActivityDomain> activityDomains = new ArrayList<>();
activities.forEach(activity ->
activityDomains.add(getActivityDomain(activity))
);
return activityDomains;
}
public ActivityDomain getById(Long id) {
Activity activity = this.activityRepository.findById(id)
.orElseThrow(() -> new RuntimeException("ID " + id + " Not found"));
return getActivityDomain(activity);
}
private ActivityDomain getActivityDomain(Activity activity) {
ActivityDomain activityDomain = new ActivityDomain();
activityDomain.setActivityId(activity.getId());
activityDomain.setName(activity.getName());
activityDomain.setType(activity.getType());
activityDomain.setDescription(activity.getDescription());
String ageRange = String.join(
" - ",
activity.getFromAge().toString(),
activity.getToAge().toString());
activityDomain.setAgeRange(ageRange);
activityDomain.setCost(activity.getCost());
activityDomain.setImageUrls(activity.getImageUrls());
activityDomain.setProviderId(activity.getProvider().getId());
activityDomain.setProviderName(activity.getProvider().getName());
activityDomain.setLocation(activity.getProvider().getStreetAddress());
activityDomain.setStartDate(activity.getSchedule().getStartDate());
activityDomain.setEndDate(activity.getSchedule().getEndDate());
activityDomain.setStartTime(activity.getSchedule().getStartTime());
activityDomain.setEndTime(activity.getSchedule().getEndTime());
activityDomain.setDayOfWeek(activity.getSchedule().getDayOfWeek());
return activityDomain;
}
}
| true |
9a0e7bc0646b278cd47211bc874c06f25ac6981a | Java | eliaidi/doraemon | /src/main/java/com/alanma/doraemon/utils/http/HttpClientTest.java | UTF-8 | 2,249 | 2.59375 | 3 | [] | no_license | package com.alanma.doraemon.utils.http;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
public class HttpClientTest {
private static HttpContext localContext = new BasicHttpContext();
private static HttpClientContext context = HttpClientContext.adapt(localContext);
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 模拟表单
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "**"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
HttpPost httpPost = new HttpPost("http://localhost:8080/spiderweb/RirectServlet");
httpPost.setEntity(entity);
// 将HttpClientContext传入execute()中
CloseableHttpResponse response = httpClient.execute(httpPost, context);
try {
HttpEntity responseEntity = response.getEntity();
System.out.println(EntityUtils.toString(responseEntity));
} finally {
response.close();
}
} finally {
httpClient.close();
}
CloseableHttpClient httpClient2 = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet("http://localhost:8080/spiderweb/RirectServlet");
// 设置相同的HttpClientContext
CloseableHttpResponse response = httpClient2.execute(httpGet, context);
try {
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
} finally {
response.close();
}
} finally {
httpClient2.close();
}
}
}
| true |
c38c4bcd9b80f82b28b59c470ee552ca1cb0d1c0 | Java | Loc-1/School-Assignments | /University/CPSC 331/SHufflepuff.java | UTF-8 | 1,456 | 3.640625 | 4 | [] | no_license | package cpsc331.A1;
//Lachlan Moore - 30030228
//Nathanael Huh - 10128366
//Junehyuk Kim - 30020861
public class SHufflepuff {
public static void main(String args[]) {
String input = args[0];
if (input.isEmpty()) {
System.out.println("Silly muggle! One integer input is required.");
}
try {
int result = Integer.parseInt(input);
if (result < 0) {
System.out.println("Silly muggle! The integer input cannot be negative.");
} else {
System.out.println(sHuff(result));
}
} catch (NumberFormatException e) {
System.out.println("Silly muggle! One integer input is required.");
}
}
private static int sHuff (int n) {
// Assertion: A non-negative integer n has been given as input.
if (n == 0) {
return 10;
} else if (n == 1) {
return 9;
} else if (n == 2) {
return 8;
} else if (n == 3) {
return 7;
} else if (n >= 4) {
return 4 * sHuff(n - 1) - 6 * sHuff(n - 2) + 4 * sHuff(n-3) - sHuff(n-4);
// Assertion:
// 1. A non-negative integer n has been given as input.
// 2. The nth Hufflepuff number Hn has been returned as output.
} else {
throw new IllegalArgumentException();
}
}
}
| true |
891f6f8406ba0aa20fa8dbbbb0bb4525cd056a26 | Java | chenxyzy/cms | /src/com/lerx/sys/util/PropertiesUtil.java | UTF-8 | 1,824 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | package com.lerx.sys.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import com.lerx.sys.util.vo.PropertiesFileInf;
public class PropertiesUtil {
private static Properties props = new Properties();
public static void updateProperties(PropertiesFileInf pf,String keyname, String keyvalue) throws FileNotFoundException, IOException {
String profile;
// String filepath=System.getProperty("user.dir");
// String profilepath = "mail.properties";
switch (pf.getFile()) {
case 1:
profile="resourcesMessage_"+pf.getLocal();
break;
case 2:
profile="resourcesStyle_"+pf.getLocal();
break;
case 3:
profile="resourcesUploadFileSize_"+pf.getLocal();
break;
case 4:
profile="resourcesHostInf_"+pf.getLocal();
break;
default:
profile="resourcesApplication_"+pf.getLocal();
break;
}
profile+=".properties";
profile=pf.getPath()+File.separator+"WEB-INF"+File.separator+"classes"+File.separator+profile;
props.load(new FileInputStream(profile));
// System.out.println("profile:"+profile);
try {
props.load(new FileInputStream(profile));
// 调用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。
// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
OutputStream fos = new FileOutputStream(profile);
props.setProperty(keyname, keyvalue);
// 以适合使用 load 方法加载到 Properties 表中的格式,
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
props.store(fos, null);
} catch (IOException e) {
// System.err.println("属性文件更新错误");
}
}
}
| true |
daf1b2cb8d23f6dc2b67fe90c61f6d1bbbf23dd7 | Java | jhhuangjh/dubbo-demo | /dubbo-provider/src/main/java/org/jh/service/impl/Provider.java | UTF-8 | 611 | 2.09375 | 2 | [] | no_license | package org.jh.service.impl;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
/**
* @author hjh
* @version 1.0
* @date 2020/8/24 22:05
* 启动Spring容器,自动发布服务
*/
public class Provider {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[]{"classpath:dubbo-provider.xml"});
context.start();
System.out.println("Provider started");
System.in.read(); // press any key to exit
}
}
| true |
67fa2790ceef67ef750f0171b2d52c904e7ca109 | Java | oscarhsanchez/app-operaciones-android | /app/src/main/java/esocial/vallasmobile/ws/WsRequest.java | UTF-8 | 10,689 | 2.171875 | 2 | [] | no_license | package esocial.vallasmobile.ws;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import esocial.vallasmobile.app.VallasApplication;
import esocial.vallasmobile.utils.Constants;
import esocial.vallasmobile.utils.Utils;
import esocial.vallasmobile.ws.request.RenewTokenRequest;
import esocial.vallasmobile.ws.response.RenewTokenResponse;
public class WsRequest {
public static final int REQUEST_TYPE_POST = 1;
public static final int REQUEST_TYPE_GET = 2;
public static final int REQUEST_TYPE_PUT = 3;
public static final int REQUEST_TYPE_PATCH = 4;
public static final int REQUEST_TYPE_DELETE = 5;
private static Boolean goToRenew = false;
protected VallasApplication context;
public WsRequest(VallasApplication context) {
this.context = context;
}
/**
* Constructs a WsResponse object and calls the webservice to know the string response that will be
* deserialized later.
*
* @param accept
* @param contentType
* @param requestType
* @param jsonAction
* @param parameters
* @param addSessionToken
* @param addSessionCookie
* @param headers
* @return
* @throws Exception
*/
public WsResponse execute(String accept, String contentType, Integer requestType, String jsonAction, List<NameValuePair> parameters, Boolean addSessionToken, Boolean addSessionCookie, List<NameValuePair> headers) throws Exception {
if (!Utils.checkInternetConnection(context)) {
Log.i("WsRequest", jsonAction + " - Sin conexion");
return null;
}
Log.i("WsRequest", jsonAction);
URL url;
HttpURLConnection conn = null;
String param = "";
for (int i = 0; i < parameters.size(); i++) {
NameValuePair pair = parameters.get(i);
param += TextUtils.isEmpty(param) ? "" : "&";
param += pair.getName() + "=" + pair.getValue();
}
byte[] postData = param.getBytes(Charset.forName("UTF-8"));
int postDataLength = postData.length;
switch (requestType) {
case REQUEST_TYPE_POST:
url = new URL(Constants.MAIN + jsonAction);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
break;
case REQUEST_TYPE_GET:
if (!TextUtils.isEmpty(param)) param = "?" + param;
url = new URL(Constants.MAIN + jsonAction + param);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", contentType);
break;
case REQUEST_TYPE_PUT:
url = new URL(Constants.MAIN + jsonAction);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
break;
case REQUEST_TYPE_PATCH:
url = new URL(Constants.MAIN + jsonAction);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PATCH");
break;
case REQUEST_TYPE_DELETE:
url = new URL(Constants.MAIN + jsonAction);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
break;
}
//Add headers
if (headers != null && headers.size() > 0) {
for(NameValuePair pair : headers){
conn.setRequestProperty(pair.getName(), pair.getValue());
}
}
if (!TextUtils.isEmpty(accept))
conn.setRequestProperty("Accept", accept);
if (requestType != REQUEST_TYPE_GET) {
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
DataOutputStream wr = null;
try {
wr = new DataOutputStream(conn.getOutputStream());
wr.write(postData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (wr != null)
try {
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// read the response
InputStream in;
int statusCode = conn.getResponseCode();
if(statusCode == 500){
in = conn.getErrorStream();
}else{
in = new BufferedInputStream(conn.getInputStream());
}
String strResponse = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
Log.v("WsRequest response", strResponse);
Log.v("WsRequest", "--------------------------------------------------------------------------------");
Log.v("WsRequest", "--------------------------------------------------------------------------------");
WsResponse wsResponse = new WsResponse(statusCode, strResponse);
Log.i("WsRequest", jsonAction + " - Terminado");
conn.disconnect();
return wsResponse;
}
/**
* Executes a webservice action, base method for all the others
* @param accion
* @param params
* @param clase
* @param method
* @param headers
* @param gson
* @return
*/
public <T> T execute(String accion, List<NameValuePair> params, Class<T> clase, int method, List<NameValuePair> headers, Gson gson) {
T response = null;
try {
WsResponse wsResponse = execute("application/json", "application/x-www-form-urlencoded",
method, accion, params, true, false, headers);
if (wsResponse != null) {
Log.d(clase.getName(), wsResponse.getResult().toString());
response = gson.fromJson(wsResponse.getResult(), clase);
if (response instanceof WsResponse) {
((WsResponse) response).setStatusCode(wsResponse.getStatusCode());
}
//Si invalid Token, hacemos refresh y volvemos a ejecutar la peticion
if (response != null && ((WsResponse)response).error!=null && ((WsResponse)response).error.code==3000) {
RenewTokenRequest request = new RenewTokenRequest(context);
RenewTokenResponse refreshResponse = request.execute(RenewTokenResponse.class);
if(refreshResponse!=null){
if(!refreshResponse.failed()){
//Guardamos la session
context.setSession(refreshResponse.Session);
wsResponse = execute("application/json", "application/x-www-form-urlencoded",
method, accion, params, true, false, getDefaultHeaders());
if (wsResponse != null) {
Log.d(clase.getName(), wsResponse.getResult().toString());
response = gson.fromJson(wsResponse.getResult(), clase);
}
if (response instanceof WsResponse) {
((WsResponse) response).setStatusCode(wsResponse.getStatusCode());
}
return response;
}
}else{
return response;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return response;
}
/**
* Executes a WebService action with default deserializer and custom headers
* @param accion
* @param params
* @param clase
* @param method
* @param headers
* @return
*/
public <T> T execute(String accion, List<NameValuePair> params, Class<T> clase, int method, List<NameValuePair> headers) {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
return execute(accion, params, clase, method, headers, gson);
}
public <T> T executeGet(String accion, List<NameValuePair> params, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_GET, null);
}
public <T> T executePost(String accion, List<NameValuePair> params, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_POST, null);
}
public <T> T executePut(String accion, List<NameValuePair> params, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_PUT, null);
}
public <T> T executeGet(String accion, List<NameValuePair> params, List<NameValuePair> headerParams, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_GET, headerParams);
}
public <T> T executePost(String accion, List<NameValuePair> params, List<NameValuePair> headerParams, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_POST, headerParams);
}
public <T> T executePut(String accion, List<NameValuePair> params, List<NameValuePair> headerParams, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_PUT, headerParams);
}
public <T> T executeDelete(String accion, List<NameValuePair> params, List<NameValuePair> headerParams, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_DELETE, null);
}
public <T> T executePatch(String accion, List<NameValuePair> params, List<NameValuePair> headerParams, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_PATCH, null);
}
public <T> T executeGetDefaultHeaders(String accion, List<NameValuePair> params, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_GET, getDefaultHeaders());
}
public <T> T executePostDefaultHeaders(String accion, List<NameValuePair> params, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_POST, getDefaultHeaders());
}
public <T> T executePutDefaultHeaders(String accion, List<NameValuePair> params, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_PUT, getDefaultHeaders());
}
public <T> T executeDeleteDefaultHeaders(String accion, List<NameValuePair> params, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_DELETE, getDefaultHeaders());
}
public <T> T executePatchDefaultHeaders(String accion, List<NameValuePair> params, Class<T> clase) {
return execute(accion, params, clase, REQUEST_TYPE_PATCH, getDefaultHeaders());
}
private List<NameValuePair> getDefaultHeaders() {
List<NameValuePair> header = new ArrayList<NameValuePair>();
header.add(new BasicNameValuePair("Authorization", context.getSession().access_token));
return header;
}
/**
* Executes a GET with default headers, and custom deserializer (used for Timeline deserializing)
* @param accion
* @param params
* @param clase
* @param deserializer
* @return
*/
public <T> T executeGetDefaultHeadersCustomDeserializer(String accion, List<NameValuePair> params, Class<T> clase, Gson deserializer) {
return execute(accion, params, clase, REQUEST_TYPE_GET, getDefaultHeaders(), deserializer);
}
} | true |
30e8e04cd66f6a1c584d43a2eeb00edc36a13ab2 | Java | HluhovMax/JavaCore | /src/main/java/com/shildt/chapter07/OverloadCons.java | UTF-8 | 484 | 3.15625 | 3 | [] | no_license | package com.shildt.chapter07;
/**
* Created by Max Hluhov on 27.08.2018.
*/
public class OverloadCons {
public static void main(String[] args) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1);
System.out.println(mybox1.volume());
System.out.println(mybox2.volume());
System.out.println(mycube.volume());
System.out.println(myclone.volume());
}
}
| true |
a623413f2cd3fa2f93fe56a3c630037333925d0c | Java | 17346507213/repository | /BookManager/src/main/java/com/book/service/impl/BooksAuthorServiceImpl.java | UTF-8 | 1,647 | 2.125 | 2 | [] | no_license |
package com.book.service.impl;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import com.book.entity.BooksAuthor;
import com.book.mapper.BooksAuthorMapper;
import com.book.service.BooksAuthorService;
import com.mysql.jdbc.StringUtils;
/**
* @author 作者: lilei
* @version 创建时间:2019年4月3日 下午1:33:25
* 类说明
*/
@Service
public class BooksAuthorServiceImpl implements BooksAuthorService {
@Autowired
private BooksAuthorMapper booksAuthorMapper;
@Override
public Map<String, Object> getAllBooksAuthorByPage(int page, int rows,String name) {
if(name!=null){
name = "%"+name+"%";
}
int startIndex = (page-1)*rows;
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", this.booksAuthorMapper.getAllBooksAuthorCount(name));
map.put("rows", this.booksAuthorMapper.getAllBooksAuthorByPage(startIndex, rows,name));
return map;
}
@Override
public int insertOrUpdateBooksAuthor(BooksAuthor booksAuthor) {
if(StringUtils.isNullOrEmpty(booksAuthor.getId())){
return this.booksAuthorMapper.insertBooksAuthor(booksAuthor);
}else{
return this.booksAuthorMapper.updateBooksAuthor(booksAuthor);
}
}
@Override
public BooksAuthor getBooksAuthorById(String id) {
return this.booksAuthorMapper.getBooksAuthorById(id);
}
@Override
public int deleteBooksAuthor(String ids) {
return this.booksAuthorMapper.deleteBooksAuthor(ids);
}
}
| true |
80ff7ab0eae0cfe8eade2f92e1f69ca6df42621a | Java | mbedward/jaitools | /utils/src/main/java/org/jaitools/jts/AbstractSmoother.java | UTF-8 | 6,182 | 2.53125 | 3 | [] | no_license | /*
* Copyright (c) 2010-2011, Michael Bedward. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jaitools.jts;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
/**
* Base class for Bezier smoothing of JTS Geometry objects.
*
* @author Michael Bedward
* @since 1.1
* @version $Id$
*/
public abstract class AbstractSmoother {
/**
* Default smoothing control. Specifies no minimum
* vertex distance and a constant number of points
* per smoothed segment.
*/
public static final SmootherControl DEFAULT_CONTROL = new SmootherControl() {
public double getMinLength() {
return 0.0;
}
public int getNumVertices(double length) {
return 10;
}
};
/** The current SmootherControl instance. */
protected SmootherControl control;;
/** The current {@code GeometryFactory} being used. */
protected final GeometryFactory geomFactory;
/**
* Class to hold interpolation parameters for a given point.
*/
protected static final class InterpPoint {
double[] t = new double[4];
double tsum;
}
/**
* Cache of previously calculated interpolation parameters
*/
protected Map<Integer, WeakReference<InterpPoint[]>> lookup =
new HashMap<Integer, WeakReference<InterpPoint[]>>();
/**
* Creates a new smoother that will use the given {@code GeometryFactory}.
*
* @param geomFactory factory to use for creating smoothed objects
*
* @throws IllegalArgumentException if {@code geomFactory} is {@code null}
*/
public AbstractSmoother(GeometryFactory geomFactory) {
if (geomFactory == null) {
throw new IllegalArgumentException("geomFactory must not be null");
}
this.geomFactory = geomFactory;
this.control = DEFAULT_CONTROL;
}
/**
* Sets a new {@code Control} object to for smoothing.
*
* @param control the control to use for smoothing; if {@code null} the
* default control will be set
*/
public void setControl(SmootherControl control) {
this.control = control == null ? DEFAULT_CONTROL : control;
}
/**
* Calculates vertices along a cubic Bazier curve given start point, end point
* and two control points.
*
* @param start start position
* @param end end position
* @param ctrl1 first control point
* @param ctrl2 second control point
* @param nv number of vertices including the start and end points
*
* @return vertices along the Bezier curve
*/
protected Coordinate[] cubicBezier(final Coordinate start, final Coordinate end,
final Coordinate ctrl1, final Coordinate ctrl2, final int nv) {
final Coordinate[] curve = new Coordinate[nv];
final Coordinate[] buf = new Coordinate[3];
for (int i = 0; i < buf.length; i++) {
buf[i] = new Coordinate();
}
curve[0] = new Coordinate(start);
curve[nv - 1] = new Coordinate(end);
InterpPoint[] ip = getInterpPoints(nv);
for (int i = 1; i < nv-1; i++) {
Coordinate c = new Coordinate();
c.x = ip[i].t[0]*start.x + ip[i].t[1]*ctrl1.x + ip[i].t[2]*ctrl2.x + ip[i].t[3]*end.x;
c.x /= ip[i].tsum;
c.y = ip[i].t[0]*start.y + ip[i].t[1]*ctrl1.y + ip[i].t[2]*ctrl2.y + ip[i].t[3]*end.y;
c.y /= ip[i].tsum;
curve[i] = c;
}
return curve;
}
/**
* Gets the interpolation parameters for a Bezier curve approximated
* by the given number of vertices.
*
* @param npoints number of vertices
*
* @return array of {@code InterpPoint} objects holding the parameter values
*/
protected InterpPoint[] getInterpPoints(int npoints) {
WeakReference<InterpPoint[]> ref = lookup.get(npoints);
InterpPoint[] ip = null;
if (ref != null) ip = ref.get();
if (ip == null) {
ip = new InterpPoint[npoints];
for (int i = 0; i < npoints; i++) {
double t = (double) i / (npoints - 1);
double tc = 1.0 - t;
ip[i] = new InterpPoint();
ip[i].t[0] = tc*tc*tc;
ip[i].t[1] = 3.0*tc*tc*t;
ip[i].t[2] = 3.0*tc*t*t;
ip[i].t[3] = t*t*t;
ip[i].tsum = ip[i].t[0] + ip[i].t[1] + ip[i].t[2] + ip[i].t[3];
}
lookup.put(npoints, new WeakReference<InterpPoint[]>(ip));
}
return ip;
}
}
| true |
1fb1896ffdb9e14be2dde201e37d333f5e3df22f | Java | ShowKa/HanbaiKanri | /src/test/java/com/showka/service/crud/z00/BushoCrudImplTest.java | UTF-8 | 2,743 | 2.21875 | 2 | [
"MIT"
] | permissive | package com.showka.service.crud.z00;
import java.util.List;
import javax.persistence.EntityNotFoundException;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.showka.common.PersistenceTestCase;
import com.showka.domain.z00.Busho;
import com.showka.entity.MBusho;
import com.showka.service.crud.z00.BushoCrudImpl;
import com.showka.value.EigyoDate;
/**
* 部署 CRUD Service Test
*
* @author 25767
*
*/
public class BushoCrudImplTest extends PersistenceTestCase {
@Autowired
private BushoCrudImpl service;
/**
* test data
*/
private static final Object[] VALUE01 = { "BS01", "01", "01", "部署01", "BS01" };
private static final Object[] VALUE02 = { "BS02", "99", "02", "部署02", "BS02" };
private static final Object[] M_BUSHO_DATE_VALUE_01 = { "BS01", d("20171112"), "BS01" };
private static final Object[] M_BUSHO_DATE_VALUE_02 = { "BS02", d("20171112"), "BS02" };
@Before
public void deletTable() {
super.deleteAll(M_BUSHO);
super.deleteAll(M_BUSHO_DATE);
}
/**
* 既存レコードのgetテスト
*/
@Test
@Transactional
public void test_getDomain1() {
super.insert(M_BUSHO, M_BUSHO_COLUMN, VALUE01, VALUE02);
super.insert(M_BUSHO_DATE, M_BUSHO_DATE_COLUMN, M_BUSHO_DATE_VALUE_01, M_BUSHO_DATE_VALUE_02);
String id = "BS02";
// getDomain
Busho result = service.getDomain(id);
// assert
assertEquals("BS02", result.getCode());
assertEquals("99", result.getBushoKubun().getCode());
assertEquals("02", result.getJigyoKubun().getCode());
assertEquals("部署02", result.getName());
assertEquals("BS02", result.getRecordId());
assertEquals(new EigyoDate(2017, 11, 12), result.getEigyoDate());
}
/**
* 存在しないレコードのgetテスト
*/
@Test(expected = EntityNotFoundException.class)
@Transactional
public void test_getDomain2() {
String id = "BS02";
// getDomain
service.getDomain(id);
fail();
}
/**
* getMBushoListテスト
*/
@Test
@Transactional
public void test_getMBushoList() {
super.insert(M_BUSHO, M_BUSHO_COLUMN, VALUE01, VALUE02);
// getDomain
List<MBusho> bushoList = service.getMBushoList();
assertEquals(2, bushoList.size());
}
/**
* 全部署取得
*/
@Test
public void test_getDomains() throws Exception {
super.insert(M_BUSHO, M_BUSHO_COLUMN, VALUE01, VALUE02);
super.insert(M_BUSHO_DATE, M_BUSHO_DATE_COLUMN, M_BUSHO_DATE_VALUE_01, M_BUSHO_DATE_VALUE_02);
List<Busho> actual = service.getDomains();
assertEquals(2, actual.size());
}
}
| true |
1b2ac4e97904312884c2d12a716bc046ba625636 | Java | fan2008shuai/dorado-demo | /dorado-demo-service/src/main/java/org/fan/dorado/demo/server/ThriftBootstrap.java | UTF-8 | 1,416 | 2.46875 | 2 | [] | no_license | package org.fan.dorado.demo.server;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.fan.dorado.demo.api.GreetingService;
import org.fan.dorado.demo.service.GreetingServiceImpl;
public class ThriftBootstrap {
public static void main(String[] args) {
try {
TServerTransport serverTransport = new TServerSocket(9090);
TBinaryProtocol.Factory proFactory = new TBinaryProtocol.Factory();
/**
* 关联处理器与GreetingService服务实现
*/
TProcessor processor = new GreetingService.Processor(new GreetingServiceImpl());
TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport);
serverArgs.processor(processor);
serverArgs.protocolFactory(proFactory);
TServer server = new TThreadPoolServer(serverArgs);
System.out.println("Start server on port 9090....");
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
}
| true |
68a1ee81a11eea35494e28164aadfa1b134294a2 | Java | luqinx/sp | /spa/src/main/java/chao/android/tools/servicepool/AndroidNoOpInstantiator.java | UTF-8 | 1,799 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | package chao.android.tools.servicepool;
import chao.java.tools.servicepool.DefaultService;
import chao.java.tools.servicepool.IService;
import chao.java.tools.servicepool.NoOpConstructorArg;
import chao.java.tools.servicepool.NoOpInstance;
import chao.java.tools.servicepool.NoOpInstantiator;
import chao.java.tools.servicepool.NoOpInterceptor;
import chao.java.tools.servicepool.annotation.Service;
import java.lang.reflect.Constructor;
import java.util.concurrent.atomic.AtomicInteger;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
import net.bytebuddy.implementation.MethodCall;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
/**
* @author qinchao
* @since 2019/6/19
*/
@Service
public class AndroidNoOpInstantiator extends DefaultService implements NoOpInstantiator {
@Override
public <T> Class<?> make(Class<T> clazz, Constructor<?> constructor, Object[] params, AtomicInteger noOpCount) {
// AndroidLazyStrategy.INSTANCE.makeDexDir();
return new ByteBuddy()
.subclass(clazz, ConstructorStrategy.Default.NO_CONSTRUCTORS)
.name(clazz.getPackage().getName() + ".NoOp" + clazz.getSimpleName() + "_" + noOpCount.incrementAndGet())
.implement(NoOpInstance.class, IService.class)
.defineConstructor(Visibility.PUBLIC).withParameters(NoOpConstructorArg.class)
.intercept(MethodCall.invoke(constructor).with(params))
.method(ElementMatchers.any()).intercept(MethodDelegation.to(NoOpInterceptor.class))
.make(AndroidLazyStrategy.INSTANCE)
.load(Spa.getContext().getClassLoader())
.getLoaded();
}
}
| true |
2dcb4ad0dd6b77151f4341cbd172261dac040a91 | Java | R123k/great | /loginsp2/app/src/main/java/com/example/rohit/login_sp/MainActivity.java | UTF-8 | 1,971 | 1.890625 | 2 | [] | no_license | package com.example.rohit.login_sp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.RegionIterator;
import android.net.nsd.NsdManager;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText etname=(EditText)findViewById(R.id.etnewname);
final EditText etpassword=(EditText)findViewById(R.id.etpassword);
Button btnLogin=(Button)findViewById(R.id.etlogin);
Button btnRegister=(Button)findViewById(R.id.etregister);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String user=etname.getText().toString();
String password=etpassword.getText().toString();
SharedPreferences preferences=getSharedPreferences("MYPREFS",MODE_PRIVATE);
String userDetails=preferences.getString(user + password + "data","username or password is incorrect");
SharedPreferences.Editor editor=preferences.edit();
editor.putString("display",userDetails);
editor.commit();
Intent Displayscreen=new Intent(MainActivity.this, Displayscreen.class);
startActivity(Displayscreen);
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent Register=new Intent(MainActivity.this, Register.class);
startActivity(Register);
}
});
}
}
| true |
ccd78fff69e5df18de8fe6dc3ab9e78cd077e73e | Java | imavishek/Calendario | /user-service/src/main/java/com/calendario/user/dto/ActiveProfileDto.java | UTF-8 | 487 | 1.882813 | 2 | [] | no_license | /**
* @ProjectName: user-service
* @PackageName: com.calendario.user.dto
* @FileName: ActiveProfileDto.java
* @Author: Avishek Das
* @CreatedDate: 04-04-2020
* @Modified_By avishekdas @Last_On 04-Apr-2020 9:42:53 pm
*/
package com.calendario.user.dto;
import java.util.UUID;
import io.swagger.annotations.ApiModel;
import lombok.Data;
@Data
@ApiModel(description = "Active profile operation dto")
public class ActiveProfileDto {
private UUID token;
private String password;
}
| true |
2edd3b92d263878fd1a8b97f86625601914c8043 | Java | DunyangNi/CSC207_Conference_Sys | /phase2/src/views/event/SpeakerScheduleView.java | UTF-8 | 1,009 | 2.796875 | 3 | [] | no_license | package views.event;
import controllers.event.EventController;
import enums.ViewEnum;
import presenters.event.EventPresenter;
import views.factory.View;
/**
* View responsible for speaker event schedule functionality
*/
public class SpeakerScheduleView implements View {
private final EventController controller;
private final EventPresenter presenter;
/**
* Constructs an instance of <code>SpeakerScheduleView</code> based on the following parameters
*
* @param controller The given EventController
* @param presenter The given EventPresenter
*/
public SpeakerScheduleView(EventController controller, EventPresenter presenter) {
this.controller = controller;
this.presenter = presenter;
}
/**
* Runs the view.
*
* @return ViewEnum.VOID
*/
public ViewEnum runView() {
presenter.myEventsHeader();
presenter.displayEventSchedule(controller.getSpeakerEvents());
return ViewEnum.VOID;
}
}
| true |
4e97d3a757899f817c77a4477743891e96ea680b | Java | GowoonJ/InuMarketAndroid | /app/src/main/java/injappcenter_and/inumarket_android/Model/myProductData.java | UTF-8 | 1,149 | 2.421875 | 2 | [] | no_license | package injappcenter_and.inumarket_android.Model;
public class myProductData {
private String productId;
private String productName;
private String category;
private boolean productSelled;
public myProductData(String productId, String productName, String category, boolean productSelled) {
this.productId = productId;
this.productName = productName;
this.category = category;
this.productSelled = productSelled;
}
public String getProductId() {
return productId;
}
public boolean isProductSelled() {
return productSelled;
}
public void setProductSelled(boolean productSelled) {
this.productSelled = productSelled;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
| true |
79021e67312f97df6186359a24d515c6ac8ead72 | Java | simplehappy2600/OpenTLDAndroid | /tld-main/src/com/trandi/opentld/TLDView.java | UTF-8 | 8,784 | 1.9375 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2013 Dan Oprescu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trandi.opentld;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import com.trandi.opentld.tld.Tld;
import com.trandi.opentld.tld.Tld.ProcessFrameStruct;
import com.trandi.opentld.tld.Util;
public class TLDView extends JavaCameraView implements CameraBridgeViewBase.CvCameraViewListener {
final private SurfaceHolder _holder;
private int _canvasImgYOffset;
private int _canvasImgXOffset;
private Mat _currentGray = new Mat();
private Mat _lastGray = new Mat();
private Tld _tld = null;
private Rect _trackedBox = null;
private ProcessFrameStruct _processFrameStruct = null;
private Properties _tldProperties;
private static final Size WORKING_FRAME_SIZE = new Size(144, 80);
private Mat _workingFrame = new Mat();
private String _errMessage;
public TLDView(Context context, AttributeSet attrs) {
super(context, attrs);
_holder = getHolder();
// Init the PROPERTIES
InputStream propsIS = null;
try{
propsIS = context.getResources().openRawResource(R.raw.parameters);
_tldProperties = new Properties();
_tldProperties.load(propsIS);
} catch (IOException e) {
Log.e(Util.TAG, "Can't load properties", e);
}finally{
if(propsIS != null){
try {
propsIS.close();
} catch (IOException e) {
Log.e(Util.TAG, "Can't close props", e);
}
}
}
// listens to its own events
setCvCameraViewListener(this);
// DEBUG
//_trackedBox = new BoundingBox(165,93,51,54, 0, 0);
// LISTEN for touches of the screen, to define the BOX to be tracked
final AtomicReference<Point> trackedBox1stCorner = new AtomicReference<Point>();
final Paint rectPaint = new Paint();
rectPaint.setColor(Color.rgb(0, 255, 0));
rectPaint.setStrokeWidth(5);
rectPaint.setStyle(Style.STROKE);
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// re-init
_errMessage = null;
_tld = null;
final Point corner = new Point(event.getX() - _canvasImgXOffset, event.getY() - _canvasImgYOffset);
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
trackedBox1stCorner.set(corner);
Log.i(Util.TAG, "1st corner: " + corner);
break;
case MotionEvent.ACTION_UP:
_trackedBox = new Rect(trackedBox1stCorner.get(), corner);
Log.i(Util.TAG, "Tracked box DEFINED: " + _trackedBox);
break;
case MotionEvent.ACTION_MOVE:
final android.graphics.Rect rect = new android.graphics.Rect(
(int)trackedBox1stCorner.get().x + _canvasImgXOffset, (int)trackedBox1stCorner.get().y + _canvasImgYOffset,
(int)corner.x + _canvasImgXOffset, (int)corner.y + _canvasImgYOffset);
final Canvas canvas =_holder.lockCanvas(rect);
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); // remove old rectangle
canvas.drawRect(rect, rectPaint);
_holder.unlockCanvasAndPost(canvas);
break;
}
return true;
}
});
}
@Override
public Mat onCameraFrame(Mat originalFrame) {
try{
// Image is too big and this requires too much CPU for a phone, so scale everything down...
Imgproc.resize(originalFrame, _workingFrame, WORKING_FRAME_SIZE);
final Size workingRatio = new Size(originalFrame.width() / WORKING_FRAME_SIZE.width, originalFrame.height() / WORKING_FRAME_SIZE.height);
// usefull to see what we're actually working with...
_workingFrame.copyTo(originalFrame.submat(originalFrame.rows() - _workingFrame.rows(), originalFrame.rows(), 0, _workingFrame.cols()));
if(_trackedBox != null){
if(_tld == null){ // run the 1st time only
Imgproc.cvtColor(_workingFrame, _lastGray, Imgproc.COLOR_RGB2GRAY);
_tld = new Tld(_tldProperties);
final Rect scaledDownTrackedBox = scaleDown(_trackedBox, workingRatio);
Log.i(Util.TAG, "Working Ration: " + workingRatio + " / Tracking Box: " + _trackedBox + " / Scaled down to: " + scaledDownTrackedBox);
try {
_tld.init(_lastGray, scaledDownTrackedBox);
}catch(Exception eInit){
// start from scratch, you have to select an init box again !
_trackedBox = null;
_tld = null;
throw eInit; // re-throw it as it will be dealt with later
}
}else{
Imgproc.cvtColor(_workingFrame, _currentGray, Imgproc.COLOR_RGB2GRAY);
_processFrameStruct = _tld.processFrame(_lastGray, _currentGray);
drawPoints(originalFrame, _processFrameStruct.lastPoints, workingRatio, new Scalar(255, 0, 0));
drawPoints(originalFrame, _processFrameStruct.currentPoints, workingRatio, new Scalar(0, 255, 0));
drawBox(originalFrame, scaleUp(_processFrameStruct.currentBBox, workingRatio), new Scalar(0, 0, 255));
_currentGray.copyTo(_lastGray);
// overlay the current positive examples on the real image(needs converting at the same time !)
//copyTo(_tld.getPPatterns(), originalFrame);
}
}
} catch(Exception e) {
_errMessage = e.getClass().getSimpleName() + " / " + e.getMessage();
Log.e(Util.TAG, "TLDView PROBLEM", e);
}
if(_errMessage != null){
Imgproc.putText(originalFrame, _errMessage, new Point(0, 300), Core.FONT_HERSHEY_PLAIN, 1.3d, new Scalar(255, 0, 0), 2);
}
return originalFrame;
}
private static void copyTo(List<Mat> patterns, Mat dest) {
if(patterns == null || patterns.isEmpty() || dest == null) return;
final int patternRows = patterns.get(0).rows();
final int patternCols = patterns.get(0).cols();
final int vertCount = dest.rows() / patternRows;
final int horizCount = patterns.size() / vertCount + 1;
int patchIdx = 0;
for(int col = dest.cols() - horizCount * patternCols - 1; col < dest.cols() && patchIdx < patterns.size(); col += patternCols){
for(int row = 0; row < dest.rows() && patchIdx < patterns.size(); row += patternRows) {
Imgproc.cvtColor(patterns.get(patchIdx), dest.submat(row, row + patternRows, col, col + patternCols), Imgproc.COLOR_GRAY2RGBA);
patchIdx++;
}
}
}
@Override
public void onCameraViewStarted(int width, int height) {
_canvasImgXOffset = (getWidth() - width) / 2;
_canvasImgYOffset = (getHeight() - height) / 2;
}
@Override
public void onCameraViewStopped() {
// TODO Auto-generated method stub
}
private static void drawPoints(Mat image, final Point[] points, final Size scale, final Scalar colour){
if(points != null){
for(Point point : points){
Imgproc.circle(image, scaleUp(point, scale), 2, colour);
}
}
}
private static void drawBox(Mat image, final Rect box, final Scalar colour){
if(box != null){
Imgproc.rectangle(image, box.tl(), box.br(), colour);
}
}
/* SCALING */
private static Point scaleUp(Point point, Size scale){
if(point == null || scale == null) return null;
return new Point(point.x * scale.width, point.y * scale.height);
}
private static Point scaleDown(Point point, Size scale){
if(point == null || scale == null) return null;
return new Point(point.x / scale.width, point.y / scale.height);
}
private static Rect scaleUp(Rect rect, Size scale) {
if(rect == null || scale == null) return null;
return new Rect(scaleUp(rect.tl(), scale), scaleUp(rect.br(), scale));
}
private static Rect scaleDown(Rect rect, Size scale) {
if(rect == null || scale == null) return null;
return new Rect(scaleDown(rect.tl(), scale), scaleDown(rect.br(), scale));
}
}
| true |
bc670c6c154b2ab19961d3d3db93f61cb61cc8f9 | Java | Aswin-MN/personal | /kernel/kernel-masterdata-service/src/main/java/io/mosip/kernel/masterdata/constant/DocumentTypeErrorCode.java | UTF-8 | 1,088 | 2.296875 | 2 | [] | no_license | package io.mosip.kernel.masterdata.constant;
/**
* Constants for Document Type.
*
* @author Ritesh Sinha
* @author Uday Kumar
* @since 1.0.0
*/
public enum DocumentTypeErrorCode {
DOCUMENT_TYPE_FETCH_EXCEPTION("KER-MSD-015","Error occured while fetching Document Types"),
DOCUMENT_TYPE_INSERT_EXCEPTION("KER-MSD-052","Error occured while inserting Document Type details"),
DOCUMENT_TYPE_NOT_FOUND_EXCEPTION("KER-MSD-118","Document Type not found"),
DOCUMENT_TYPE_UPDATE_EXCEPTION("KER-MSD-091","Error occur while updating Document Type details"),
DOCUMENT_TYPE_DELETE_DEPENDENCY_EXCEPTION("KER-MSD-124","Cannot delete dependency found"),
DOCUMENT_TYPE_DELETE_EXCEPTION("KER-MSD-092","Error occured while deleting Document Type details");
private final String errorCode;
private final String errorMessage;
private DocumentTypeErrorCode(final String errorCode, final String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public String getErrorCode() {
return errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
}
| true |
393f6e83142db235f8dd40fa9c81e9e0e9dffb36 | Java | vistanovalaura/LabBook | /LabBook/src/main/java/sk/upjs/paz1c/business/UserIdentificationManager.java | UTF-8 | 2,514 | 2.765625 | 3 | [] | no_license | package sk.upjs.paz1c.business;
import java.util.List;
import sk.upjs.paz1c.entities.Admin;
import sk.upjs.paz1c.entities.User;
import sk.upjs.paz1c.persistent.DAOfactory;
public class UserIdentificationManager {
private static int typeOfUser;
private static Long id;
public static int getTypeOfUser() {
return typeOfUser;
}
public static Long getId() {
return id;
}
public static User getUser() {
List<User> users = DAOfactory.INSTANCE.getUserDAO().getAll();
for (User u : users) {
if (u.getUserID().equals(id)) {
return u;
}
}
return null;
}
public static Admin getAdmin() {
List<Admin> admins = DAOfactory.INSTANCE.getAdminDAO().getAll();
for (Admin a : admins) {
if (a.getAdminID().equals(id)) {
return a;
}
}
return null;
}
// nastavi id a typ usera + podla toho aka hodnota sa vrati sa vyberie dalsie
// okno (pre admina, pre usera alebo wrongData)
public static int setUser(String userName, String password) {
PasswordManager pm = new PasswordManager();
List<User> users = DAOfactory.INSTANCE.getUserDAO().getAll();
for (User user : users) {
if (user.getName().equals(userName) && pm.isCorrectPassword(password, user.getUserID(), 1)) {
UserIdentificationManager.typeOfUser = 1;
UserIdentificationManager.id = user.getUserID();
return 1;
}
}
List<Admin> admins = DAOfactory.INSTANCE.getAdminDAO().getAll();
for (Admin admin : admins) {
if (admin.getName().equals(userName) && pm.isCorrectPassword(password, admin.getAdminID(), 2)) {
UserIdentificationManager.typeOfUser = 2;
UserIdentificationManager.id = admin.getAdminID();
return 2;
}
}
return -1;
}
// public static int setUser(String userName, String password) {
// List<User> users = DAOfactory.INSTANCE.getUserDAO().getAll();
// for (User user : users) {
// if (user.getName().equals(userName) && user.getPassword().equals(password)) {
// UserIdentificationManager.typeOfUser = 1;
// UserIdentificationManager.id = user.getUserID();
// return 1;
// }
// }
// List<Admin> admins = DAOfactory.INSTANCE.getAdminDAO().getAll();
// for (Admin admin : admins) {
// if (admin.getName().equals(userName) && admin.getPassword().equals(password)) {
// UserIdentificationManager.typeOfUser = 2;
// UserIdentificationManager.id = admin.getAdminID();
// return 2;
// }
// }
// return -1;
// }
public static void logOut() {
UserIdentificationManager.typeOfUser = 0;
UserIdentificationManager.id = null;
}
}
| true |
90827f894c9da7b12f12d3de4eba8661869c4549 | Java | jmattfong/futuretext | /src/com/organforce/futuretext/ScheduledTextService.java | UTF-8 | 6,058 | 2.03125 | 2 | [] | no_license | package com.organforce.futuretext;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
public class ScheduledTextService extends Service {
private TextDbAdapter db;
public static NotificationManager mNotificationManager;
public static int NOTIFICATION_ID = 1;
private FutureText text;
private long histID;
private Context thisContext = this;
@Override
public void onStart(Intent intent, int startId) {
if(intent != null){
super.onStart(intent, startId);
long id = Long.parseLong(intent.getData().getLastPathSegment());
text = db.fetchTextObject(id);
//---when the SMS has been sent---
registerReceiver(br, new IntentFilter("SMS_SENT"));
sendSMS(text.recipient, text.content);
updateNextTime(text);
scheduleFutureText(this, text);
}
}
@Override
public void onCreate() {
super.onCreate();
db = new TextDbAdapter(this);
db.open();
}
@Override
public void onDestroy() {
db.close();
super.onDestroy();
}
private void updateNextTime(FutureText text) {
text.time = text.nextTime();
if(text.time == null) {
db.deleteText(text._id);
}
else {
db.updateText(text._id, text);
}
}
public static void scheduleFutureText(Context context, FutureText text) {
if(text.time != null) {
scheduleFutureText(context, text._id, text.time);
}
}
public static void scheduleFutureText(Context context, long id, long time) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = getPendingIntentForScheduledText(context, id);
am.cancel(pendingIntent);
am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
public static void unscheduleFutureText(Context context, long id) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = getPendingIntentForScheduledText(context, id);
am.cancel(pendingIntent);
}
public static PendingIntent getPendingIntentForScheduledText(Context context, long id) {
Intent i = new Intent(context, ScheduledTextService.class);
Uri uri = Uri.withAppendedPath(Uri.parse("ftext://text/id/"), String.valueOf(id));
i.setData(uri);
return PendingIntent.getService(context, 0,
i, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
SmsManager sms = SmsManager.getDefault();
ArrayList<String> multipartMessage = sms.divideMessage(message);
ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
sentIntents.add(sentPI);
for(int i = 0; i < multipartMessage.size() - 1; i++){
//sentIntents.add(null);
}
sms.sendMultipartTextMessage(phoneNumber, null, multipartMessage, sentIntents, null);
//sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
private BroadcastReceiver br = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
CharSequence contentTitle = "Future Text: " + text.recipient;
CharSequence contentText = text.content;
CharSequence tickerText = "";
switch (getResultCode())
{
case Activity.RESULT_OK:
tickerText = "Future Text sent!";
histID = db.addTextToHistory(text, true);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
tickerText = "ERROR: Generic failure";
contentTitle = "Future Text failed to send.";
contentText = text.recipient + ": " + contentText;
histID = db.addTextToHistory(text, false);
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
tickerText = "ERROR: No service";
contentTitle = "Future Text failed to send.";
contentText = text.recipient + ": " + contentText;
histID = db.addTextToHistory(text, false);
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
tickerText = "ERROR: Null PDU";
contentTitle = "Future Text failed to send.";
contentText = text.recipient + ": " + contentText;
histID = db.addTextToHistory(text, false);
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
tickerText = "ERROR: Radio off";
contentTitle = "Future Text failed to send.";
contentText = text.recipient + ": " + contentText;
histID = db.addTextToHistory(text, false);
break;
}
Log.e("resultCode: ", ""+getResultCode());
//notification
// Get the notification manager service.
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(NOTIFICATION_ID);
NOTIFICATION_ID++;
Context context = getApplicationContext();
Intent notificationIntent = new Intent(thisContext, ViewText.class);
notificationIntent.putExtra(TextDbAdapter.KEY_ROWID, histID);
Log.e("ScheduledTextService: histID", ""+histID);
Log.e("NotificationIntent: ", ""+notificationIntent.getExtras().getLong(TextDbAdapter.KEY_ROWID));
PendingIntent contentIntent = PendingIntent.getActivity(thisContext, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new Notification(R.drawable.icon, tickerText, System.currentTimeMillis());
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
};
}
| true |
113124e5b0944c3e65dff5593dff2e09d275c401 | Java | NaGyXML/yjyu2 | /.svn/pristine/46/4621a738510be3482791f1f168b83a14959c9687.svn-base | UTF-8 | 529 | 2.109375 | 2 | [] | no_license | package com.yangjiayu.service.impl;
import com.yangjiayu.entity.Address;
import com.yangjiayu.service.IAddressService;
import org.springframework.stereotype.Service;
/**
* Created by 86188 on 2019/8/21.
* 收货地址 业务层接口实现类
*/
@Service
public class AddressServiceImpl implements IAddressService {
@Override
public void addAddress(String username, Integer uid, Address address) {
//初始化設置收貨地址最大值 MAXADDRESS
//根據uid查詢用戶收貨地址信息
}
}
| true |
d031bda42b912874487fd618e8d96e955d38c4b0 | Java | JohnLee-Organization/spring | /plugin/ssdp/src/main/java/net/lizhaoweb/ssdp/model/EnumTransportProtocol.java | UTF-8 | 1,530 | 2.46875 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright (c) 2016, Stupid Bird and/or its affiliates. All rights reserved.
* STUPID BIRD PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
* @Project : common
* @Package : net.lizhaoweb.ssdp.model
* @author <a href="http://www.lizhaoweb.net">李召(John.Lee)</a>
* @email 404644381@qq.com
* @Time : 16:15
*/
package net.lizhaoweb.ssdp.model;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
/**
* <h1>模型 [枚举] - 传输协议</h1>
*
* @author <a href="http://www.lizhaoweb.cn">李召(John.Lee)</a>
* @version 1.0.0.0.1
* @notes Created on 2016年11月30日<br>
* Revision of last commit:$Revision$<br>
* Author of last commit:$Author$<br>
* Date of last commit:$Date$<br>
*/
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public enum EnumTransportProtocol {
HTTP_1_1("HTTP", "1.1");
/**
* 协议
*/
@Getter
@NonNull
private String protocol;
/**
* 版本号
*/
@Getter
@NonNull
private String version;
/**
* @param protocol
* @return
*/
public static EnumTransportProtocol fromProtocol(String protocol, String version) {
for (EnumTransportProtocol type : values()) {
if (type.protocol.equalsIgnoreCase(protocol) && type.version.equalsIgnoreCase(version)) {
return type;
}
}
throw new IllegalArgumentException(String.format("protocol/version [%s/%s]", protocol, version));
}
}
| true |
1964d1364e0d7db324deb8f31bab31d549ff8142 | Java | Charly706/Kontoverwaltung | /Konto3/src/Konto.java | UTF-8 | 681 | 3.859375 | 4 | [] | no_license | //Datei: Konto3/Konto.java
//Beispiel : Konstruktor
public class Konto {
private int kontonummer;
private double saldo;
// −−> Konstruktor
public Konto(int nummer) {
kontonummer = nummer;
saldo = 0.0;
}
public int getKontonummer() {
return kontonummer;
}
// setKontonummer(nummer) entfernt
public double getSaldo() {
return saldo;
}
// setSaldo(betrag) entfernt
public void einzahlen(double betrag) {
saldo = saldo + betrag;
}
public void auszahlen(double betrag) {
saldo = saldo - betrag;
}
public void auszug() {
System.out.println("Kontonummer: " + kontonummer + " Saldo: " + saldo
+ " Euro");
}
} | true |
323a817db5fc14c957e093ed555d943a734121b7 | Java | domcj/rabbitmq | /src/main/java/com/domcj/rabbitmq/controller/SendController.java | UTF-8 | 657 | 2.078125 | 2 | [] | no_license | package java.com.domcj.rabbitmq.controller;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.space.rabbitmq.sender.FirstSender;
/**
* @author domcj
* @date 2018/11/25 17:45
* @email domcj@foxmail.com
*/
@RestController
public class SendController {
@Autowired
private FirstSender firstSender;
@GetMapping("/send")
public String send(String message){
String uuid = UUID.randomUUID().toString();
firstSender.send(uuid,message);
return uuid;
}
}
| true |
31b9eb1d76088326883ba6f1271ed3f6c3ee0e2f | Java | Juan-Pablo-Barrientos/testHeroku | /Java Proyecto 123/src/main/java/servlet/ListadoCompras.java | UTF-8 | 1,848 | 2.203125 | 2 | [] | no_license | package servlet;
import java.io.IOException;
import java.util.LinkedList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entities.CompraView;
import entities.Usuario;
import logic.CompraViewLogic;
/**
* Servlet implementation class ListadoCompras
*/
@WebServlet("/ListadoCompras")
public class ListadoCompras extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ListadoCompras() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Usuario usr;
if (request.getSession().getAttribute("usuario") != null) {
usr = (Usuario) request.getSession().getAttribute("usuario");
if (usr.getTipo().equals("admin")) {
CompraViewLogic compraViewLogic = new CompraViewLogic();
LinkedList<CompraView> rems = compraViewLogic.getAll();
request.setAttribute("listaCompraView", rems);
request.getRequestDispatcher("/WEB-INF/ListadoCompras.jsp").forward(request, response);
} else {
response.sendRedirect(request.getContextPath() + "/Homepage.jsp");
}
} else {
response.sendRedirect(request.getContextPath() + "/Homepage.jsp?=load");
}
}
}
| true |
d5f6fb41493a777d74c79ad2aaf5428bc1ca6db7 | Java | aryendr95/TagFrame | /app/src/main/java/com/tagframe/tagframe/Adapters/Time_Line_Adapter.java | UTF-8 | 7,517 | 1.726563 | 2 | [] | no_license | package com.tagframe.tagframe.Adapters;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;
import com.squareup.picasso.Picasso;
import com.tagframe.tagframe.Models.TimeLine_Model;
import com.tagframe.tagframe.R;
import com.tagframe.tagframe.Services.Broadcastresults;
import com.tagframe.tagframe.Services.IntentServiceOperations;
import com.tagframe.tagframe.UI.Acitivity.MakeNewEvent;
import com.tagframe.tagframe.UI.Acitivity.Modules;
import com.tagframe.tagframe.Utils.Utility;
import com.tagframe.tagframe.Utils.AppPrefs;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by abhinav on 03/05/2016.
*/
public class Time_Line_Adapter extends BaseAdapter {
Context ctx;
ArrayList<TimeLine_Model> tagStream_models;
LayoutInflater inflater;
AppPrefs user_data;
public Time_Line_Adapter(Context ctx, ArrayList<TimeLine_Model> tagStream_models) {
this.ctx = ctx;
this.tagStream_models = tagStream_models;
user_data = new AppPrefs(ctx);
inflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return tagStream_models.size();
}
@Override
public Object getItem(int position) {
return tagStream_models.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_list_events, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
final TimeLine_Model tagStream = tagStream_models.get(position);
mViewHolder.tvTitlle.setText(tagStream.getTittle());
mViewHolder.tvname.setText(tagStream.getUser_name());
mViewHolder.tvcurrentduration.setText(tagStream.getCreated_on());
mViewHolder.iveventimage.setVisibility(View.VISIBLE);
mViewHolder.iveventvideo.setVisibility(View.GONE);
mViewHolder.tvlike.setText(tagStream.getNumber_of_likes());
Picasso.with(ctx).load(tagStream.getThumbnail()).into(mViewHolder.iveventimage);
try {
Picasso.with(ctx).load(tagStream.getProfile_picture()).into(mViewHolder.ivpropic);
} catch (Exception e) {
mViewHolder.ivpropic.setImageResource(R.drawable.pro_image);
}
mViewHolder.ll_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
share(tagStream.getSharelink(), ctx);
}
});
if (tagStream.getLike_video().equals("No")) {
mViewHolder.tvlike_direct.setText("Like");
mViewHolder.ivlike.setImageResource(R.drawable.like);
} else {
mViewHolder.tvlike_direct.setText("UnLike");
mViewHolder.ivlike.setImageResource(R.drawable.unlike);
}
mViewHolder.ll_like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (tagStream.getLike_video().equals("No")) {
Broadcastresults mReceiver = ((Modules) ctx).register_reviever();
Intent intent = new Intent(ctx, IntentServiceOperations.class);
intent.putExtra("operation", Utility.operation_like);
intent.putExtra("user_id", user_data.getString(Utility.user_id));
intent.putExtra("event_id", tagStream.getEvent_id());
intent.putExtra("receiver", mReceiver);
ctx.startService(intent);
tagStream.setNumber_of_likes((Integer.parseInt(tagStream.getNumber_of_likes()) + 1) + "");
tagStream.setLike_video("Yes");
notifyDataSetChanged();
} else {
Broadcastresults mReceiver = ((Modules) ctx).register_reviever();
Intent intent = new Intent(ctx, IntentServiceOperations.class);
intent.putExtra("operation", Utility.operation_unlike);
intent.putExtra("user_id", user_data.getString(Utility.user_id));
intent.putExtra("event_id", tagStream.getEvent_id());
intent.putExtra("receiver", mReceiver);
tagStream.setNumber_of_likes((Integer.parseInt(tagStream.getNumber_of_likes()) - 1) + "");
tagStream.setLike_video("No");
ctx.startService(intent);
notifyDataSetChanged();
}
}
});
mViewHolder.iveventimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ctx, MakeNewEvent.class);
intent.putExtra("data_url", tagStream.getData_url());
intent.putExtra("tittle", tagStream.getTittle());
intent.putExtra("from", "tagstream");
intent.putExtra("description", tagStream.getDescription());
intent.putParcelableArrayListExtra("framelist", tagStream.getFrameList_modelArrayList());
intent.putExtra("eventtype", Utility.eventtype_internet);
intent.putExtra("eventid", tagStream.getEvent_id());
ctx.startActivity(intent);
}
});
return convertView;
}
private class MyViewHolder {
TextView tvTitlle, tvname, tvcurrentduration, tvlike, tvlike_direct;
ImageView iveventimage, ivlike;
VideoView iveventvideo;
CircleImageView ivpropic;
LinearLayout ll_like, ll_share;
public MyViewHolder(View item) {
tvTitlle = (TextView) item.findViewById(R.id.list_event_tittle);
tvname = (TextView) item.findViewById(R.id.list_user_name);
tvcurrentduration = (TextView) item.findViewById(R.id.list_user_duration);
iveventimage = (ImageView) item.findViewById(R.id.list_event_image);
ll_like = (LinearLayout) item.findViewById(R.id.lllike);
ll_share = (LinearLayout) item.findViewById(R.id.llshare);
tvlike = (TextView) item.findViewById(R.id.txt_likes);
ivlike = (ImageView) item.findViewById(R.id.imglike);
tvlike_direct = (TextView) item.findViewById(R.id.txt_like_directive);
ivpropic = (CircleImageView) item.findViewById(R.id.list_pro_image);
iveventvideo = (VideoView) item.findViewById(R.id.list_event_video);
}
}
public void share(String link, Context ctx) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,
"Hey check out this event at TagFrame:" + link);
sendIntent.setType("text/plain");
ctx.startActivity(sendIntent);
}
}
| true |
588be5f1c8211d44c17ce75da3df2532dd96fc6d | Java | brelats/PowerfulOres | /src/com/gamepathics/Sticks/StickEnchantment.java | UTF-8 | 1,224 | 2.5625 | 3 | [] | no_license | package com.gamepathics.Sticks;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.enchantments.EnchantmentTarget;
import org.bukkit.inventory.ItemStack;
public class StickEnchantment extends Enchantment {
String name;
int startLevel;
public StickEnchantment(NamespacedKey key) {
super(key);
// TODO Auto-generated constructor stub
}
@Override
public int getMaxLevel() {
return 0;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "PowerfulOres";
}
@Override
public int getStartLevel() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isCursed() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isTreasure() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean canEnchantItem(ItemStack item) {
return item.getType() == Material.STICK;
}
@Override
public boolean conflictsWith(Enchantment other) {
return other == Enchantment.DIG_SPEED;
}
@Override
public EnchantmentTarget getItemTarget() {
// TODO Auto-generated method stub
return EnchantmentTarget.ALL;
}
}
| true |
6fb687ea55a6047638d97abdea0d654f83abb0c0 | Java | sniezek/tabletop | /server/src/main/java/tabletop/domain/game/constants/BattleshipConstants.java | UTF-8 | 3,446 | 3.046875 | 3 | [] | no_license | package tabletop.domain.game.constants;
import tabletop.domain.game.GameCategory;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class BattleshipConstants {
public static final String displayName = "Battleship";
public static final String description = "Battleship is a guessing game for two players. It is played on ruled grids" +
" (paper or board) on which the players' fleets of ships (including battleships) are marked. The locations " +
"of the fleet are concealed from the other player. Players alternate turns calling \"shots\" at the other " +
"player's ships, and the objective of the game is to destroy the opposing player's fleet.";
public static final String longDescription = "The game is played on four grids, two for each player. The grids are " +
"typically square – usually 10×10 – and the individual squares in the grid are identified by letter and " +
"number. On one grid the player arranges ships and records the shots by the opponent. On the other grid " +
"the player records their own shots.\nBefore play begins, each player secretly arranges their ships on " +
"their primary grid. Each ship occupies a number of consecutive squares on the grid, arranged either " +
"horizontally or vertically. The number of squares for each ship is determined by the type of the ship. " +
"The ships cannot overlap (i.e., only one ship can occupy any given square in the grid). The types and " +
"numbers of ships allowed are the same for each player. These may vary depending on the rules. " +
"After the ships have been positioned, the game proceeds in a series of rounds. In each round, " +
"each player takes a turn to announce a target square in the opponent's grid which is to be shot at. " +
"The opponent announces whether or not the square is occupied by a ship, and if it is a \"miss\", the " +
"player marks their primary grid with a white peg; if a \"hit\" they mark this on their own primary grid " +
"with a red peg. The attacking player notes the hit or miss on their own \"tracking\" grid with the " +
"appropriate color peg (red for \"hit\", white for \"miss\"), in order to build up a picture of the " +
"opponent's fleet.\nWhen all of the squares of a ship have been hit, the ship is sunk, and the ship's " +
"owner announces this (e.g. \"You sank my battleship!\"). If all of a player's ships have been sunk, " +
"the game is over and their opponent wins.";
public static final String imageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/Battleship_game_board.svg/300px-Battleship_game_board.svg.png";
public static final String bannerUrl = "https://aos.iacpublishinglabs.com/question/aq/1400px-788px/pieces-game-battleship_e45bf936940bf5e7.jpg?domain=cx.aos.ask.com";
public static final String time = "20 minutes";
public static final Integer randomChance = 3;
public static final Set<GameCategory> gameCategories;
public static final Integer minAge = 7;
public static final Integer difficulty = 1;
static {
Set<GameCategory> tmpSet = new HashSet<>();
tmpSet.add(GameCategory.STRATEGY);
gameCategories = Collections.unmodifiableSet(tmpSet);
}
}
| true |
bc58ba7991ada1d1eee69b836d76a235aaec3c69 | Java | Sorendil/TPMaven | /src/main/java/fr/tp/rossi/rest/Tag.java | UTF-8 | 2,061 | 2.421875 | 2 | [] | no_license | package fr.tp.rossi.rest;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.core.InjectParam;
import fr.tp.rossi.model.MBookmark;
import fr.tp.rossi.model.MTag;
import fr.tp.rossi.rest.exception.BadRequestException;
import fr.tp.rossi.rest.exception.NotFoundException;
import fr.tp.rossi.service.IServiceBookmark;
@Path("tag")
public class Tag {
@Context
private UriInfo context;
@InjectParam
private IServiceBookmark serviceBookmark;
/**
* Construct
*/
public Tag() {
}
/**
* Retourne le tag d'ID id
*
* @return
*/
@GET
@Path("{id}")
@Produces({ MediaType.APPLICATION_JSON })
public Response getTag(@PathParam("id") Integer id) {
if (id == null)
throw new BadRequestException("The tag id is required");
MTag tag = serviceBookmark.findTagById(id);
// Si le tag n'existe pas
if (tag == null)
throw new NotFoundException("The tag doesn't exist");
return Response.status(Response.Status.OK) // Retourne code 200
.entity(tag).build();
}
/**
* Retourne la liste des tags
*
* @return
*/
@GET
@Path("all")
@Produces({ MediaType.APPLICATION_JSON })
public List<MTag> getTags() {
return serviceBookmark.getAllTags();
}
/**
* Supprime le tag de nom name
*
* @return
*/
@DELETE
@Path("{id}")
@Produces({ MediaType.APPLICATION_JSON })
public Response deleteTag(@PathParam("id") Integer id) {
if (id == null)
throw new BadRequestException("The tag id is required");
MTag tag = serviceBookmark.findTagById(id);
// Si le tag n'existe pas
if (tag == null)
throw new NotFoundException("The tag doesn't exist");
// TODO : Gérer les erreurs de suppression ratées
serviceBookmark.delete(tag);
return Response.status(Response.Status.OK) // Retourne code 200
.entity("Deleted").build();
}
}
| true |
a06aeb22a5ff29f6863ed7b4acbaf42587bfe76d | Java | princewillzz/GeoParking | /geo-parking/src/main/java/xyz/willz/geoparking/GeoParkingApplication.java | UTF-8 | 883 | 1.921875 | 2 | [] | no_license | package xyz.willz.geoparking;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import xyz.willz.geoparking.service.storage.ImageStorageProperties;
import xyz.willz.geoparking.service.storage.StorageService;
@SpringBootApplication
@EnableConfigurationProperties(ImageStorageProperties.class)
public class GeoParkingApplication {
public static void main(String[] args) {
SpringApplication.run(GeoParkingApplication.class, args);
System.out.println("Application Started...✔✔✔🙌💯✔");
}
@Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.init();
};
}
}
| true |
abf12f9f92fb1a9e16a4ea918d2586bb9b87f5ed | Java | ILeybourne/COMP2913-Software-Engineering-Project-Sports-Centre-Management-Project | /api/src/main/java/uk/ac/leeds/comp2913/api/DataAccessLayer/Repository/ActivityTypeRepository.java | UTF-8 | 530 | 1.945313 | 2 | [] | no_license | package uk.ac.leeds.comp2913.api.DataAccessLayer.Repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import uk.ac.leeds.comp2913.api.Domain.Model.ActivityType;
@Repository
public interface ActivityTypeRepository extends JpaRepository<ActivityType, Long> {
Page<ActivityType> findByResourceId(Pageable pageable, Long resource_id);
}
| true |
df275257fbd034b52d8a1f1d05a4e9cec12cfc83 | Java | openanthem-admin/prev-nimbus-core | /nimbus-extn-activiti/src/main/java/com/anthem/nimbus/platform/core/extension/activiti/AssignmentUserTask.java | UTF-8 | 2,272 | 1.851563 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* Copyright 2016-2018 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package com.anthem.nimbus.platform.core.extension.activiti;
import org.activiti.designer.integration.annotation.Help;
import org.activiti.designer.integration.annotation.Property;
import org.activiti.designer.integration.annotation.TaskName;
import org.activiti.designer.integration.annotation.TaskNames;
import org.activiti.designer.integration.servicetask.PropertyType;
import org.activiti.designer.integration.usertask.AbstractCustomUserTask;
/**
*
* @author Jayant Chaudhuri
*
*/
@Help(displayHelpShort = "Represents a task that can be assigned to a user/queue", displayHelpLong = "Represents a task that can be assigned to a user/queue")
@TaskNames(
{
@TaskName(locale = "en", name = "Represents a task that can be assigned to a user/queue"),
}
)
public class AssignmentUserTask extends AbstractCustomUserTask {
public static final String KEY = "assignment";
@Property(type=PropertyType.MULTILINE_TEXT, displayName="URL", required=true)
@Help(displayHelpShort="Command URL")
private String url;
@Property(type=PropertyType.MULTILINE_TEXT, displayName="Exit Condition", required=false)
@Help(displayHelpShort="Exit Condition")
private String exitCondition;
@Property(type=PropertyType.MULTILINE_TEXT, displayName="Eval URL", required=false)
@Help(displayHelpShort="URL to be evaluated on State Change")
private String evalURLs;
@Override
public String contributeToPaletteDrawer() {
return "Nimbus - User Task";
}
public String getName() {
return "Assignment Task";
}
@Override
public String getSmallIconPath() {
return "icons/userTask.png";
}
} | true |
d04442c31c49f3ae0434306e572ca47c4bf69e2a | Java | Anandharaj0930/MicroServicesProject | /sample-microservice-image/src/main/java/it/sella/sample/microservice/image/samplemicroserviceimage/ImageList.java | UTF-8 | 919 | 2.21875 | 2 | [] | no_license | package it.sella.sample.microservice.image.samplemicroserviceimage;
import java.util.List;
/**
* Created by gbs04154 on 07-01-2019.
*/
public class ImageList {
private List<Image> images;
private String port;
private String serviceName;
public ImageList(final List<Image> images, final String port, final String serviceName) {
this.images = images;
this.port = port;
this.serviceName = serviceName;
}
public List<Image> getImages() {
return images;
}
public void setImages(final List<Image> images) {
this.images = images;
}
public String getPort() {
return port;
}
public void setPort(final String port) {
this.port = port;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
}
| true |
f9c162dd9af1ca8342c7f5790ab69db096bea27e | Java | cubo2411vn/WebTraiCay | /src/java/dao/HoaDonDAO.java | UTF-8 | 4,361 | 2.609375 | 3 | [] | no_license | /*
* 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 dao;
import connect.DBConnect;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.HoaDon;
import model.CT_HoaDon;
/**
*
* @author SinoMax
*/
public class HoaDonDAO {
public ArrayList<HoaDon> getListBill() {
try {
Connection connection = DBConnect.getConnecttion();
String sql = "SELECT * FROM dondathang";
PreparedStatement ps = connection.prepareCall(sql);
ResultSet rs = ps.executeQuery();
ArrayList<HoaDon> list = new ArrayList<>();
while (rs.next()) {
HoaDon bill = new HoaDon();
bill.setMaddh(rs.getLong("maddh"));
bill.setMakh(rs.getLong("makh"));
bill.setTongtien(rs.getDouble("tongtien"));
bill.setDiachi(rs.getString("diachi"));
bill.setNgaydat(rs.getTimestamp("ngaydat"));
list.add(bill);
}
return list;
} catch (SQLException ex) {
Logger.getLogger(HoaDonDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public HoaDon getHoaDon(long maddh) {
try {
Connection connection = DBConnect.getConnecttion();
String sql = "SELECT * FROM dondathang WHERE maddh='" + maddh + "'";
PreparedStatement ps = connection.prepareCall(sql);
ResultSet rs = ps.executeQuery();
HoaDon bill = new HoaDon();
while (rs.next()) {
bill.setMaddh(rs.getLong("maddh"));
bill.setMaddh(rs.getLong("maddh"));
bill.setMakh(rs.getLong("makh"));
bill.setTongtien(rs.getDouble("tongtien"));
bill.setDiachi(rs.getString("diachi"));
bill.setNgaydat(rs.getTimestamp("ngaydat"));
}
return bill;
} catch (SQLException ex) {
Logger.getLogger(HoaDonDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public void insertBill(HoaDon bill) throws SQLException {
Connection connection = DBConnect.getConnecttion();
String sql = "INSERT INTO dondathang VALUES(?,?,?,?,?)";
PreparedStatement ps = connection.prepareCall(sql);
ps.setLong(1, bill.getMaddh());
ps.setLong(2, bill.getMakh());
ps.setDouble(3, bill.getTongtien());
ps.setString(4, bill.getDiachi());
ps.setTimestamp(5, bill.getNgaydat());
ps.executeUpdate();
}
public boolean delete(long maddh){
Connection connection = DBConnect.getConnecttion();
String sql = "DELETE FROM dondathang WHERE maddh = ?";
try {
PreparedStatement ps = connection.prepareCall(sql);
ps.setLong(1, maddh);
int temp = ps.executeUpdate();
return temp == 1;
} catch (SQLException e) {
}
return false;
}
public static void main(String[] args) throws SQLException {
HoaDonDAO dao = new HoaDonDAO();
for(HoaDon p : dao.getListBill()){
System.out.println(p.getMaddh()+ " - "+p.getTongtien());
}
}
}
| true |
ed1f459aa6b7f1009f951838e7769eeef0cb550e | Java | lamadipen/Algo | /CrackingCode/MasterAlgorithm/src/test/java/com/dp/cci/graphandtrees/ValidateBSTTest.java | UTF-8 | 1,110 | 2.84375 | 3 | [] | no_license | package com.dp.cci.graphandtrees;
import org.junit.Before;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ValidateBSTTest {
private ValidateBST validateBST;
private TreeNode start, end, node1, node2, node3, node4, node5;
@Before
public void setUp() {
validateBST = new ValidateBST();
start = new TreeNode(10);
node1 = new TreeNode(5);
node2 = new TreeNode(15);
node3 = new TreeNode(2);
node4 = new TreeNode(7);
node5 = new TreeNode(12);
end = new TreeNode(18);
start.leftNode = node1;
start.rightNode = node2;
node1.leftNode = node3;
node1.rightNode = node4;
node2.leftNode = node5;
}
@Test
public void isValidBST_successful() {
assertTrue(validateBST.isValidBSTInorderTracersal(start));
}
@Test
public void isValidBST_unsuccessful() {
node3.rightNode = end;
assertFalse(validateBST.isValidBSTInorderTracersal(start));
}
}
| true |
07d33a8a39d0fd09503bf8a00762460f5e2c6bba | Java | erdo/android-fore | /app-examples/example-jv-06db/src/main/java/foo/bar/example/foredb/OG.java | UTF-8 | 3,754 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | package foo.bar.example.foredb;
import android.app.Application;
import java.util.HashMap;
import java.util.Map;
import co.early.fore.core.WorkMode;
import co.early.fore.core.logging.AndroidLogger;
import co.early.fore.core.logging.Logger;
import co.early.fore.core.time.SystemTimeWrapper;
import co.early.fore.net.retrofit2.CallProcessorRetrofit2;
import co.early.fore.net.InterceptorLogging;
import foo.bar.example.foredb.api.CustomGlobalErrorHandler;
import foo.bar.example.foredb.api.CustomGlobalRequestInterceptor;
import foo.bar.example.foredb.api.CustomRetrofitBuilder;
import foo.bar.example.foredb.api.todoitems.TodoItemService;
import foo.bar.example.foredb.db.todoitems.TodoItemDatabase;
import foo.bar.example.foredb.feature.bossmode.BossMode;
import foo.bar.example.foredb.feature.remote.RemoteWorker;
import foo.bar.example.foredb.feature.todoitems.TodoListModel;
import foo.bar.example.foredb.message.UserMessage;
import retrofit2.Retrofit;
import static co.early.fore.core.Affirm.notNull;
/**
*
* OG - Object Graph, pure DI implementation
*
* Copyright © 2019 early.co. All rights reserved.
*/
public class OG {
private static boolean initialized = false;
private static final Map<Class<?>, Object> dependencies = new HashMap<>();
public static void setApplication(Application application) {
setApplication(application, WorkMode.ASYNCHRONOUS);
}
public static void setApplication(Application application, final WorkMode workMode) {
notNull(application);
notNull(workMode);
// create dependency graph
AndroidLogger logger = new AndroidLogger("fore_");
SystemTimeWrapper systemTimeWrapper = new SystemTimeWrapper();
TodoItemDatabase todoItemDatabase = TodoItemDatabase.getInstance(
application,
false,
workMode);
TodoListModel todoListModel = new TodoListModel(
todoItemDatabase,
logger,
systemTimeWrapper,
workMode);
BossMode bossMode = new BossMode(
todoListModel,
systemTimeWrapper,
workMode,
logger);
Retrofit retrofit = CustomRetrofitBuilder.create(
new CustomGlobalRequestInterceptor(logger),
new InterceptorLogging(logger));//logging interceptor should be the last one
CallProcessorRetrofit2<UserMessage> callProcessor = new CallProcessorRetrofit2<UserMessage>(
new CustomGlobalErrorHandler(logger),
logger);
RemoteWorker remoteWorker = new RemoteWorker(
todoListModel,
retrofit.create(TodoItemService.class),
callProcessor,
systemTimeWrapper,
logger,
workMode);
// add models to the dependencies map if you will need them later
dependencies.put(BossMode.class, bossMode);
dependencies.put(TodoListModel.class, todoListModel);
dependencies.put(RemoteWorker.class, remoteWorker);
dependencies.put(Logger.class, logger);
}
public static void init() {
if (!initialized) {
initialized = true;
// run any necessary initialization code once object graph has been created here
get(TodoListModel.class).fetchLatestFromDb();
}
}
public static <T> T get(Class<T> model) {
notNull(model);
T t = model.cast(dependencies.get(model));
notNull(t);
return t;
}
public static <T> void putMock(Class<T> clazz, T object) {
notNull(clazz);
notNull(object);
dependencies.put(clazz, object);
}
}
| true |
a37837eb4dc7dab94125b9ec56a3b839df223ea6 | Java | CSPAIstatOrganization/EditRulesWrapper | /src/ddi/physicaldataproduct/_3_1/PhysicalStructureType.java | UTF-8 | 10,371 | 1.65625 | 2 | [] | no_license | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.08.22 at 02:00:24 PM CEST
//
package ddi.physicaldataproduct._3_1;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import ddi.reusable._3_1.ReferenceType;
import ddi.reusable._3_1.VersionableType;
/**
* Description of a physical structure .These are used by record layouts to describe the full structure of a physical instance.
*
* <p>Java class for PhysicalStructureType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PhysicalStructureType">
* <complexContent>
* <extension base="{ddi:reusable:3_1}VersionableType">
* <sequence>
* <element ref="{ddi:physicaldataproduct:3_1}LogicalProductReference" maxOccurs="unbounded"/>
* <element name="Format" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="DefaultDataType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="DefaultDelimiter" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="DefaultDecimalPositions" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/>
* <element ref="{ddi:physicaldataproduct:3_1}DefaultDecimalSeparator" minOccurs="0"/>
* <element ref="{ddi:physicaldataproduct:3_1}DefaultDigitGroupSeparator" minOccurs="0"/>
* <element name="DefaultMissingData" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element ref="{ddi:physicaldataproduct:3_1}GrossRecordStructure" maxOccurs="unbounded"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PhysicalStructureType", propOrder = {
"logicalProductReference",
"format",
"defaultDataType",
"defaultDelimiter",
"defaultDecimalPositions",
"defaultDecimalSeparator",
"defaultDigitGroupSeparator",
"defaultMissingData",
"grossRecordStructure"
})
public class PhysicalStructureType
extends VersionableType
{
@XmlElement(name = "LogicalProductReference", required = true)
protected List<ReferenceType> logicalProductReference;
@XmlElement(name = "Format")
protected String format;
@XmlElement(name = "DefaultDataType")
protected String defaultDataType;
@XmlElement(name = "DefaultDelimiter")
protected String defaultDelimiter;
@XmlElement(name = "DefaultDecimalPositions")
protected BigInteger defaultDecimalPositions;
@XmlElement(name = "DefaultDecimalSeparator")
protected String defaultDecimalSeparator;
@XmlElement(name = "DefaultDigitGroupSeparator")
protected String defaultDigitGroupSeparator;
@XmlElement(name = "DefaultMissingData")
protected String defaultMissingData;
@XmlElement(name = "GrossRecordStructure", required = true)
protected List<GrossRecordStructureType> grossRecordStructure;
/**
* References the logical data product that describes the intellectual content of this physical data product.Gets the value of the logicalProductReference property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the logicalProductReference property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLogicalProductReference().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ReferenceType }
*
*
*/
public List<ReferenceType> getLogicalProductReference() {
if (logicalProductReference == null) {
logicalProductReference = new ArrayList<ReferenceType>();
}
return this.logicalProductReference;
}
/**
* Gets the value of the format property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFormat() {
return format;
}
/**
* Sets the value of the format property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFormat(String value) {
this.format = value;
}
/**
* Gets the value of the defaultDataType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDefaultDataType() {
return defaultDataType;
}
/**
* Sets the value of the defaultDataType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDefaultDataType(String value) {
this.defaultDataType = value;
}
/**
* Gets the value of the defaultDelimiter property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDefaultDelimiter() {
return defaultDelimiter;
}
/**
* Sets the value of the defaultDelimiter property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDefaultDelimiter(String value) {
this.defaultDelimiter = value;
}
/**
* Gets the value of the defaultDecimalPositions property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getDefaultDecimalPositions() {
return defaultDecimalPositions;
}
/**
* Sets the value of the defaultDecimalPositions property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setDefaultDecimalPositions(BigInteger value) {
this.defaultDecimalPositions = value;
}
/**
* The character used to separate the integer and the fraction part of a number (if an explicit separator is used in the data) that is applied to the majority of the dataitems reducing the amount of repetitive markup required. It can be overridden at the dataitem level. Allowed values are: None (default), Dot, Comma, Other. On the basis of the data definition in DDI documents, data processing tools could compute the necessary precision width on the basis of the format width and the existence of separators. Appropriate data types could be used, i.e. float or double, short or long. The decimal separator definition only makes sense with some XML Schema primitives. This is a default which may be overridden in specific cases.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDefaultDecimalSeparator() {
return defaultDecimalSeparator;
}
/**
* Sets the value of the defaultDecimalSeparator property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDefaultDecimalSeparator(String value) {
this.defaultDecimalSeparator = value;
}
/**
* The character used to separate groups of digits (if an explicit separator is used in the data) that is applied to the majority of the dataitems reducing the amount of repetitive markup required. It can be overridden at the dataitem level. Allowed values are: None (default), Dot, Comma, Other. The decimal separator definition makes only sense with some XML Schema primitives. This is a default which may be overridden in specific cases.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDefaultDigitGroupSeparator() {
return defaultDigitGroupSeparator;
}
/**
* Sets the value of the defaultDigitGroupSeparator property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDefaultDigitGroupSeparator(String value) {
this.defaultDigitGroupSeparator = value;
}
/**
* Gets the value of the defaultMissingData property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDefaultMissingData() {
return defaultMissingData;
}
/**
* Sets the value of the defaultMissingData property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDefaultMissingData(String value) {
this.defaultMissingData = value;
}
/**
* Characteristics of the physical storage of a logical record, as described in the DataRelationship section of the logical product.Gets the value of the grossRecordStructure property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the grossRecordStructure property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getGrossRecordStructure().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link GrossRecordStructureType }
*
*
*/
public List<GrossRecordStructureType> getGrossRecordStructure() {
if (grossRecordStructure == null) {
grossRecordStructure = new ArrayList<GrossRecordStructureType>();
}
return this.grossRecordStructure;
}
}
| true |
1bbc09d2690614eeb6f1c524beacece2c3c09d0b | Java | wachi35676/Second-Semester-Codes | /OOP_Project/src/Restaurant.java | UTF-8 | 4,784 | 3.25 | 3 | [] | no_license | import java.util.ArrayList;
public class Restaurant extends User{
private String restaurantName;
private ArrayList<Food> menu;
private String fileName;
Restaurant(String userName, String password, String fileName, String restaurantName){
super(userName, password);
FileHandling fileHandling = new FileHandling();
this.restaurantName = restaurantName;
this.fileName = fileName;
menu = fileHandling.getFoodList(fileName);
}
public String checkOrders(ArrayList<Order> orders){
String str = "";
Integer bill = 0;
for (int i = 0; i < orders.size(); i++) {
if (orders.get(i).getRestaurantUserName().equals(getUserName())){
str += "Order " + i + ":\n";
str += orders.get(i).checkOrdersStatus();
bill += orders.get(i).getFood().getFoodPrice();
}
}
str += "Your Total Earnings: " + bill;
return str;
}
public void handleRestaurantOwner(ArrayList <Order> orders){
UserInterface userInterface = new UserInterface();
int options = 0;
do {
options = userInterface.getIntInput("1 --> Add Food\n2 --> Edit Food\n3 --> Delete Food\n4 --> Check Orders\n5 --> Update Orders Status\n0 --> Log Out\n");
switch (options) {
case 1: {
addFood();
break;
}
case 2: {
editRestaurant();
break;
}
case 3: {
removeItem();
break;
}
case 4:{
userInterface.givePrompt(checkOrders(orders));
break;
}
case 5:{
updateOrderStatus(orders);
}
}
}while (options != 0);
}
private void updateOrderStatus(ArrayList<Order>orders){
UserInterface userInterface = new UserInterface();
String str = "";
for (int i = 0; i < orders.size(); i++) {
if (orders.get(i).getRestaurantUserName().equals(getUserName()) && orders.get(i).getOrderStatus().equals("Order Requested From Restaurant")){
str += "Order " + i + ":\n";
str += orders.get(i).checkOrdersStatus();
}
}
int choice = userInterface.getIntInput(str + "Select an Order which is ready for delivery (-1 to exit)");
if(choice != -1) {
orders.get(choice).setOrderStatus("Ready. Waiting for rider to pick up.");
}
}
private void addFood() {
FileHandling fileHandling = new FileHandling();
UserInterface userInterface = new UserInterface();
if (getFullMenu().size()<=15) {
String foodName = userInterface.getInput("Enter Name of Food: ");
Integer foodPrice = userInterface.getIntInput("Enter Price of Food: ");
getFullMenu().add(new Food(foodName, foodPrice));
fileHandling.updateFoodList(getFileName(), getFullMenu());
}
else {
userInterface.givePrompt("Can not add anymore to the menu");
}
}
public ArrayList<Food> getFullMenu(){
return menu;
}
public String getMenu(){
String completeMenu = "";
for (int i = 0; i < menu.size(); i++) {
completeMenu += "Food Item " + i + ":\n" + menu.get(i).toString();
}
return completeMenu;
}
public String getRestaurantName() {
return restaurantName;
}
public String getFileName() {
return fileName;
}
public void editRestaurant(){
UserInterface userInterface = new UserInterface();
FileHandling fileHandling = new FileHandling();
int foodToEdit = userInterface.getIntInput(getMenu() + "\nEnter item number to Edit: ");
String foodName = userInterface.getInput("Enter Name of Food: ");
Integer foodPrice = userInterface.getIntInput("Enter Price of Food: ");
getFullMenu().set(foodToEdit,new Food(foodName, foodPrice));
fileHandling.updateFoodList(getFileName(), getFullMenu());
}
public void removeItem(){
UserInterface userInterface = new UserInterface();
FileHandling fileHandling = new FileHandling();
int foodToRemove = userInterface.getIntInput(getMenu() + "\nEnter item number to remove: ");
getFullMenu().remove(foodToRemove);
fileHandling.updateFoodList(getFileName(), getFullMenu());
}
}
| true |
1850d7f9c310761479e577979e3134dd36dd2510 | Java | Anthony123asd/MovieCatalogue3 | /MovieCatalogue3/app/src/main/java/com/latihan/dicoding/moviecatalogue3/MainActivity.java | UTF-8 | 2,839 | 2.25 | 2 | [] | no_license | package com.latihan.dicoding.moviecatalogue3;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements MovieFragment.OnListFragmentInteractionListener {
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getSupportActionBar() == null) {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
if (hasNetwork(getApplicationContext()) != true) {
Toast.makeText(this, "Anda tidak terkoneksi ke internet!", Toast.LENGTH_LONG);
}
// Set up the ViewPager with the sections adapter.
ViewPager mViewPager;
mViewPager = findViewById(R.id.container);
TabLayout mTabLayout;
mTabLayout = findViewById(R.id.tabs);
TabAdapter mTabAdapter;
mTabAdapter = new TabAdapter(getSupportFragmentManager());
mTabAdapter.addFragment(new MovieFragment(), "Movie");
mTabAdapter.addFragment(new MovieFragment(), "TV Show");
mViewPager.setAdapter(mTabAdapter);
mViewPager.setAdapter(mTabAdapter);
mTabLayout.setupWithViewPager(mViewPager);
}
@Override
public void onListFragmentInteraction() {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_change_settings) {
Intent mIntent = new Intent(Settings.ACTION_LOCALE_SETTINGS);
startActivity(mIntent);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
public boolean hasNetwork(Context context) {
boolean isConnected = false; // Initial Value
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
isConnected = true;
}
return isConnected;
}
}
| true |
6a3af28448a55dfa1cb5a3a4bffaebd138097235 | Java | 210712jwa/Project0_ColtenMurray | /src/test/java/com/revature/service/ClientServiceTest.java | UTF-8 | 10,268 | 2.75 | 3 | [] | no_license | package com.revature.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
// You may need to type this import manually to make use of
// the argument matchers for Mockito, such as eq() or any()
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.revature.dao.AccountDAO;
import com.revature.dao.ClientDAO;
import com.revature.dto.AddOrEditClientDTO;
import com.revature.exception.BadParameterException;
import com.revature.exception.DatabaseException;
import com.revature.exception.ClientNotFoundException;
import com.revature.model.Account;
import com.revature.model.Client;
public class ClientServiceTest {
private ClientService clientService;
private ClientDAO clientDao;
private AccountDAO accountDao;
@Before
public void setUp() throws Exception {
this.clientDao = mock(ClientDAO.class); // I'm using Mockito to create a fake clientDao object
this.accountDao = mock(AccountDAO.class);
this.clientService = new ClientService(clientDao, accountDao); // Here I am injecting the mocked object into a ClientService object
}
/*
* getAllClients
*/
@Test
public void test_getAllClients_positive() throws DatabaseException, SQLException {
// Because we're not using a real ClientDAO object and instead a mocked ClientDAO,
// we need to actually specify what we want the mocked ClientDAO to return whenever we invoke the clientDao.getAllClients() method
List<Client> mockReturnValues = new ArrayList<>();
mockReturnValues.add(new Client(1, "Black Pearl", 40));
mockReturnValues.add(new Client(2, "Royal Fortune", 10));
when(clientDao.getAllClients()).thenReturn(mockReturnValues);
List<Account> blackPearlAccounts = new ArrayList<>();
blackPearlAccounts.add(new Account(1, "Jack Sparrow", 28, 1));
blackPearlAccounts.add(new Account(2, "Captain Hook", 60, 1));
when(accountDao.getAllAccountsFromClient(eq(1))).thenReturn(blackPearlAccounts);
List<Account> royalFortuneAccounts = new ArrayList<>();
royalFortuneAccounts.add(new Account(10, "test1", 100, 2));
royalFortuneAccounts.add(new Account(53, "test2", 101, 2));
when(accountDao.getAllAccountsFromClient(eq(2))).thenReturn(royalFortuneAccounts);
// actual = the real data being returned by the getAllClients method from clientService
List<Client> actual = clientService.getAllClients();
System.out.println(actual);
// expected = what we expect for the clients List to contain
List<Client> expected = new ArrayList<>();
Client s1 = new Client(1, "Black Pearl", 40);
s1.setAccounts(blackPearlAccounts);
Client s2 = new Client(2, "Royal Fortune", 10);
s2.setAccounts(royalFortuneAccounts);
expected.add(s1);
expected.add(s2);
// So, we do an assertEquals, to have these two compared to each other
assertEquals(expected, actual);
}
@Test
public void test_getAllClients_negative() throws SQLException {
when(clientDao.getAllClients()).thenThrow(SQLException.class);
// Simulate a situation where clientDao.getAllClients() throws a SQLException
try {
clientService.getAllClients();
fail(); // We only reach the fail() assertion IF DatabaseException is not thrown and caught
// So this allows us to test for the DatabaseException occurring.
// Additionally, in the catch block, we're also checking the exception message itself
} catch (DatabaseException e) {
String exceptionMessage = e.getMessage();
assertEquals("Something went wrong with our DAO operations", exceptionMessage);
}
}
/*
* getClientById
*/
@Test
public void test_getClientById_idStringIsNotAnInt() throws DatabaseException, ClientNotFoundException {
try {
clientService.getClientById("asdfasdf");
fail();
} catch (BadParameterException e) {
assertEquals("asdfasdf was passed in by the user as the id, but it is not an int", e.getMessage());
}
}
@Test
public void test_getClientById_existingId() throws SQLException, DatabaseException, ClientNotFoundException, BadParameterException {
when(clientDao.getClientById(eq(1))).thenReturn(new Client(1, "Black Pearl", 1));
Client actual = clientService.getClientById("1");
Client expected = new Client(1, "Black Pearl", 1);
expected.setAccounts(new ArrayList<>());
assertEquals(expected, actual);
}
@Test
public void test_getClientById_clientDoesNotExist() throws DatabaseException, ClientNotFoundException, BadParameterException {
try {
clientService.getClientById("10"); // Because I'm not providing a mock response for getClientId when the int parameter
// passed into that method is 10, it will by default return a null value
fail();
} catch (ClientNotFoundException e) {
assertEquals("Client with id 10 was not found", e.getMessage());
}
}
@Test
public void test_getClientById_sqlExceptionEncountered() throws SQLException, ClientNotFoundException, BadParameterException {
try {
when(clientDao.getClientById(anyInt())).thenThrow(SQLException.class);
clientService.getClientById("1");
fail();
} catch (DatabaseException e) {
assertEquals("Something went wrong with our DAO operations", e.getMessage());
}
}
/*
* addClient
*/
@Test
public void test_addClient_positivePath() throws SQLException, DatabaseException, BadParameterException {
AddOrEditClientDTO dto = new AddOrEditClientDTO();
dto.setName("Black Pearl");
dto.setAge(10);
when(clientDao.addClient(eq(dto))).thenReturn(new Client(1, "Black Pearl", 10));
Client actual = clientService.addClient(dto);
Client expected = new Client(1, "Black Pearl", 10);
expected.setAccounts(new ArrayList<>());
assertEquals(expected, actual);
}
@Test
public void test_addClient_blankName() throws DatabaseException {
AddOrEditClientDTO dto = new AddOrEditClientDTO();
dto.setName("");
dto.setAge(10);
try {
clientService.addClient(dto);
fail();
} catch (BadParameterException e) {
assertEquals("Client name cannot be blank", e.getMessage());
}
}
@Test
public void test_addClient_blankNameWithSpaces() throws DatabaseException {
AddOrEditClientDTO dto = new AddOrEditClientDTO();
dto.setName(" ");
dto.setAge(10);
try {
clientService.addClient(dto);
fail();
} catch (BadParameterException e) {
assertEquals("Client name cannot be blank", e.getMessage());
}
}
@Test
public void test_addClient_negativeAge() throws DatabaseException {
AddOrEditClientDTO dto = new AddOrEditClientDTO();
dto.setName("Bach's Client");
dto.setAge(-1);
try {
clientService.addClient(dto);
fail();
} catch (BadParameterException e) {
assertEquals("Client age cannot be less than 0", e.getMessage());
}
}
@Test
public void test_addClient_negativeAgeAndBlankName() throws DatabaseException {
AddOrEditClientDTO dto = new AddOrEditClientDTO();
dto.setName("");
dto.setAge(-10);
try {
clientService.addClient(dto);
fail();
} catch (BadParameterException e) {
assertEquals("Client name cannot be blank and age cannot be less than 0", e.getMessage());
}
}
@Test(expected = DatabaseException.class)
public void test_addClient_SQLExceptionEncountered() throws SQLException, DatabaseException, BadParameterException {
when(clientDao.addClient(any())).thenThrow(SQLException.class);
AddOrEditClientDTO dto = new AddOrEditClientDTO();
dto.setName("Black Pearl");
dto.setAge(10);
clientService.addClient(dto);
}
/*
* editClient
*/
@Test
public void test_editClient_positivePath() throws DatabaseException, ClientNotFoundException, BadParameterException, SQLException {
AddOrEditClientDTO dto = new AddOrEditClientDTO();
dto.setName("Black Pearl");
dto.setAge(100);
Client clientWithId10 = new Client(10, "Jolly Roger", 5);
when(clientDao.getClientById(eq(10))).thenReturn(clientWithId10);
when(clientDao.editClient(eq(10), eq(dto))).thenReturn(new Client(10, "Black Pearl", 100));
Client actual = clientService.editClient("10", dto);
Client expected = new Client(10, "Black Pearl", 100);
expected.setAccounts(new ArrayList<>());
assertEquals(expected, actual);
}
@Test
public void test_editClient_clientDoesNotExist() throws DatabaseException, BadParameterException {
AddOrEditClientDTO dto = new AddOrEditClientDTO();
dto.setName("Black Pearl");
dto.setAge(100);
try {
clientService.editClient("1000", dto);
fail();
} catch (ClientNotFoundException e) {
assertEquals("Client with id 1000 was not found", e.getMessage());
}
}
@Test(expected = BadParameterException.class)
public void test_editClient_invalidId() throws DatabaseException, ClientNotFoundException, BadParameterException {
AddOrEditClientDTO dto = new AddOrEditClientDTO();
dto.setName("Black Pearl");
dto.setAge(100);
clientService.editClient("abc", dto);
}
@Test(expected = DatabaseException.class)
public void test_editClient_SQLExceptionEncountered() throws SQLException, DatabaseException, ClientNotFoundException, BadParameterException {
AddOrEditClientDTO dto = new AddOrEditClientDTO();
dto.setName("Black Pearl");
dto.setAge(100);
when(clientDao.getClientById(eq(10))).thenReturn(new Client(10, "Jolly Roger", 5));
when(clientDao.editClient(eq(10), eq(dto))).thenThrow(SQLException.class);
clientService.editClient("10", dto);
}
@Test
public void test_deleteClient_clientDoesNotExist() throws DatabaseException, BadParameterException {
try {
clientService.deleteClient("1000");
fail();
} catch (ClientNotFoundException e) {
assertEquals("Trying to delete client with an id of 1000, but it does not exist", e.getMessage());
}
}
@Test(expected = BadParameterException.class)
public void test_deleteClient_invalidId() throws DatabaseException, ClientNotFoundException, BadParameterException {
clientService.deleteClient("abc");
}
/*
* Exercise: Create tests for DeleteClient and have full test coverage
*/
}
| true |
cd045b8e52a3230c7df16227dbd8d8dedefa4027 | Java | lannerson/java-estoque | /sgps/src/sgps/classeMapeada/Cidade.java | UTF-8 | 2,779 | 2.171875 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sgps.classeMapeada;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* @author martins
*/
@Entity
@Table(name = "CIDADE", catalog = "sgps", schema = "")
@NamedQueries({
@NamedQuery(name = "Cidade.findAll", query = "SELECT c FROM Cidade c"),
@NamedQuery(name = "Cidade.findByIdcidade", query = "SELECT c FROM Cidade c WHERE c.cidadePK.idcidade = :idcidade"),
@NamedQuery(name = "Cidade.findByNomecidade", query = "SELECT c FROM Cidade c WHERE c.cidadePK.nomecidade = :nomecidade")})
public class Cidade implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected CidadePK cidadePK;
@OneToMany(mappedBy = "cidade")
private List<Endereco> enderecoList;
@JoinColumn(name = "SIGLAESTADOCIDADE", referencedColumnName = "IDESTADO")
@ManyToOne
private Uf siglaestadocidade;
public Cidade() {
}
public Cidade(CidadePK cidadePK) {
this.cidadePK = cidadePK;
}
public Cidade(int idcidade, String nomecidade) {
this.cidadePK = new CidadePK(idcidade, nomecidade);
}
public CidadePK getCidadePK() {
return cidadePK;
}
public void setCidadePK(CidadePK cidadePK) {
this.cidadePK = cidadePK;
}
public List<Endereco> getEnderecoList() {
return enderecoList;
}
public void setEnderecoList(List<Endereco> enderecoList) {
this.enderecoList = enderecoList;
}
public Uf getSiglaestadocidade() {
return siglaestadocidade;
}
public void setSiglaestadocidade(Uf siglaestadocidade) {
this.siglaestadocidade = siglaestadocidade;
}
@Override
public int hashCode() {
int hash = 0;
hash += (cidadePK != null ? cidadePK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Cidade)) {
return false;
}
Cidade other = (Cidade) object;
if ((this.cidadePK == null && other.cidadePK != null) || (this.cidadePK != null && !this.cidadePK.equals(other.cidadePK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "sgps.classeMapeada.Cidade[cidadePK=" + cidadePK + "]";
}
}
| true |
f8c34a0e6af4d809692afe0a2427a1afe99b1240 | Java | alesaudate/contas | /src/main/java/br/com/alesaudate/contas/interfaces/incoming/DateCorrectionReader.java | UTF-8 | 2,160 | 2.765625 | 3 | [] | no_license | package br.com.alesaudate.contas.interfaces.incoming;
import br.com.alesaudate.contas.domain.Document;
import br.com.alesaudate.contas.domain.Entry;
import br.com.alesaudate.contas.utils.Dates;
import lombok.AllArgsConstructor;
import java.io.IOException;
import java.text.ParseException;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;
@AllArgsConstructor
public class DateCorrectionReader implements DataReader {
DataReader underlying;
@Override
public boolean fileIsCorrect(byte[] data) {
return underlying.fileIsCorrect(data);
}
@Override
public Document loadDocument(byte[] data) throws IOException, ParseException {
Document loaded = underlying.loadDocument(data);
List<Entry> entries = loaded.getEntries().stream().sorted(Comparator.comparing(Entry::getDate)).collect(Collectors.toList());
LocalDate compareDate = LocalDate.now();
if (someItemsAheadOfGivenDate(entries, compareDate)) {
int correctYear = getCorrectYear(entries);
entries.stream().forEach(entry -> correctDate(entry, correctYear, compareDate));
}
return loaded;
}
private int getCorrectYear(List<Entry> entries) {
List<Integer> years = entries.stream().map(entry -> Dates.localDate(entry.getDate()).getYear()).distinct().sorted(Integer::compareTo).collect(Collectors.toList());
return years.size() == 1 ? years.get(0) - 1 : years.get(0);
}
private boolean someItemsAheadOfGivenDate(List<Entry> entries, LocalDate compareDate) {
int currentMonth = compareDate.getMonthValue();
return entries.stream().filter(entry -> Dates.localDate(entry.getDate()).getMonthValue() > currentMonth).findAny().isPresent();
}
private void correctDate(Entry entry, int correctYear, LocalDate compareDate) {
int nowMonth = compareDate.getMonthValue();
LocalDate entryDate = Dates.localDate(entry.getDate());
if (entryDate.getMonthValue() > nowMonth) {
entryDate = entryDate.withYear(correctYear);
entry.setDate(Dates.date(entryDate));
}
}
}
| true |
03883bfd60ba25013dcf8ec081c59689c7db324c | Java | msins/questionnaire | /src/main/java/edu/fer/project/questionnaire/model/Question.java | UTF-8 | 2,454 | 2.609375 | 3 | [] | no_license | package edu.fer.project.questionnaire.model;
import java.util.Comparator;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
@Entity
public class Question {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Column
private String text;
@Column
private Type type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "scenario_id")
private Scenario scenario;
@OneToMany(mappedBy = "question", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("ordering ASC")
private SortedSet<Choice> choices = new TreeSet<>(Comparator.comparingInt(Choice::getOrdering));
public Question() {
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Scenario getScenario() {
return scenario;
}
public void setScenario(Scenario scenario) {
this.scenario = scenario;
}
public SortedSet<Choice> getChoices() {
return choices;
}
public void addChoice(Choice choice) {
this.choices.add(choice);
choice.setQuestion(this);
}
public void removeChoice(Choice choice) {
this.choices.remove(choice);
choice.setQuestion(null);
}
@Override
public String toString() {
return text;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Question)) {
return false;
}
Question question = (Question) o;
return Objects.equals(text, question.text);
}
@Override
public int hashCode() {
return Objects.hash(text);
}
public enum Type {
MULTIPLE_CHOICE("Multiple choices"),
SCALING("Scaling question");
@Column
private String name;
Type(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
| true |
88d57ad11fbb262bfcc46eab771e5c35a727ab82 | Java | dembanakh/mana-wars | /core/test/com/mana_wars/presentation/presenters/BattlePresenterTest.java | UTF-8 | 4,291 | 2.1875 | 2 | [
"MIT"
] | permissive | package com.mana_wars.presentation.presenters;
import com.mana_wars.model.entity.battle.data.ReadableBattleSummaryData;
import com.mana_wars.model.entity.battle.participant.BattleParticipant;
import com.mana_wars.model.entity.battle.participant.BattleParticipantData;
import com.mana_wars.model.entity.skills.ActiveSkill;
import com.mana_wars.model.interactor.BattleInteractor;
import com.mana_wars.presentation.view.BattleView;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicInteger;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class BattlePresenterTest {
private BattlePresenter presenter;
@Mock
private BattleView view;
@Mock
private BattleInteractor interactor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
presenter = new BattlePresenter(view, interactor, Runnable::run);
}
@Test
public void testApplyUserSkill_Failure() {
ActiveSkill skill = mock(ActiveSkill.class);
when(interactor.tryApplyUserSkill(skill)).thenReturn(false);
presenter.applyUserSkill(skill, 0);
verifyNoMoreInteractions(view);
}
@Test
public void testApplyUserSkill_Success() {
ActiveSkill skill = mock(ActiveSkill.class);
when(interactor.tryApplyUserSkill(skill)).thenReturn(true);
presenter.applyUserSkill(skill, 0);
verify(view).blockSkills(0);
}
@Test
public void testOnStartBattle() {
ReadableBattleSummaryData data = mock(ReadableBattleSummaryData.class);
when(interactor.getFinishBattleObservable()).thenAnswer((Answer<Single<ReadableBattleSummaryData>>)
invocation -> Single.just(data));
when(interactor.getEnemiesNumber()).thenReturn(2);
presenter.onStartBattle();
verify(view).startBattle(2);
verify(view).finishBattle(data);
}
@Test
public void testSetOpponents() {
BattleParticipant user = mock(BattleParticipant.class);
Subject<Integer> health = PublishSubject.create();
when(user.getHealthObservable()).thenReturn(health);
BattleParticipantData data = mock(BattleParticipantData.class);
when(user.getData()).thenReturn(data);
AtomicInteger viewHealth = new AtomicInteger();
when(view.setUser(data)).thenAnswer((Answer<Consumer<? extends Integer>>) invocation -> viewHealth::set);
when(user.getCurrentTarget()).thenReturn(2);
presenter.setOpponents(user, Collections.emptyList());
assertEquals(0, viewHealth.get());
health.onNext(100);
assertEquals(100, viewHealth.get());
verify(view).cleanEnemies();
verify(view).setEnemyCount(0);
verify(view).setActiveEnemy(2);
}
@Test
public void testSetEnemies() {
BattleParticipant enemy = mock(BattleParticipant.class);
Subject<Integer> health = PublishSubject.create();
when(enemy.getHealthObservable()).thenReturn(health);
BattleParticipantData data = mock(BattleParticipantData.class);
when(enemy.getData()).thenReturn(data);
AtomicInteger viewHealth = new AtomicInteger();
when(view.addEnemy(data)).thenAnswer((Answer<Consumer<? extends Integer>>) invocation -> viewHealth::set);
presenter.setEnemies(Collections.singletonList(enemy), 2);
verify(view).cleanEnemies();
verify(view).setEnemyCount(1);
verify(view).setActiveEnemy(2);
assertEquals(0, viewHealth.get());
health.onNext(100);
assertEquals(100, viewHealth.get());
}
@Test
public void testChangeActiveEnemy() {
when(interactor.changeUserTarget()).thenReturn(2);
presenter.changeActiveEnemy();
verify(view).setActiveEnemy(2);
}
} | true |
e3c62dbd8dd1f0f98d32a0e028f7e3872bdde99d | Java | ertugrulozcan/LogicalCircuitSimulator | /aero/logicsimulator/GUI/DesignPanel.java | ISO-8859-9 | 4,436 | 2.484375 | 2 | [] | no_license | package aero.logicsimulator.GUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import aero.logicsimulator.program.Logger;
import aero.logicsimulator.program.Program;
public class DesignPanel extends JPanel
{
private static final long serialVersionUID = 1L;
//
// Deikenler, sabitler, snf yeleri
//
private static JTabbedPane tabbedPane;
private static ImageIcon closeButtonIcon = null;
private static ImageIcon closeButtonHoverIcon = null;
public DesignPanel()
{
this.InitializeAssets();
this.setLayout(new BorderLayout());
this.tabbedPane = new JTabbedPane();
this.add(this.tabbedPane);
this.tabbedPane.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
if(tabbedPane.getTabCount() == 0)
{
AddStartPageTab();
}
}
});
AddStartPageTab();
}
private void InitializeAssets()
{
String assetsPath;
try
{
assetsPath = URLDecoder.decode(getClass().getClassLoader().getResource(".").getPath() + "Assets", "utf-8");
closeButtonIcon = new ImageIcon(ImageIO.read(new File(assetsPath + "/Icons/close.png")));
closeButtonHoverIcon = new ImageIcon(ImageIO.read(new File(assetsPath + "/Icons/close_hover.png")));
}
catch (UnsupportedEncodingException e)
{}
catch (IOException e)
{}
}
public static void AddNewTab(String tabTitle)
{
tabbedPane.addTab(tabTitle, new DesignBoard());
JPanel pnlTab = new JPanel(new GridBagLayout());
pnlTab.setOpaque(false);
JLabel lblTitle = new JLabel(tabTitle);
lblTitle.setBorder(new EmptyBorder(3, 0, 3, 20));
JLabel closeButton = new JLabel(closeButtonIcon);
closeButton.setPreferredSize(new Dimension(10, 10));
closeButton.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent e)
{
closeButton.setIcon(closeButtonHoverIcon);
}
@Override
public void mouseExited(MouseEvent e)
{
closeButton.setIcon(closeButtonIcon);
}
@Override
public void mouseClicked(MouseEvent e)
{
tabbedPane.remove(tabbedPane.getSelectedIndex());
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
pnlTab.add(lblTitle, gbc);
gbc.gridx++;
gbc.weightx = 0;
pnlTab.add(closeButton, gbc);
tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, pnlTab);
tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
}
public static void AddStartPageTab()
{
String tabTitle = Program.strings.start;
tabbedPane.addTab(tabTitle, new StartPage());
JPanel pnlTab = new JPanel(new GridBagLayout());
pnlTab.setOpaque(false);
JLabel lblTitle = new JLabel(tabTitle);
lblTitle.setBorder(new EmptyBorder(3, 0, 3, 20));
JLabel closeButton = new JLabel(closeButtonIcon);
closeButton.setPreferredSize(new Dimension(10, 10));
closeButton.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent e)
{
closeButton.setIcon(closeButtonHoverIcon);
}
@Override
public void mouseExited(MouseEvent e)
{
closeButton.setIcon(closeButtonIcon);
}
@Override
public void mouseClicked(MouseEvent e)
{
tabbedPane.remove(tabbedPane.getSelectedIndex());
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
pnlTab.add(lblTitle, gbc);
gbc.gridx++;
gbc.weightx = 0;
pnlTab.add(closeButton, gbc);
tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, pnlTab);
}
}
| true |
29e23326f7f82f96706555fb1894f55fd8e1c95f | Java | limidata/geekstore | /src/main/java/io/geekstore/service/ProductOptionService.java | UTF-8 | 2,153 | 2.078125 | 2 | [
"MIT"
] | permissive | /*
* Copyright (c) 2020 GeekStore.
* All rights reserved.
*/
package io.geekstore.service;
import io.geekstore.common.utils.BeanMapper;
import io.geekstore.entity.ProductOptionEntity;
import io.geekstore.entity.ProductOptionGroupEntity;
import io.geekstore.mapper.ProductOptionEntityMapper;
import io.geekstore.mapper.ProductOptionGroupEntityMapper;
import io.geekstore.service.helpers.ServiceHelper;
import io.geekstore.types.product.CreateProductOptionInput;
import io.geekstore.types.product.UpdateProductOptionInput;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created on Nov, 2020 by @author bobo
*/
@Service
@RequiredArgsConstructor
public class ProductOptionService {
private final ProductOptionEntityMapper productOptionEntityMapper;
private final ProductOptionGroupEntityMapper productOptionGroupEntityMapper;
public List<ProductOptionEntity> findAll() {
return this.productOptionEntityMapper.selectList(null);
}
public ProductOptionEntity findOne(Long id) {
return this.productOptionEntityMapper.selectById(id);
}
public ProductOptionEntity create(CreateProductOptionInput input) {
ServiceHelper.getEntityOrThrow(
productOptionGroupEntityMapper, ProductOptionGroupEntity.class, input.getProductOptionGroupId());
ProductOptionEntity productOptionEntity = new ProductOptionEntity();
productOptionEntity.setCode(input.getCode());
productOptionEntity.setName(input.getName());
productOptionEntity.setGroupId(input.getProductOptionGroupId());
productOptionEntityMapper.insert(productOptionEntity);
return productOptionEntity;
}
public ProductOptionEntity update(UpdateProductOptionInput input) {
ProductOptionEntity productOptionEntity = ServiceHelper.getEntityOrThrow(
productOptionEntityMapper, ProductOptionEntity.class, input.getId()
);
BeanMapper.patch(input, productOptionEntity);
productOptionEntityMapper.updateById(productOptionEntity);
return productOptionEntity;
}
}
| true |
443ab2266199a9c0ef810d171d642a3efc93196e | Java | qq329169773/LimitQuery | /src/main/java/com/jd/MethodLimit/limit/A.java | UTF-8 | 2,989 | 3.203125 | 3 | [] | no_license | package com.jd.MethodLimit.limit;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 漏桶算法实现
*
* @author win7zr
*/
class LimitBuck {
private double maxCapacity; // 允许最大容量
private double warnCapacity; // 设置的报警容量
private double rate;
private long lastAddTokenTimeStamp = 0l ;
private long initTimeSeconds = 0l;
private double tokens;
private int addTokenTimes = 0 ;
public static LimitBuck initLimitBuck(int maxCapacity, int warnCapacity){
return new LimitBuck(maxCapacity,warnCapacity);
}
private LimitBuck(int maxCapacity, int warnCapacity) {
super();
this.maxCapacity = maxCapacity;
this.warnCapacity = warnCapacity;
this.rate = maxCapacity / 1000.0;
this.initTimeSeconds = System.currentTimeMillis() / 1000;
this.addTokenTimes = 0 ;
this.lastAddTokenTimeStamp = System.currentTimeMillis() ;
}
private void clearn(long currentTime){
this.tokens = 0.0d ;
this.initTimeSeconds = currentTime / 1000;
this.addTokenTimes = 0 ;
this.lastAddTokenTimeStamp = currentTime ;
}
private void createToken(){
long currentTime = System.currentTimeMillis();
if(tokens > maxCapacity || currentTime == lastAddTokenTimeStamp){
return ;
}else{
if(initTimeSeconds != (currentTime / 1000)){
//说明已经不是之前的那一秒钟
clearn(currentTime);
}
addTokenTimes++ ;
double addTokens = 0.0d ;
addTokens = (currentTime- lastAddTokenTimeStamp) * rate ;
System.out.println("第"+addTokenTimes+" 次添加Tokens ("+addTokens+")");
tokens += addTokens ;
lastAddTokenTimeStamp = currentTime;
}
}
synchronized boolean getToken() {
createToken();
if(tokens <= 0){
return false ;
}
--tokens;
System.out.println("可以执行当前的方法: tokens 还有: " + tokens);
return true ;
}
}
class TokenClient implements Runnable{
LimitBuck limitBuck ;
public TokenClient(LimitBuck limitBuck) {
super();
this.limitBuck = limitBuck;
}
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(30));
} catch (InterruptedException e) {
e.printStackTrace();
}
if(!limitBuck.getToken()){
System.out.println("没有足够的Token , 无法自行方法");
}
}
}
class AddInter implements Runnable{
AtomicInteger data ;
public AddInter(AtomicInteger data){
this.data = data ;
}
@Override
public void run() {
System.out.println(data.incrementAndGet());
}
}
public class A {
public static void main(String[] args) throws InterruptedException {
/* LimitBuck limitBuck = LimitBuck.initLimitBuck(800, 300);
for(int index = 0 ; index < 1000 ; index++ ){
new Thread(new TokenClient(limitBuck)).start();
}*/
AtomicInteger data = new AtomicInteger(0) ;
for(int index = 0 ; index < 10 ; index++){
new Thread(new AddInter(data)).start();
}
TimeUnit.SECONDS.sleep(10);
System.out.println(data);
}
}
| true |
7f6ed3a9fcaf4cc26ef0844a51579e0fa694bb6c | Java | anu-doi/ariestodspace | /staging/src/main/java/au/edu/anu/ariestodspace/staging/data/CurrentANUPeople.java | UTF-8 | 957 | 2.140625 | 2 | [] | no_license | package au.edu.anu.ariestodspace.staging.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="current_anu_people")
public class CurrentANUPeople {
private Long id;
private String universityId;
private String surname;
private String givenName;
public CurrentANUPeople() {
}
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="university_id")
public String getUniversityId() {
return universityId;
}
public void setUniversityId(String universityId) {
this.universityId = universityId;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
@Column(name="given_name")
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
}
| true |
b2df4f1040899ff1ef3969bfde72e2a2bdcb6b63 | Java | markvaradi94/fullstack-curs11-homework-client | /src/main/java/ro/fasttrackit/curs11/homework/client/service/StudentCourseService.java | UTF-8 | 865 | 2.296875 | 2 | [] | no_license | package ro.fasttrackit.curs11.homework.client.service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import ro.fasttrackit.curs11.homework.client.model.entity.StudentCourseEntity;
import ro.fasttrackit.curs11.homework.client.repository.StudentCourseRepository;
import java.util.List;
import static java.util.Collections.unmodifiableList;
@Service
@RequiredArgsConstructor
public class StudentCourseService {
private final StudentCourseRepository repository;
private final StudentService studentService;
private final CourseService courseService;
public List<StudentCourseEntity> getAll() {
return unmodifiableList(repository.findAll());
}
public StudentCourseEntity addStudentCourse(StudentCourseEntity studentCourseEntity) {
return repository.save(studentCourseEntity);
}
}
| true |
a50754b236c6781abe734611e0b947effe52cd18 | Java | acang/51love | /src/com/common/test.java | GB18030 | 1,867 | 2.140625 | 2 | [] | no_license | package com.common;
import com.common.*;
import com.sun.image.codec.jpeg.*;
import com.web.bean.QueryRecord;
import com.web.bean.QueryResult;
import javax.imageio.event.*;
import com.web.obj.*;
import java.util.List;
import java.util.regex.*;
public class test {
public test() {
}
public static void p()
{
// ϴͼƬСͼ
//
// ϴͼƬеͼ
// ImageUtil.getFixedBoundIcon(dirpath + photoPath,height_mid,width_mid, outPathMid);
try
{
//ImageUtil.getFixedBoundIcon("d:/phsrc/2.jpg", 594,594, "d:/phdesc");
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public static void main(String args[])
{
// String str="ceponline163@yahoo.com.cn";
// Pattern pattern = Pattern.compile("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+",Pattern.CASE_INSENSITIVE);
// Matcher matcher = pattern.matcher(str);
// System.out.println(matcher.matches());
// String str = "\\d{6,}";
// Pattern pattern = Pattern.compile(str,Pattern.CASE_INSENSITIVE);
// Matcher matcher = pattern.matcher("123578990");
// System.out.println(matcher.matches());
String sql = "from Userinfo as u where u.sex = 11 and u.isdel = 0 and u.img=1 and u.lysize>=30 and u.s2='Ͼ' and u.csdate >= to_date('1976-12-31','YYYY-MM-DD') and u.csdate<= to_date('1995-01-01','YYYY-MM-DD') and (u.jyyx like '1____1__' or u.jyyx like '1_____1_') order by u.lasttime desc";
QueryResult qrxttj = null;
System.out.println(sql);
qrxttj = QueryRecord.queryByHbm(sql,100,1,false,0);
List xttjList = qrxttj.resultList;
for(int i =0;i < xttjList.size();i ++)
{
Userinfo ui = (Userinfo)xttjList.get(i);
System.out.println(ui.getUsername()+"----"+ui.getLcname()+"---"+ui.getLasttime());
}
}
}
| true |
75755646bb9a36f8de528e98e6f0e7df55fdb4c1 | Java | judaco/BikeBeacon | /app/src/main/java/com/bikebeacon/ui/TestActivity.java | UTF-8 | 4,937 | 1.945313 | 2 | [] | no_license | package com.bikebeacon.ui;
import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.bikebeacon.R;
import com.bikebeacon.background.AlertDispatcher;
import com.bikebeacon.background.Constants;
import com.bikebeacon.background.RecordController;
import com.bikebeacon.pojo.Alert;
import java.io.IOException;
import java.util.Locale;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import static com.bikebeacon.background.Constants.FCM_RECEIVED_RESPONSE;
import static com.bikebeacon.background.Constants.FCM_RESPONSE;
public class TestActivity extends Activity implements View.OnClickListener, Callback, TextToSpeech.OnInitListener {
private TextToSpeech mTTS;
private String mTTSReponse;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.INTERNET,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.RECORD_AUDIO}, 123);
}
findViewById(R.id.btn_fire_alert).setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_fire_alert:
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mTTSReponse = context.getSharedPreferences("com.bikebeacon", MODE_APPEND).getString(FCM_RESPONSE, "null");
if (mTTSReponse.equals("null")) {
Log.e("TestActivity", "onReceive: No response.");
return;
}
mTTS = new TextToSpeech(context, TestActivity.this, "com.google.android.tts");
LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
}
}, new IntentFilter(FCM_RECEIVED_RESPONSE));
Toast.makeText(this, "Alert Shot Started", Toast.LENGTH_SHORT).show();
Alert alert = new Alert(Constants.AlertAction.ALERT_NEW);
alert.setGPSCoords("test,test");
alert.setCellTowersID("test,test,test");
alert.setIsClosed(false);
alert.setPreviousAlertId("null");
AlertDispatcher.getDispatcher().fireAlert(alert, this);
break;
}
}
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
TestActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(TestActivity.this, "Failed alert shot.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(@NonNull Call call, @NonNull final Response response) throws IOException {
TestActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (response.code() != 200) {
System.out.println(response.toString());
Toast.makeText(TestActivity.this, "Alert shot failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
mTTS.setLanguage(Locale.UK);
mTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String s) {
}
@Override
public void onDone(String s) {
Log.d("TestActivity", "onDone: Spoke.");
RecordController.getController().startRecording(TestActivity.this);
}
@Override
public void onError(String s) {
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mTTS.speak(mTTSReponse, TextToSpeech.QUEUE_FLUSH, null, "ThisIsARandomID");
} else
mTTS.speak(mTTSReponse, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
| true |
2d54369b9f53862b5793cc0327bb9aad62fe3a03 | Java | artokaik/TiRaLabra | /TiRaLabra/src/tiralabra/algoritmit/KarpHeld.java | UTF-8 | 6,400 | 2.78125 | 3 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tiralabra.algoritmit;
import tiralabra.algoritmit.apu.Prim;
import tiralabra.tietorakenteet.pino.Pino;
import tiralabra.tietorakenteet.verkko.XYKoordinaatti;
import tiralabra.tietorakenteet.verkko.XYVerkko;
/**
* Karp-Held heuristiikka on pienimpiin virittäviin l-puihin perustuva
* heuristiikka. Se löytää optimaalisen reitin melko usein, mutta ei kuitenkaan
* aina. Mikäli se ei löydä optimaalista reittiä, se pystyy antamaan hyvin
* lähellä totuutta olevan arvion lyhimmän reitin pituudesta.
*
* Muuttuja int[] solmupainot
*
*
* @author Arto
*/
public class KarpHeld extends ReitinEtsija {
private int[] solmupainot;
private int[] asteet;
private boolean[][] virittavaPuu;
private double[][] valepainot;
private double minimi;
private boolean valmis;
private int iteraatiot;
/**
*
* @param verkko
*/
public KarpHeld(XYVerkko verkko) {
this(verkko,100000);
}
/**
*
* @param verkko
* @param iteraatiot
*/
public KarpHeld(XYVerkko verkko, int iteraatiot) {
super(verkko);
solmupainot = new int[solmut.length];
valepainot = new double[solmut.length][solmut.length];
valmis = false;
minimi = 0;
this.iteraatiot = iteraatiot;
}
/**
* 1. Asetetaan β(v) ← 0 kaikille pisteille v (β on solmupaino).
*
* 2. Asetetaan α′(u,v)←α(u,v)+β(u)+β(v)kaikille viivoille(u,v) (α on valepaino) .
*
* 3. Etsitään minimaalinen virittävä 1-puu S valepainoja α′(u,v) käyttäen.
* Jos tällaista ei löydy, ei myöskään Hamiltonin piiriä löydy ja voidaan
* lopettaa.
*
* 4. Jos S′ on piiri, niin tallennetaan minimaalinen Hamiltonin piiri H = S′
* ja lopetetaan.
*
* 5. Jos S′ ei ole piiri ja S′:sta laskettu alaraja on kasvanut K
* iteraatiokierroksen aikana, niin asetetaan β(v) ← β(v) + dS′ (v) − 2
* jokaiselle pisteelle v ja mennään kohtaan 2. (K on etukäteen kiinnitetty
* iteraatiokierrosten maksimimäärä, dS(v) on solmun asteluku virittävässä l-puussa S.)
*
* 6. Jos S′:sta laskettu alaraja ei ole kasvanut K:n iteraatiokierroksen
* aikana, lopetetaan ja tulostetaan ko. alaraja.
*
* Palauttaa true jos lyhin reitti löytyy, muuten false.
*
* @return
*/
public boolean etsiLyhinReitti() {
int n = 0;
double alaraja = 0;
while (n < iteraatiot) {
paivitaValepainot(); //2
Prim prim = new Prim(valepainot); //3
asteet = new int[solmut.length];
virittavaPuu = prim.lTree(0);
paivitaAsteet();
double uusiAlaraja = laskeAlaraja();
if (onkoPiiri()) { //4
rakennaPino();
valmis = true;
return true;
} else if (alaraja < uusiAlaraja) {
alaraja = uusiAlaraja;
paivitaSolmupainot();
n = 0;
} else { //5
paivitaSolmupainot();
n++;
}
}
minimi = alaraja;
return false;
}
/**
* Päivittää laskennalliset solmupainot.
*/
public void paivitaSolmupainot() {
for (int i = 0; i < solmupainot.length; i++) {
solmupainot[i] = solmupainot[i] + asteet[i] - 2;
}
}
/**
* Rakentaa lyhimmästä reitistä pinon ja tallentaa sen lyhinReitti-muuttujaan. Näin tuloste saadaan samalla tavalla kuin muista algoritmeista.
*/
public void rakennaPino() {
this.lyhimmanReitinPituus = 0;
int v = 0;
lyhinReitti.push(v);
int n = 1;
while (n < solmut.length) {
for (int i = 0; i < kaaret.length; i++) {
if (virittavaPuu[v][i] || virittavaPuu[i][v]) {
virittavaPuu[i][v] = false;
virittavaPuu[v][i] = false;
lyhinReitti.push(i);
this.lyhimmanReitinPituus += kaaret[v][i];
v = i;
break;
}
}
n++;
}
this.lyhimmanReitinPituus += kaaret[v][0];
}
/**
*laskee ja päivittää alarajan lyhimmän reitin pituudelle.
* @return Palauttaa alarajan lyhimmän reitin pituudelle.
*/
public double laskeAlaraja() {
double alaraja = 0;
for (int i = 0; i < kaaret.length; i++) {
for (int j = 0; j < kaaret.length; j++) {
if (virittavaPuu[i][j]) {
alaraja += kaaret[i][j];
}
}
}
for (int i = 0; i < asteet.length; i++) {
alaraja += (asteet[i] - 2) * solmupainot[i];
}
return alaraja;
}
/**
*laskee onko virittävä l-puu piiri vai ei (virittävä l-puu on piiri täsmälleen silloin jos kaikkien solmujen asteluku on 2)
* @return palauttaa true jos kyseessä on piiri, muuten false.
*/
public boolean onkoPiiri() {
for (int i = 0; i < asteet.length; i++) {
if (asteet[i] != 2) {
return false;
}
}
return true;
}
/**
* Päivittää kaarien valepainot
*/
public void paivitaValepainot() {
for (int i = 0; i < valepainot.length; i++) {
for (int j = 0; j < valepainot.length; j++) {
valepainot[i][j] = this.kaaret[i][j] + solmupainot[i] + solmupainot[j];
}
}
}
/**
* päivittää solmujen asteet virittävässä l-puussa.
*/
public void paivitaAsteet() {
for (int i = 0; i < solmut.length; i++) {
for (int j = 0; j < solmut.length; j++) {
if (virittavaPuu[i][j]) {
asteet[i]++;
asteet[j]++;
}
}
}
}
/**
*
* @return
*/
public boolean[][] getVirittavaPuu() {
return virittavaPuu;
}
/**
*
* @return
*/
public boolean isValmis() {
return valmis;
}
/**
*
* @return
*/
public double getMinimi() {
return minimi;
}
}
| true |
6e1313e4874e47fc244869dc7b6e52c8aa0b02c1 | Java | curtbinder/RAWebServer | /src/info/curtbinder/rawebserver/UI/MainFrame.java | UTF-8 | 3,224 | 2.671875 | 3 | [] | no_license | package info.curtbinder.rawebserver.UI;
import info.curtbinder.rawebserver.Classes.Globals;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.ImageObserver;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;
public class MainFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static final int minWidth = 380; // 370;
private static final int minHeight = 420;
private JPanel contentPane;
private JTextArea ta;
private JScrollPane scrollPane;
private MainMenuBar mainMenu;
public MainMenuBar getMainMenu ( ) {
return mainMenu;
}
public MainFrame () {
setTitle( Globals.appTitle );
// setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
//setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE );
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
// center on screen
setBounds( 100, 100, minWidth, minHeight );
setMinimumSize( new Dimension( minWidth, minHeight ) );
mainMenu = new MainMenuBar();
setJMenuBar( mainMenu );
contentPane = new JPanel();
contentPane.setBorder( new EmptyBorder( 5, 5, 5, 5 ) );
contentPane.setLayout( new BoxLayout( contentPane, BoxLayout.Y_AXIS ) );
setContentPane( contentPane );
ta = new JTextArea();
ta.setLineWrap(true);
ta.setWrapStyleWord( true );
ta.setEditable( false );
DefaultCaret caret = (DefaultCaret) ta.getCaret();
caret.setUpdatePolicy( DefaultCaret.ALWAYS_UPDATE );
scrollPane = new JScrollPane( ta );
contentPane.add( scrollPane );
JButton clearBtn = new JButton();
clearBtn.setText("Clear Output Window");
clearBtn.setAlignmentX(CENTER_ALIGNMENT);
clearBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ClearLog();
}
});
contentPane.add(Box.createVerticalStrut(5));
contentPane.add(clearBtn);
//Handle the minimized event and hide the frame entirely.
addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent arg0) {
setVisible(false);
}
@Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
});
}
public void Log ( String msg ) {
ta.insert( msg +"\n",0 );
}
public void ClearLog()
{
ta.setText("");
}
}
| true |
5241fe61657e0c4ef74c85fdfc40a4cbad1aa155 | Java | aidyk/TagoApp | /java_src/com/google/android/gms/tagmanager/zzg.java | UTF-8 | 939 | 1.695313 | 2 | [] | no_license | package com.google.android.gms.tagmanager;
import android.content.Context;
import android.net.Uri;
import com.google.android.gms.tagmanager.DataLayer;
import java.util.Map;
/* access modifiers changed from: package-private */
public final class zzg implements DataLayer.zzb {
private final Context zzri;
public zzg(Context context) {
this.zzri = context;
}
@Override // com.google.android.gms.tagmanager.DataLayer.zzb
public final void zzf(Map<String, Object> map) {
String queryParameter;
Object obj;
Object obj2 = map.get("gtm.url");
if (obj2 == null && (obj = map.get("gtm")) != null && (obj instanceof Map)) {
obj2 = ((Map) obj).get("url");
}
if (obj2 != null && (obj2 instanceof String) && (queryParameter = Uri.parse((String) obj2).getQueryParameter("referrer")) != null) {
zzcw.zzh(this.zzri, queryParameter);
}
}
}
| true |
50bf9980c4c875b3d1f63bbedc8f139a3b1b75db | Java | bigblue311/zhaile | /zhaile.app.searchEngine/src/com/zhaile/search/engine/db/DBProductSearchable.java | UTF-8 | 11,643 | 2.078125 | 2 | [] | no_license | package com.zhaile.search.engine.db;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.collect.Lists;
import com.victor.framework.common.shared.Result;
import com.victor.framework.common.tools.CollectionTools;
import com.victor.framework.common.tools.DateTools;
import com.victor.framework.search.basic.KeyWord;
import com.victor.framework.search.basic.PriceRange;
import com.victor.framework.search.basic.ResultAttribute;
import com.victor.framework.search.basic.SearchQuery;
import com.victor.framework.search.basic.SearchResult;
import com.victor.framework.search.cache.ComputableCache;
import com.victor.framework.search.enumerate.SearchResultEnum;
import com.zhaile.dal.cache.PriceRangeCache;
import com.zhaile.dal.dao.LogSearchDAO;
import com.zhaile.dal.dao.ProductDAO;
import com.zhaile.dal.dao.ShopDAO;
import com.zhaile.dal.dao.ShopTagDAO;
import com.zhaile.dal.log.DbLogger;
import com.zhaile.dal.model.ProductDO;
import com.zhaile.dal.model.ShopDO;
import com.zhaile.dal.model.ShopTagDO;
import com.zhaile.dal.query.condition.ProductQueryCondition;
import com.zhaile.search.engine.Searchable;
public class DBProductSearchable implements Searchable<ProductDO> {
@Autowired
private ProductDAO productDAO;
@Autowired
private ShopDAO shopDAO;
@Autowired
private LogSearchDAO logSearchDAO;
@Autowired
private ShopTagDAO shopTagDAO;
@Autowired
private PriceRangeCache priceRangeCache;
@Autowired
private DbLogger dblogger;
private final ComputableCache<SearchQuery,SearchResult<ProductDO>> cache
= new ComputableCache<SearchQuery,SearchResult<ProductDO>>(this);
@Override
public SearchResult<ProductDO> comput(SearchQuery searchQuery) {
ProductQueryCondition sqc = new ProductQueryCondition();
sqc.setQueryMap(searchQuery.getQueryMap());
Result<Integer> cntResult = productDAO.getCount(sqc);
Result<List<ProductDO>> pageResult = productDAO.getPage(sqc);
if(cntResult.isSuccess() && pageResult.isSuccess()){
return SearchResult.newInstance(pageResult.getDataObject(),wrapResultAttribute(pageResult.getDataObject()),cntResult.getDataObject(),
"查询成功", true);
} else {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public boolean forceUpdate(SearchResult<ProductDO> searchResult) {
return !DateTools.isValid(3, searchResult.getTimestamp());
}
@Override
public SearchResult<ProductDO> search(Long customerId, String keyword) {
dblogger.write(customerId, keyword, 0l);
return search(keyword);
}
@Override
public SearchResult<ProductDO> search(Long customerId, Long tagId) {
try {
String keyword = shopTagDAO.getById(tagId).getDataObject().getContent();
shopTagDAO.SearchCountIncrease(tagId);
dblogger.write(customerId, keyword, tagId);
return search(tagId);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> search(Long customerId, String keyword,
Date gmtModifyStart, Date gmtModifyEnd) {
dblogger.write(customerId, keyword, 0l);
return search(keyword,gmtModifyStart,gmtModifyEnd);
}
@Override
public SearchResult<ProductDO> search(Long customerId, Long tagId,
Date gmtModifyStart, Date gmtModifyEnd) {
try {
String keyword = shopTagDAO.getById(tagId).getDataObject().getContent();
shopTagDAO.SearchCountIncrease(tagId);
dblogger.write(customerId, keyword, tagId);
return search(tagId,gmtModifyStart,gmtModifyEnd);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public List<KeyWord> keywordAutoComplete(Long shopId, Long categoryId,String key) {
SearchQuery searchQuery = new SearchQuery(SearchResultEnum.商品);
searchQuery.start(0).pageSize(20).shopId(shopId).categoryId(categoryId).keyword(key);
SearchResult<ProductDO> result = this.comput(searchQuery);
List<KeyWord> autoList = Lists.newArrayList();
if(result.isSuccess()) {
List<ProductDO> list = result.getDataObject();
for(ProductDO product : list){
ShopDO shop = shopDAO.getById(product.getShopId()).getDataObject();
if(shop!=null) {
KeyWord keyWord = new KeyWord(product.getName(),shop.getName(),product.getPrice().toString());
autoList.add(keyWord);
}
}
}
return autoList;
}
@Override
public List<ShopTagDO> tagAutoComplete(String key) {
return shopTagDAO.getOnlyProdTag(key).getDataObject();
}
@Override
public List<String> keywordTop10() {
return logSearchDAO.getTop(10l).getDataObject();
}
@Override
public List<ShopTagDO> tagTop10() {
return shopTagDAO.getOnlyProdTag().getDataObject();
}
@Override
public SearchResult<ProductDO> findProduct(Long shopId) {
try {
SearchQuery searchQuery = new SearchQuery(SearchResultEnum.商品);
searchQuery.shopId(shopId);
return (SearchResult<ProductDO>) cache.comput(searchQuery);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> findProduct(Long shopId, String keyword) {
try {
SearchQuery searchQuery = new SearchQuery(SearchResultEnum.商品);
searchQuery.shopId(shopId).keyword(keyword);
return (SearchResult<ProductDO>) cache.comput(searchQuery);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> findShop(Long categoryId,String keyword) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0, "查询失败", false);
}
@Override
public SearchResult<ProductDO> search(String keyword) {
try {
SearchQuery searchQuery = new SearchQuery(SearchResultEnum.商品);
searchQuery.keyword(keyword);
return (SearchResult<ProductDO>) cache.comput(searchQuery);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> search(Long categoryId) {
try {
SearchQuery searchQuery = new SearchQuery(SearchResultEnum.商品);
searchQuery.categoryId(categoryId);
return (SearchResult<ProductDO>) cache.comput(searchQuery);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> search(String keyword, Date gmtModifyStart, Date gmtModifyEnd) {
try {
SearchQuery searchQuery = new SearchQuery(SearchResultEnum.商品);
searchQuery.keyword(keyword)
.gmtModifyStart(gmtModifyStart).gmtModifyEnd(gmtModifyEnd);
return (SearchResult<ProductDO>) cache.comput(searchQuery);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> search(Long tagId, Date gmtModifyStart, Date gmtModifyEnd) {
try {
SearchQuery searchQuery = new SearchQuery(SearchResultEnum.商家);
String keyword = shopTagDAO.getById(tagId).getDataObject().getContent();
searchQuery.tagId(tagId).keyword(keyword)
.gmtModifyStart(gmtModifyStart).gmtModifyEnd(gmtModifyEnd);
return (SearchResult<ProductDO>) cache.comput(searchQuery);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> bestSellTop10() {
Result<List<ProductDO>> result = productDAO.getBestSellerTop10();
if(result.isSuccess()){
List<ProductDO> list = result.getDataObject();
return SearchResult.newInstance(list,wrapResultAttribute(list), list.size(), result.getMessage(), true);
} else {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> getById(Long... id) {
Result<List<ProductDO>> result = productDAO.getByIds(id);
if(result.isSuccess()){
List<ProductDO> list = result.getDataObject();
return SearchResult.newInstance(list,wrapResultAttribute(list), list.size(), result.getMessage(), true);
} else {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> getRandom(int count,Long... categoryId) {
Result<List<ProductDO>> result = productDAO.getRandom(count,categoryId);
if(result.isSuccess()){
List<ProductDO> list = result.getDataObject();
return SearchResult.newInstance(list,wrapResultAttribute(list), list.size(), result.getMessage(), true);
} else {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
private ResultAttribute wrapResultAttribute(List<ProductDO> list) {
if(list == null || CollectionTools.isEmpty(list)) {
return null;
}
ResultAttribute attr = new ResultAttribute();
for(ProductDO prod : list) {
if(prod!=null) {
if(prod.getShopId()!=null) {
Long shopId = prod.getShopId();
Map<Long,Integer> shopMap =attr.getShopId();
if(!shopMap.containsKey(shopId)) {
shopMap.put(shopId,1);
} else {
shopMap.put(shopId,shopMap.get(shopId)+1);
}
attr.setShopId(shopMap);
}
if(prod.getCategoryId()!=null) {
Long categoryId = prod.getCategoryId();
Map<Long,Integer> categoryMap =attr.getCategoryId();
if(!categoryMap.containsKey(categoryId)) {
categoryMap.put(categoryId,1);
} else {
categoryMap.put(categoryId,categoryMap.get(categoryId)+1);
}
attr.setCategoryId(categoryMap);
}
PriceRange priceRange = priceRangeCache.getPriceRange(prod.getPrice());
if(priceRange!=null){
Long priceRangeId = priceRange.getId();
Map<Long,Integer> priceRangeMap = attr.getPriceRange();
if(!priceRangeMap.containsKey(priceRangeId)) {
priceRangeMap.put(priceRangeId,1);
} else {
priceRangeMap.put(priceRangeId,priceRangeMap.get(priceRangeId)+1);
}
attr.setPriceRange(priceRangeMap);
}
}
}
return attr;
}
@Override
public SearchResult<ProductDO> findProduct(Long shopId, Long categoryId) {
try {
SearchQuery searchQuery = new SearchQuery(SearchResultEnum.商品);
searchQuery.shopId(shopId).categoryId(categoryId);
return (SearchResult<ProductDO>) cache.comput(searchQuery);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> findProduct(Long shopId, Long categoryId,
String keyword) {
try {
SearchQuery searchQuery = new SearchQuery(SearchResultEnum.商品);
searchQuery.shopId(shopId).categoryId(categoryId).keyword(keyword);
return (SearchResult<ProductDO>) cache.comput(searchQuery);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
@Override
public SearchResult<ProductDO> search(Long customerId, Long categoryId, String keyword) {
try {
SearchQuery searchQuery = new SearchQuery(SearchResultEnum.商品);
searchQuery.categoryId(categoryId).keyword(keyword);
return (SearchResult<ProductDO>) cache.comput(searchQuery);
} catch (Exception e) {
return SearchResult.newInstance(new ArrayList<ProductDO>(),null,0,
"查询失败", false);
}
}
}
| true |
bb97f25a530c69ac6dd0ef5a439694137f0f6089 | Java | alamom/mcoc_mod_11.1 | /src/com/google/android/gms/internal/cc.java | UTF-8 | 1,059 | 1.867188 | 2 | [] | no_license | package com.google.android.gms.internal;
import java.util.HashMap;
import java.util.Map;
@ez
public class cc
implements by
{
static final Map<String, Integer> pK = new HashMap();
static
{
pK.put("resize", Integer.valueOf(1));
pK.put("playVideo", Integer.valueOf(2));
pK.put("storePicture", Integer.valueOf(3));
pK.put("createCalendarEvent", Integer.valueOf(4));
}
public void a(gv paramgv, Map<String, String> paramMap)
{
String str = (String)paramMap.get("a");
switch (((Integer)pK.get(str)).intValue())
{
case 2:
default:
gs.U("Unknown MRAID command called.");
}
for (;;)
{
return;
new dd(paramgv, paramMap).execute();
continue;
new dc(paramgv, paramMap).execute();
continue;
new de(paramgv, paramMap).execute();
}
}
}
/* Location: C:\tools\androidhack\marvel_bitva_chempionov_v11.1.0_mod_lenov.ru\classes.jar!\com\google\android\gms\internal\cc.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
a95d4027df10dd1956197c2fbb121a86f0d27103 | Java | xinsec/caiyuan | /src/main/java/cn/hellyuestc/caiyuan/util/MyUtil.java | UTF-8 | 943 | 2.578125 | 3 | [] | no_license | package cn.hellyuestc.caiyuan.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
import org.mindrot.jbcrypt.BCrypt;
public class MyUtil {
private static FileInputStream caiyuanIS;
static {
try {
caiyuanIS = new FileInputStream("classpath:caiyuan.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static String bcrypt(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}
public static String createRandomCode() {
return new Date().getTime() + UUID.randomUUID().toString().replace("-", "");
}
public static Properties getCaiyuanProperties() {
Properties caiyuanProperties = new Properties();
try {
caiyuanProperties.load(caiyuanIS);
} catch (IOException e) {
e.printStackTrace();
}
return caiyuanProperties;
}
}
| true |
280760ad5651630f8b63eb000ce3e1ada913906b | Java | miaosongtian/xzsd | /sc2019/sc-provider/sc-xzsd-app/src/main/java/com/xzsd/app/register/controller/RegisterController.java | UTF-8 | 1,375 | 2.0625 | 2 | [] | no_license | package com.xzsd.app.register.controller;
import com.neusoft.core.restful.AppResponse;
import com.neusoft.security.client.utils.SecurityUtils;
import com.xzsd.app.register.entity.RegisterInfo;
import com.xzsd.app.register.service.RegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("register")
public class RegisterController {
private static final Logger logger = LoggerFactory.getLogger(RegisterController.class);
@Resource
private RegisterService registerService;
/**
* 新增门店
* author: miaosongtian
* time:2020-04-22
*/
@PostMapping("clientRegister")
public AppResponse clientRegister(RegisterInfo registerInfo) {
try {
//获取用户id
String userCode = "客户注册账号";
registerInfo.setCreateBy(userCode);
AppResponse appResponse = registerService.clientRegister(registerInfo);
return appResponse;
} catch (Exception e) {
logger.error("客户注册异常", e);
System.out.println(e.toString());
throw e;
}
}
}
| true |
be45635a5d29746acc32b5863468543a8c5b9e51 | Java | songk1992/bitacademydiary | /study-previous/src/main/java/practice04/prob3/Book.java | UTF-8 | 1,040 | 3.65625 | 4 | [] | no_license | package practice04.prob3;
public class Book {
private int bookNum;
private String title;
private String genre;
private int stateCode;
public Book(int bookNum, String title, String genre) {
this.bookNum = bookNum;
this.title = title;
this.genre = genre;
this.stateCode = 1;
}
public void rent() {
this.stateCode = 0;
System.out.println( title + " 이(가) 대여 됐습니다.");
}
public void print() {
System.out.print( "책 제목 :" + title );
System.out.print( ", 장르:" + genre );
System.out.print( ", 대여 유무:");
if(stateCode==1) {
System.out.println("재고있음");
}
else {
System.out.println("재고없음");
}
}
public int getBookNum() {
return bookNum;
}
public void setBookNum(int bookNum) {
this.bookNum = bookNum;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
}
| true |
0d9c071350e1b9cd2935c644488069f4761ac9c1 | Java | WangYouzheng1994/hyjf | /hyjf-mybatis/src/main/java/com/hyjf/mybatis/model/customize/ProductStatisCustomize.java | UTF-8 | 3,334 | 1.898438 | 2 | [] | no_license | package com.hyjf.mybatis.model.customize;
import java.io.Serializable;
import java.math.BigDecimal;
public class ProductStatisCustomize implements Serializable {
private Integer id;
private Integer inCount;
private Integer outCount;
private BigDecimal inAmount;
private BigDecimal outAmount;
private BigDecimal outInterest;
private BigDecimal loanBalance;
private BigDecimal investAmount;
private Integer createTime;
private String dataDate;
private String dataMonth;
//日期选择查询
private Integer timeStart;
private Integer timeEnd;
private String vFlag;
private Integer userId;//用户id
private BigDecimal principal;//出借人本金
/***
* 新老用户分布
*/
private BigDecimal amount;//操作金额
private Integer regTime;//注册时间
public Integer getRegTime() {
return regTime;
}
public void setRegTime(Integer regTime) {
this.regTime = regTime;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public BigDecimal getPrincipal() {
return principal;
}
public void setPrincipal(BigDecimal principal) {
this.principal = principal;
}
public String getvFlag() {
return vFlag;
}
public void setvFlag(String vFlag) {
this.vFlag = vFlag;
}
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public Integer getTimeStart() {
return timeStart;
}
public void setTimeStart(Integer timeStart) {
this.timeStart = timeStart;
}
public Integer getTimeEnd() {
return timeEnd;
}
public void setTimeEnd(Integer timeEnd) {
this.timeEnd = timeEnd;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getInCount() {
return inCount;
}
public void setInCount(Integer inCount) {
this.inCount = inCount;
}
public Integer getOutCount() {
return outCount;
}
public void setOutCount(Integer outCount) {
this.outCount = outCount;
}
public BigDecimal getInAmount() {
return inAmount;
}
public void setInAmount(BigDecimal inAmount) {
this.inAmount = inAmount;
}
public BigDecimal getOutAmount() {
return outAmount;
}
public void setOutAmount(BigDecimal outAmount) {
this.outAmount = outAmount;
}
public BigDecimal getOutInterest() {
return outInterest;
}
public void setOutInterest(BigDecimal outInterest) {
this.outInterest = outInterest;
}
public BigDecimal getLoanBalance() {
return loanBalance;
}
public void setLoanBalance(BigDecimal loanBalance) {
this.loanBalance = loanBalance;
}
public BigDecimal getInvestAmount() {
return investAmount;
}
public void setInvestAmount(BigDecimal investAmount) {
this.investAmount = investAmount;
}
public Integer getCreateTime() {
return createTime;
}
public void setCreateTime(Integer createTime) {
this.createTime = createTime;
}
public String getDataDate() {
return dataDate;
}
public void setDataDate(String dataDate) {
this.dataDate = dataDate;
}
public String getDataMonth() {
return dataMonth;
}
public void setDataMonth(String dataMonth) {
this.dataMonth = dataMonth;
}
} | true |
75ca4c2cb9386db88757737466708158cb2ab1a6 | Java | TaquyeddineZegaoui/opensilex | /opensilex-phis/src/main/java/opensilex/service/resource/dto/sensor/SensorPostDTO.java | UTF-8 | 5,152 | 2.25 | 2 | [] | no_license | //******************************************************************************
// SensorPostDTO.java
// SILEX-PHIS
// Copyright © INRA 2019
// Creation date: 11 avr. 2019
// Contact: morgane.vidal@inra.fr, anne.tireau@inra.fr, pascal.neveu@inra.fr
//******************************************************************************
package opensilex.service.resource.dto.sensor;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.Email;
import opensilex.service.configuration.DateFormat;
import opensilex.service.documentation.DocumentationAnnotation;
import opensilex.service.model.Sensor;
import opensilex.service.resource.dto.manager.AbstractVerifiedClass;
import opensilex.service.resource.validation.interfaces.Date;
import opensilex.service.resource.validation.interfaces.Required;
import opensilex.service.resource.validation.interfaces.URL;
/**
* DTO for the POST sensor service.
*
* @author Morgane Vidal <morgane.vidal@inra.fr>
*/
public class SensorPostDTO extends AbstractVerifiedClass {
// type of the sensor. Uri of the concept (must be subclass of SensingDevice
// concept)
private String rdfType;
// label of the sensor
private String label;
// brand of the sensor
private String brand;
// model of the sensor
private String model;
// serial number of the sensor
private String serialNumber;
// in service date of the sensor
private String inServiceDate;
// purchase date of the sensor
private String dateOfPurchase;
// date of last calibration of the sensor
private String dateOfLastCalibration;
// email of the person in charge of the sensor
private String personInCharge;
public SensorPostDTO() {
}
public SensorPostDTO(Sensor sensor) {
rdfType = sensor.getRdfType();
label = sensor.getLabel();
brand = sensor.getBrand();
model = sensor.getModel();
serialNumber = sensor.getSerialNumber();
inServiceDate = sensor.getInServiceDate();
dateOfPurchase = sensor.getDateOfPurchase();
dateOfLastCalibration = sensor.getDateOfLastCalibration();
personInCharge = sensor.getPersonInCharge();
}
@Override
public Sensor createObjectFromDTO() {
Sensor sensor = new Sensor();
sensor.setRdfType(rdfType);
sensor.setLabel(label);
sensor.setBrand(brand);
sensor.setModel(model);
sensor.setSerialNumber(serialNumber);
sensor.setInServiceDate(inServiceDate);
sensor.setDateOfPurchase(dateOfPurchase);
sensor.setDateOfLastCalibration(dateOfLastCalibration);
sensor.setPersonInCharge(personInCharge);
return sensor;
}
@URL
@Required
@ApiModelProperty(example = DocumentationAnnotation.EXAMPLE_SENSOR_RDF_TYPE)
public String getRdfType() {
return rdfType;
}
public void setRdfType(String rdfType) {
this.rdfType = rdfType;
}
@Required
@ApiModelProperty(example = DocumentationAnnotation.EXAMPLE_SENSOR_LABEL)
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@Required
@ApiModelProperty(example = DocumentationAnnotation.EXAMPLE_SENSOR_BRAND)
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
@ApiModelProperty(example = DocumentationAnnotation.EXAMPLE_SENSOR_SERIAL_NUMBER)
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
@Date(DateFormat.YMD)
@Required
@ApiModelProperty(example = DocumentationAnnotation.EXAMPLE_SENSOR_IN_SERVICE_DATE)
public String getInServiceDate() {
return inServiceDate;
}
public void setInServiceDate(String inServiceDate) {
this.inServiceDate = inServiceDate;
}
@Date(DateFormat.YMD)
@ApiModelProperty(example = DocumentationAnnotation.EXAMPLE_SENSOR_DATE_OF_PURCHASE)
public String getDateOfPurchase() {
return dateOfPurchase;
}
public void setDateOfPurchase(String dateOfPurchase) {
this.dateOfPurchase = dateOfPurchase;
}
@Date(DateFormat.YMD)
@ApiModelProperty(example = DocumentationAnnotation.EXAMPLE_SENSOR_DATE_OF_LAST_CALIBRATION)
public String getDateOfLastCalibration() {
return dateOfLastCalibration;
}
public void setDateOfLastCalibration(String dateOfLastCalibration) {
this.dateOfLastCalibration = dateOfLastCalibration;
}
@Email
@Required
@ApiModelProperty(example = DocumentationAnnotation.EXAMPLE_USER_EMAIL)
public String getPersonInCharge() {
return personInCharge;
}
public void setPersonInCharge(String personInCharge) {
this.personInCharge = personInCharge;
}
@ApiModelProperty(example = DocumentationAnnotation.EXAMPLE_SENSOR_MODEL)
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
} | true |
7e1471c5fe9e5a5e1b7fd3a22229dc8d8a989aa3 | Java | MrNANMU/wcshxxgps | /app/src/main/java/gpsutils/wcshxx/com/gps/config/Config.java | UTF-8 | 2,875 | 2.484375 | 2 | [] | no_license | package gpsutils.wcshxx.com.gps.config;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import gpsutils.wcshxx.com.gps.utils.LogUtils;
import gpsutils.wcshxx.com.gps.utils.SharePreUtils;
import gpsutils.wcshxx.com.gps.utils.ToastUtils;
public class Config {
/**
* APP设置字典表
*/
public interface Setting{
String MAX_ITEMS = "MAX_ITEMS";
String INTERVAL = "INTERVAL";
String READER = "READER";
String SHOW_TYPE = "SHOW_TYPE";
}
/**
* 浏览文本阅读器设置
* 0:使用系统浏览器打开
* 1:使用APP打开
* -1:无默认设置
*/
public interface Reader{
int SYSTEM = 0;
int APP = 1;
int NOT_SELECT = -1;
}
//初始化
public static void reset(){
setInterval(10000);
setMaxItemsNumber(35);
setReader(Reader.NOT_SELECT);
setShowType((Set) null);
}
public static void setInterval(int millisecond){
SharePreUtils.saveInt(Setting.INTERVAL,millisecond);
}
//GPS更新时间间隔
public static int getInterval(){
return SharePreUtils.getInt(Setting.INTERVAL);
}
public static void setMaxItemsNumber(int max){
SharePreUtils.saveInt(Setting.MAX_ITEMS,max);
}
//动态数据最大显示条数
public static int getMaxItemsNumber(){
return SharePreUtils.getInt(Setting.MAX_ITEMS);
}
//文件浏览方式
public static void setReader(int reader){
switch (reader){
case Reader.APP:
case Reader.NOT_SELECT:
case Reader.SYSTEM:
SharePreUtils.saveInt(Setting.READER, reader);
break;
default:
LogUtils.e("参数不在预设范围[-1,0,1]内 : reader = "+reader);
ToastUtils.show("设置默认阅读器失败");
break;
}
}
public static int getReader(){
return SharePreUtils.getInt(Setting.READER);
}
public static void setShowType(String...types){
Set<String> set = null;
if(types != null && types.length > 0){
set = new HashSet<>(Arrays.asList(types));
}
SharePreUtils.saveSet(Setting.SHOW_TYPE,set);
}
public static void setShowType(Set<String> types){
SharePreUtils.saveSet(Setting.SHOW_TYPE,types);
}
public static List<String> getShowType(){
Set<String> set = SharePreUtils.getSet(Setting.SHOW_TYPE);
if(set == null){
set = new HashSet<>();
set.add("$GPGGA");
}
return new ArrayList<>(set);
}
public static Set<String> getShowTypeSet(){
return SharePreUtils.getSet(Setting.SHOW_TYPE);
}
}
| true |
178b3321eebc23521f729a4250d1bc396ac867c9 | Java | WilsonParker/Tworaveler | /app/src/main/java/com/developer/hare/tworaveler/Net/Net.java | UTF-8 | 4,153 | 2.359375 | 2 | [] | no_license | package com.developer.hare.tworaveler.Net;
import com.developer.hare.tworaveler.Util.LogManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Hare on 2017-08-01.
*/
public class Net {
private static final Net ourInstance = new Net();
private static final String U = "http://13.124.128.125:3002";
private static Retrofit retrofit;
private NetFactoryIm netFactoryIm;
public Net() {
init();
}
private void init() {
// init cookie manager
CookieHandler cookieHandler = new CookieManager();
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
cookieHandler.setDefault(cookieManager);
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.addInterceptor(new AddCookiesInterceptor())
.addInterceptor(new ReceivedCookiesInterceptor())
.cookieJar(new JavaNetCookieJar(cookieHandler))
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(U)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static Net getInstance() {
return ourInstance;
}
public static String getU() {
return U;
}
public NetFactoryIm getFactoryIm() {
if (netFactoryIm == null)
netFactoryIm = retrofit.create(NetFactoryIm.class);
return netFactoryIm;
}
private void urlConnect() {
URL url;
try {
url = new URL("http://13.124.128.125:3002/users/email_login");
String params = "email=a7@naver.com&pw=aaaa1111";
String result = "";
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setDefaultUseCaches(false);
OutputStream outputStream = httpUrlConnection.getOutputStream();
outputStream.write(params.getBytes());
outputStream.flush();
outputStream.close();
InputStream inputStream = httpUrlConnection.getInputStream();
String buffer = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((buffer = bufferedReader.readLine()) != null) {
result += buffer;
}
bufferedReader.close();
LogManager.log(LogManager.LOG_INFO, getClass(), "urlConnect()", "result : " + result);
Map<String, List<String>> resMap = httpUrlConnection.getHeaderFields();
for (String key : resMap.keySet()) {
LogManager.log(LogManager.LOG_INFO, getClass(), "urlConnect()", "key : : " + key + " / " + resMap.get(key));
}
} catch (Exception e) {
LogManager.log(getClass(), "urlConnect()", e);
}
}
}
| true |
a1b4f8fbdb7301435d42b7d85e51195bf41226cf | Java | AlexeyDer/KursWorkSiaod | /src/main/java/KursWork/AVL.java | UTF-8 | 7,041 | 3.078125 | 3 | [] | no_license | package KursWork;
public class AVL {
DataBase db;
public Vertex root;
public int height(Vertex p) {
return (p == null) ? 0 : p.getHeight();
}
public int max(int a, int b) {
return (a > b) ? a : b;
}
public Vertex search(Vertex p, String key) {
if (p == null || p.getPeople().getFioVklad().equals(key)) {
return p;
}
if (key.compareTo(p.getPeople().getFioVklad()) < 0)
return search(p.getLeft(), key);
else
return search(p.getRight(), key);
}
public Vertex LR(Vertex y) {
Vertex x = y.getLeft();
Vertex T2 = x.getRight();
x.setRight(y);
y.setLeft(T2);
y.setHeight(max(height(y.getLeft()), height(y.getRight())) + 1);
x.setHeight(max(height(x.getLeft()), height(x.getRight())) + 1);
return x;
}
public Vertex RL(Vertex x) {
Vertex y = x.getRight();
Vertex T2 = y.getLeft();
y.setLeft(x);
x.setRight(T2);
x.setHeight(max(height(x.getLeft()), height(x.getRight())) + 1);
y.setHeight(max(height(y.getLeft()), height(y.getRight())) + 1);
return y;
}
public int getBalance(Vertex p) {
if (p == null)
return 0;
return height(p.getLeft()) - height(p.getRight());
}
public static int compareData(People a, People b) {
if (a.getDate().compareTo(b.getDate()) < 0)
return -1;
else if (a.getFioVklad().compareTo(b.getFioVklad()) > 0)
return 1;
else
return 0;
}
public static int compareFioVklad(People a, People b) {
if (a.getFioVklad().compareTo(b.getFioVklad()) < 0)
return 1;
else if (a.getFioVklad().compareTo(b.getFioVklad()) > 0)
return -1;
else
return 0;
}
public static int compareFioAdv(People a, People b) {
if (a.getFioAdv().compareTo(b.getFioAdv()) < 0)
return 1;
else if (a.getFioVklad().compareTo(b.getFioVklad()) > 0)
return -1;
else
return 0;
}
public static int compareSum(People a, People b) {
if (a.getSum() > b.getSum())
return 1;
else if (a.getSum() < b.getSum())
return -1;
else
return 0;
}
private static int b = 1;
public Vertex insert(Vertex p, People data) {
if (p == null)
return (new Vertex(data));
int compFioVklad = compareFioVklad(data, p.getPeople());
if (compFioVklad > 0)
p.setLeft(insert(p.getLeft(), data));
else if (compFioVklad < 0) {
p.setRight(insert(p.getRight(), data));
} else {
// if (p.getAgain() != null) {
// KursWork.Vertex k = p;
// while (p.getAgain() != null) {
// p = p.getAgain();
// }
// p.setAgain(k);
// } else
p.setAgain(p);
return p;
}
p.setHeight(1 + max(height(p.getLeft()), height(p.getRight())));
int balance = getBalance(p);
// LL
if (balance > 1 && compareFioVklad(data, p.getLeft().getPeople()) > 0) {
return LR(p);
}
// RR
if (balance < -1 && compareFioVklad(data, p.getRight().getPeople()) < 0)
return RL(p);
// LR
if (balance > 1 && compareFioVklad(data, p.getLeft().getPeople()) < 0) {
p.setLeft(RL(p.getLeft()));
return LR(p);
}
// RL
if (balance < -1 && compareFioVklad(data, p.getRight().getPeople()) > 0) {
p.setRight(LR(p.getRight()));
return RL(p);
}
return p;
}
public Vertex minValueNode(Vertex vertex) {
Vertex p = vertex;
while (p.getLeft() != null)
p = p.getLeft();
return p;
}
private static int g = 1;
public static void setG(int g) {
AVL.g = g;
}
public void print(Vertex p) {
if (p != null) {
print(p.getLeft());
System.out.print(g++ + " ФИО Вкладчика: " + p.getPeople().getFioVklad());
System.out.print(" Сумма вклада: " + p.getPeople().getSum());
System.out.print(" Дата вкалада: " + p.getPeople().getDate());
System.out.println(" ФИО Адвоката: " + p.getPeople().getFioAdv());
System.out.println("---------------------------------");
if (p.getAgain() != null) {
System.out.print(g++ + " ФИО Вкладчика: " + p.getAgain().getPeople().getFioVklad());
System.out.print(" Сумма вклада: " + p.getAgain().getPeople().getSum());
System.out.print(" Дата вкалада: " + p.getAgain().getPeople().getDate());
System.out.println(" ФИО Адвоката: " + p.getAgain().getPeople().getFioAdv());
System.out.println("---------------------------------");
}
print(p.getRight());
}
}
// public KursWork.Vertex delete(KursWork.Vertex root, int data) {
// if (root == null)
// return root;
//
// if (data < root.getData())
// root.setLeft(delete(root.getLeft(), data));
// else if (data > root.getData())
// root.setRight(delete(root.getRight(), data));
// else {
// if ((root.getLeft() == null || (root.getRight() == null))) {
// KursWork.Vertex temp = null;
// if (temp == root.getLeft())
// temp = root.getRight();
// else
// temp = root.getLeft();
//
// if (temp == null) {
// temp = root;
// root = null;
// } else
// root = temp;
// } else {
// KursWork.Vertex temp = minValueNode(root.getRight());
// root.setData(temp.getData());
// root.setRight(delete(root.getRight(), temp.getData()));
// }
// }
//
// if (root == null)
// return root;
//
// root.setHeight(max(height(root.getLeft()), height(root.getRight())) + 1);
//
// int balance = getBalance(root);
//
// // LL
// if (balance > 1 && getBalance(root.getLeft()) >= 0)
// return LR(root);
//
// // LR
// if (balance > 1 && getBalance(root.getLeft()) < 0) {
// root.setLeft(RL(root.getLeft()));
// return LR(root);
// }
//
// // RR
// if (balance < -1 && getBalance(root.getRight()) <= 0)
// return RL(root);
//
// // RL
// if (balance < -1 && getBalance(root.getRight()) > 0) {
// root.setRight(LR(root.getRight()));
// return RL(root);
// }
//
// return root;
// }
}
| true |
a85ef0426f712bc1962cc9e1b2ac810b46c63b77 | Java | 121rajesh/ExaminationPortal_SpringBoot | /src/main/java/com/app/form/ResultOutForm.java | UTF-8 | 163 | 1.796875 | 2 | [] | no_license | package com.app.form;
public interface ResultOutForm {
Integer getResId();
Integer getScore();
String getName();
String getEmailId();
String getSubName();
}
| true |
3adc6d1b06317749ea3d47b38f8bbd74e01ff921 | Java | robinshang/droidddle | /mobile/src/main/java/org/goodev/droidddle/widget/QuickReturnRecyclerView.java | UTF-8 | 12,641 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | package org.goodev.droidddle.widget;
import android.content.Context;
import android.os.Build;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import org.goodev.droidddle.utils.Utils;
/**
* Add view with BottomToolBarRecyclerView.setReturningView to be used as a QuickReturnView
* when the user scrolls down the content.
* <p>
* Created by johnen on 14-11-11.
*/
public class QuickReturnRecyclerView extends BaseRecyclerView {
private static final String TAG = QuickReturnRecyclerView.class.getName();
private static final int STATE_ONSCREEN = 0;
private int mState = STATE_ONSCREEN;
private static final int STATE_OFFSCREEN = 1;
private static final int STATE_RETURNING = 2;
OnScrollListener mListener1;
private View mReturningView;
private int mMinRawY = 0;
private int mReturningViewHeight;
private int mGravity = Gravity.BOTTOM;
private boolean mIsLoadingMore;
private boolean mHasMoreData = true;
private OnLoadingMoreListener mMoreListener;
public QuickReturnRecyclerView(Context context) {
super(context);
init();
}
public QuickReturnRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public QuickReturnRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
}
/**
* The view that should be showed/hidden when scrolling the content.
* Make sure to set the gravity on the this view to either Gravity.Bottom or
* Gravity.TOP and to put it preferable in a FrameLayout.
*
* @param view Any kind of view
*/
public void setReturningView(View view) {
mReturningView = view;
try {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mReturningView.getLayoutParams();
mGravity = params.gravity;
} catch (ClassCastException e) {
throw new RuntimeException("The return view need to be put in a FrameLayout");
}
measureView(mReturningView);
mReturningViewHeight = mReturningView.getMeasuredHeight();
setOnScrollListener(new RecyclerScrollListener());
int left = getPaddingLeft();
int right = getPaddingRight();
int top = getPaddingTop() + mReturningViewHeight;
int bottom = getPaddingBottom();
setPadding(left, top, right, bottom);
}
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
/**
* if layout manager do not have this method , will return 0
*
* @return
*/
public int findFirstVisibleItemPosition() {
LayoutManager manager = getLayoutManager();
int firstVisibleItems = 0;
if (manager instanceof LinearLayoutManager) {
firstVisibleItems = ((LinearLayoutManager) manager).findFirstVisibleItemPosition();
} else if (manager instanceof GridLayoutManager) {
firstVisibleItems = ((GridLayoutManager) manager).findFirstVisibleItemPosition();
} else if (manager instanceof StaggeredGridLayoutManager) {
StaggeredGridLayoutManager sg = ((StaggeredGridLayoutManager) manager);
int[] items = new int[sg.getSpanCount()];
items = ((StaggeredGridLayoutManager) manager).findFirstVisibleItemPositions(items);
firstVisibleItems = items[0];
}
return firstVisibleItems;
}
public void checkLoadingMore() {
boolean firstVisible = false;
LayoutManager manager = getLayoutManager();
int visibleItemCount = manager.getChildCount();
int totalItemCount = manager.getItemCount();
int firstVisibleItems = 0;
if (manager instanceof LinearLayoutManager) {
firstVisibleItems = ((LinearLayoutManager) manager).findFirstVisibleItemPosition();
} else if (manager instanceof GridLayoutManager) {
firstVisibleItems = ((GridLayoutManager) manager).findFirstVisibleItemPosition();
} else if (manager instanceof StaggeredGridLayoutManager) {
StaggeredGridLayoutManager sg = ((StaggeredGridLayoutManager) manager);
int[] items = new int[sg.getSpanCount()];
items = ((StaggeredGridLayoutManager) manager).findFirstVisibleItemPositions(items);
firstVisibleItems = items[0];
}
// boolean topOfFirstItemVisible = manager.getChildAt(0).getTop() >= mFirstTop;
// enabling or disabling the refresh layout
if (firstVisibleItems == 0) {
View child = manager.getChildAt(0);
if (child != null) {
LayoutParams lp = (LayoutParams) child.getLayoutParams();
firstVisible = manager.getChildAt(0).getTop() >= (getPaddingTop() + lp.topMargin);
}
}
// firstVisible = firstVisibleItems == 0 && topOfFirstItemVisible;
mMoreListener.isFirstItemFullVisible(firstVisible);
if (!mIsLoadingMore && mHasMoreData) {
if ((visibleItemCount + firstVisibleItems) >= totalItemCount - 1) {
if (!Utils.hasInternet(getContext())) {
return;
}
mIsLoadingMore = true;
mMoreListener.onLoadingMore();
}
}
}
public void finishLoadingMore(boolean hasMoreData) {
mIsLoadingMore = false;
mHasMoreData = hasMoreData;
}
public OnLoadingMoreListener getOnLoadingMoreListener() {
return mMoreListener;
}
public void setOnLoadingMoreListener(OnLoadingMoreListener listener) {
mMoreListener = listener;
setOnScrollListener(new RecyclerScrollListener());
}
@Override
public void setOnScrollListener(OnScrollListener listener) {
if (mListener1 == null) {
mListener1 = listener;
} else if (mListener1 != listener) {
super.setOnScrollListener(new ScrollListenerWrap(mListener1, listener));
return;
}
super.setOnScrollListener(listener);
}
static class ScrollListenerWrap extends OnScrollListener {
OnScrollListener mListener1;
OnScrollListener mListener2;
public ScrollListenerWrap(OnScrollListener listener1, OnScrollListener listener2) {
mListener1 = listener1;
mListener2 = listener2;
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
mListener1.onScrollStateChanged(recyclerView, newState);
mListener2.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
mListener1.onScrolled(recyclerView, dx, dy);
mListener2.onScrolled(recyclerView, dx, dy);
}
}
private class RecyclerScrollListener extends OnScrollListener {
private int mScrolledY;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
QuickReturnRecyclerView rv = (QuickReturnRecyclerView) recyclerView;
if (mMoreListener != null) {
checkLoadingMore();
}
if (mReturningView == null) {
return;
}
if (mGravity == Gravity.BOTTOM) {
mScrolledY += dy;
if (mScrolledY < 0) {
mScrolledY = 0;
}
} else if (mGravity == Gravity.TOP) {
mScrolledY -= dy;
if (mScrolledY > 0) {
mScrolledY = 0;
}
}
// L.d("dy "+dy +" mScrolledY "+mScrolledY);
if (mReturningView == null)
return;
int translationY = 0;
int rawY = mScrolledY;
switch (mState) {
case STATE_OFFSCREEN:
if (mGravity == Gravity.BOTTOM) {
if (rawY >= mMinRawY) {
mMinRawY = rawY;
} else {
mState = STATE_RETURNING;
}
} else if (mGravity == Gravity.TOP) {
if (rawY <= mMinRawY) {
mMinRawY = rawY;
} else {
mState = STATE_RETURNING;
}
}
translationY = rawY;
break;
case STATE_ONSCREEN:
if (mGravity == Gravity.BOTTOM) {
if (rawY > mReturningViewHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
} else if (mGravity == Gravity.TOP) {
if (rawY < -mReturningViewHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
}
translationY = rawY;
break;
case STATE_RETURNING:
if (mGravity == Gravity.BOTTOM) {
translationY = (rawY - mMinRawY) + mReturningViewHeight;
if (translationY < 0) {
translationY = 0;
mMinRawY = rawY + mReturningViewHeight;
}
if (rawY == 0) {
mState = STATE_ONSCREEN;
translationY = 0;
}
if (translationY > mReturningViewHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
} else if (mGravity == Gravity.TOP) {
translationY = (rawY + Math.abs(mMinRawY)) - mReturningViewHeight;
if (translationY > 0) {
translationY = 0;
mMinRawY = rawY - mReturningViewHeight;
}
if (rawY == 0) {
mState = STATE_ONSCREEN;
translationY = 0;
}
if (translationY < -mReturningViewHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
}
break;
}
/** this can be used if the build is below honeycomb **/
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
TranslateAnimation anim = new TranslateAnimation(0, 0, translationY, translationY);
anim.setFillAfter(true);
anim.setDuration(0);
mReturningView.startAnimation(anim);
} else {
mReturningView.setTranslationY(translationY);
}
}
}
}
| true |
5d66c95d2bd56466c8ed65a68708747bb0b95400 | Java | nguyentai1996/sosanhluong365 | /app/src/main/java/com/example/timviec365/model/DbCity.java | UTF-8 | 585 | 2.09375 | 2 | [] | no_license |
package com.example.timviec365.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class DbCity {
@SerializedName("cit_id")
@Expose
private String citId;
@SerializedName("cit_name")
@Expose
private String citName;
public String getCitId() {
return citId;
}
public void setCitId(String citId) {
this.citId = citId;
}
public String getCitName() {
return citName;
}
public void setCitName(String citName) {
this.citName = citName;
}
}
| true |
13728ab290737f85b73b9d8b3870b1b7a9a7abc1 | Java | fraewn/JavaEE_MigrationTool | /code/migrationtool/migrationtool-ext-microservice/migrationtool-ext-servicemigrater/migrationtool-ext-servicemigrater-core/result/3-A/src/main/java/core/beans/messages/AuditMessage.java | UTF-8 | 1,042 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | package core.beans.messages;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "AUDIT")
public class AuditMessage {
@Id
private String id;
private Date createDate;
private String msg;
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the createDate
*/
public Date getCreateDate() {
return createDate;
}
/**
* @param createDate the createDate to set
*/
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
/**
* @return the msg
*/
public String getMsg() {
return msg;
}
/**
* @param msg the msg to set
*/
public void setMsg(String msg) {
this.msg = msg;
}
}
| true |
40b73168da4995c3df2a71e5c76b9308bc1b2df0 | Java | Samsung/Castanets | /chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/header/AnimatedProgressBar.java | UTF-8 | 2,730 | 2.40625 | 2 | [
"BSD-3-Clause"
] | permissive | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.autofill_assistant.header;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.view.View;
import org.chromium.chrome.browser.compositor.animation.CompositorAnimator;
import org.chromium.chrome.browser.widget.MaterialProgressBar;
import java.util.ArrayDeque;
import java.util.Queue;
/**
* Wrapper around {@link MaterialProgressBar} to animate progress changes and enable/disable
* pulsing.
*/
class AnimatedProgressBar {
// The number of ms the progress bar would take to go from 0 to 100%.
private static final int PROGRESS_BAR_SPEED_MS = 3_000;
private final MaterialProgressBar mProgressBar;
private boolean mIsRunningProgressAnimation;
private int mLastProgress;
private Queue<ValueAnimator> mPendingIncreaseAnimations = new ArrayDeque<>();
AnimatedProgressBar(MaterialProgressBar progressBar) {
mProgressBar = progressBar;
}
public void show() {
mProgressBar.setVisibility(View.VISIBLE);
}
public void hide() {
mProgressBar.setVisibility(View.INVISIBLE);
}
/**
* Set the progress to {@code progress}. The transition to the new progress value is
* animated.
*/
public void setProgress(int progress) {
if (progress == mLastProgress) {
return;
}
ValueAnimator progressAnimation = ValueAnimator.ofInt(mLastProgress, progress);
progressAnimation.setDuration(
PROGRESS_BAR_SPEED_MS * Math.abs(progress - mLastProgress) / 100);
progressAnimation.setInterpolator(CompositorAnimator.ACCELERATE_INTERPOLATOR);
progressAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (mPendingIncreaseAnimations.isEmpty()) {
mIsRunningProgressAnimation = false;
} else {
mIsRunningProgressAnimation = true;
mPendingIncreaseAnimations.poll().start();
}
}
});
progressAnimation.addUpdateListener(
animation -> mProgressBar.setProgress((int) animation.getAnimatedValue()));
mLastProgress = progress;
if (mIsRunningProgressAnimation) {
mPendingIncreaseAnimations.offer(progressAnimation);
} else {
mIsRunningProgressAnimation = true;
progressAnimation.start();
}
}
}
| true |
1b6c4b5393049e2795968c597fe5db0427d94b57 | Java | huntergdavis/PlayNTestApp | /notewar/core/src/main/java/com/huntergdavis/NoteWar/core/NoteWar.java | UTF-8 | 2,063 | 3.15625 | 3 | [] | no_license | package com.huntergdavis.NoteWar.core;
import static playn.core.PlayN.*;
import playn.core.Game;
import playn.core.Image;
import playn.core.ImageLayer;
import playn.core.GroupLayer;
public class NoteWar implements Game {
@Override
public void init() {
// load in our user set window properties
WindowProperties gameWindowProperties = new WindowProperties();
// set our root layer properties
graphics().setSize(gameWindowProperties.xSize,gameWindowProperties.ySize);
// load in background and root layer
loadBackground(gameWindowProperties);
// setup a new gameboard
GameBoard levelOne = setupGameBoard();
// setup our tile engine
TileEngine tileEngine = new TileEngine();
// load the tile textures and board
tileEngine.setupGameBoardTilesAndLayer(levelOne, gameWindowProperties);
// load units
loadUnits();
}
@Override
public void paint(float alpha) {
// the background automatically paints itself, so no need to do anything here!
}
@Override
public void update(float delta) {
}
/*
* required function
* returns the update rate
*/
@Override
public int updateRate() {
return 25;
}
// Private Functions
// graphics related functions
/*
* creates a background image
* loads it into a background layer
* adds it to the root layer
*/
private void loadBackground(WindowProperties windowProperties) {
// create and add background image layer
Image bgImage = assets().getImage("images/bg.png");
ImageLayer bgLayer = graphics().createImageLayer(bgImage);
graphics().rootLayer().add(bgLayer);
}
// game related functions
/*
* setup a random game board
*/
private GameBoard setupGameBoard() {
// set a new gameboard
return new GameBoard(40);
}
/*
* load in some units
*/
private void loadUnits() {
// create 1000 soliders
Soldier units[] = new Soldier[1000];
for(int i =0;i<1000;i++) {
units[i] = new Soldier();
}
units[233].setPosition(3,5);
}
}
| true |
31c6f2084a7e31fc588de117382796e073057513 | Java | ppijet/Collection6.3 | /kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/chellenges/Order.java | UTF-8 | 827 | 3 | 3 | [] | no_license | package com.kodilla.good.patterns.chellenges;
public class Order {
int orderNumber;
String product;
int quantity;
double price;
String currency;
public Order(final int orderNumber, final String product,
final int quantity, final double price,
final String currency) {
this.orderNumber = orderNumber;
this.product = product;
this.quantity = quantity;
this.price = price;
this.currency = currency;
}
public int getOrderNumber() {
return orderNumber;
}
public String getProduct() {
return product;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
public String getCurrency() {
return currency;
}
}
| true |
71667a9887c5b57a5ec2c3cffe393956d45080f0 | Java | zouxiangyun21586/spring_springmvc_hibernate_shiro | /src/com/yr/dao/implement/UserDaoImplement.java | UTF-8 | 2,549 | 2.265625 | 2 | [] | no_license | package com.yr.dao.implement;
import java.math.BigInteger;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import com.yr.dao.UserDao;
import com.yr.entity.Page;
import com.yr.entity.Role;
import com.yr.entity.User;
@Repository
public class UserDaoImplement implements UserDao{
@Resource
private SessionFactory sessionFactory;
@Override
public Page<User> query(Page<User> page) {
Session session=sessionFactory.getCurrentSession();
int startIndex = page.getPageSize() * (page.getPage()-1);
int pageSize = page.getPageSize();
Query q = session.createQuery("from User").setFirstResult(startIndex).setMaxResults(pageSize);
//查询总数
Query q1 = session.createNativeQuery("select count(*) from User");
BigInteger count = (BigInteger) q1.getSingleResult();
page.setPageSizeCount(count.intValue());
List<User> listRole= q.getResultList();
page.setT(listRole);
return page;
}
@Override
public String addUser(User user) {
Session session=sessionFactory.getCurrentSession();
Role role=session.get(Role.class,2);
user.getRoleSet().add(role);
session.save(user);
return "success";
}
@Override
public void deleteUser(Integer userId) {
Session session=sessionFactory.getCurrentSession();
Query query=session.createQuery("delete from User where id=?");
query.setParameter(0,userId);
query.executeUpdate();
}
@Override
public String findOut(String account) {
Session session=sessionFactory.getCurrentSession();
Query query=session.createQuery("select count(*) from User where account=?");
Long result=(Long) query.setParameter(0,account).getSingleResult();
return String.valueOf(result);
}
@Override
public String queryIsNull() {
Session session=sessionFactory.getCurrentSession();
Long result=(Long) session.createQuery("select count(*) from User").getSingleResult();
return String.valueOf(result);
}
@Override
public User queryToId(Integer id) {
Session session=sessionFactory.getCurrentSession();
User user=session.get(User.class,id);
return user;
}
@Override
public void updateUser(String userName, String account,Integer userId) {
Session session=sessionFactory.getCurrentSession();
User user=session.get(User.class,userId);
user.setUserName(userName);
user.setAccount(account);
session.save(user);
}
} | true |
9f7e0cb192eec2a26a4e0fd63f5becc30b1ddada | Java | wilfredw/java-demo | /excel-demo/src/main/java/com/wei/java/excel/easyexcel/model/DemoData.java | UTF-8 | 954 | 1.960938 | 2 | [] | no_license | package com.wei.java.excel.easyexcel.model;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@EqualsAndHashCode
public class DemoData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private String date;
@ExcelProperty("数字标题")
private String doubleData;
@ExcelProperty("value4")
private String value4;
@ExcelProperty("value5")
private String value5;
@ExcelProperty("value6")
private String value6;
@ExcelProperty("value7")
private String value7;
@ExcelProperty("value8")
private String value8;
@ExcelProperty("value9")
private String value9;
@ExcelProperty("value10")
private String value10;
/**
* 忽略这个字段
*/
@ExcelIgnore
private String ignore;
} | true |
508f36cc8393b7c7c4f318195473767d799c23c0 | Java | SoftDev-ie/Basic-Projects | /operations1/Test2.java | UTF-8 | 219 | 2.40625 | 2 | [] | no_license | package operations1;
public class Test2 {
public static void main(String args[]){
String s1[]= {"hello","goodbye","okay"};
int i;
for(i =0; i<s1.length; i++){
System.out.println(s1[i]);
}
}
}
| true |