hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
fe02a07482808447c73838001b7613acbd699725 | 3,145 | package by.vorokhobko.secondPart.filter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* Filter.
*
* Class Filter is designed for matching in program.
* @author Evgeny Vorokhobko ([email protected].
* @since 10.02.2018.
* @version 1.
*/
public class Filter {
/**
* The class field.
*/
private ArrayList<String> list = new ArrayList<>();
/**
* The class field.
*/
private ArrayList<String> result = new ArrayList<>();
/**
* The class field.
*/
private Pattern pattern;
/**
* The main method.
* @param args - args.
*/
public static void main(String[] args) {
new Filter().start();
}
/**
* The method start is method for starting program.
*/
private void start() {
try (Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out)) {
electoralMethod(in, out);
}
}
/**
* Method adds argument in the program.
* @param in - in.
*/
private void addArgument(Scanner in) {
System.out.println("Please enter the argument: ");
String textFirst = in.nextLine();
String[] firstLine = textFirst.split(" ");
String findElement = "";
if (firstLine.length > 1) {
for (String count : firstLine) {
findElement += count.concat("|");
}
textFirst = findElement;
}
this.pattern = Pattern.compile(textFirst);
}
/**
* Method adds string in the program.
* @param in - in.
*/
private void addCompareString(Scanner in) {
System.out.println("Please enter a string for comparison: ");
while (true) {
String textSecond = in.nextLine();
if (textSecond.isEmpty()) {
break;
}
this.list.add(textSecond);
}
}
/**
* Method compares String elements in the program.
* @param search - search.
*/
private boolean compare(String search) {
return this.pattern.matcher(search).matches();
}
/**
* Method electoral element in the program.
* @param in - in.
* @param out - out.
*/
private void electoralMethod(Scanner in, PrintWriter out) {
addArgument(in);
addCompareString(in);
System.out.println("Result: ");
for (String element : this.list) {
for (int j = 0; j < element.split(" ").length; j++) {
String result = element.split(" ")[j].replace(";", "");
if (compare(result)) {
this.result.add(element);
break;
}
}
}
printResult(out);
}
/**
* Method print all element users.
* @param out - out.
*/
private void printResult(PrintWriter out) {
for (String line : this.result) {
out.println(line);
}
if (this.result.size() == 0) {
out.println("No matches in rows!");
}
}
} | 27.347826 | 71 | 0.533227 |
e2b835567430cf2deaa4f09bc39cf512aed06911 | 1,822 | /*
* Copyright (C) 2011-2014 Aestas/IT
*
* 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.aestasit.markdown.slidery.converters;
import static com.aestasit.markdown.Resources.classpath;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import com.aestasit.markdown.slidery.configuration.Configuration;
/**
* Presentation converter that is based on <a href="http://paulrouget.com/dzslides/">DZSlides</a> framework.
*
* @author Andrey Adamovich
*
*/
public class DZSlidesConverter extends TextTemplateConverter {
public static final String CONVERTER_ID = "dzslides";
protected void beforeStart(final Configuration config) {
config.templateFile(classpath("dzslides/template.html"));
config.staticFile(classpath("dzslides/onstage.html"));
config.staticFile(classpath("dzslides/embedder.html"));
}
protected void transformDocument(final Document slidesDocument, final Configuration config) {
super.transformDocument(slidesDocument, config);
if (config.listsIncremented()) {
for (final Element list : slidesDocument.select("div ul, div ol")) {
list.addClass("incremental");
}
}
}
public String getId() {
return CONVERTER_ID;
}
public String getDescription() {
return "http://paulrouget.com/dzslides/";
}
}
| 30.366667 | 108 | 0.736553 |
bc8c9e41311931385d74e0cb175123ea236d45eb | 497 | package main.flowstoneenergy.items.tools.electrum;
import main.flowstoneenergy.FlowstoneEnergy;
import main.flowstoneenergy.core.libs.ModInfo;
import net.minecraft.item.ItemAxe;
public class ItemAxeElectrum extends ItemAxe {
public ItemAxeElectrum(ToolMaterial material) {
super(material);
this.setCreativeTab(FlowstoneEnergy.tab);
this.setUnlocalizedName(ModInfo.MODID + ".electrum.axe");
//this.setTextureName(ModInfo.MODID + ":tools/electrumAxe");
}
}
| 33.133333 | 68 | 0.752515 |
88b9728fcb9518275105ca58babbd54a352ef177 | 889 | package com.nattguld.http.proxies;
import java.util.Objects;
import com.nattguld.util.generics.kvps.impl.StringKeyValuePair;
import com.nattguld.util.hashing.Hasher;
/**
*
* @author randqm
*
*/
public class ProxyAuthCredentials extends StringKeyValuePair {
/**
* The base 64 auth.
*/
private String base64Auth;
/**
* Creates new credentials.
*
* @param username The username.
*
* @param password The password.
*/
public ProxyAuthCredentials(String username, String password) {
super(username, password);
}
/**
* Retrieves the base64 authentication.
*
* @return The base64 authentication.
*/
public String getBase64Auth() {
if (Objects.isNull(base64Auth)) {
this.base64Auth = Hasher.base64(getKey() + ":" + getValue());
}
return base64Auth;
}
@Override
public String toString() {
return getKey() + ":" + getValue();
}
}
| 17.431373 | 64 | 0.677165 |
6959f52bfaaef3b326d399b00bc937a51b2768a4 | 80 | package org.baeldung.javaxval.validationgroup;
public interface BasicInfo {
}
| 13.333333 | 46 | 0.8125 |
f5539ef510bb4b8d5656ca5645e1670892fcda7c | 284 | package com.yanxin.common.model;
import com.yanxin.common.model.base.BasePermisedDoor;
/**
* Generated by JFinal.
*/
@SuppressWarnings("serial")
public class PermisedDoor extends BasePermisedDoor<PermisedDoor> {
public static final PermisedDoor dao = new PermisedDoor().dao();
}
| 23.666667 | 66 | 0.774648 |
4614639bb8c036ff1761e2434832e493b8df5a88 | 207 | package org.sristi.sristi.utils;
/**
* Created by Ariyan Khan on 09-03-2016.
*/
public abstract class AppInfo {
//It holds the APP Code for every version
public static final int APP_CODE = 0;
}
| 17.25 | 45 | 0.690821 |
98bde055918c8d3096e53d3a26d160753afc4f49 | 1,298 | package com.webank.wecross.account;
import com.webank.wecross.exception.WeCrossException;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AccountAccessControlFilterFactory {
private static Logger logger = LoggerFactory.getLogger(AccountAccessControlFilterFactory.class);
private boolean enableAccessControl;
public AccountAccessControlFilter buildFilter(
String username, boolean isAdmin, String[] accountAllowPaths) throws WeCrossException {
if (enableAccessControl && !isAdmin) {
AccountAccessControlFilter filter = new AccountAccessControlFilter(accountAllowPaths);
if (logger.isDebugEnabled()) {
logger.debug(
"Build account access control filter, account:{} filter:{}",
username,
Arrays.toString(filter.dumpPermission()));
}
return filter;
} else {
return new DisabledAccountAccessControlFilter(accountAllowPaths);
}
}
public void setEnableAccessControl(boolean enableAccessControl) {
this.enableAccessControl = enableAccessControl;
}
public boolean isEnableAccessControl() {
return enableAccessControl;
}
}
| 35.081081 | 100 | 0.679507 |
a56800156a9ee70d3b4812719bbd281fc842c3ab | 8,784 | /*
* Copyright 2022 Starwhale, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.starwhale.mlops.agent.task.inferencetask.action.normal;
import ai.starwhale.mlops.agent.container.ImageConfig;
import ai.starwhale.mlops.agent.container.ImageConfig.CPUConfig;
import ai.starwhale.mlops.agent.container.ImageConfig.GPUConfig;
import ai.starwhale.mlops.agent.container.ImageConfig.Mount;
import ai.starwhale.mlops.agent.exception.ErrorCode;
import ai.starwhale.mlops.agent.node.SourcePool.AllocateRequest;
import ai.starwhale.mlops.agent.task.Context;
import ai.starwhale.mlops.agent.task.inferencetask.InferenceTask;
import ai.starwhale.mlops.agent.task.inferencetask.InferenceTask.ActionStatus;
import ai.starwhale.mlops.agent.task.inferencetask.InferenceTaskStatus;
import ai.starwhale.mlops.domain.node.Device;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@Service
public class Preparing2RunningAction extends AbsBasePPLTaskAction {
private static final String containerBasePath = "/opt/starwhale/";
private static final String swmpDirEnv = "SW_SWMP_WORKDIR";
private static final String statusFileEnv = "SW_TASK_STATUS_FILE";
private static final String logDirEnv = "SW_TASK_LOG_DIR";
private static final String resultDirEnv = "SW_TASK_RESULT_DIR";
private static final String swdsFileEnv = "SW_TASK_INPUT_CONFIG";
/*@Override
public boolean valid(InferenceTask task, Context context) {
// todo: Check if the previous steps have been prepared
return task.getActionStatus() != ActionStatus.inProgress;
}*/
@Override
public void orElse(InferenceTask task, Context context) {
// represent last step occurred some errors
// todo:fault tolerance
task.setActionStatus(ActionStatus.completed);
taskPersistence.save(task);
}
@Override
public InferenceTask processing(InferenceTask oldTask, Context context) throws Exception {
ImageConfig imageConfig = ImageConfig.builder()
.autoRemove(false) // finally rm
.image(oldTask.getImageId())
.labels(Map.of(
"task-id", oldTask.getId().toString(),
"task-type", oldTask.getTaskType().name(),
"swmp-name", oldTask.getSwModelPackage().getName(),
"swmp-version", oldTask.getSwModelPackage().getVersion(),
"device-type", oldTask.getDeviceClass().name(),
"device-num", oldTask.getDeviceAmount().toString()
))
.build();
// preAllocate fail, try again
if (CollectionUtil.isEmpty(oldTask.getDevices())) {
Set<Device> allocated = null;
// allocate device(GPU or CPU) for task
switch (oldTask.getDeviceClass()) {
case CPU:
allocated = sourcePool.allocate(AllocateRequest.builder().cpuNum(oldTask.getDeviceAmount()).build());
imageConfig.setCpuConfig(
CPUConfig.builder().cpuCount(Long.valueOf(oldTask.getDeviceAmount())).build()
);
break;
case GPU:
allocated = sourcePool.allocate(AllocateRequest.builder().gpuNum(oldTask.getDeviceAmount()).build());
imageConfig.setGpuConfig(
GPUConfig.builder()
.count(oldTask.getDeviceAmount())
.capabilities(List.of(List.of("gpu")))
.deviceIds(allocated.stream().map(Device::getId).collect(Collectors.toList()))
.build()
);
break;
case UNKNOWN:
log.error("unknown device class");
throw ErrorCode.allocateError.asException("unknown device class");
}
// allocate device to this task,if fail will throw exception, now it is blocked
oldTask.setDevices(allocated);
}
switch (oldTask.getTaskType()) {
case PPL:
imageConfig.setCmd(List.of("ppl"));
break;
case CMP:
imageConfig.setCmd(List.of("cmp"));
break;
}
taskPersistence.preloadingSWMP(oldTask);
imageConfig.setMounts(List.of(
Mount.builder()
.readOnly(false)
.source(fileSystemPath.oneActiveTaskDir(oldTask.getId()))
.target(containerBasePath)
.type("BIND")
.build()
/*Mount.builder()
.readOnly(false)
.source(taskPersistence.preloadingSWMP(oldTask)) // pull swmp(tar) and uncompress it to the swmp dir
.target(containerBasePath + "swmp")
.type("BIND")
.build()*/
));
// generate the file used by container(default dir)
taskPersistence.generateConfigFile(oldTask);
// task container env
imageConfig.setEnv(List.of(
env("SW_PYPI_INDEX_URL", agentProperties.getTask().getPypiIndexUrl()),
env("SW_PYPI_EXTRA_INDEX_URL", agentProperties.getTask().getPypiExtraIndexUrl()),
env("SW_PYPI_TRUSTED_HOST", agentProperties.getTask().getPypiTrustedHost()),
env("SW_SWMP_NAME", oldTask.getSwModelPackage().getName()),
env("SW_SWMP_VERSION", oldTask.getSwModelPackage().getVersion())
));
// fill with task info
Optional<String> containerId = containerClient.createAndStartContainer(imageConfig);
// whether the container create and start success
if (containerId.isPresent()) {
InferenceTask newTask = BeanUtil.toBean(oldTask, InferenceTask.class);
newTask.setContainerId(containerId.get());
newTask.setStatus(InferenceTaskStatus.RUNNING);
return newTask;
} else {
// should throw exception and handled by the fail method
throw ErrorCode.containerError.asException(
String.format("start task container by image:%s fail", oldTask.getImageId()));
}
}
private String env(String key, String value) {
return String.format("%s=%s", key, value);
}
@Override
public void success(InferenceTask oldTask, InferenceTask newTask, Context context) {
// rm from current
taskPool.preparingTasks.remove(oldTask);
// tail it to the running list
taskPool.runningTasks.add(newTask);
}
@Override
public void fail(InferenceTask oldTask, Context context, Exception e) {
log.error("execute task:{}, error:{}", oldTask.getId(), e.getMessage());
// rollback and wait again until next time
/*if (CollectionUtil.isNotEmpty(oldTask.getDevices())) {
sourcePool.release(oldTask.getDevices());
oldTask.setDevices(null);
}*/
oldTask.setActionStatus(ActionStatus.completed);
if (oldTask.getRetryRunNum() >= agentProperties.getTask().getRetryRunMaxNum()) {
// release device and move to failed list
log.error("task:{} maximum number of failed retries:{} has been reached, task failed",
oldTask.getId(), agentProperties.getTask().getRetryRunMaxNum());
sourcePool.release(oldTask.getDevices());
oldTask.setStatus(InferenceTaskStatus.FAIL);
taskPool.preparingTasks.remove(oldTask);
taskPool.failedTasks.add(oldTask);
taskPersistence.save(oldTask);
} else {
// todo: retry or take it to the tail of queue
oldTask.retryRun();
taskPersistence.save(oldTask);
}
}
}
| 44.363636 | 124 | 0.620219 |
c0ba2bf328675e8d9a88433eec4c529be3eaa79b | 1,077 | /*
* 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 classes;
import java.util.ArrayList;
import java.util.List;
public class Golya extends Balozo{
private final double KEDVEZMENY_SZAZALEK=0.2;
private List<ZeneSzam> kivantSzamok;
public Golya(int sorszam, String nev,int evfolyam) {
super(sorszam, nev,evfolyam);
kivantSzamok=new ArrayList<>();
}
public void kivalaszt(ZeneSzam z){
kivantSzamok.add(z);
}
public List<ZeneSzam> getKivantSzamok() {
return kivantSzamok;
}
@Override
public void fogyaszt(int osszeg) {
super.fogyaszt((int) (osszeg-(osszeg*KEDVEZMENY_SZAZALEK))); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String toString() {
if(super.getTancszam()==0) return super.getNev()+" (g)";
return super.getNev()+" ("+super.getTancszam()+" tánc , "+super.getZsebpenz()+" Ft) (g)";
}
}
| 24.477273 | 133 | 0.675023 |
462fd65e2f9c08df32eed3bee31ff6cd4615f1cc | 259 | package com.zing.mode.adapter.extend;
/**
* @author zing
* @date 2018/3/6 18:06
*/
public class VeryHeightVoltage {
private int voltage = 120;
public int power() {
System.out.println("电源提供电压:" + voltage);
return voltage;
}
}
| 16.1875 | 48 | 0.6139 |
36ab74f21975ea36fd05499cf987062ae39db5cf | 324 | package com.algaworks.algafood.domain.repository;
import java.util.List;
import com.algaworks.algafood.domain.model.Restaurante;
public interface RestauranteRepository {
List<Restaurante> listar();
Restaurante porId(Long id);
Restaurante adicionar(Restaurante restaurante);
void remover(Restaurante restaurante);
}
| 21.6 | 55 | 0.811728 |
517e1227768585f1f58c99cfa0ad61bc4372c443 | 516 | package com.nacid.bl.applications.base;
import com.nacid.bl.nomenclatures.Country;
/**
* User: ggeorgiev
* Date: 4.10.2019 г.
* Time: 14:26
*/
public interface DocumentRecipientBase {
public int getId();
public int getApplicationId();
public Country getCountry();
public int getCountryId();
public String getName();
public String getCity();
public String getDistrict();
public String getPostCode();
public String getAddress();
public String getMobilePhone();
}
| 16.645161 | 42 | 0.684109 |
4de73119fe2a6e3315f9c725dc7cd695046bb1fc | 2,205 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.flink.api.java.operators.translation;
import org.apache.flink.api.common.functions.AbstractRichFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.operators.UnaryOperatorInformation;
import org.apache.flink.api.common.operators.base.MapOperatorBase;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.types.TypeInformation;
public class PlanProjectOperator<T, R extends Tuple> extends MapOperatorBase<T, R, MapFunction<T, R>> {
public PlanProjectOperator(int[] fields, String name, TypeInformation<T> inType, TypeInformation<R> outType) {
super(new MapProjector<T, R>(fields, outType.createSerializer().createInstance()), new UnaryOperatorInformation<T, R>(inType, outType), name);
}
public static final class MapProjector<T, R extends Tuple>
extends AbstractRichFunction
implements MapFunction<T, R>
{
private static final long serialVersionUID = 1L;
private final int[] fields;
private final R outTuple;
private MapProjector(int[] fields, R outTupleInstance) {
this.fields = fields;
this.outTuple = outTupleInstance;
}
// TODO We should use code generation for this.
@Override
public R map(T inTuple) throws Exception {
for(int i=0; i<fields.length; i++) {
outTuple.setField(((Tuple)inTuple).getField(fields[i]), i);
}
return outTuple;
}
}
}
| 37.372881 | 144 | 0.755102 |
cceeb64495f7cb4616aede672f3a572f4f3d559b | 2,286 | /**
* ########################## GoodCrawler ############################
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.sbs.goodcrawler.extractor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sbs.goodcrawler.exception.QueueException;
import org.sbs.goodcrawler.jobconf.ExtractConfig;
import org.sbs.goodcrawler.page.ExtractedPage;
import org.sbs.goodcrawler.page.Page;
/**
* @author shenbaise([email protected])
* @date 2013-7-2
* 默认的提取器
*/
public class DefaultExtractWorker extends ExtractWorker {
private Log log = LogFactory.getLog(this.getClass());
public DefaultExtractWorker(ExtractConfig conf, Extractor extractor) {
super(conf, extractor);
}
@Override
public void run() {
Page page ;
while(!isStop()){
try {
while(null!=(page=pendingPages.getElementT())){
work(page);
if(isStop())
break;
}
} catch (QueueException e) {
log.error(e.getMessage());
}
}
}
@Override
public void onSuccessed(Page page) {
// ok
page = null;
pendingPages.getSuccess().incrementAndGet();
}
@Override
public void onFailed(Page page) {
// pendingPages.addFailedPage(page);
pendingPages.getFailure().incrementAndGet();
}
@Override
public void onIgnored(Page page) {
pendingPages.getIgnored().incrementAndGet();
}
@Override
public ExtractedPage<?, ?> doExtract(Page page) {
return extractor.onExtract(page);
}
}
| 28.936709 | 76 | 0.686789 |
c3fcb19edada9c77118c442816e434fa8157edd0 | 975 | /**
*
*/
package cjlite.web.core;
import java.util.HashMap;
import java.util.Map;
import cjlite.utils.Strings;
import cjlite.web.mvc.ModelView;
import cjlite.web.mvc.View;
import cjlite.web.render.RenderException;
import cjlite.web.render.Renderer;
import cjlite.web.render.RendererManager;
/**
* @author kevin
*
*/
public class RendererManagerImpl implements RendererManager {
private Map<String, Renderer> rendererMap = new HashMap<String, Renderer>();
public RendererManagerImpl(Map<String, Renderer> map) {
this.rendererMap.putAll(map);
}
@Override
public Renderer getRenderer(ModelView modelView) throws RenderException {
View view = modelView.getView();
Renderer renderer = rendererMap.get(view.getType());
if (renderer == null) {
String msg = Strings
.fillArgs("Renderer for View'{0}' is not register in system, please register it before using",
view.getType());
throw new RenderException(msg);
}
return renderer;
}
}
| 23.214286 | 99 | 0.734359 |
7047d4ffbf29258b9af44a231955a84eef05c15f | 3,674 | package com.cafeyvinowinebar.Cafe_y_Vino;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.messaging.FirebaseMessaging;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Upon the creation of the app's process we create the notification channels for different types of messages
* And we initialize an ExecutorService with a thread pool matching the ammount of cores available on the device
* This executor is responsible for all the background work of the app; gets shutdown when the app's process is terminated
*/
public class App extends Application {
public static final String PUERTA = "channelPuerta";
public static final String RESERVA = "channelReserva";
public static final String PEDIDO = "channelPedido";
public static final String CUENTA = "channelCuenta";
public static final String DATOS = "channelDatos";
public static final String SENDER_ID = "1096226926741";
private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
public static final ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_CORES * 2);
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channelPuerta = new NotificationChannel(
PUERTA,
"Puerta",
NotificationManager.IMPORTANCE_HIGH
);
channelPuerta.setDescription("Solicitudes y confirmaciones de entrada al restaurante");
NotificationChannel channelReserva = new NotificationChannel(
RESERVA,
"Reservas",
NotificationManager.IMPORTANCE_HIGH
);
channelReserva.setDescription("Solicitudes y confirmaciones de las reservaciones");
NotificationChannel channelPedido = new NotificationChannel(
PEDIDO,
"Pedidos",
NotificationManager.IMPORTANCE_HIGH
);
channelPedido.setDescription("Enviar y recibir confirmaciones de los pedidos");
NotificationChannel channelCuenta = new NotificationChannel(
CUENTA,
"Cuentas",
NotificationManager.IMPORTANCE_HIGH
);
channelCuenta.setDescription("Solicitudes y confirmaciones de las cuentas");
NotificationChannel channelDatos = new NotificationChannel(
DATOS,
"Promociones y mensajes personalizados",
NotificationManager.IMPORTANCE_HIGH
);
channelDatos.setDescription("Recibir promociones y otros mensajes de la administración del restaurante");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channelPuerta);
manager.createNotificationChannel(channelReserva);
manager.createNotificationChannel(channelPedido);
manager.createNotificationChannel(channelCuenta);
manager.createNotificationChannel(channelDatos);
}
}
@Override
public void onTerminate() {
super.onTerminate();
executor.shutdown();
}
}
| 40.373626 | 122 | 0.683451 |
e1daac6fc2e84a884353253b431b9245fc0a5e45 | 1,411 | package effects.simple;
import effects.Effect;
import util.Color;
import util.Image;
public class Effect_Abberation extends Effect
{
/**
*
*/
private static final long serialVersionUID = -962229356025762746L;
public static final boolean TWO_WAY_ABBERATION = true;
public static final boolean ONE_WAY_ABBERATION = false;
private int abberationH;
private int abberationV;
public Effect_Abberation(int abberation, boolean twoWay)
{
this.abberationH = abberation;
if(twoWay = TWO_WAY_ABBERATION)
abberationV = abberation;
else
abberationV = 0;
}
@Override
public Image apply(Image img)
{
//Loop through image
//Each pixel equals pixel + colour offsets
int pixelCopy[][] = new int[img.width][img.height];
for(int r = abberationV; r < img.height - abberationV - 1; r++)
{
for(int c = abberationH; c < img.width - abberationH - 1; c++)
{
int[] rgb = new int[Color.COUNT];
//Shift RGB colour channels
rgb[0] += Color.getColor(img.pixels[c -abberationH][r - abberationV], Color.RED);
rgb[1] += Color.getColor(img.pixels[c ][r], Color.GREEN);
rgb[2] += Color.getColor(img.pixels[c + abberationH][r - abberationV], Color.BLUE);
pixelCopy[c][r] = Color.makeColor(rgb[Color.RED], rgb[Color.GREEN], rgb[Color.BLUE]);
}
}
img.pixels = pixelCopy;
return img;
}
}
| 21.378788 | 90 | 0.654146 |
1c14e518cf5d3ac391059291635111198d793a15 | 3,952 | /* Copyright 2008 Edward Yakop.
*
* 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 org.qi4j.runtime.property;
import org.junit.Assert;
import org.junit.Test;
import org.qi4j.api.composite.TransientBuilder;
import org.qi4j.api.composite.TransientComposite;
import org.qi4j.api.entity.EntityBuilder;
import org.qi4j.api.entity.EntityComposite;
import org.qi4j.api.property.Immutable;
import org.qi4j.api.property.Property;
import org.qi4j.api.unitofwork.UnitOfWork;
import org.qi4j.bootstrap.AssemblyException;
import org.qi4j.bootstrap.ModuleAssembly;
import org.qi4j.test.AbstractQi4jTest;
import org.qi4j.test.EntityTestAssembler;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public final class ImmutablePropertyTest
extends AbstractQi4jTest
{
private static final String KUALA_LUMPUR = "Kuala Lumpur";
@Test
public final void testCreationalWithStateFor()
{
Location location = createLocation( KUALA_LUMPUR );
testNamePropertyGet( location, KUALA_LUMPUR );
}
private Location createLocation( String locationName )
{
TransientBuilder<Location> locationBuilder = module.newTransientBuilder( Location.class );
Location locState = locationBuilder.prototypeFor( Location.class );
locState.name().set( locationName );
return locationBuilder.newInstance();
}
private void testNamePropertyGet( Location location, String locationName )
{
assertNotNull( location );
assertEquals( locationName, location.name().get() );
}
@Test
public final void testCreationWithStateOfComposite()
{
TransientBuilder<Location> locationBuilder = module.newTransientBuilder( Location.class );
Location locState = locationBuilder.prototype();
locState.name().set( KUALA_LUMPUR );
Location location = locationBuilder.newInstance();
testNamePropertyGet( location, KUALA_LUMPUR );
}
@Test( expected = IllegalStateException.class )
public final void testSetter()
{
Location location = createLocation( KUALA_LUMPUR );
// Must fail!
Property<String> stringProperty = location.name();
stringProperty.set( "abc" );
}
@Test
public final void testImmutableEntityProperty()
{
UnitOfWork uow = module.newUnitOfWork();
try
{
EntityBuilder<LocationEntity> builder = uow.newEntityBuilder( LocationEntity.class );
builder.instance().name().set( "Rickard" );
Location location = builder.newInstance();
try
{
location.name().set( "Niclas" );
Assert.fail( "Should be immutable" );
}
catch( IllegalStateException e )
{
// Ok
}
}
finally
{
uow.discard();
}
}
public final void assemble( ModuleAssembly module )
throws AssemblyException
{
module.transients( LocationComposite.class );
module.entities( LocationEntity.class );
new EntityTestAssembler().assemble( module );
}
interface LocationComposite
extends Location, TransientComposite
{
}
interface LocationEntity
extends Location, EntityComposite
{
}
interface Location
{
@Immutable
Property<String> name();
}
}
| 29.714286 | 98 | 0.676113 |
d6ee65ad489d1f8b1b719dadc367f35bdda93a16 | 335 | package com.openatc.agent.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Token {
private String context;
// 0 从登录接口获得的token; 1 根据用户名创建token
private int source;
private long starttime;
private long endtime;
}
| 19.705882 | 38 | 0.770149 |
bbf98e26e1a64ff76f725623efe27ee0e41d2bc4 | 654 | package org.joo.virgo.node;
import org.joo.virgo.RuleContext;
import org.joo.virgo.model.ExecutionResult;
public class IfExecutionNode implements ExecutionNode {
private ExpressionExecutionNode condition;
private ExecutionNode action;
public IfExecutionNode(ExpressionExecutionNode condition, ExecutionNode action) {
this.condition = condition;
this.action = action;
}
@Override
public boolean execute(RuleContext context, ExecutionResult result) {
boolean conditionSatisfied = condition.execute(context, result);
if (!conditionSatisfied)
return false;
action.execute(context, result);
return true;
}
}
| 26.16 | 83 | 0.762997 |
5c000de20297f6bf8876b6c2840b4b8b73c318d5 | 257 | package me.adeane6.model.asset;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import me.adeane6.model.Entity;
@Getter
@Setter
@NoArgsConstructor
public class Asset extends Entity {
private AssetAttributes attributes;
}
| 17.133333 | 39 | 0.805447 |
3e3f92c1f83d0287a02223a4ac962565e77e55d4 | 906 | package net.viperfish.crawler.html.engine;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.Assert;
import org.junit.Test;
public class TestPrioritizedURLQueue {
@Test
public void testPriority() throws MalformedURLException, InterruptedException {
PrioritizedURLBlockingQueue queue = new DefaultPrioritizedURLBlockingQueue();
URL least = new URL("https://www.least.com");
URL second = new URL("https://www.second.com");
URL first = new URL("https://www.first.com");
for (int i = 0; i < 2; ++i) {
queue.offer(least);
}
for (int i = 0; i < 5; ++i) {
queue.offer(second);
}
for (int i = 0; i < 100; ++i) {
queue.offer(first);
}
Assert.assertEquals(3, queue.size());
Assert.assertEquals(first, queue.take().getSource());
Assert.assertEquals(second, queue.take().getSource());
Assert.assertEquals(least, queue.take().getSource());
}
}
| 25.166667 | 80 | 0.689845 |
f3610aff1b8e76add0c56dc3a1c1619ae4fff3bc | 4,724 | package org.nikkii.embedhttp;
import org.nikkii.embedhttp.handler.HttpRequestHandler;
import org.nikkii.embedhttp.impl.HttpCapability;
import org.nikkii.embedhttp.impl.HttpRequest;
import org.nikkii.embedhttp.impl.HttpResponse;
import org.nikkii.embedhttp.impl.HttpSession;
import org.nikkii.embedhttp.impl.HttpStatus;
import org.nikkii.embedhttp.util.content.ContentTypeMap;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.net.URLConnection;
import java.util.BitSet;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The main HttpServer class
*
* @author Nikki
*/
public class HttpServer implements Runnable {
/**
* The request service
*/
private ExecutorService service = Executors.newCachedThreadPool();
/**
* The server socket
*/
private ServerSocket socket;
/**
* A list of HttpRequestHandlers for the server
*/
private List<HttpRequestHandler> handlers = new LinkedList<HttpRequestHandler>();
@SuppressWarnings("serial")
private BitSet capabilities = new BitSet() {
{
set(HttpCapability.HTTP_1_1.ordinal(), true);
set(HttpCapability.STANDARD_POST.ordinal(), true);
}
};
private boolean running;
/**
* Construct a new HttpServer
*/
public HttpServer() {
URLConnection.setFileNameMap(new ContentTypeMap());
}
/**
* Construct and bind the HttpServer
*
* @param port The port to bind to
* @throws IOException If we are unable to bind to the specified port.
*/
public HttpServer(int port) throws IOException {
bind(port);
}
/**
* Bind the server to the specified port
*
* @param port The port to bind to
* @throws IOException If we are unable to bind to the specified port.
*/
public void bind(int port) throws IOException {
bind(new InetSocketAddress(port));
}
/**
* Bind the server to the specified SocketAddress
*
* @param addr The address to bind to
* @throws IOException If an error occurs while binding, usually port already in
* use.
*/
public void bind(SocketAddress addr) throws IOException {
socket = new ServerSocket();
socket.bind(addr);
}
/**
* Start the server in a new thread
*/
public void start() {
if (socket == null) {
throw new RuntimeException("Cannot bind a server that has not been initialized!");
}
running = true;
Thread t = new Thread(this);
t.setName("HttpServer");
t.start();
}
/**
* Stop the server
*/
public void stop() {
running = false;
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Run and process requests.
*/
@Override
public void run() {
while (running) {
try {
// Read the request
service.execute(new HttpSession(this, socket.accept()));
} catch (IOException e) {
// Ignore mostly.
}
}
}
/**
* Get the port number that the service is listening on. Useful when initializing
* with an automatically-assigned port number.
*
* @return The port we are bound to.
*/
public int getPort() {
return socket.getLocalPort();
}
/**
* Set a capability
*
* @param capability The capability to set
* @param value The value to set
*/
public void setCapability(HttpCapability capability, boolean value) {
capabilities.set(capability.ordinal(), value);
}
/**
* Add a request handler
*
* @param handler The request handler to add
*/
public void addRequestHandler(HttpRequestHandler handler) {
handlers.add(handler);
}
/**
* Remove a request handler
*
* @param handler The request handler to remove
*/
public void removeRequestHandler(HttpRequestHandler handler) {
handlers.remove(handler);
}
/**
* Dispatch a request to all handlers
*
* @param httpRequest The request to dispatch
* @throws IOException If an error occurs while sending the response from the
* handler
*/
public void dispatchRequest(HttpRequest httpRequest) throws IOException {
for (HttpRequestHandler handler : handlers) {
HttpResponse resp = handler.handleRequest(httpRequest);
if (resp != null) {
httpRequest.getSession().sendResponse(resp);
return;
}
}
if (!hasCapability(HttpCapability.THREADEDRESPONSE)) {
// If it's still here nothing handled it.
httpRequest.getSession().sendResponse(new HttpResponse(HttpStatus.NOT_FOUND, HttpStatus.NOT_FOUND.toString()));
}
}
/**
* Check if the server has a specific capability defined
*
* @param capability The capability to check
* @return The capability flag
*/
public boolean hasCapability(HttpCapability capability) {
return capabilities.get(capability.ordinal());
}
}
| 23.270936 | 114 | 0.708721 |
24d6c4a07d9db1b073089ef9d50cc883cd03f393 | 3,925 | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* licenses this file to you 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 the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apereo.portal.groups.pags.dao.jpa;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.apereo.portal.groups.pags.dao.IPersonAttributesGroupDefinition;
import org.junit.Before;
import org.junit.Test;
public class PersonAttributesGroupDefinitionImplTest {
PersonAttributesGroupDefinitionImpl a;
PersonAttributesGroupDefinitionImpl b;
PersonAttributesGroupDefinitionImpl c;
PersonAttributesGroupDefinitionImpl d;
Set<IPersonAttributesGroupDefinition> setOfA;
@Before
public void initTestVars() {
a = new PersonAttributesGroupDefinitionImpl("a", "An a");
b = new PersonAttributesGroupDefinitionImpl("b", "An b");
c = new PersonAttributesGroupDefinitionImpl("c", "An c");
d = new PersonAttributesGroupDefinitionImpl("d", "An d");
setOfA = new HashSet<>(1);
setOfA.add(a);
}
@Test
public void testSetMember() {
b.setMembers(setOfA);
assertNotNull("member set null", b.getMembers());
assertEquals("member is not one", 1, b.getMembers().size());
assertTrue("member is 'a'", b.getMembers().contains(a));
}
@Test
public void testGetDeepMembers() {
Set<IPersonAttributesGroupDefinition> setOfB = new HashSet<>(1);
setOfB.add(b);
b.setMembers(setOfA);
c.setMembers(setOfB);
assertNotNull("member set null", b.getDeepMembers());
assertEquals("member is not 1", 1, b.getDeepMembers().size());
assertTrue("member is 'a'", b.getDeepMembers().contains(a));
assertNotNull("member set null", c.getDeepMembers());
assertEquals("member is not 2", 2, c.getDeepMembers().size());
assertTrue("member is 'a'", c.getDeepMembers().contains(a));
assertTrue("member is 'b'", c.getDeepMembers().contains(b));
Set<IPersonAttributesGroupDefinition> setOfBC = new HashSet<>(1);
setOfBC.add(b);
setOfBC.add(c);
c.setMembers(setOfB);
d.setMembers(setOfBC);
assertNotNull("member set null", d.getDeepMembers());
assertEquals("member is not 3", 3, d.getDeepMembers().size());
assertTrue("member is 'a'", d.getDeepMembers().contains(a));
assertTrue("member is 'b'", d.getDeepMembers().contains(b));
assertTrue("member is 'b'", d.getDeepMembers().contains(c));
}
@Test(expected = AssertionError.class)
public void testExceptionSelfMemberRef() {
a.setMembers(setOfA);
}
@Test(expected = IllegalArgumentException.class)
public void testMembersRecursion() {
Set<IPersonAttributesGroupDefinition> setOfB = new HashSet<>(1);
setOfB.add(b);
Set<IPersonAttributesGroupDefinition> setOfC = new HashSet<>(1);
setOfC.add(c);
b.setMembers(setOfA);
c.setMembers(setOfB);
System.out.println("Count: " + c.getDeepMembers().size());
System.out.println("Count: " + c.getDeepMembers().size());
a.setMembers(setOfC);
}
}
| 40.463918 | 99 | 0.683567 |
56d0f7fddeb95e07c6b56924fe09f55b070d87da | 36,059 | package com.example.demo.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CommentExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public CommentExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andCommentidIsNull() {
addCriterion("CommentID is null");
return (Criteria) this;
}
public Criteria andCommentidIsNotNull() {
addCriterion("CommentID is not null");
return (Criteria) this;
}
public Criteria andCommentidEqualTo(Integer value) {
addCriterion("CommentID =", value, "commentid");
return (Criteria) this;
}
public Criteria andCommentidNotEqualTo(Integer value) {
addCriterion("CommentID <>", value, "commentid");
return (Criteria) this;
}
public Criteria andCommentidGreaterThan(Integer value) {
addCriterion("CommentID >", value, "commentid");
return (Criteria) this;
}
public Criteria andCommentidGreaterThanOrEqualTo(Integer value) {
addCriterion("CommentID >=", value, "commentid");
return (Criteria) this;
}
public Criteria andCommentidLessThan(Integer value) {
addCriterion("CommentID <", value, "commentid");
return (Criteria) this;
}
public Criteria andCommentidLessThanOrEqualTo(Integer value) {
addCriterion("CommentID <=", value, "commentid");
return (Criteria) this;
}
public Criteria andCommentidIn(List<Integer> values) {
addCriterion("CommentID in", values, "commentid");
return (Criteria) this;
}
public Criteria andCommentidNotIn(List<Integer> values) {
addCriterion("CommentID not in", values, "commentid");
return (Criteria) this;
}
public Criteria andCommentidBetween(Integer value1, Integer value2) {
addCriterion("CommentID between", value1, value2, "commentid");
return (Criteria) this;
}
public Criteria andCommentidNotBetween(Integer value1, Integer value2) {
addCriterion("CommentID not between", value1, value2, "commentid");
return (Criteria) this;
}
public Criteria andSupplieridIsNull() {
addCriterion("SupplierID is null");
return (Criteria) this;
}
public Criteria andSupplieridIsNotNull() {
addCriterion("SupplierID is not null");
return (Criteria) this;
}
public Criteria andSupplieridEqualTo(Integer value) {
addCriterion("SupplierID =", value, "supplierid");
return (Criteria) this;
}
public Criteria andSupplieridNotEqualTo(Integer value) {
addCriterion("SupplierID <>", value, "supplierid");
return (Criteria) this;
}
public Criteria andSupplieridGreaterThan(Integer value) {
addCriterion("SupplierID >", value, "supplierid");
return (Criteria) this;
}
public Criteria andSupplieridGreaterThanOrEqualTo(Integer value) {
addCriterion("SupplierID >=", value, "supplierid");
return (Criteria) this;
}
public Criteria andSupplieridLessThan(Integer value) {
addCriterion("SupplierID <", value, "supplierid");
return (Criteria) this;
}
public Criteria andSupplieridLessThanOrEqualTo(Integer value) {
addCriterion("SupplierID <=", value, "supplierid");
return (Criteria) this;
}
public Criteria andSupplieridIn(List<Integer> values) {
addCriterion("SupplierID in", values, "supplierid");
return (Criteria) this;
}
public Criteria andSupplieridNotIn(List<Integer> values) {
addCriterion("SupplierID not in", values, "supplierid");
return (Criteria) this;
}
public Criteria andSupplieridBetween(Integer value1, Integer value2) {
addCriterion("SupplierID between", value1, value2, "supplierid");
return (Criteria) this;
}
public Criteria andSupplieridNotBetween(Integer value1, Integer value2) {
addCriterion("SupplierID not between", value1, value2, "supplierid");
return (Criteria) this;
}
public Criteria andCommentdateIsNull() {
addCriterion("CommentDate is null");
return (Criteria) this;
}
public Criteria andCommentdateIsNotNull() {
addCriterion("CommentDate is not null");
return (Criteria) this;
}
public Criteria andCommentdateEqualTo(Date value) {
addCriterion("CommentDate =", value, "commentdate");
return (Criteria) this;
}
public Criteria andCommentdateNotEqualTo(Date value) {
addCriterion("CommentDate <>", value, "commentdate");
return (Criteria) this;
}
public Criteria andCommentdateGreaterThan(Date value) {
addCriterion("CommentDate >", value, "commentdate");
return (Criteria) this;
}
public Criteria andCommentdateGreaterThanOrEqualTo(Date value) {
addCriterion("CommentDate >=", value, "commentdate");
return (Criteria) this;
}
public Criteria andCommentdateLessThan(Date value) {
addCriterion("CommentDate <", value, "commentdate");
return (Criteria) this;
}
public Criteria andCommentdateLessThanOrEqualTo(Date value) {
addCriterion("CommentDate <=", value, "commentdate");
return (Criteria) this;
}
public Criteria andCommentdateIn(List<Date> values) {
addCriterion("CommentDate in", values, "commentdate");
return (Criteria) this;
}
public Criteria andCommentdateNotIn(List<Date> values) {
addCriterion("CommentDate not in", values, "commentdate");
return (Criteria) this;
}
public Criteria andCommentdateBetween(Date value1, Date value2) {
addCriterion("CommentDate between", value1, value2, "commentdate");
return (Criteria) this;
}
public Criteria andCommentdateNotBetween(Date value1, Date value2) {
addCriterion("CommentDate not between", value1, value2, "commentdate");
return (Criteria) this;
}
public Criteria andEventmetricIsNull() {
addCriterion("EventMetric is null");
return (Criteria) this;
}
public Criteria andEventmetricIsNotNull() {
addCriterion("EventMetric is not null");
return (Criteria) this;
}
public Criteria andEventmetricEqualTo(Integer value) {
addCriterion("EventMetric =", value, "eventmetric");
return (Criteria) this;
}
public Criteria andEventmetricNotEqualTo(Integer value) {
addCriterion("EventMetric <>", value, "eventmetric");
return (Criteria) this;
}
public Criteria andEventmetricGreaterThan(Integer value) {
addCriterion("EventMetric >", value, "eventmetric");
return (Criteria) this;
}
public Criteria andEventmetricGreaterThanOrEqualTo(Integer value) {
addCriterion("EventMetric >=", value, "eventmetric");
return (Criteria) this;
}
public Criteria andEventmetricLessThan(Integer value) {
addCriterion("EventMetric <", value, "eventmetric");
return (Criteria) this;
}
public Criteria andEventmetricLessThanOrEqualTo(Integer value) {
addCriterion("EventMetric <=", value, "eventmetric");
return (Criteria) this;
}
public Criteria andEventmetricIn(List<Integer> values) {
addCriterion("EventMetric in", values, "eventmetric");
return (Criteria) this;
}
public Criteria andEventmetricNotIn(List<Integer> values) {
addCriterion("EventMetric not in", values, "eventmetric");
return (Criteria) this;
}
public Criteria andEventmetricBetween(Integer value1, Integer value2) {
addCriterion("EventMetric between", value1, value2, "eventmetric");
return (Criteria) this;
}
public Criteria andEventmetricNotBetween(Integer value1, Integer value2) {
addCriterion("EventMetric not between", value1, value2, "eventmetric");
return (Criteria) this;
}
public Criteria andEventtypeIsNull() {
addCriterion("EventType is null");
return (Criteria) this;
}
public Criteria andEventtypeIsNotNull() {
addCriterion("EventType is not null");
return (Criteria) this;
}
public Criteria andEventtypeEqualTo(Integer value) {
addCriterion("EventType =", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeNotEqualTo(Integer value) {
addCriterion("EventType <>", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeGreaterThan(Integer value) {
addCriterion("EventType >", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeGreaterThanOrEqualTo(Integer value) {
addCriterion("EventType >=", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeLessThan(Integer value) {
addCriterion("EventType <", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeLessThanOrEqualTo(Integer value) {
addCriterion("EventType <=", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeIn(List<Integer> values) {
addCriterion("EventType in", values, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeNotIn(List<Integer> values) {
addCriterion("EventType not in", values, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeBetween(Integer value1, Integer value2) {
addCriterion("EventType between", value1, value2, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeNotBetween(Integer value1, Integer value2) {
addCriterion("EventType not between", value1, value2, "eventtype");
return (Criteria) this;
}
public Criteria andEventimpactIsNull() {
addCriterion("EventImpact is null");
return (Criteria) this;
}
public Criteria andEventimpactIsNotNull() {
addCriterion("EventImpact is not null");
return (Criteria) this;
}
public Criteria andEventimpactEqualTo(Integer value) {
addCriterion("EventImpact =", value, "eventimpact");
return (Criteria) this;
}
public Criteria andEventimpactNotEqualTo(Integer value) {
addCriterion("EventImpact <>", value, "eventimpact");
return (Criteria) this;
}
public Criteria andEventimpactGreaterThan(Integer value) {
addCriterion("EventImpact >", value, "eventimpact");
return (Criteria) this;
}
public Criteria andEventimpactGreaterThanOrEqualTo(Integer value) {
addCriterion("EventImpact >=", value, "eventimpact");
return (Criteria) this;
}
public Criteria andEventimpactLessThan(Integer value) {
addCriterion("EventImpact <", value, "eventimpact");
return (Criteria) this;
}
public Criteria andEventimpactLessThanOrEqualTo(Integer value) {
addCriterion("EventImpact <=", value, "eventimpact");
return (Criteria) this;
}
public Criteria andEventimpactIn(List<Integer> values) {
addCriterion("EventImpact in", values, "eventimpact");
return (Criteria) this;
}
public Criteria andEventimpactNotIn(List<Integer> values) {
addCriterion("EventImpact not in", values, "eventimpact");
return (Criteria) this;
}
public Criteria andEventimpactBetween(Integer value1, Integer value2) {
addCriterion("EventImpact between", value1, value2, "eventimpact");
return (Criteria) this;
}
public Criteria andEventimpactNotBetween(Integer value1, Integer value2) {
addCriterion("EventImpact not between", value1, value2, "eventimpact");
return (Criteria) this;
}
public Criteria andEventdescriptionIsNull() {
addCriterion("EventDescription is null");
return (Criteria) this;
}
public Criteria andEventdescriptionIsNotNull() {
addCriterion("EventDescription is not null");
return (Criteria) this;
}
public Criteria andEventdescriptionEqualTo(String value) {
addCriterion("EventDescription =", value, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionNotEqualTo(String value) {
addCriterion("EventDescription <>", value, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionGreaterThan(String value) {
addCriterion("EventDescription >", value, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionGreaterThanOrEqualTo(String value) {
addCriterion("EventDescription >=", value, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionLessThan(String value) {
addCriterion("EventDescription <", value, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionLessThanOrEqualTo(String value) {
addCriterion("EventDescription <=", value, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionLike(String value) {
addCriterion("EventDescription like", value, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionNotLike(String value) {
addCriterion("EventDescription not like", value, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionIn(List<String> values) {
addCriterion("EventDescription in", values, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionNotIn(List<String> values) {
addCriterion("EventDescription not in", values, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionBetween(String value1, String value2) {
addCriterion("EventDescription between", value1, value2, "eventdescription");
return (Criteria) this;
}
public Criteria andEventdescriptionNotBetween(String value1, String value2) {
addCriterion("EventDescription not between", value1, value2, "eventdescription");
return (Criteria) this;
}
public Criteria andCommodityidIsNull() {
addCriterion("CommodityID is null");
return (Criteria) this;
}
public Criteria andCommodityidIsNotNull() {
addCriterion("CommodityID is not null");
return (Criteria) this;
}
public Criteria andCommodityidEqualTo(Integer value) {
addCriterion("CommodityID =", value, "commodityid");
return (Criteria) this;
}
public Criteria andCommodityidNotEqualTo(Integer value) {
addCriterion("CommodityID <>", value, "commodityid");
return (Criteria) this;
}
public Criteria andCommodityidGreaterThan(Integer value) {
addCriterion("CommodityID >", value, "commodityid");
return (Criteria) this;
}
public Criteria andCommodityidGreaterThanOrEqualTo(Integer value) {
addCriterion("CommodityID >=", value, "commodityid");
return (Criteria) this;
}
public Criteria andCommodityidLessThan(Integer value) {
addCriterion("CommodityID <", value, "commodityid");
return (Criteria) this;
}
public Criteria andCommodityidLessThanOrEqualTo(Integer value) {
addCriterion("CommodityID <=", value, "commodityid");
return (Criteria) this;
}
public Criteria andCommodityidIn(List<Integer> values) {
addCriterion("CommodityID in", values, "commodityid");
return (Criteria) this;
}
public Criteria andCommodityidNotIn(List<Integer> values) {
addCriterion("CommodityID not in", values, "commodityid");
return (Criteria) this;
}
public Criteria andCommodityidBetween(Integer value1, Integer value2) {
addCriterion("CommodityID between", value1, value2, "commodityid");
return (Criteria) this;
}
public Criteria andCommodityidNotBetween(Integer value1, Integer value2) {
addCriterion("CommodityID not between", value1, value2, "commodityid");
return (Criteria) this;
}
public Criteria andCreatetimeIsNull() {
addCriterion("CreateTime is null");
return (Criteria) this;
}
public Criteria andCreatetimeIsNotNull() {
addCriterion("CreateTime is not null");
return (Criteria) this;
}
public Criteria andCreatetimeEqualTo(Date value) {
addCriterion("CreateTime =", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeNotEqualTo(Date value) {
addCriterion("CreateTime <>", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeGreaterThan(Date value) {
addCriterion("CreateTime >", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeGreaterThanOrEqualTo(Date value) {
addCriterion("CreateTime >=", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeLessThan(Date value) {
addCriterion("CreateTime <", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeLessThanOrEqualTo(Date value) {
addCriterion("CreateTime <=", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeIn(List<Date> values) {
addCriterion("CreateTime in", values, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeNotIn(List<Date> values) {
addCriterion("CreateTime not in", values, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeBetween(Date value1, Date value2) {
addCriterion("CreateTime between", value1, value2, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeNotBetween(Date value1, Date value2) {
addCriterion("CreateTime not between", value1, value2, "createtime");
return (Criteria) this;
}
public Criteria andSnIsNull() {
addCriterion("SN is null");
return (Criteria) this;
}
public Criteria andSnIsNotNull() {
addCriterion("SN is not null");
return (Criteria) this;
}
public Criteria andSnEqualTo(String value) {
addCriterion("SN =", value, "sn");
return (Criteria) this;
}
public Criteria andSnNotEqualTo(String value) {
addCriterion("SN <>", value, "sn");
return (Criteria) this;
}
public Criteria andSnGreaterThan(String value) {
addCriterion("SN >", value, "sn");
return (Criteria) this;
}
public Criteria andSnGreaterThanOrEqualTo(String value) {
addCriterion("SN >=", value, "sn");
return (Criteria) this;
}
public Criteria andSnLessThan(String value) {
addCriterion("SN <", value, "sn");
return (Criteria) this;
}
public Criteria andSnLessThanOrEqualTo(String value) {
addCriterion("SN <=", value, "sn");
return (Criteria) this;
}
public Criteria andSnLike(String value) {
addCriterion("SN like", value, "sn");
return (Criteria) this;
}
public Criteria andSnNotLike(String value) {
addCriterion("SN not like", value, "sn");
return (Criteria) this;
}
public Criteria andSnIn(List<String> values) {
addCriterion("SN in", values, "sn");
return (Criteria) this;
}
public Criteria andSnNotIn(List<String> values) {
addCriterion("SN not in", values, "sn");
return (Criteria) this;
}
public Criteria andSnBetween(String value1, String value2) {
addCriterion("SN between", value1, value2, "sn");
return (Criteria) this;
}
public Criteria andSnNotBetween(String value1, String value2) {
addCriterion("SN not between", value1, value2, "sn");
return (Criteria) this;
}
public Criteria andUsernameIsNull() {
addCriterion("UserName is null");
return (Criteria) this;
}
public Criteria andUsernameIsNotNull() {
addCriterion("UserName is not null");
return (Criteria) this;
}
public Criteria andUsernameEqualTo(String value) {
addCriterion("UserName =", value, "username");
return (Criteria) this;
}
public Criteria andUsernameNotEqualTo(String value) {
addCriterion("UserName <>", value, "username");
return (Criteria) this;
}
public Criteria andUsernameGreaterThan(String value) {
addCriterion("UserName >", value, "username");
return (Criteria) this;
}
public Criteria andUsernameGreaterThanOrEqualTo(String value) {
addCriterion("UserName >=", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLessThan(String value) {
addCriterion("UserName <", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLessThanOrEqualTo(String value) {
addCriterion("UserName <=", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLike(String value) {
addCriterion("UserName like", value, "username");
return (Criteria) this;
}
public Criteria andUsernameNotLike(String value) {
addCriterion("UserName not like", value, "username");
return (Criteria) this;
}
public Criteria andUsernameIn(List<String> values) {
addCriterion("UserName in", values, "username");
return (Criteria) this;
}
public Criteria andUsernameNotIn(List<String> values) {
addCriterion("UserName not in", values, "username");
return (Criteria) this;
}
public Criteria andUsernameBetween(String value1, String value2) {
addCriterion("UserName between", value1, value2, "username");
return (Criteria) this;
}
public Criteria andUsernameNotBetween(String value1, String value2) {
addCriterion("UserName not between", value1, value2, "username");
return (Criteria) this;
}
public Criteria andUpdatetimeIsNull() {
addCriterion("UpdateTime is null");
return (Criteria) this;
}
public Criteria andUpdatetimeIsNotNull() {
addCriterion("UpdateTime is not null");
return (Criteria) this;
}
public Criteria andUpdatetimeEqualTo(Date value) {
addCriterion("UpdateTime =", value, "updatetime");
return (Criteria) this;
}
public Criteria andUpdatetimeNotEqualTo(Date value) {
addCriterion("UpdateTime <>", value, "updatetime");
return (Criteria) this;
}
public Criteria andUpdatetimeGreaterThan(Date value) {
addCriterion("UpdateTime >", value, "updatetime");
return (Criteria) this;
}
public Criteria andUpdatetimeGreaterThanOrEqualTo(Date value) {
addCriterion("UpdateTime >=", value, "updatetime");
return (Criteria) this;
}
public Criteria andUpdatetimeLessThan(Date value) {
addCriterion("UpdateTime <", value, "updatetime");
return (Criteria) this;
}
public Criteria andUpdatetimeLessThanOrEqualTo(Date value) {
addCriterion("UpdateTime <=", value, "updatetime");
return (Criteria) this;
}
public Criteria andUpdatetimeIn(List<Date> values) {
addCriterion("UpdateTime in", values, "updatetime");
return (Criteria) this;
}
public Criteria andUpdatetimeNotIn(List<Date> values) {
addCriterion("UpdateTime not in", values, "updatetime");
return (Criteria) this;
}
public Criteria andUpdatetimeBetween(Date value1, Date value2) {
addCriterion("UpdateTime between", value1, value2, "updatetime");
return (Criteria) this;
}
public Criteria andUpdatetimeNotBetween(Date value1, Date value2) {
addCriterion("UpdateTime not between", value1, value2, "updatetime");
return (Criteria) this;
}
public Criteria andUpdateuserIsNull() {
addCriterion("UpdateUser is null");
return (Criteria) this;
}
public Criteria andUpdateuserIsNotNull() {
addCriterion("UpdateUser is not null");
return (Criteria) this;
}
public Criteria andUpdateuserEqualTo(String value) {
addCriterion("UpdateUser =", value, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserNotEqualTo(String value) {
addCriterion("UpdateUser <>", value, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserGreaterThan(String value) {
addCriterion("UpdateUser >", value, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserGreaterThanOrEqualTo(String value) {
addCriterion("UpdateUser >=", value, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserLessThan(String value) {
addCriterion("UpdateUser <", value, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserLessThanOrEqualTo(String value) {
addCriterion("UpdateUser <=", value, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserLike(String value) {
addCriterion("UpdateUser like", value, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserNotLike(String value) {
addCriterion("UpdateUser not like", value, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserIn(List<String> values) {
addCriterion("UpdateUser in", values, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserNotIn(List<String> values) {
addCriterion("UpdateUser not in", values, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserBetween(String value1, String value2) {
addCriterion("UpdateUser between", value1, value2, "updateuser");
return (Criteria) this;
}
public Criteria andUpdateuserNotBetween(String value1, String value2) {
addCriterion("UpdateUser not between", value1, value2, "updateuser");
return (Criteria) this;
}
public Criteria andIsdeleteIsNull() {
addCriterion("IsDelete is null");
return (Criteria) this;
}
public Criteria andIsdeleteIsNotNull() {
addCriterion("IsDelete is not null");
return (Criteria) this;
}
public Criteria andIsdeleteEqualTo(Integer value) {
addCriterion("IsDelete =", value, "isdelete");
return (Criteria) this;
}
public Criteria andIsdeleteNotEqualTo(Integer value) {
addCriterion("IsDelete <>", value, "isdelete");
return (Criteria) this;
}
public Criteria andIsdeleteGreaterThan(Integer value) {
addCriterion("IsDelete >", value, "isdelete");
return (Criteria) this;
}
public Criteria andIsdeleteGreaterThanOrEqualTo(Integer value) {
addCriterion("IsDelete >=", value, "isdelete");
return (Criteria) this;
}
public Criteria andIsdeleteLessThan(Integer value) {
addCriterion("IsDelete <", value, "isdelete");
return (Criteria) this;
}
public Criteria andIsdeleteLessThanOrEqualTo(Integer value) {
addCriterion("IsDelete <=", value, "isdelete");
return (Criteria) this;
}
public Criteria andIsdeleteIn(List<Integer> values) {
addCriterion("IsDelete in", values, "isdelete");
return (Criteria) this;
}
public Criteria andIsdeleteNotIn(List<Integer> values) {
addCriterion("IsDelete not in", values, "isdelete");
return (Criteria) this;
}
public Criteria andIsdeleteBetween(Integer value1, Integer value2) {
addCriterion("IsDelete between", value1, value2, "isdelete");
return (Criteria) this;
}
public Criteria andIsdeleteNotBetween(Integer value1, Integer value2) {
addCriterion("IsDelete not between", value1, value2, "isdelete");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | 33.357077 | 102 | 0.59203 |
7026b88c4a8373d09a788e405e08b3944acdb2a1 | 1,708 | package com.siyeh.igtest.migration.raw_use_of_parameterized_type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
@interface Anno {
<warning descr="Raw use of parameterized class 'Class'">Class</warning> method() default List.class;
Class<? extends List> method2() default List.class;
}
class RawUseOfParameterizedType {
void array() {
final <warning descr="Raw use of parameterized class 'ArrayList'">ArrayList</warning>[] array =
new ArrayList[10];
}
void anonymous() {
new <warning descr="Raw use of parameterized class 'Callable'">Callable</warning>() {
@Override
public Object call() throws Exception {
return null;
}
};
}
void innerClass() {
Map.Entry<String, String> entry;
}
interface Foo {
List<?>[] fun(int size);
}
Foo methodRef() {
return List[]::new;
}
}
interface X {
<warning descr="Raw use of parameterized class 'List'">List</warning> foo(<warning descr="Raw use of parameterized class 'Map'">Map</warning> map);
}
class Y implements X {
Y(Map<String, <warning descr="Raw use of parameterized class 'Comparable'">Comparable</warning>> properties) {}
@Override
public <warning descr="Raw use of parameterized class 'List'">List</warning> foo(Map map) {
return null;
}
boolean m(Object o) {
final Class<List<String>[][]> aClass = (Class)List[][].class;
return o instanceof List[];
}
int f(Object o) {
return ((List[])o).length;
}
}
class Z extends Y {
Z(Map<String, Comparable> properties) {
this(properties, "");
}
Z(Map<String, Comparable> properties, String s) {
super(properties);
}
}
| 24.753623 | 149 | 0.668618 |
4b793a0e9b252959739dc631e19eb2f8e2617bec | 3,150 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 org.apache.doris.common.util;
import org.apache.doris.analysis.Analyzer;
import org.apache.doris.qe.ConnectContext;
import org.apache.doris.qe.StmtExecutor;
public class VectorizedUtil {
/**
* 1. Return false if there is no current connection (Rule1 to be changed)
* 2. Returns the vectorized switch value of the query 'globalState.enableQueryVec'
* 3. If it is not currently a query, return the vectorized switch value of the session 'enableVectorizedEngine'
* @return true: vec. false: non-vec
*/
public static boolean isVectorized() {
ConnectContext connectContext = ConnectContext.get();
if (connectContext == null) {
return false;
}
StmtExecutor stmtExecutor = connectContext.getExecutor();
if (stmtExecutor == null) {
return connectContext.getSessionVariable().enableVectorizedEngine();
}
Analyzer analyzer = stmtExecutor.getAnalyzer();
if (analyzer == null) {
return connectContext.getSessionVariable().enableVectorizedEngine();
}
return analyzer.enableQueryVec();
}
/**
* The purpose of this function is to turn off the vectorization switch for the current query.
* When the vectorization engine cannot meet the requirements of the current query,
* it will convert the current query into a non-vectorized query.
* Note that this will only change the **vectorization switch for a single query**,
* and will not affect other queries in the same session.
* Therefore, even if the vectorization switch of the current query is turned off,
* the vectorization properties of subsequent queries will not be affected.
*
* Session: set enable_vectorized_engine=true;
* Query1: select * from table (vec)
* Query2: select * from t1 left join (select count(*) as count from t2) t3 on t1.k1=t3.count (switch to non-vec)
* Query3: select * from table (still vec)
*/
public static void switchToQueryNonVec() {
ConnectContext connectContext = ConnectContext.get();
if (connectContext == null) {
return;
}
Analyzer analyzer = connectContext.getExecutor().getAnalyzer();
if (analyzer == null) {
return;
}
analyzer.disableQueryVec();
}
}
| 42.567568 | 117 | 0.691746 |
9069c717526ef5d125817336db2ef558527883bc | 418 | package robson.games.tictactoe.model;
import org.junit.Assert;
import org.junit.Test;
public class FieldTest {
@Test
public void shouldControlItsAssignee() {
Field field = new Field(0, 1);
Assert.assertFalse(field.isAssigned());
field.assign(new Player('X'));
Assert.assertTrue(field.isAssigned());
Assert.assertEquals(new Player('X'), field.getAssigned());
}
}
| 23.222222 | 66 | 0.660287 |
101021d77d2a43d88d0887d726e41012ecb9f2e3 | 1,707 | /*******************************************************************************
* Copyright (c) 2006 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.chart.script.internal.attribute;
import org.eclipse.birt.chart.model.attribute.FontDefinition;
import org.eclipse.birt.report.model.api.extension.IFont;
/**
*
*/
public class FontImpl implements IFont
{
private FontDefinition fd = null;
public FontImpl( FontDefinition fd )
{
this.fd = fd;
}
public String getName( )
{
return fd.getName( );
}
public float getSize( )
{
return fd.getSize( );
}
public boolean isBold( )
{
return fd.isBold( );
}
public boolean isItalic( )
{
return fd.isItalic( );
}
public boolean isStrikeThrough( )
{
return fd.isStrikethrough( );
}
public boolean isUnderline( )
{
return fd.isUnderline( );
}
public void setBold( boolean isBold )
{
fd.setBold( isBold );
}
public void setItalic( boolean isItalic )
{
fd.setItalic( isItalic );
}
public void setStrikeThrough( boolean isStrikeThrough )
{
fd.setStrikethrough( isStrikeThrough );
}
public void setUnderline( boolean isUnderline )
{
fd.setUnderline( isUnderline );
}
public void setName( String name )
{
fd.setName( name );
}
public void setSize( float size )
{
fd.setSize( size );
}
}
| 18.554348 | 81 | 0.635032 |
474508e38d1b57e4d6e836b8c83d916dc0e71a75 | 748 | package luozix.start.lambdas.exams.examples.chapter1.answers.chapter9;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import luozix.start.lambdas.exams.answers.chapter9.BlockingArtistAnalyzer;
public class BlockingArtistAnalyzerTest {
private final luozix.start.lambdas.exams.answers.chapter9.BlockingArtistAnalyzer analyser = new BlockingArtistAnalyzer(
new FakeLookupService()::lookupArtistName);
@Test
public void largerGroupsAreLarger() {
assertTrue(analyser.isLargerGroup("The Beatles", "John Coltrane"));
}
@Test
public void smallerGroupsArentLarger() {
assertFalse(analyser.isLargerGroup("John Coltrane", "The Beatles"));
}
}
| 28.769231 | 120 | 0.770053 |
2490c504bc8b322685d58a9e844c5d120a8ba074 | 833 | package pl.solutions.software.sokolik.bartosz.security;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
@ConfigurationProperties(prefix = "microservice.security")
public class SecurityProperties {
private long expirationTime;
private String secret;
public long getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(long expirationTime) {
this.expirationTime = expirationTime;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
| 26.870968 | 81 | 0.762305 |
a4509a60960b40f3a33bb40c1812a562b5de50a0 | 4,819 | package java.android.quanlybanhang.DatBan;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.android.quanlybanhang.Activity.KhachHangActivity;
import java.android.quanlybanhang.DatBan.History.Data.DonHang;
import java.android.quanlybanhang.DatBan.History.DonHangNhanFrament;
import java.android.quanlybanhang.R;
import java.android.quanlybanhang.Sonclass.KhachHang;
import java.sql.Timestamp;
import java.util.ArrayList;
public class DanhGiaCuaHang extends AppCompatActivity {
private ArrayList<DonHang> list;
DonHang donHang;
Button bnt_dongy;
RatingBar ratingBar;
EditText editTextNumber;
public static int ss =0;
String flag ;
private ArrayList<DonHang> donHangs;
DonHangNhanFrament donHangNhanFrament= new DonHangNhanFrament();
private FirebaseDatabase mFirebaseInstance;
private DatabaseReference mFirebaseDatabase;
private KhachHang khachHang = KhachHangActivity.khachHang;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_danh_gia_cua_hang);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
DonHangNhanFrament.dialogthanhcong=1;
flag= intent.getStringExtra("flag");
if((DonHang) bundle.getSerializable("list")!=null){
donHang =(DonHang) bundle.getSerializable("list");
}
bnt_dongy = findViewById(R.id.bnt_dongy);
ratingBar = findViewById(R.id.ratingBar);
editTextNumber= findViewById(R.id.editTextNumber);
bnt_dongy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (flag.equals("1")) {
float result = ratingBar.getRating();
if (editTextNumber.getText().toString().isEmpty()) {
editTextNumber.setError("Bạn quên nhập đánh giá!!!");
editTextNumber.requestFocus();
} else if (result < 1) {
Toast.makeText(DanhGiaCuaHang.this, "Bạn ơi ,vui lòng đánh giá 1 sao", Toast.LENGTH_LONG).show();
} else {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("rating").child("idcuahang").child(donHang.getIdQuan()).child(donHang.getIdKhachhang()).child(donHang.getIdDonHang());
databaseReference.child("tenkhachhang").setValue(donHang.getTenKhachhang());
databaseReference.child("numberrating").setValue(result);
databaseReference.child("comment").setValue(editTextNumber.getText() + "");
databaseReference.child("date").setValue(hamlaydate());
DonHangNhanFrament.dialogthanhcong = 2;
onBackPressed();
}
}
else {
float result = ratingBar.getRating();
if (editTextNumber.getText().toString().isEmpty()) {
editTextNumber.setError("Bạn quên nhập đánh giá!!!");
editTextNumber.requestFocus();
} else if (result < 1) {
Toast.makeText(DanhGiaCuaHang.this, "vui lòng đánh giá sao", Toast.LENGTH_LONG).show();
} else {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("rating").child("idshipper").child(donHang.getIdShipper()).child(donHang.getIdKhachhang()).child(donHang.getIdDonHang());
databaseReference.child("tenkhachhang").setValue(donHang.getTenKhachhang());
databaseReference.child("numberrating").setValue(result);
databaseReference.child("comment").setValue(editTextNumber.getText() + "");
databaseReference.child("date").setValue(hamlaydate());
DonHangNhanFrament.dialogthanhcong = 2;
onBackPressed();
}
}
}
});
}
//ham chuyen ngay thanh chuoi
public String hamlaydate() {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
return timestamp.getTime()+"";
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
} | 46.336538 | 235 | 0.630629 |
40c8fc9c6e1f7ce8c8b17e48923313302936300d | 3,085 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.wikimedia.gobblin.converter;
import java.util.Iterator;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.converter.DataConversionException;
import org.wikimedia.gobblin.TimestampedRecord;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
public class TestTimestampedRecordConverterWrapper {
@Test(expectedExceptions = RuntimeException.class)
public void testNoConfig() {
WorkUnitState workUnitState = new WorkUnitState();
TimestampedRecordConverterWrapper converter =
(TimestampedRecordConverterWrapper) new TimestampedRecordConverterWrapper().init(workUnitState);
}
@Test(expectedExceptions = RuntimeException.class)
public void testWrongConfig() {
WorkUnitState workUnitState = new WorkUnitState();
workUnitState.setProp(
TimestampedRecordConverterWrapper.CONVERTER_TIMESTAMPED_RECORD_WRAPPED,
"WrongClass");
TimestampedRecordConverterWrapper converter =
(TimestampedRecordConverterWrapper) new TimestampedRecordConverterWrapper().init(workUnitState);
}
@Test
public void testConvertRecord() throws DataConversionException {
WorkUnitState workUnitState = new WorkUnitState();
workUnitState.setProp(
TimestampedRecordConverterWrapper.CONVERTER_TIMESTAMPED_RECORD_WRAPPED,
"org.apache.gobblin.converter.string.StringToBytesConverter");
TimestampedRecordConverterWrapper converter =
(TimestampedRecordConverterWrapper) new TimestampedRecordConverterWrapper().init(workUnitState);
TimestampedRecord<String> input = new TimestampedRecord("test", Optional.absent());
Iterator<TimestampedRecord<byte[]>> iterator = converter.convertRecord(null, input, new WorkUnitState()).iterator();
Assert.assertTrue(iterator.hasNext());
TimestampedRecord<byte[]> output = iterator.next();
Assert.assertEquals(input.getTimestamp(), output.getTimestamp());
Assert.assertEquals(input.getPayload().getBytes(Charsets.UTF_8), output.getPayload());
Assert.assertFalse(iterator.hasNext());
}
}
| 43.450704 | 124 | 0.745543 |
e881aa9ca5afbdf9f0fac09f49d06a9e0cba3d7e | 4,188 | /*
* Copyright 2012-2017 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 org.openhubframework.openhub.core.common.asynch.msg;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.openhubframework.openhub.core.common.asynch.msg.MessageHelper.allowedActions;
import java.time.Instant;
import java.util.UUID;
import org.junit.Test;
import org.openhubframework.openhub.api.entity.Message;
import org.openhubframework.openhub.api.entity.MessageActionType;
import org.openhubframework.openhub.api.entity.MsgStateEnum;
import org.openhubframework.openhub.test.data.ExternalSystemTestEnum;
import org.openhubframework.openhub.test.data.ServiceTestEnum;
/**
* Test suite for {@link MessageHelper}.
*
* @author Karel Kovarik
*/
public class MessageHelperTest {
@Test
public void test_allowedActions() {
assertThat(allowedActions(createMessage(MsgStateEnum.NEW)), hasSize(1));
assertThat(allowedActions(createMessage(MsgStateEnum.NEW)).contains(MessageActionType.CANCEL),
is(Boolean.TRUE));
assertThat(allowedActions(createMessage(MsgStateEnum.OK)), hasSize(1));
assertThat(allowedActions(createMessage(MsgStateEnum.OK)).contains(MessageActionType.RESTART),
is(Boolean.TRUE));
assertThat(allowedActions(createMessage(MsgStateEnum.IN_QUEUE)), hasSize(1));
assertThat(allowedActions(createMessage(MsgStateEnum.IN_QUEUE)).contains(MessageActionType.CANCEL),
is(Boolean.TRUE));
assertThat(allowedActions(createMessage(MsgStateEnum.PROCESSING)), hasSize(1));
assertThat(allowedActions(createMessage(MsgStateEnum.PROCESSING)).contains(MessageActionType.CANCEL),
is(Boolean.TRUE));
assertThat(allowedActions(createMessage(MsgStateEnum.PARTLY_FAILED)), hasSize(1));
assertThat(allowedActions(createMessage(MsgStateEnum.FAILED)), hasSize(1));
assertThat(allowedActions(createMessage(MsgStateEnum.FAILED)).contains(MessageActionType.RESTART),
is(Boolean.TRUE));
assertThat(allowedActions(createMessage(MsgStateEnum.WAITING)), hasSize(1));
assertThat(allowedActions(createMessage(MsgStateEnum.WAITING)).contains(MessageActionType.CANCEL),
is(Boolean.TRUE));
assertThat(allowedActions(createMessage(MsgStateEnum.WAITING_FOR_RES)), hasSize(1));
assertThat(allowedActions(createMessage(MsgStateEnum.WAITING_FOR_RES)).contains(MessageActionType.CANCEL),
is(Boolean.TRUE));
assertThat(allowedActions(createMessage(MsgStateEnum.POSTPONED)), hasSize(1));
assertThat(allowedActions(createMessage(MsgStateEnum.POSTPONED)).contains(MessageActionType.CANCEL),
is(Boolean.TRUE));
assertThat(allowedActions(createMessage(MsgStateEnum.CANCEL)), hasSize(1));
assertThat(allowedActions(createMessage(MsgStateEnum.CANCEL)).contains(MessageActionType.RESTART),
is(Boolean.TRUE));
}
protected Message createMessage(MsgStateEnum stateEnum) {
Message msg = new Message();
Instant now = Instant.now();
msg.setState(stateEnum);
msg.setMsgTimestamp(now);
msg.setReceiveTimestamp(now);
msg.setSourceSystem(ExternalSystemTestEnum.CRM);
msg.setCorrelationId(UUID.randomUUID().toString());
msg.setService(ServiceTestEnum.CUSTOMER);
msg.setOperationName("helloWorld");
msg.setPayload("test-payload");
msg.setLastUpdateTimestamp(now);
return msg;
}
} | 46.021978 | 114 | 0.734957 |
e342fca2fb5307a8e6717b3ea42e345033cea10a | 13,708 | package life.catalogue.db;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.zaxxer.hikari.pool.HikariProxyConnection;
import life.catalogue.api.model.Dataset;
import life.catalogue.api.model.User;
import life.catalogue.api.vocab.Datasets;
import life.catalogue.api.vocab.Origin;
import life.catalogue.api.vocab.TaxonomicStatus;
import life.catalogue.common.tax.SciNameNormalizer;
import life.catalogue.db.mapper.DatasetMapper;
import life.catalogue.db.mapper.DatasetPartitionMapper;
import life.catalogue.db.mapper.NamesIndexMapper;
import life.catalogue.db.mapper.UserMapper;
import life.catalogue.postgres.PgCopyUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.gbif.nameparser.api.NameType;
import org.junit.rules.ExternalResource;
import org.postgresql.jdbc.PgConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* A junit test rule that truncates all CoL tables, potentially loads some test
* data from a sql dump file. Do not modify the db schema in the sql files.
* <p>
* The rule was designed to run as a junit {@link org.junit.Rule} before every
* test.
* <p>
* Unless an explicit factory is given, this rule requires a connected postgres server with mybatis via the {@link PgSetupRule}.
* Make sure its setup!
*/
public class TestDataRule extends ExternalResource implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(TestDataRule.class);
public static final User TEST_USER = new User();
static {
TEST_USER.setUsername("test");
TEST_USER.setFirstname("Tim");
TEST_USER.setLastname("Tester");
TEST_USER.setEmail("[email protected]");
TEST_USER.getRoles().add(User.Role.ADMIN);
}
public final TestData testData;
private SqlSession session;
private final Supplier<SqlSessionFactory> sqlSessionFactorySupplier;
public final static TestData NONE = new TestData("none", null, null, null, true, false, Collections.emptyMap(),3);
/**
* Inits the datasets table with real col data from colplus-repo
*/
public final static TestData DATASETS = new TestData("datasets", null, null, null, false, true, Collections.emptyMap());
public final static TestData APPLE = new TestData("apple", 11, 3, 2, 3, 11, 12);
public final static TestData FISH = new TestData("fish", 100, 2, 4, 3, 100, 101, 102);
public final static TestData TREE = new TestData("tree", 11, 2, 2, 3, 11);
public final static TestData DRAFT = new TestData("draft", 3, 1, 2, 3);
public final static TestData DRAFT_WITH_SECTORS = new TestData("draft_with_sectors", 3, 2, 3, 3);
public static class TestData {
public final String name;
public final Integer key;
public final Set<Integer> datasetKeys;
final Integer sciNameColumn;
final Integer taxStatusColumn;
final Map<String, Map<String, Object>> defaultValues;
private final boolean datasets;
private final boolean none;
public TestData(String name, Integer key, Integer sciNameColumn, Integer taxStatusColumn, Integer... datasetKeys) {
this(name, key, sciNameColumn, taxStatusColumn, Collections.emptyMap(), datasetKeys);
}
public TestData(String name, Integer key, Integer sciNameColumn, Integer taxStatusColumn, Map<String, Map<String, Object>> defaultValues, Integer... datasetKeys) {
this(name, key, sciNameColumn, taxStatusColumn, false, false, defaultValues, datasetKeys);
}
private TestData(String name, Integer key, Integer sciNameColumn, Integer taxStatusColumn, boolean none, boolean initAllDatasets, Map<String, Map<String, Object>> defaultValues, Integer... datasetKeys) {
this.name = name;
this.key = key;
this.sciNameColumn = sciNameColumn;
this.taxStatusColumn = taxStatusColumn;
if (datasetKeys == null) {
this.datasetKeys = Collections.EMPTY_SET;
} else {
this.datasetKeys = ImmutableSet.copyOf(datasetKeys);
}
this.none = none;
this.datasets = initAllDatasets;
this.defaultValues = defaultValues;
}
@Override
public String toString() {
return name + " ("+ key +")";
}
}
public static TestDataRule empty() {
return new TestDataRule(NONE);
}
public static TestDataRule apple() {
return new TestDataRule(APPLE);
}
public static TestDataRule apple(SqlSessionFactory sqlSessionFactory) {
return new TestDataRule(APPLE, () -> sqlSessionFactory);
}
public static TestDataRule fish() {
return new TestDataRule(FISH);
}
public static TestDataRule tree() {
return new TestDataRule(TREE);
}
public static TestDataRule draft() {
return new TestDataRule(DRAFT);
}
public static TestDataRule draftWithSectors() {
return new TestDataRule(DRAFT_WITH_SECTORS);
}
public static TestDataRule datasets() {
return new TestDataRule(DATASETS);
}
public static TestDataRule datasets(SqlSessionFactory sqlSessionFactory) {
return new TestDataRule(DATASETS, () -> sqlSessionFactory);
}
private TestDataRule(TestData testData, Supplier<SqlSessionFactory> sqlSessionFactorySupplier) {
this.testData = testData;
this.sqlSessionFactorySupplier = sqlSessionFactorySupplier;
}
public TestDataRule(TestData testData) {
this(testData, PgSetupRule::getSqlSessionFactory);
}
public <T> T getMapper(Class<T> mapperClazz) {
return session.getMapper(mapperClazz);
}
public void commit() {
session.commit();
}
public SqlSession getSqlSession() {
return session;
}
@Override
protected void before() throws Throwable {
LOG.info("Loading {} test data", testData);
initSession();
// remove potential old (global) data
truncate(session);
// create required partitions to load data
partition();
loadData(false);
updateSequences();
// finally create a test user to use in tests
session.getMapper(UserMapper.class).create(TEST_USER);
session.commit();
}
@Override
protected void after() {
session.close();
try (SqlSession session = sqlSessionFactorySupplier.get().openSession(false)) {
LOG.info("remove managed sequences not bound to a table");
DatasetPartitionMapper pm = session.getMapper(DatasetPartitionMapper.class);
for (Dataset d : session.getMapper(DatasetMapper.class).process(null)) {
LOG.debug("Remove managed sequences for dataset {}", d.getKey());
pm.deleteManagedSequences(d.getKey());
}
session.commit();
}
}
@Override
public void close() {
after();
}
public void initSession() {
if (session == null) {
session = sqlSessionFactorySupplier.get().openSession(false);
}
}
public void partition() {
for (Integer dk : testData.datasetKeys) {
MybatisTestUtils.partition(session, dk);
}
session.commit();
}
public void updateSequences() throws Exception {
DatasetPartitionMapper pm = session.getMapper(DatasetPartitionMapper.class);
for (int dk : testData.datasetKeys) {
pm.createManagedSequences(dk);
}
if (testData.key != null) {
pm.updateIdSequences(testData.key);
}
session.commit();
}
private void truncate(SqlSession session) throws SQLException {
LOG.info("Truncate global tables");
try (java.sql.Statement st = session.getConnection().createStatement()) {
st.execute("TRUNCATE \"user\" CASCADE");
st.execute("TRUNCATE dataset CASCADE");
st.execute("TRUNCATE dataset_archive CASCADE");
st.execute("TRUNCATE sector CASCADE");
st.execute("TRUNCATE estimate CASCADE");
st.execute("TRUNCATE decision CASCADE");
st.execute("TRUNCATE name_match");
st.execute("TRUNCATE names_index RESTART IDENTITY CASCADE");
session.getConnection().commit();
}
}
public void truncateDraft() throws SQLException {
LOG.info("Truncate draft partition tables");
try (java.sql.Statement st = session.getConnection().createStatement()) {
st.execute("TRUNCATE sector CASCADE");
for (String table : new String[]{"name", "name_usage"}) {
st.execute("TRUNCATE " + table + "_" + Datasets.COL + " CASCADE");
}
session.getConnection().commit();
}
}
/**
* @param skipGlobalTable if true only loads tables partitioned by datasetKey
*/
public void loadData(final boolean skipGlobalTable) throws SQLException, IOException {
session.getConnection().commit();
ScriptRunner runner = new ScriptRunner(session.getConnection());
runner.setSendFullScript(true);
if (!skipGlobalTable) {
// common data for all tests and even the empty one
runner.runScript(Resources.getResourceAsReader(PgConfig.DATA_FILE));
}
if (!testData.none) {
System.out.format("Load %s test data\n\n", testData);
if (testData.datasets) {
// known datasets
runner.runScript(Resources.getResourceAsReader(PgConfig.DATASETS_FILE));
} else {
try (Connection c = sqlSessionFactorySupplier.get().openSession(false).getConnection()) {
PgConnection pgc;
if (c instanceof HikariProxyConnection) {
HikariProxyConnection hpc = (HikariProxyConnection) c;
pgc = hpc.unwrap(PgConnection.class);
} else {
pgc = (PgConnection) c;
}
if (!skipGlobalTable) {
copyGlobalTable(pgc, "dataset");
copyGlobalTable(pgc, "dataset_import");
copyGlobalTable(pgc, "dataset_patch");
copyGlobalTable(pgc, "dataset_archive");
copyGlobalTable(pgc, "sector");
if (copyGlobalTable(pgc, "names_index")) {
// update names index keys if we added data
session.getMapper(NamesIndexMapper.class).updateSequence();
}
copyGlobalTable(pgc, "name_match");
}
for (int key : testData.datasetKeys) {
copyDataset(pgc, key);
c.commit();
}
runner.runScript(Resources.getResourceAsReader("test-data/sequences.sql"));
}
session.commit();
}
}
}
private void copyDataset(PgConnection pgc, int key) throws IOException, SQLException {
copyPartitionedTable(pgc, "verbatim", key, ImmutableMap.of("dataset_key", key));
copyPartitionedTable(pgc, "reference", key, datasetEntityDefaults(key));
copyPartitionedTable(pgc, "name", key,
datasetEntityDefaults(key, ImmutableMap.<String, Object>of(
"origin", Origin.SOURCE,
"type", NameType.SCIENTIFIC
)),
ImmutableMap.<String, Function<String[], String>>of(
"scientific_name_normalized", row -> SciNameNormalizer.normalize(row[testData.sciNameColumn])
)
);
copyPartitionedTable(pgc, "name_rel", key, datasetEntityDefaults(key));
copyPartitionedTable(pgc, "name_usage", key,
datasetEntityDefaults(key, ImmutableMap.<String, Object>of("origin", Origin.SOURCE)),
ImmutableMap.<String, Function<String[], String>>of(
"is_synonym", this::isSynonym
)
);
copyPartitionedTable(pgc, "distribution", key, datasetEntityDefaults(key));
copyPartitionedTable(pgc, "vernacular_name", key, datasetEntityDefaults(key));
}
private Map<String, Object> datasetEntityDefaults(int datasetKey) {
return datasetEntityDefaults(datasetKey, new HashMap<>());
}
private Map<String, Object> datasetEntityDefaults(int datasetKey, Map<String, Object> defaults) {
return ImmutableMap.<String, Object>builder()
.putAll(defaults)
.put("dataset_key", datasetKey)
.put("created_by", 0)
.put("modified_by", 0)
.build();
}
private String isSynonym(String[] row) {
TaxonomicStatus ts = TaxonomicStatus.valueOf(row[testData.taxStatusColumn]);
return String.valueOf(ts.isSynonym());
}
private boolean copyGlobalTable(PgConnection pgc, String table) throws IOException, SQLException {
return copyTable(pgc, table + ".csv", table, Collections.EMPTY_MAP, Collections.EMPTY_MAP);
}
private boolean copyPartitionedTable(PgConnection pgc, String table, int datasetKey, Map<String, Object> defaults) throws IOException, SQLException {
return copyPartitionedTable(pgc, table, datasetKey, defaults, Collections.EMPTY_MAP);
}
private boolean copyPartitionedTable(PgConnection pgc, String table, int datasetKey, Map<String, Object> defaults, Map<String, Function<String[], String>> funcs) throws IOException, SQLException {
return copyTable(pgc, table + "_" + datasetKey + ".csv", table + "_" + datasetKey, defaults, funcs);
}
private boolean copyTable(PgConnection pgc, String filename, String table, Map<String, Object> defaults, Map<String, Function<String[], String>> funcs)
throws IOException, SQLException {
String resource = "/test-data/" + testData.name.toLowerCase() + "/" + filename;
URL url = PgCopyUtils.class.getResource(resource);
if (url != null) {
// global defaults to add?
if (testData.defaultValues.containsKey(table)) {
defaults = new HashMap<>(defaults);
defaults.putAll(testData.defaultValues.get(table));
}
PgCopyUtils.copy(pgc, table, resource, defaults, funcs);
return true;
}
return false;
}
}
| 35.791123 | 207 | 0.699737 |
8fe76c365ad080bbd7e6aa0dfe4615c7975022a5 | 922 | package me.calvin.modules.search.domain.request;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
/** 图片信息入参对象 */
@Data
@ApiModel(value = "SearchUrlImagesReq", description = "Url图片信息操作对象")
public class SearchUrlImagesReq {
@NotEmpty(message = "urls 字段必须")
@ApiModelProperty(value = "图片urls", name = "urls", required = true)
private HashMap<String, String> urls;
@NotBlank(message = "topk 字段必须")
@ApiModelProperty(value = "返回topk个结果", name = "topk", required = true)
String topk;
@NotBlank(message = "save 字段必须")
@ApiModelProperty(value = "0 不存,1 存盘,必填", name = "save", required = true)
String save;
@NotBlank(message = "类型")
@ApiModelProperty(value = "0:通用搜索,1:人脸搜索", name = "type", required = true)
String type;
}
| 29.741935 | 76 | 0.727766 |
b7ed5ed1a1a2472dab36fd89ff0d072f23e0a9a3 | 1,294 | package cc.novoline.gui.screen.click;
import cc.novoline.gui.screen.click.Scroll;
import cc.novoline.gui.screen.setting.SettingType;
// $FF: synthetic class
class Tab$1 {
static final int[] $SwitchMap$cc$novoline$gui$screen$click$Scroll;
static final int[] $SwitchMap$cc$novoline$gui$screen$setting$SettingType = new int[SettingType.values().length];
static {
try {
$SwitchMap$cc$novoline$gui$screen$setting$SettingType[SettingType.COMBOBOX.ordinal()] = 1;
} catch (NoSuchFieldError var5) {
;
}
try {
$SwitchMap$cc$novoline$gui$screen$setting$SettingType[SettingType.SELECTBOX.ordinal()] = 2;
} catch (NoSuchFieldError var4) {
;
}
try {
$SwitchMap$cc$novoline$gui$screen$setting$SettingType[SettingType.TEXTBOX.ordinal()] = 3;
} catch (NoSuchFieldError var3) {
;
}
$SwitchMap$cc$novoline$gui$screen$click$Scroll = new int[Scroll.values().length];
try {
$SwitchMap$cc$novoline$gui$screen$click$Scroll[Scroll.DOWN.ordinal()] = 1;
} catch (NoSuchFieldError var2) {
;
}
try {
$SwitchMap$cc$novoline$gui$screen$click$Scroll[Scroll.UP.ordinal()] = 2;
} catch (NoSuchFieldError var1) {
;
}
}
}
| 28.130435 | 115 | 0.631376 |
6ddc786aa399ac25b62102abe15f1ebdd97c0be0 | 6,419 | package com.flipkart.android.proteus.parser.custom;
import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.flipkart.android.proteus.ProteusContext;
import com.flipkart.android.proteus.ProteusView;
import com.flipkart.android.proteus.ViewTypeParser;
import com.flipkart.android.proteus.processor.BooleanAttributeProcessor;
import com.flipkart.android.proteus.processor.ColorResourceProcessor;
import com.flipkart.android.proteus.processor.DimensionAttributeProcessor;
import com.flipkart.android.proteus.processor.NumberAttributeProcessor;
import com.flipkart.android.proteus.processor.StringAttributeProcessor;
import com.flipkart.android.proteus.value.Layout;
import com.flipkart.android.proteus.value.ObjectValue;
import com.flipkart.android.proteus.view.custom.StepProgressBar;
import com.flipkart.android.proteus.view.custom.StepProgressView;
/**
* Created by Prasad Rao on 02-03-2020 19:27
**/
public class StepProgressBarParser<T extends StepProgressView> extends ViewTypeParser<T> {
@NonNull
@Override
public String getType() {
return "StepProgressView";
}
@Nullable
@Override
public String getParentType() {
return "View";
}
@NonNull
@Override
public ProteusView createView(@NonNull ProteusContext context, @NonNull Layout layout, @NonNull ObjectValue data,
@Nullable ViewGroup parent, int dataIndex) {
final ViewGroup.LayoutParams lp =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
StepProgressBar stepProgressBar = new StepProgressBar(context);
stepProgressBar.setLayoutParams(lp);
return stepProgressBar;
}
@Override
protected void addAttributeProcessors() {
addAttributeProcessor("markers", new StringAttributeProcessor<T>() {
@Override
public void setString(T view, String value) {
view.setMarkers(value);
}
});
addAttributeProcessor("textFont", new StringAttributeProcessor<T>() {
@Override
public void setString(T view, String value) {
Typeface typeface;
typeface = Typeface.createFromAsset(view.getContext().getAssets(), value);
if (typeface != null) {
view.setTextFont(typeface);
}
}
});
addAttributeProcessor("currentProgress", new NumberAttributeProcessor<T>() {
@Override
public void setNumber(T view, @NonNull Number value) {
view.setCurrentProgress(value.intValue());
}
});
addAttributeProcessor("totalProgress", new NumberAttributeProcessor<T>() {
@Override
public void setNumber(T view, @NonNull Number value) {
view.setTotalProgress(value.intValue());
}
});
addAttributeProcessor("progressColor", new ColorResourceProcessor<T>() {
@Override
public void setColor(T view, int color) {
view.setProgressColor(color);
}
@Override
public void setColor(T view, ColorStateList colors) {
view.setProgressColor(colors.getDefaultColor());
}
});
addAttributeProcessor("markerWidth", new DimensionAttributeProcessor<T>() {
@Override
public void setDimension(T view, float dimension) {
view.setMarkerWidth(dimension);
}
});
addAttributeProcessor("textMargin", new DimensionAttributeProcessor<T>() {
@Override
public void setDimension(T view, float dimension) {
view.setTextMargin(dimension);
}
});
addAttributeProcessor("markerTextSize", new DimensionAttributeProcessor<T>() {
@Override
public void setDimension(T view, float dimension) {
view.setMarkerTextSize(dimension);
}
});
addAttributeProcessor("progressBackgroundColor", new ColorResourceProcessor<T>() {
@Override
public void setColor(T view, int color) {
view.setProgressBackgroundColor(color);
}
@Override
public void setColor(T view, ColorStateList colors) {
view.setProgressBackgroundColor(colors.getDefaultColor());
}
});
addAttributeProcessor("markerTextColor", new ColorResourceProcessor<T>() {
@Override
public void setColor(T view, int color) {
view.setMarkerTextColor(color);
}
@Override
public void setColor(T view, ColorStateList colors) {
view.setMarkerTextColor(colors.getDefaultColor());
}
});
addAttributeProcessor("markerColor", new ColorResourceProcessor<T>() {
@Override
public void setColor(T view, int color) {
view.setMarkerColor(color);
}
@Override
public void setColor(T view, ColorStateList colors) {
view.setMarkerColor(colors.getDefaultColor());
}
});
addAttributeProcessor("edgeRadius", new DimensionAttributeProcessor<T>() {
@Override
public void setDimension(T view, float dimension) {
view.setEdgeRadius(dimension);
}
});
addAttributeProcessor("progressBarHeight", new DimensionAttributeProcessor<T>() {
@Override
public void setDimension(T view, float dimension) {
view.setProgressBarHeight(dimension);
}
});
addAttributeProcessor("showMarkerText", new BooleanAttributeProcessor<T>() {
@Override
public void setBoolean(T view, boolean value) {
view.setShowMarkerText(value);
}
});
addAttributeProcessor("stepSize", new NumberAttributeProcessor<T>() {
@Override
public void setNumber(T view, @NonNull Number value) {
view.addMarkersWithStepSize(value.intValue());
}
});
}
}
| 35.269231 | 117 | 0.622371 |
3f70003c551756d7daff0d4afcc69ee21e5fa476 | 9,194 | /*-
* Copyright 2015 Crimson Hexagon
*
* 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 prt.shining.rsm.lettuce.cluster;
import com.crimsonhexagon.rsm.RedisSession;
import com.crimsonhexagon.rsm.RedisSessionClient;
import com.crimsonhexagon.rsm.RedisSessionManager;
import io.lettuce.core.AbstractRedisClient;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulConnection;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
import io.lettuce.core.cluster.pubsub.api.sync.RedisClusterPubSubCommands;
import io.lettuce.core.codec.RedisCodec;
import io.lettuce.core.pubsub.RedisPubSubListener;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.pubsub.api.sync.RedisPubSubCommands;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Session;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class LettuceClusterSessionManager extends RedisSessionManager {
public static final String DEFAULT_URI = "redis://localhost:6379";
protected final Log log = LogFactory.getLog(getClass());
private AbstractRedisClient client = RedisClient.create();
private StatefulConnection<String, Object> connection;
StatefulRedisPubSubConnection<String, String> pubSubConnection;
private String nodes = DEFAULT_URI;
private String password;
private String sentinelMaster;
@Override
protected synchronized void startInternal() throws LifecycleException {
super.startInternal();
//start a thread to subscribe redis key expire event
RedisPubSubCommands<String, String> redisPubSubCommands = pubSubConnection.sync();
redisPubSubCommands.getStatefulConnection().addListener(new RedisPubSubListener<String, String>() {
@Override
public void message(String channel, String message) {
log.info("msg=" + message + "on channel " + channel);
if (message == null) {
log.info("message can not ne null");
return;
}
String sessionKeyId = message;
if (sessionKeyId.startsWith(getSessionKeyPrefix())) {
expireExpiredSessionInRedis(sessionKeyId);
}
}
@Override
public void message(String pattern, String channel, String message) {
}
@Override
public void subscribed(String channel, long count) {
}
@Override
public void psubscribed(String pattern, long count) {
}
@Override
public void unsubscribed(String channel, long count) {
}
@Override
public void punsubscribed(String pattern, long count) {
}
});
if (redisPubSubCommands instanceof RedisClusterPubSubCommands) {
((RedisClusterPubSubCommands<String, String>) redisPubSubCommands).masters().commands().subscribe("__keyevent@0__:expired");
} else {
redisPubSubCommands.subscribe("__keyevent@0__:expired");
}
}
private void expireExpiredSessionInRedis(String sessionKeyId) {
RedisSession session = new RedisSession(null);
session.setValid(true);
session.setId(sessionKeyId.replaceFirst(getSessionKeyPrefix(), ""));
session.setManager(this);
//invoke session expire to fire session destroy event when session expired in redis
session.expire();
}
@Override
protected final RedisSessionClient buildClient() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
if (nodes == null || nodes.trim().length() == 0) {
log.error("Nodes can not be empty");
throw new IllegalStateException("Manager must specify node string. e.g., nodes=\"redis://node1.com:6379 redis://node2.com:6379\"");
}
RedisCodec<String, Object> codec = new ContextClassloaderJdkSerializationCodec(getContainerClassLoader());
List<String> nodes = Arrays.asList(getNodes().trim().split("\\s+"));
this.connection = createRedisConnection(nodes, codec);
return new LettuceClusterSessionClient(connection, codec);
}
private StatefulConnection<String, Object> createRedisConnection(List<String> nodes, RedisCodec<String, Object> codec) {
if (nodes.size() == 1) {
RedisURI redisURI = RedisURI.create(nodes.get(0));
if (sentinelMaster != null) {
redisURI = RedisURI.Builder.sentinel(nodes.get(0), sentinelMaster).build();
}
if (password != null) {
redisURI.setPassword(password);
}
pubSubConnection = ((RedisClient)client).connectPubSub(redisURI);
StatefulRedisConnection<String, Object> connection = ((RedisClient)client).connect(codec, redisURI);
return connection;
} else {
if (sentinelMaster != null) {
RedisURI.Builder redisURIBuilder = RedisURI.Builder.sentinel(nodes.get(0), sentinelMaster);
for (int index = 1; index <= nodes.size() - 1; index++) {
redisURIBuilder.withSentinel(nodes.get(index));
}
RedisURI redisURI = redisURIBuilder.build();
if (password != null) {
redisURI.setPassword(password);
}
pubSubConnection = ((RedisClient)client).connectPubSub(redisURI);
StatefulRedisConnection<String, Object> connection = ((RedisClient)client).connect(codec, redisURI);
return connection;
}
ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
.enableAdaptiveRefreshTrigger(ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT, ClusterTopologyRefreshOptions.RefreshTrigger.PERSISTENT_RECONNECTS)
.adaptiveRefreshTriggersTimeout(Duration.ofSeconds(30))
.build();
List<RedisURI> uris = nodes.stream()
.map(RedisURI::create)
.map(uri -> {
if (password != null) {
uri.setPassword(password);
}
return uri; })
.collect(Collectors.toList());
client = RedisClusterClient.create(uris);
((RedisClusterClient) client).setOptions(ClusterClientOptions.builder()
.topologyRefreshOptions(topologyRefreshOptions)
.build());
pubSubConnection = ((RedisClusterClient) client).connectPubSub();
((StatefulRedisClusterPubSubConnection<String, String>) pubSubConnection).setNodeMessagePropagation(true);
StatefulRedisClusterConnection<String, Object> connection = ((RedisClusterClient) client).connect(codec);
return connection;
}
}
@Override
public Session findSession(String id) throws IOException {
Session session = super.findSession(id);
if (session != null) {
log.trace("update session's access time and end access time when get session from redis to avoid remove session that not expired in redis");
session.access();
session.endAccess();
}
return session;
}
@Override
public void unload() throws IOException {
if (connection != null) {
connection.close();
}
if (client != null) {
client.shutdown();
}
}
public String getNodes() {
return nodes;
}
public void setNodes(String nodes) {
this.nodes = nodes;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSentinelMaster() {
return sentinelMaster;
}
public void setSentinelMaster(String sentinelMaster) {
this.sentinelMaster = sentinelMaster;
}
}
| 37.991736 | 178 | 0.652273 |
f4af631c5ed9c2a2335b82b1fcd05f2d66dcae8a | 221 | package com.yulu.mybatis.mapper;
import java.util.List;
import com.yulu.entity.Order;
/**
* 订单的映射接口
*
*/
public interface OrderMapper {
/**
* 通过订单管理查询用户信息(一对一)
* @return
*/
List<Order> findAllOrderUser();
}
| 12.277778 | 32 | 0.669683 |
76f1499353ad25493c908042ee9fb89b03685907 | 2,922 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.aws;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Represents the range of IPv4 Ports.
*/
final class PortRange {
private static final Pattern PORT_NUMBER_REGEX = Pattern.compile("^(\\d+)$");
private static final Pattern PORT_RANGE_REGEX = Pattern.compile("^(\\d+)-(\\d+)$");
private static final int MIN_PORT = 0;
private static final int MAX_PORT = 65535;
private final int fromPort;
private final int toPort;
/**
* Creates {@link PortRange} from the {@code spec} String.
*
* @param spec port number (e.g "5701") or port range (e.g. "5701-5708")
* @throws IllegalArgumentException if the specified spec is not a valid port or port range
*/
PortRange(String spec) {
Matcher portNumberMatcher = PORT_NUMBER_REGEX.matcher(spec);
Matcher portRangeMatcher = PORT_RANGE_REGEX.matcher(spec);
if (portNumberMatcher.find()) {
int port = Integer.parseInt(spec);
this.fromPort = port;
this.toPort = port;
} else if (portRangeMatcher.find()) {
this.fromPort = Integer.parseInt(portRangeMatcher.group(1));
this.toPort = Integer.parseInt(portRangeMatcher.group(2));
} else {
throw new IllegalArgumentException(String.format("Invalid port range specification: %s", spec));
}
validatePorts();
}
private void validatePorts() {
if (fromPort < MIN_PORT || fromPort > MAX_PORT) {
throw new IllegalArgumentException(
String.format("Specified port (%s) outside of port range (%s-%s)", fromPort, MIN_PORT, MAX_PORT));
}
if (toPort < MIN_PORT || toPort > MAX_PORT) {
throw new IllegalArgumentException(
String.format("Specified port (%s) outside of port range (%s-%s)", toPort, MIN_PORT, MAX_PORT));
}
if (fromPort > toPort) {
throw new IllegalArgumentException(String.format("Port %s is greater than %s", fromPort, toPort));
}
}
int getFromPort() {
return fromPort;
}
int getToPort() {
return toPort;
}
@Override
public String toString() {
return String.format("%d-%d", fromPort, toPort);
}
}
| 34.376471 | 114 | 0.644079 |
309cd8a51683734f415436154a55720146b006e6 | 14,899 | /*
* Copyright 2021 Wultra s.r.o.
*
* 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 io.getlime.security.powerauth.app.nextstep.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.getlime.security.powerauth.app.nextstep.configuration.NextStepServerConfiguration;
import io.getlime.security.powerauth.app.nextstep.converter.ParameterConverter;
import io.getlime.security.powerauth.app.nextstep.repository.CredentialRepository;
import io.getlime.security.powerauth.app.nextstep.repository.catalogue.RepositoryCatalogue;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.CredentialDefinitionEntity;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.CredentialEntity;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.CredentialPolicyEntity;
import io.getlime.security.powerauth.lib.nextstep.model.entity.CredentialGenerationParam;
import io.getlime.security.powerauth.lib.nextstep.model.entity.UsernameGenerationParam;
import io.getlime.security.powerauth.lib.nextstep.model.exception.InvalidConfigurationException;
import org.passay.CharacterData;
import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.PasswordGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* This service handles generation of credentials.
*
* @author Roman Strobl, [email protected]
*/
@Service
public class CredentialGenerationService {
private final Logger logger = LoggerFactory.getLogger(CredentialGenerationService.class);
private final CredentialRepository credentialRepository;
private final NextStepServerConfiguration nextStepServerConfiguration;
private final ParameterConverter parameterConverter = new ParameterConverter();
/**
* Credential generation service constructor.
* @param repositoryCatalogue Repository catalogue.
* @param nextStepServerConfiguration Next Step server configuration.
*/
public CredentialGenerationService(RepositoryCatalogue repositoryCatalogue, NextStepServerConfiguration nextStepServerConfiguration) {
this.credentialRepository = repositoryCatalogue.getCredentialRepository();
this.nextStepServerConfiguration = nextStepServerConfiguration;
}
/**
* Generate a username as defined in credential policy.
* @param credentialDefinition Credential definition.
* @return Generated username.
* @throws InvalidConfigurationException Thrown in case username could not be generated.
*/
public String generateUsername(CredentialDefinitionEntity credentialDefinition) throws InvalidConfigurationException {
final CredentialPolicyEntity credentialPolicy = credentialDefinition.getCredentialPolicy();
switch (credentialPolicy.getUsernameGenAlgorithm()) {
case RANDOM_DIGITS:
try {
return generateRandomUsernameWithDigits(credentialDefinition);
} catch (InvalidConfigurationException ex) {
throw ex;
} catch (Exception ex) {
throw new InvalidConfigurationException(ex);
}
case RANDOM_LETTERS:
try {
return generateRandomUsernameWithLetters(credentialDefinition);
} catch (InvalidConfigurationException ex) {
throw ex;
} catch (Exception ex) {
throw new InvalidConfigurationException(ex);
}
case NO_USERNAME:
return null;
default:
throw new InvalidConfigurationException("Unsupported username generation algorithm: " + credentialPolicy.getUsernameGenAlgorithm());
}
}
/**
* Generate a credential value as defined in credential policy.
* @param credentialDefinition Credential definition.
* @return Generated credential value.
* @throws InvalidConfigurationException Thrown in case credential value could not be generated.
*/
public String generateCredentialValue(CredentialDefinitionEntity credentialDefinition) throws InvalidConfigurationException {
final CredentialPolicyEntity credentialPolicy = credentialDefinition.getCredentialPolicy();
switch (credentialPolicy.getCredentialGenAlgorithm()) {
case RANDOM_PASSWORD:
try {
return generateRandomPassword(credentialPolicy);
} catch (InvalidConfigurationException ex) {
throw ex;
} catch (Exception ex) {
throw new InvalidConfigurationException(ex);
}
case RANDOM_PIN:
try {
return generateRandomPin(credentialPolicy);
} catch (InvalidConfigurationException ex) {
throw ex;
} catch (Exception ex) {
throw new InvalidConfigurationException(ex);
}
default:
throw new InvalidConfigurationException("Unsupported credential value generation algorithm: " + credentialPolicy.getCredentialGenAlgorithm());
}
}
/**
* Generate random username with digits.
* @param credentialDefinition Credential definition.
* @return Generated username.
* @throws InvalidConfigurationException Thrown when Next Step configuration is invalid.
*/
private String generateRandomUsernameWithDigits(CredentialDefinitionEntity credentialDefinition) throws InvalidConfigurationException {
final CredentialPolicyEntity credentialPolicy = credentialDefinition.getCredentialPolicy();
final UsernameGenerationParam param;
try {
param = parameterConverter.fromString(credentialPolicy.getUsernameGenParam(), UsernameGenerationParam.class);
} catch (JsonProcessingException ex) {
throw new InvalidConfigurationException(ex);
}
final int length = param.getLength();
final SecureRandom secureRandom = new SecureRandom();
final int generateUsernameMaxAttempts = nextStepServerConfiguration.getGenerateUsernameMaxAttempts();
for (int i = 0; i < generateUsernameMaxAttempts; i++) {
final BigInteger bound = BigInteger.valueOf(Math.round(Math.pow(10, length)));
final BigInteger randomNumber = new BigInteger(bound.bitLength(), secureRandom).mod(bound);
final String username = randomNumber.toString();
if (username.length() < length) {
// This can happen with leading zeros
continue;
}
final Optional<CredentialEntity> credentialOptional = credentialRepository.findByCredentialDefinitionAndUsername(credentialDefinition, username);
if (credentialOptional.isPresent()) {
// Username is already taken
continue;
}
return username;
}
throw new InvalidConfigurationException("Username could not be generated, all attempts failed");
}
/**
* Generate random username with letters.
* @param credentialDefinition Credential definition.
* @return Generated username.
* @throws InvalidConfigurationException Thrown when Next Step configuration is invalid.
*/
private String generateRandomUsernameWithLetters(CredentialDefinitionEntity credentialDefinition) throws InvalidConfigurationException {
final CredentialPolicyEntity credentialPolicy = credentialDefinition.getCredentialPolicy();
final UsernameGenerationParam param;
try {
param = parameterConverter.fromString(credentialPolicy.getUsernameGenParam(), UsernameGenerationParam.class);
} catch (JsonProcessingException ex) {
throw new InvalidConfigurationException(ex);
}
final int length = param.getLength();
final SecureRandom secureRandom = new SecureRandom();
final int generateUsernameMaxAttempts = nextStepServerConfiguration.getGenerateUsernameMaxAttempts();
for (int i = 0; i < generateUsernameMaxAttempts; i++) {
final StringBuilder usernameBuilder = new StringBuilder();
for (int j = 0; j < length; j++) {
final char c = (char) (secureRandom.nextInt(26) + 'a');
usernameBuilder.append(c);
}
final String username = usernameBuilder.toString();
final Optional<CredentialEntity> credentialOptional = credentialRepository.findByCredentialDefinitionAndUsername(credentialDefinition, username);
if (credentialOptional.isPresent()) {
// Username is already taken
continue;
}
return username;
}
throw new InvalidConfigurationException("Username could not be generated, all attempts failed");
}
/**
* Generate random password.
* @param credentialPolicy Credential policy.
* @return Generated password.
* @throws InvalidConfigurationException Thrown when Next Step configuration is invalid.
*/
private String generateRandomPassword(CredentialPolicyEntity credentialPolicy) throws InvalidConfigurationException {
final CredentialGenerationParam param;
try {
param = parameterConverter.fromString(credentialPolicy.getCredentialGenParam(), CredentialGenerationParam.class);
} catch (JsonProcessingException ex) {
throw new InvalidConfigurationException(ex);
}
final int length = param.getLength();
int countFromRules = 0;
final boolean includeSmallLetters = param.isIncludeSmallLetters();
final Integer smallLettersCount = param.getSmallLettersCount();
if (smallLettersCount != null) {
countFromRules += smallLettersCount;
}
final boolean includeCapitalLetters = param.isIncludeCapitalLetters();
final Integer capitalLettersCount = param.getCapitalLettersCount();
if (capitalLettersCount != null) {
countFromRules += capitalLettersCount;
}
final boolean includeDigits = param.isIncludeDigits();
final Integer digitsCount = param.getDigitsCount();
if (digitsCount != null) {
countFromRules += digitsCount;
}
final boolean includeSpecialChars = param.isIncludeSpecialChars();
final Integer specialCharsCount = param.getSpecialCharsCount();
if (specialCharsCount != null) {
countFromRules += specialCharsCount;
}
if (!includeSmallLetters && !includeCapitalLetters && !includeDigits && !includeSpecialChars) {
throw new InvalidConfigurationException("Invalid configuration of algorithm RANDOM_PASSWORD: at least one character rule is required");
}
if (countFromRules > 0 && countFromRules != length) {
throw new InvalidConfigurationException("Invalid configuration of algorithm RANDOM_PASSWORD: credential length does not match rules");
}
final PasswordGenerator passwordGenerator = new PasswordGenerator();
final List<CharacterRule> characterRules = new ArrayList<>();
if (includeSmallLetters) {
final CharacterRule rule;
if (smallLettersCount == null) {
rule = new CharacterRule(EnglishCharacterData.LowerCase);
} else {
rule = new CharacterRule(EnglishCharacterData.LowerCase, smallLettersCount);
}
characterRules.add(rule);
}
if (includeCapitalLetters) {
final CharacterRule rule;
if (capitalLettersCount == null) {
rule = new CharacterRule(EnglishCharacterData.UpperCase);
} else {
rule = new CharacterRule(EnglishCharacterData.UpperCase, capitalLettersCount);
}
characterRules.add(rule);
}
if (includeDigits) {
final CharacterRule rule;
if (digitsCount == null) {
rule = new CharacterRule(EnglishCharacterData.Digit);
} else {
rule = new CharacterRule(EnglishCharacterData.Digit, digitsCount);
}
characterRules.add(rule);
}
if (includeSpecialChars) {
final CharacterRule rule;
if (specialCharsCount == null) {
rule = new CharacterRule(new SpecialCharacters());
} else {
rule = new CharacterRule(new SpecialCharacters(), specialCharsCount);
}
characterRules.add(rule);
}
return passwordGenerator.generatePassword(length, characterRules);
}
/**
* Generate random PIN.
* @param credentialPolicy Credential policy.
* @return Random PIN.
* @throws InvalidConfigurationException Thrown when Next Step configuration is invalid.
*/
private String generateRandomPin(CredentialPolicyEntity credentialPolicy) throws InvalidConfigurationException {
final CredentialGenerationParam param;
try {
param = parameterConverter.fromString(credentialPolicy.getCredentialGenParam(), CredentialGenerationParam.class);
} catch (JsonProcessingException ex) {
throw new InvalidConfigurationException(ex);
}
final int length = param.getLength();
final PasswordGenerator passwordGenerator = new PasswordGenerator();
return passwordGenerator.generatePassword(length, new CharacterRule(EnglishCharacterData.Digit));
}
/**
* Custom character data definition for special characters.
*/
private static class SpecialCharacters implements CharacterData {
private static final String ERROR_CODE = "INSUFFICIENT_SPECIAL_CHARACTERS";
private static final String CHARACTERS = "^<>{};:.,~!?@#$%=&*[]()";
@Override
public String getErrorCode() {
return ERROR_CODE;
}
@Override
public String getCharacters() {
return CHARACTERS;
}
}
} | 46.126935 | 158 | 0.684207 |
a865a8a313fefd40a24c9d4509f5a098f5c8d42f | 338 | package Main;
import java.nio.file.Paths;
public class Configuration {
public static final String BES_URI = "http://localhost:9090/api/HRController/";
public static final String absoluteFileSystemPath =
Paths.get(System.getProperty("user.dir")).getParent().toAbsolutePath()
+ "\\FileSystem\\";
}
| 30.727273 | 83 | 0.677515 |
e3e39888ccf7263fe77d0a7c56ba6dc19247d973 | 3,322 | /*
* (C) Copyright 2020 Nuxeo (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* Nelson Silva <[email protected]>
*/
package org.nuxeo.ecm.platform.preview.io;
import java.io.IOException;
import java.io.Serializable;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.Blobs;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.PathRef;
import org.nuxeo.ecm.core.blob.BlobInfo;
import org.nuxeo.ecm.core.blob.BlobManager;
import org.nuxeo.ecm.core.blob.ManagedBlob;
import org.nuxeo.ecm.core.blob.SimpleManagedBlob;
import org.nuxeo.ecm.core.io.marshallers.json.AbstractJsonWriterTest;
import org.nuxeo.ecm.core.io.marshallers.json.JsonAssert;
import org.nuxeo.ecm.core.io.marshallers.json.document.DocumentModelJsonWriter;
import org.nuxeo.ecm.core.io.registry.context.RenderingContext;
import org.nuxeo.ecm.core.io.registry.context.RenderingContext.CtxBuilder;
import org.nuxeo.ecm.core.test.CoreFeature;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
@Features(CoreFeature.class)
@Deploy("org.nuxeo.ecm.platform.preview")
@Deploy("org.nuxeo.ecm.platform.preview:test-dummy-blob-provider.xml")
public class BlobPreviewJsonEnricherTest extends AbstractJsonWriterTest.Local<DocumentModelJsonWriter, DocumentModel> {
@Inject
protected BlobManager blobManager;
@Inject
private CoreSession session;
public BlobPreviewJsonEnricherTest() {
super(DocumentModelJsonWriter.class, DocumentModel.class);
}
@Before
public void setup() throws IOException {
Blob b = Blobs.createBlob("foo", "video/mp4");
String key = blobManager.getBlobProvider("dummy").writeBlob(b);
key = "dummy:" + key;
DocumentModel doc = session.createDocumentModel("/", "doc", "File");
BlobInfo blobInfo = new BlobInfo();
blobInfo.key = key;
blobInfo.mimeType = "video/mp4";
Blob blob = new SimpleManagedBlob(blobInfo);
doc.setPropertyValue("file:content", (Serializable) blob);
session.createDocument(doc);
session.save();
}
@Test
public void test() throws Exception {
DocumentModel doc = session.getDocument(new PathRef("/doc"));
ManagedBlob blob = (ManagedBlob) doc.getPropertyValue("file:content");
String k = DummyManagedBlobProvider.getBlobKey(blob);
RenderingContext ctx = CtxBuilder.properties("*").enrich("blob", "preview").get();
JsonAssert json = jsonAssert(doc, ctx);
json.has("properties").has("file:content").has("preview").isEquals("http://example.com/" + k + "/embed");
}
}
| 37.75 | 119 | 0.729079 |
58fb5593fe351c54e3e1c11811a123d534087cf4 | 1,793 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands;
import frc.robot.Constants.driveTrain;
import frc.robot.subsystems.MyDriveTrain;
import edu.wpi.first.wpilibj2.command.CommandBase;
// Travels set distance while turning at a certain speed. Way of turning without
// rotation sensing, or driving in graceful arcs.
public class AutoDriveTurn extends CommandBase {
MyDriveTrain locDriveTrain;
Double locSpeed = 0.0;
Double locRSpeed = 0.0;
Double initialPosition = 0.0;
Double locDistance = 0.0;
/** Creates a new AutoDriveTurn. */
public AutoDriveTurn(MyDriveTrain driveTrain, double speed, double rSpeed, double distance) {
// Use addRequirements() here to declare subsystem dependencies.
addRequirements(driveTrain);
locDriveTrain = driveTrain;
locSpeed = speed;
locRSpeed = rSpeed;
locDistance = distance;
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
initialPosition = Math.abs(locDriveTrain.getEncoderPosition());
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
locDriveTrain.drive(locSpeed, locRSpeed);
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
locSpeed = 0.0;
locRSpeed = 0.0;
locDriveTrain.drive(locSpeed, locRSpeed);
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
if (locDistance < Math.abs(locDriveTrain.getEncoderPosition()) - initialPosition) {
return true;
}
return false;
}
}
| 29.393443 | 95 | 0.727273 |
8e3ea3a0c932c329712374a0e853e001fc83ebad | 332 | import java.util.*;
import java.io.*;
class pattern
{
public static void main(String [] args)
{
Scanner kb=new Scanner(System.in);
System.out.println("Enter the limit");
int n=kb.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(j);
}System.out.println();
}
}
}
| 15.090909 | 40 | 0.572289 |
75af65fd179fefd485cf9671d5b28a9ecf7b3afa | 16,621 | /*
* =============================================================================
*
* Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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 org.thymeleaf.util;
import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.util.List;
/**
* <p>
* Character sequence that aggregates one or several {@link CharSequence} objects, without the need to clone them
* or convert them to String.
* </p>
* <p>
* Special implementation of the {@link CharSequence} interface that can replace {@link String} objects
* wherever a specific text literal is composed of several parts and we want to avoid creating new
* {@link String} objects for them, using instead objects of this class that simply keep an array
* of references to the original CharSequences.
* </p>
* <p>
* Note that any mutable {@link CharSequence} implementations used to build objects of this class should
* <strong>never</strong> be modified after the creation of the aggregated object.
* </p>
*
*
* <p>
* This class is <strong>thread-safe</strong>
* </p>
*
*
* @author Daniel Fernández
*
* @since 3.0.0
*
*/
public final class AggregateCharSequence implements Serializable, IWritableCharSequence {
protected static final long serialVersionUID = 823987612L;
private static final int[] UNIQUE_ZERO_OFFSET = new int[] { 0 };
private final CharSequence[] values;
private final int[] offsets;
private final int length;
// This variable will mimic the hashCode cache mechanism in java.lang.String
private int hash; // defaults to 0
public AggregateCharSequence(final CharSequence component) {
super();
if (component == null) {
throw new IllegalArgumentException("Component argument is null, which is forbidden");
}
this.values = new CharSequence[] { component };
this.offsets = UNIQUE_ZERO_OFFSET;
this.length = component.length();
}
public AggregateCharSequence(final CharSequence component0, final CharSequence component1) {
super();
if (component0 == null || component1 == null) {
throw new IllegalArgumentException("At least one component argument is null, which is forbidden");
}
this.values = new CharSequence[] { component0, component1 };
this.offsets = new int[] { 0, component0.length() };
this.length = this.offsets[1] + component1.length();
}
public AggregateCharSequence(final CharSequence component0, final CharSequence component1, final CharSequence component2) {
super();
if (component0 == null || component1 == null || component2 == null) {
throw new IllegalArgumentException("At least one component argument is null, which is forbidden");
}
this.values = new CharSequence[] { component0, component1, component2 };
this.offsets = new int[] { 0, component0.length(), component0.length() + component1.length() };
this.length = this.offsets[2] + component2.length();
}
public AggregateCharSequence(final CharSequence component0, final CharSequence component1, final CharSequence component2, final CharSequence component3) {
super();
if (component0 == null || component1 == null || component2 == null || component3 == null) {
throw new IllegalArgumentException("At least one component argument is null, which is forbidden");
}
this.values = new CharSequence[] { component0, component1, component2, component3 };
this.offsets = new int[] { 0, component0.length(), component0.length() + component1.length(), component0.length() + component1.length() + component2.length() };
this.length = this.offsets[3] + component3.length();
}
public AggregateCharSequence(final CharSequence component0, final CharSequence component1, final CharSequence component2, final CharSequence component3, final CharSequence component4) {
super();
if (component0 == null || component1 == null || component2 == null || component3 == null || component4 == null) {
throw new IllegalArgumentException("At least one component argument is null, which is forbidden");
}
this.values = new CharSequence[] { component0, component1, component2, component3, component4 };
this.offsets = new int[] { 0, component0.length(), component0.length() + component1.length(), component0.length() + component1.length() + component2.length(), component0.length() + component1.length() + component2.length() + component3.length() };
this.length = this.offsets[4] + component3.length();
}
public AggregateCharSequence(final CharSequence[] components) {
// NOTE: We have this set of constructors instead of only one with a varargs argument in order to
// avoid unnecessary creation of String[] objects
super();
if (components == null) {
throw new IllegalArgumentException("Components argument array cannot be null");
}
if (components.length == 0) {
// We want always at least one String
this.values = new CharSequence[]{""};
this.offsets = UNIQUE_ZERO_OFFSET;
this.length = 0;
} else {
this.values = new CharSequence[components.length];
this.offsets = new int[components.length];
int totalLength = 0;
int i = 0;
while (i < components.length) {
if (components[i] == null) {
throw new IllegalArgumentException("Components argument contains at least a null, which is forbidden");
}
final int componentLen = components[i].length();
this.values[i] = components[i];
this.offsets[i] = (i == 0 ? 0 : this.offsets[i - 1] + this.values[i - 1].length());
totalLength += componentLen;
i++;
}
this.length = totalLength;
}
}
public AggregateCharSequence(final List<? extends CharSequence> components) {
super();
if (components == null) {
throw new IllegalArgumentException("Components argument array cannot be null");
}
final int componentsSize = components.size();
if (componentsSize == 0) {
// We want always at least one String
this.values = new CharSequence[]{""};
this.offsets = UNIQUE_ZERO_OFFSET;
this.length = 0;
} else {
this.values = new CharSequence[componentsSize];
this.offsets = new int[componentsSize];
int totalLength = 0;
int i = 0;
while (i < componentsSize) {
final CharSequence element = components.get(i);
if (element == null) {
throw new IllegalArgumentException("Components argument contains at least a null, which is forbidden");
}
final int componentLen = element.length();
this.values[i] = element;
this.offsets[i] = (i == 0 ? 0 : this.offsets[i - 1] + this.values[i - 1].length());
totalLength += componentLen;
i++;
}
this.length = totalLength;
}
}
public int length() {
return this.length;
}
public char charAt(final int index) {
if ((index < 0) || (index >= this.length)) {
throw new StringIndexOutOfBoundsException(index);
}
int n = this.values.length;
while (n-- != 0) {
if (this.offsets[n] <= index) {
return this.values[n].charAt(index - this.offsets[n]);
}
}
// Should never reach here!
throw new IllegalStateException("Bad computing of charAt at AggregatedString");
}
public CharSequence subSequence(final int beginIndex, final int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > this.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
if (subLen == 0) {
return "";
}
int n1 = this.values.length;
while (n1-- != 0) {
if (this.offsets[n1] < endIndex) { // Will always happen eventually, as the first offset is 0
break;
}
}
int n0 = n1 + 1;
while (n0-- != 0) {
if (this.offsets[n0] <= beginIndex) { // Will always happen eventually, as the first offset is 0
break;
}
}
if (n0 == n1) {
// Shortcut: let the CharSequence#subSequence method do the job...
return this.values[n0].subSequence((beginIndex - this.offsets[n0]), (endIndex - this.offsets[n0]));
}
final char[] chars = new char[endIndex - beginIndex];
int charsOffset = 0;
int nx = n0;
while (nx <= n1) {
final int nstart = Math.max(beginIndex, this.offsets[nx]) - this.offsets[nx];
final int nend = Math.min(endIndex, this.offsets[nx] + this.values[nx].length()) - this.offsets[nx];
copyChars(this.values[nx], nstart, nend, chars, charsOffset);
charsOffset += (nend - nstart);
nx++;
}
return new String(chars);
}
public void write(final Writer writer) throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Writer cannot be null");
}
for (int i = 0; i < this.values.length; i++) {
writer.write(this.values[i].toString());
}
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AggregateCharSequence)) {
return false;
}
final AggregateCharSequence that = (AggregateCharSequence) o;
if (this.values.length == 1 && that.values.length == 1) {
if (this.values[0] instanceof String && that.values[0] instanceof String) {
return this.values[0].equals(that.values[0]);
}
}
if (this.length != that.length) {
return false;
}
if (this.length == 0) {
return true;
}
if (this.hash != 0 && that.hash != 0 && this.hash != that.hash) {
return false;
}
int i = 0;
int m1 = 0;
int n1 = 0;
int len1 = this.values[m1].length();
int m2 = 0;
int n2 = 0;
int len2 = that.values[m2].length();
while (i < this.length) {
// Move to the next value array if needed, including skipping those with len == 0
while (n1 >= len1 && (m1 + 1) < this.values.length) {
m1++; n1 = 0;
len1 = this.values[m1].length();
}
while (n2 >= len2 && (m2 + 1) < that.values.length) {
m2++; n2 = 0;
len2 = that.values[m2].length();
}
// Shortcut, in case we have to identical Strings ready to be compared with one another
if (n1 == 0 && n2 == 0 && len1 == len2 && this.values[m1] instanceof String && that.values[m2] instanceof String) {
if (!this.values[m1].equals(that.values[m2])) {
return false;
}
n1 = len1; // Force skipping this value position
n2 = len2; // Force skipping this value position
i += len1;
continue;
}
// Character-by-character matching
if (this.values[m1].charAt(n1) != that.values[m2].charAt(n2)) {
return false;
}
n1++;
n2++;
i++;
}
return true;
}
public int hashCode() {
// This method mimics the local-variable cache mechanism from java.lang.String
// ---------------------------------------
// NOTE: Even if relying on the specific implementation of String.hashCode() might seem
// a potential issue for cross-platform compatibility, the fact is that the
// implementation of String.hashCode() is actually a part of the Java Specification
// since Java 1.2, and its internal workings are explained in the JavaDoc for the
// String.hashCode() method.
// ---------------------------------------
int h = this.hash;
if (h == 0 && this.length > 0) {
if (this.values.length == 1) {
h = this.values[0].hashCode(); // Might be cached at the String object, let's benefit from that
} else {
final CharSequence[] vals = this.values;
CharSequence val;
int valLen;
for (int x = 0; x < vals.length; x++) {
val = vals[x];
valLen = val.length();
for (int i = 0; i < valLen; i++) {
h = 31 * h + val.charAt(i);
}
}
}
this.hash = h;
}
return h;
}
public boolean contentEquals(final StringBuffer sb) {
synchronized (sb) {
return contentEquals((CharSequence) sb);
}
}
public boolean contentEquals(final CharSequence cs) {
if (this.length != cs.length()) {
return false;
}
if (this.length == 0) {
return true;
}
// Shortcut in case argument is another AggregatedString
if (cs.equals(this)) {
return true;
}
if (cs instanceof String) {
if (this.values.length == 1 && this.values[0] instanceof String) {
return this.values[0].equals(cs);
}
if (this.hash != 0 && this.hash != cs.hashCode()) {
return false;
}
}
// Deal with argument as a generic CharSequence
int i = 0;
int m1 = 0;
int n1 = 0;
int len1 = this.values[m1].length();
while (i < this.length) {
// Move to the next value array if needed, including skipping those with len == 0
while (n1 >= len1 && (m1 + 1) < this.values.length) {
m1++; n1 = 0;
len1 = this.values[m1].length();
}
// Character-by-character matching
if (this.values[m1].charAt(n1) != cs.charAt(i)) {
return false;
}
n1++;
i++;
}
return true;
}
@Override
public String toString() {
if (this.length == 0) {
return "";
}
if (this.values.length == 1) {
return this.values[0].toString();
}
final char[] chars = new char[this.length];
for (int i = 0; i < this.values.length; i++) {
copyChars(this.values[i], 0, this.values[i].length(), chars, this.offsets[i]);
}
return new String(chars);
}
private static void copyChars(
final CharSequence src, final int srcBegin, final int srcEnd, final char[] dst, final int dstBegin) {
if (src instanceof String) {
((String)src).getChars(srcBegin, srcEnd, dst, dstBegin);
return;
}
int i = srcBegin;
while (i < srcEnd) {
dst[dstBegin + (i - srcBegin)] = src.charAt(i);
i++;
}
}
}
| 30.894052 | 255 | 0.550569 |
9902daef513d2d9347efb53eb4218111760af8e8 | 1,175 | /**
* iBizSys 5.0 机器人生产代码(不要直接修改当前代码)
* http://www.ibizsys.net
*/
package net.ibizsys.psrt.srv.codelist;
import net.ibizsys.paas.codelist.CodeItem;
import net.ibizsys.paas.codelist.CodeItems;
import net.ibizsys.paas.codelist.CodeList;
import net.ibizsys.paas.sysmodel.StaticCodeListModelBase;
import net.ibizsys.paas.sysmodel.CodeListGlobal;
@CodeList(id="4bc7f1433da3a22f25eff878790f0be5",name="代码表或模式",type="STATIC",userscope=false,emptytext="未定义")
@CodeItems({
@CodeItem(value="NUMBERORMODE",text="数字或处理",realtext="数字或处理")
,@CodeItem(value="STRINGORMODE",text="文本或模式",realtext="文本或模式")
})
/**
* 静态代码表[代码表或模式]模型基类
*/
public abstract class CodeList20CodeListModelBase extends net.ibizsys.paas.sysmodel.StaticCodeListModelBase {
/**
* 数字或处理
*/
public final static String NUMBERORMODE = "NUMBERORMODE";
/**
* 文本或模式
*/
public final static String STRINGORMODE = "STRINGORMODE";
public CodeList20CodeListModelBase() {
super();
this.initAnnotation(CodeList20CodeListModelBase.class);
CodeListGlobal.registerCodeList("net.ibizsys.psrt.srv.codelist.CodeList20CodeListModel", this);
}
} | 26.704545 | 110 | 0.72766 |
e6ed5613e215c83e7b37e980318daba31e2acf70 | 1,401 | package chopchop.model.usage;
import static chopchop.testutil.TypicalUsages.Date.USAGE_DATE_A;
import static chopchop.testutil.TypicalUsages.Date.USAGE_DATE_B;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class RecipeUsageTest {
@Test
void getName() {
var u = new RecipeUsage("A", USAGE_DATE_A);
assertEquals("A", u.getName());
}
@Test
void getDate() {
var u = new RecipeUsage("A", USAGE_DATE_A);
assertEquals(USAGE_DATE_A, u.getDate());
}
@Test
void getPrintableDate() {
var u = new RecipeUsage("A", USAGE_DATE_A);
assertEquals("0001-01-01 01:01", u.getPrintableDate());
}
@Test
void isAfter() {
var u = new RecipeUsage("A", USAGE_DATE_A);
var u1 = new RecipeUsage("A", USAGE_DATE_B);
assertFalse(u.isAfter(u1.getDate()));
assertTrue(u1.isAfter(u.getDate()));
assertFalse(u1.isAfter(u1.getDate()));
}
@Test
void isBefore() {
var u = new RecipeUsage("A", USAGE_DATE_A);
var u1 = new RecipeUsage("A", USAGE_DATE_B);
assertFalse(u1.isBefore(u.getDate()));
assertTrue(u.isBefore(u1.getDate()));
assertFalse(u1.isBefore(u1.getDate()));
}
}
| 29.1875 | 64 | 0.648822 |
0aec1cd2403d4babbfd12550af89e7600e3cb7c1 | 1,680 | package models;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CipherTest {
@Test
void encoding() {
Cipher testCipher = new Cipher();
String plainText = "welcome to coding";
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int key = 3;
plainText = plainText.toLowerCase();
String cText ="";
for (int i = 0; i<plainText.length(); i++){
int charIndex = alphabet.indexOf(plainText.charAt(i));
int newIndex = (charIndex + key) % 26;
char cipherChar = alphabet.charAt(newIndex);
cText += String.valueOf(cipherChar);
}
assertEquals(cText,testCipher.encoding(plainText, 3));
}
@Test
void decoding() {
Cipher testCipher = new Cipher();
String plainText = "";
String codedText ="";
String alphabet = "abcde";
int key = 3;
for (int i = 0; i<plainText.length(); i++){
int charIndex = alphabet.indexOf(plainText.charAt(i));
int newIndex = (charIndex - key) % 26;
if(newIndex < 0){
newIndex = alphabet.length() + newIndex;
}
char plainChar = alphabet.charAt(newIndex);
plainText = plainText + plainChar;
}
assertEquals(plainText,testCipher.encoding(codedText, 3));
}
@Test
void allLowerCase_returnsAllLowerCase_String() {
Cipher testCipher = new Cipher();
String plainText = "welcome to coding";
assertEquals(plainText,testCipher.toLowerCase());
}
}
| 28.965517 | 70 | 0.560714 |
a21507e1bab91c6fec881ef0efe731652ab4322a | 2,231 | package com.education.api.config.shiro;
import com.education.common.cache.CacheBean;
import com.education.common.utils.ObjectUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* redisCache
* @author zengjintao
* @version 1.0
* @create_at 2020/7/1 20:19
*/
public class RedisCache<K, V> implements Cache<K, V> {
private CacheBean redisCacheBean;
public RedisCache(CacheBean redisCacheBean) {
this.redisCacheBean = redisCacheBean;
}
/**
* 获取缓存key的value
* @param k
* @return
* @throws CacheException
*/
@Override
public V get(K k) throws CacheException {
return redisCacheBean.get(k);
}
/**
* 设置缓存
* @param key
* @param value
* @return
* @throws CacheException
*/
@Override
public V put(K key, V value) throws CacheException {
redisCacheBean.put(key, value);
return value;
}
/**
* 删除指定缓存数据
* @param k
* @return
* @throws CacheException
*/
@Override
public V remove(K k) throws CacheException {
V value = redisCacheBean.get(k);
redisCacheBean.remove(k);
return value;
}
/**
* 删除redis中的所有缓存
* @throws CacheException
*/
@Override
public void clear() throws CacheException {
redisCacheBean.remove();
}
/**
* 获取缓存中key大小
* @return
*/
@Override
public int size() {
return this.keys().size();
}
/**
* 获取缓存中的所有key
* @return
*/
@Override
public Set<K> keys() {
return (Set<K>) redisCacheBean.getKeys();
}
/**
* 用户获取缓存中的集合对象
* @return
*/
@Override
public Collection<V> values() {
Collection collection = keys(); // 获取缓存中的所有key
if (ObjectUtils.isNotEmpty(collection)) {
Set<V> values = new HashSet<>(); // 用来存储缓存中的所有value集合
collection.forEach(key -> {
values.add(this.get((K) key));
});
return values;
}
return Collections.emptySet();
}
}
| 20.657407 | 65 | 0.580009 |
232cdc70b5e1a48df07861934fedc1de98f210c1 | 2,352 | /*
* XML Type: CT_RPrChange
* Namespace: http://schemas.openxmlformats.org/wordprocessingml/2006/main
* Java type: org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrChange
*
* Automatically generated - do not modify.
*/
package org.openxmlformats.schemas.wordprocessingml.x2006.main.impl;
import javax.xml.namespace.QName;
import org.apache.xmlbeans.QNameSet;
/**
* An XML CT_RPrChange(@http://schemas.openxmlformats.org/wordprocessingml/2006/main).
*
* This is a complex type.
*/
public class CTRPrChangeImpl extends org.openxmlformats.schemas.wordprocessingml.x2006.main.impl.CTTrackChangeImpl implements org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrChange {
private static final long serialVersionUID = 1L;
public CTRPrChangeImpl(org.apache.xmlbeans.SchemaType sType) {
super(sType);
}
private static final QName[] PROPERTY_QNAME = {
new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "rPr"),
};
/**
* Gets the "rPr" element
*/
@Override
public org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrOriginal getRPr() {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrOriginal target = null;
target = (org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrOriginal)get_store().find_element_user(PROPERTY_QNAME[0], 0);
return (target == null) ? null : target;
}
}
/**
* Sets the "rPr" element
*/
@Override
public void setRPr(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrOriginal rPr) {
generatedSetterHelperImpl(rPr, PROPERTY_QNAME[0], 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
}
/**
* Appends and returns a new empty "rPr" element
*/
@Override
public org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrOriginal addNewRPr() {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrOriginal target = null;
target = (org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrOriginal)get_store().add_element_user(PROPERTY_QNAME[0]);
return target;
}
}
}
| 36.75 | 194 | 0.708333 |
5b8c38625c3144f7bfd38df3929d959824400631 | 2,051 | package com.hashmapinc.tempus.witsml.DrillTest.model.user;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"account",
"password"
})
public class UserInfo {
@JsonProperty("account")
@ApiModelProperty(notes = "The User Name")
private String account;
@JsonProperty("password")
@ApiModelProperty(notes = "Password")
private String password;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<>();
@JsonProperty("account")
@ApiModelProperty(notes = "The User Name")
public String getAccount() {
return account;
}
@JsonProperty("account")
@ApiModelProperty(notes = "The User Name")
public void setAccount(String account) {
this.account = account;
}
@JsonProperty("password")
@ApiModelProperty(notes = "Password")
public String getPassword() {
return password;
}
@JsonProperty("password")
@ApiModelProperty(notes = "Password")
public void setPassword(String password) {
this.password = password;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public String toString() {
return new ToStringBuilder(this).append("account", account).append("password", password).append("additionalProperties", additionalProperties).toString();
}
}
| 29.3 | 161 | 0.718186 |
75c33a2a353ef41ef9cd10cf90fd367caab97231 | 61,403 | package com.boguenon.service.modules.bayes.editor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.help.UnsupportedOperationException;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import org.openmarkov.core.action.AddProbNodeEdit;
import org.openmarkov.core.exception.IncompatibleEvidenceException;
import org.openmarkov.core.exception.InvalidStateException;
import org.openmarkov.core.exception.NoFindingException;
import org.openmarkov.core.exception.NodeNotFoundException;
import org.openmarkov.core.exception.NonProjectablePotentialException;
import org.openmarkov.core.exception.NotEvaluableNetworkException;
import org.openmarkov.core.exception.UnexpectedInferenceException;
import org.openmarkov.core.inference.InferenceAlgorithm;
import org.openmarkov.core.inference.annotation.InferenceManager;
import org.openmarkov.core.model.graph.Link;
import org.openmarkov.core.model.network.EvidenceCase;
import org.openmarkov.core.model.network.Finding;
import org.openmarkov.core.model.network.Node;
import org.openmarkov.core.model.network.NodeType;
import org.openmarkov.core.model.network.PolicyType;
import org.openmarkov.core.model.network.ProbNet;
import org.openmarkov.core.model.network.ProbNode;
import org.openmarkov.core.model.network.Variable;
import org.openmarkov.core.model.network.potential.Potential;
import org.openmarkov.core.model.network.potential.PotentialRole;
import org.openmarkov.core.model.network.potential.PotentialType;
import org.openmarkov.core.model.network.potential.TablePotential;
import org.openmarkov.core.model.network.potential.UniformPotential;
import org.openmarkov.core.oopn.Instance.ParameterArity;
import org.openmarkov.inference.tasks.VariableElimination.VEPropagation;
import com.boguenon.service.modules.bayes.CPGXML;
import com.boguenon.service.modules.bayes.mode.EditionMode;
import com.boguenon.service.modules.bayes.mode.EditionModeManager;
public class EditorPanel {
protected ProbNet probNet;
/**
* Static field for serializable class.
*/
private static final long serialVersionUID = 2789011585460326400L;
/**
* Constant that indicates the value of the Expansion Threshold by default.
*/
// This should be in a future a configuration option that should be read on
// start
private static final int DEFAULT_THRESHOLD_VALUE = 5;
/**
* Current edition mode.
*/
private EditionMode editionMode = null;
/**
* This variable indicates which is the expansion threshold of the network
*/
private double currentExpansionThreshold = DEFAULT_THRESHOLD_VALUE;
/**
* Network panel associated to this editor panel
*/
private CPGXML networkPanel = null;
/**
* Pre resolution evidence
*/
private EvidenceCase preResolutionEvidence;
/**
* Array of Evidence cases treated for this editor panel
*/
private List<EvidenceCase> postResolutionEvidence;
/**
* Each position of this array indicates if the corresponding evidence case
* is currently compiled (if true) or not (if false)
*/
private List<Boolean> evidenceCasesCompilationState;
/**
* Minimum value of the range of each utility node.
*/
private HashMap<Variable, Double> minUtilityRange;
/**
* Maximum value of the range of each utility node.
*/
private HashMap<Variable, Double> maxUtilityRange;
/**
* This variable indicates which is the evidence case that is currently
* being treated
*/
private int currentCase;
/**
* Inference manager
*/
private InferenceManager inferenceManager = null;
/**
* Inference algorithm used to evaluate this network
*/
private InferenceAlgorithm inferenceAlgorithm = null;
/**
* This variable indicates if the propagation mode is automatic or manual.
*/
private boolean automaticPropagation;
/**
* This variable indicates if propagation should be done right now (if being
* in Inference Mode).
*/
private boolean propagationActive;
/**
* This variable indicates if it has been a change in the properties or in
* the potential values in some node.
*/
private boolean networkChanged = true;
/**
* Visual representation of the network
*/
public VisualNetwork visualNetwork = null;
private boolean approximateInferenceWarningGiven = false;
private boolean canBeExpanded = false;
private EditionModeManager editionModeManager;
/**
* Constructor that creates the instance.
* @param networkPanel network that will be edited.
*/
public EditorPanel (CPGXML networkPanel, VisualNetwork visualNetwork)
{
this.networkPanel = networkPanel;
this.probNet = networkPanel.getProbNet ();
this.visualNetwork = visualNetwork;
automaticPropagation = true;
propagationActive = true;
preResolutionEvidence = new EvidenceCase ();
postResolutionEvidence = new ArrayList<EvidenceCase> (1);
currentCase = 0;
EvidenceCase evidenceCase = new EvidenceCase ();
postResolutionEvidence.add (currentCase, evidenceCase);
evidenceCasesCompilationState = new ArrayList<Boolean> (1);
evidenceCasesCompilationState.add (currentCase, false);
minUtilityRange = new HashMap<Variable, Double> ();
maxUtilityRange = new HashMap<Variable, Double> ();
initialize ();
inferenceManager = new InferenceManager ();
editionModeManager = new EditionModeManager (this, probNet);
editionMode = editionModeManager.getDefaultEditionMode ();
}
/**
* This method initializes this instance.
*/
private void initialize ()
{
}
/**
* Changes the presentation mode of the text of the nodes.
* @param value new value of the presentation mode of the text of the nodes.
*/
public void setByTitle (boolean value)
{
visualNetwork.setByTitle (value);
}
/**
* Returns the presentation mode of the text of the nodes.
* @return true if the title of the nodes is the name or false if it is the
* name.
*/
public boolean getByTitle ()
{
return visualNetwork.getByTitle ();
}
/**
* Overwrite 'paint' method to avoid to call it explicitly.
* @param g the graphics context in which to paint.
*/
public void paint()
{
visualNetwork.paint();
}
/**
* Returns the edition mode.
* @return edition mode.
*/
public EditionMode getEditionMode ()
{
return editionMode;
}
/**
* Changes the state of the edition and carries out the necessary actions in
* each case.
* @param newState new edition state.
*/
public void setEditionMode (String newEditionModeName)
{
EditionMode newEditionMode = editionModeManager.getEditionMode (newEditionModeName);
if (!editionMode.equals (newEditionMode))
{
editionMode = newEditionMode;
}
}
/**
* Returns the number of selected nodes.
* @return number of selected nodes.
*/
public int getSelectedNodesNumber ()
{
return visualNetwork.getSelectedNodesNumber ();
}
/**
* Returns the number of selected links.
* @return number of selected links.
*/
public int getSelectedLinksNumber ()
{
return visualNetwork.getSelectedLinksNumber ();
}
/**
* Returns a list containing the selected nodes.
* @return a list containing the selected nodes.
*/
public List<VisualNode> getSelectedNodes ()
{
return visualNetwork.getSelectedNodes ();
}
/**
* Returns a list containing the selected links.
* @return a list containing the selected links.
*/
public List<VisualLink> getSelectedLinks ()
{
return visualNetwork.getSelectedLinks ();
}
// private boolean requestCostEffectiveness(Window owner,
// String suffixTypeAnalysis, boolean isProbabilistic) {
// costEffectivenessDialog = new CostEffectivenessDialog(owner);
// costEffectivenessDialog.showSimulationsNumberElements(isProbabilistic);
// return (costEffectivenessDialog.requestData(probNet.getName(),
// suffixTypeAnalysis) == CostEffectivenessDialog.OK_BUTTON);
// }
/**
* This method shows a dialog box with the additionalProperties of a link.
* If some property has changed, insert a new undo point into the network
* undo manager.
* @param link
*/
public void changeLinkProperties (VisualLink link)
{
/*
* This method must be implemented to activate the possibility of
* editing the additionalProperties of a link in future versions.
*/
}
/**
* This method imposes a policy in a decision node.
*/
public void imposePolicyInNode ()
{
VisualNode node = null;
List<VisualNode> selectedNode = visualNetwork.getSelectedNodes ();
if (selectedNode.size () == 1)
{
node = selectedNode.get (0);
if (node.getNode ().getNodeType () == NodeType.DECISION)
{
Node probNode = node.getNode ();
// TODO manage other kind of policy types from the interface
probNode.setPolicyType (PolicyType.OPTIMAL);
List<Variable> variables = new ArrayList<Variable> ();
// it is added first conditioned variable
variables.add (node.getNode ().getVariable ());
List<Node> nodes = probNode.getProbNet ().getNodes();
for (Node possibleParent : nodes)
{
if (probNode.isParent(possibleParent))
{
variables.add (possibleParent.getVariable ());
}
}
UniformPotential policy = new UniformPotential (
variables,
PotentialRole.POLICY);
List<Potential> policies = new ArrayList<Potential> ();
policies.add (policy);
probNode.setPotentials (policies);
// imposePolicyDialog.setTitle ("ImposePolicydialog.Title.Label");
// if (imposePolicyDialog.requestValues () == NodePropertiesDialog.OK_BUTTON)
// {
// // change its color
// ((VisualDecisionNode) node).setHasPolicy (true);
// networkChanged = true;
// }
// else
// { // if user cancels policy imposition then no potential is
// // restored to the probnode
// List<Potential> noPolicy = new ArrayList<Potential> ();
// probNode.setPotentials (noPolicy);
// }
}
}
}
/**
* This method edits an imposed policy of a decision node.
*/
public void editNodePolicy ()
{
System.out.println ("Pulsada la opción 'Editar Política'"); // ...Borrar
VisualNode node = null;
List<VisualNode> selectedNode = visualNetwork.getSelectedNodes ();
if (selectedNode.size () == 1)
{
node = selectedNode.get (0);
if (node.getNode ().getNodeType () == NodeType.DECISION)
{
Node probNode = node.getNode ();
// TODO manage other kind of policy types from the interface
// probNode.setPolicyType(PolicyType.OPTIMAL);
// Potential imposedPolicy = probNode.getPotentials ().get (0);
// PotentialEditDialog imposePolicyDialog = new PotentialEditDialog (
// Utilities.getOwner (this),
// probNode, false);
// if (imposePolicyDialog.requestValues () == NodePropertiesDialog.OK_BUTTON)
// {
// // change it colour
// ((VisualDecisionNode) node).setHasPolicy (true);
// networkChanged = true;
// }
}
}
}
/**
* This method removes an imposed policy from a decision node.
*/
public void removePolicyFromNode ()
{
System.out.println ("Pulsada la opción 'Eliminar Política'"); // ...Borrar
VisualNode node = null;
List<VisualNode> selectedNode = visualNetwork.getSelectedNodes ();
if (selectedNode.size () == 1)
{
node = selectedNode.get (0);
if (node.getNode ().getNodeType () == NodeType.DECISION)
{
Node probNode = node.getNode ();
ArrayList<Potential> noPolicy = new ArrayList<> ();
probNode.setPotentials (noPolicy);
((VisualDecisionNode) node).setHasPolicy (false);
}
}
networkChanged = true;
}
/**
* This method shows the expected utility of a decision node.
*/
public void showExpectedUtilityOfNode ()
{
VisualNode node = null;
List<VisualNode> selectedNode = visualNetwork.getSelectedNodes ();
if (selectedNode.size () == 1)
{
node = selectedNode.get (0);
Node probNode = node.getNode ();
try
{
// Potential expectedUtility = null;// =
// inferenceAlgorithm.getExpectedtedUtility(node.getProbNode().getVariable());
Potential expectedUtility;
expectedUtility = inferenceAlgorithm.getExpectedUtilities (probNode.getVariable ());
ProbNode dummyNode = new ProbNode (new ProbNet (), probNode.getVariable (),
probNode.getNodeType ());
dummyNode.setPotential (expectedUtility);
// PotentialEditDialog expectedUtilityDialog = new PotentialEditDialog (
// Utilities.getOwner (this),
// dummyNode,
// false, true);
// expectedUtilityDialog.setTitle ("ExpectedUtilityDialog.Title.Label");
// expectedUtilityDialog.requestValues ();
}
catch (IncompatibleEvidenceException | UnexpectedInferenceException e)
{
System.err.println("ExceptionGeneric : " + e.getMessage());
e.printStackTrace ();
}
}
networkChanged = false;
}
/**
* This method shows the optimal policy for a decision node.
*/
public void showOptimalPolicyOfNode ()
{
VisualNode node = null;
List<VisualNode> selectedNode = visualNetwork.getSelectedNodes ();
if (selectedNode.size () == 1)
{
node = selectedNode.get (0);
ProbNet dummyProbNet = new ProbNet ();
Node dummy = null;
try
{
// Potential optimalPolicy =
// inferenceAlgorithm.getOptimizedPolicies().get(node.getProbNode().getVariable());
Potential optimalPolicy = inferenceAlgorithm.getOptimizedPolicy (node.getNode ().getVariable ());
dummyProbNet.addPotential (optimalPolicy);
Variable conditionedVariable = optimalPolicy.getVariable (0);
dummy = dummyProbNet.getNode (conditionedVariable);
dummy.setNodeType (NodeType.DECISION);
dummy.setPolicyType (PolicyType.OPTIMAL);
for (Variable variable : optimalPolicy.getVariables ())
{
if (variable.equals (conditionedVariable))
{
continue;
}
try
{
dummyProbNet.addLink (variable, conditionedVariable, true);
}
catch (NodeNotFoundException e)
{
throw new RuntimeException ("Node not found: " + e.getMessage ());
}
}
// PotentialEditDialog optimalPolicyDialog = new PotentialEditDialog (
// Utilities.getOwner (this),
// dummy, false,
// true);
// optimalPolicyDialog.setTitle ("OptimalPolicyDialog.Title.Label");
// optimalPolicyDialog.requestValues ();
}
catch (IncompatibleEvidenceException | UnexpectedInferenceException e)
{
System.err.println("ExceptionGeneric : " + e.getMessage());
e.printStackTrace ();
}
}
networkChanged = false;
}
/**
* This method returns the current Evidence Case.
* @return the current Evidence Case.
*/
public EvidenceCase getCurrentEvidenceCase ()
{
return postResolutionEvidence.get (currentCase);
}
/**
* This method returns the Evidence Case.
* @param caseNumber the number of the case to be returned.
* @return the selected Evidence Case.
*/
public EvidenceCase getEvidenceCase (int caseNumber)
{
return postResolutionEvidence.get (caseNumber);
}
/**
* This method returns list of evidence cases
* @return the list of Evidence Cases.
*/
public ArrayList<EvidenceCase> getEvidence ()
{
ArrayList<EvidenceCase> evidence = new ArrayList<EvidenceCase> ();
for (EvidenceCase postResolutionEvidenceCase : postResolutionEvidence)
{
if (!postResolutionEvidenceCase.isEmpty ())
{
evidence.add (postResolutionEvidenceCase);
}
}
if (!evidence.isEmpty () || !preResolutionEvidence.isEmpty ())
{
evidence.add (0, preResolutionEvidence);
}
return evidence;
}
/**
* This method returns the number of the Evidence Case that is currently
* selected
* @return the number of the current Evidence Case.
*/
public int getCurrentCase ()
{
return currentCase;
}
public EvidenceCase getPreResolutionEvidence ()
{
return preResolutionEvidence;
}
/**
* This method sets which is the current evidence case.
* @param currentCase new value for the current evidence case.
*/
public void setCurrentCase (int currentCase)
{
this.currentCase = currentCase;
}
/**
* This method returns the number of Evidence Cases that the ArrayList is
* currently holding .
* @return the number of Evidence Cases in the ArrayList.
*/
public int getNumberOfCases ()
{
return postResolutionEvidence.size ();
}
/**
* This method returns a boolean indicating if the case number passed as
* parameter is currently compiled.
* @param caseNumber number of the evidence case.
* @return the compilation state of the case.
*/
public boolean getEvidenceCasesCompilationState (int caseNumber)
{
return evidenceCasesCompilationState.get (caseNumber);
}
/**
* This method sets which is the compilation state of the case.
* @param caseNumber number of the evidence case to be set.
* @param value true if compiled; false otherwise.
*/
public void setEvidenceCasesCompilationState (int caseNumber, boolean value)
{
this.evidenceCasesCompilationState.set (caseNumber, value);
}
/**
* This method sets the list of evidence cases
* @param owner window that owns the dialog box.
*/
public void setEvidence (EvidenceCase preResolutionEvidence,
List<EvidenceCase> postResolutionInference)
{
this.postResolutionEvidence = (postResolutionInference == null) ? new ArrayList<EvidenceCase> ()
: postResolutionInference;
this.preResolutionEvidence = (preResolutionEvidence == null) ? new EvidenceCase ()
: preResolutionEvidence;
if (postResolutionEvidence.isEmpty ())
{
this.postResolutionEvidence.add (new EvidenceCase ());
}
currentCase = this.postResolutionEvidence.size () - 1;
// Update visual info on evidence
for (VisualNode node : visualNetwork.getAllNodes ())
{
node.setPostResolutionFinding (false);
}
for (EvidenceCase evidenceCase : postResolutionEvidence)
{
for (Finding finding : evidenceCase.getFindings ())
{
for (VisualNode node : visualNetwork.getAllNodes ())
{
if (node.getNode ().getVariable ().equals (finding.getVariable ()))
{
node.setPostResolutionFinding (true);
}
}
}
}
for (VisualNode node : visualNetwork.getAllNodes ())
{
node.setPreResolutionFinding (false);
}
for (Finding finding : preResolutionEvidence.getFindings ())
{
for (VisualNode node : visualNetwork.getAllNodes ())
{
if (node.getNode ().getVariable ().equals (finding.getVariable ()))
{
node.setPreResolutionFinding (true);
}
}
}
// Update evidenceCasesCompilationState
evidenceCasesCompilationState.clear ();
for (int i = 0; i < postResolutionEvidence.size (); ++i)
{
evidenceCasesCompilationState.add (false);
}
}
/**
* This method returns true if propagation type currently set is automatic;
* false if manual.
* @return true if the current propagation type is automatic.
*/
public boolean isAutomaticPropagation ()
{
return automaticPropagation;
}
/**
* This method sets the current propagation type.
* @param automaticPropagation new value of the propagation type.
*/
public void setAutomaticPropagation (boolean automaticPropagation)
{
this.automaticPropagation = automaticPropagation;
}
/**
* This method returns the propagation status: true if propagation should be
* done right now; false otherwise.
* @return true if propagation should be done right now.
*/
public boolean isPropagationActive ()
{
return propagationActive;
}
/**
* This method sets the propagation status.
* @param propagationActive new value of the propagation status.
*/
public void setPropagationActive (boolean propagationActive)
{
this.propagationActive = propagationActive;
this.visualNetwork.setPropagationActive (propagationActive);
}
/**
* This method returns the associated network panel.
* @return the associated network panel.
*/
public CPGXML getNetworkPanel ()
{
return networkPanel;
}
/**
* This method changes the current expansion threshold.
* @param expansionThreshold new value of the expansion threshold.
*/
public void setExpansionThreshold (double expansionThreshold)
{
this.currentExpansionThreshold = expansionThreshold;
}
/**
* This method returns the current expansion threshold.
* @return the value of the current expansion threshold.
*/
public double getExpansionThreshold ()
{
return currentExpansionThreshold;
}
/**
* This method updates the expansion state (expanded/contracted) of the
* nodes. It is used in transitions from edition to inference mode and vice
* versa, and also when the user modifies the current expansion threshold in
* the Inference tool bar
* @param newWorkingMode new value of the working mode.
*/
public void updateNodesExpansionState (int newWorkingMode)
{
if (newWorkingMode == CPGXML.EDITION_WORKING_MODE)
{
VisualNode visualNode = null;
List<VisualNode> allNodes = visualNetwork.getAllNodes ();
if (allNodes.size () > 0)
{
for (int i = 0; i < allNodes.size (); i++)
{
visualNode = allNodes.get (i);
if (visualNode.isExpanded ())
{
visualNode.setExpanded (false);
}
}
}
}
else if (newWorkingMode == CPGXML.INFERENCE_WORKING_MODE)
{
VisualNode visualNode = null;
List<VisualNode> allNodes = visualNetwork.getAllNodes ();
if (allNodes.size () > 0)
{
for (int i = 0; i < allNodes.size (); i++)
{
visualNode = allNodes.get (i);
if (visualNode.getNode ().getRelevance () >= getExpansionThreshold ())
{
visualNode.setExpanded (true);
}
else
{
visualNode.setExpanded (false);
}
}
}
}
}
/**
* This method updates the value of each state for each node in the network
* with the current individual probabilities.
*/
public void updateIndividualProbabilities ()
{
// if some visualNode has a number of values different from the
// number of evidence cases in memory, we need to recreate its
// visual states and consider that the network has been changed.
for (VisualNode visualNode : visualNetwork.getAllNodes ())
{
InnerBox innerBox = visualNode.getInnerBox ();
VisualState visualState = null;
if (innerBox instanceof FSVariableBox)
{
visualState = ((FSVariableBox) innerBox).getVisualState (0);
updateVisualStateAndEvidence(innerBox, visualState);
}
else if (innerBox instanceof NumericVariableBox)
{
visualState = ((NumericVariableBox) innerBox).getVisualState ();
updateVisualStateAndEvidence(innerBox, visualState);
}
}
if ((propagationActive)
&& (networkPanel.getWorkingMode () == CPGXML.INFERENCE_WORKING_MODE))
{
// if the network has been changed, propagation must be done in
// each evidence case in memory. Otherwise, only propagation in
// current case is needed.
if (networkChanged)
{
for (int i = 0; i < postResolutionEvidence.size (); i++)
{
doPropagation (getEvidenceCase (i), i);
}
updateNodesFindingState (postResolutionEvidence.get (currentCase));
networkChanged = false;
}
else
{
if (evidenceCasesCompilationState.get (currentCase) == false)
{
if (!doPropagation (postResolutionEvidence.get (currentCase), currentCase)) setPropagationActive (false);
}
}
}
else if (evidenceCasesCompilationState.get (currentCase) == false)
{
// Even if propagation mode is manual, a propagation should be
// done the first time that inference mode is selected
doPropagation (postResolutionEvidence.get (currentCase), currentCase);
}
updateAllVisualStates ("", currentCase);
}
private void updateVisualStateAndEvidence(InnerBox innerBox, VisualState visualState)
{
if (visualState.getNumberOfValues () != postResolutionEvidence.size ())
{
innerBox.update(postResolutionEvidence.size());
networkChanged = true;
for (int i = 0; i < postResolutionEvidence.size (); i++)
{
evidenceCasesCompilationState.set (i, false);
}
}
}
/**
* This method removes all the findings established in the current evidence
* case.
*/
public void removeAllFindings ()
{
setPropagationActive (isAutomaticPropagation ());
List<VisualNode> visualNodes = visualNetwork.getAllNodes ();
for (int i = 0; i < visualNodes.size (); i++)
{
visualNodes.get (i).setPostResolutionFinding (false);
}
List<Finding> findings = postResolutionEvidence.get (currentCase).getFindings ();
for (int i = 0; i < findings.size (); i++)
{
try
{
postResolutionEvidence.get (currentCase).removeFinding (findings.get (i).getVariable ());
}
catch (NoFindingException exc)
{
System.err.println("ExceptionNoFinding : " + exc.getMessage());
}
}
if (!doPropagation (postResolutionEvidence.get (currentCase), currentCase))
setPropagationActive (false);
// networkPanel.getMainPanel ().getInferenceToolBar ().setCurrentEvidenceCaseName (currentCase);
// networkPanel.getMainPanel ().getMainPanelMenuAssistant ().updateOptionsFindingsDependent (networkPanel);
}
/**
* This method removes the findings that a node could have in all the
* evidence cases in memory. It is invoked when a change takes place in
* properties or probabilities of a the node
* @param node the node in which to remove the findings.
*/
public void removeNodeEvidenceInAllCases (Node node)
{
for (int i = 0; i < postResolutionEvidence.size (); i++)
{
List<Finding> findings = postResolutionEvidence.get (i).getFindings ();
for (int j = 0; j < findings.size (); j++)
{
try
{
if (node.getVariable () == (findings.get (j).getVariable ()))
{
postResolutionEvidence.get (i).removeFinding (findings.get (j).getVariable ());
if (isAutomaticPropagation () && (inferenceAlgorithm != null))
{
if (!doPropagation (postResolutionEvidence.get (i), i)) setPropagationActive (false);
}
if (i == currentCase)
{
List<VisualNode> visualNodes = visualNetwork.getAllNodes ();
for (int k = 0; k < visualNodes.size (); k++)
{
if (visualNodes.get (k).getNode () == node)
{
visualNodes.get (k).setPostResolutionFinding (false);// ...asaez....PENDIENTE........
}
}
}
}
}
catch (NoFindingException exc)
{
System.err.println("ExceptionNoFinding : " + exc.getMessage());
}
}
}
// networkPanel.getMainPanel ().getMainPanelMenuAssistant ().updateOptionsFindingsDependent (networkPanel);
}
/**
* This method returns true if there are any finding in the current evidence
* case.
* @return true if the current evidence case has at least one finding.
*/
public boolean areThereFindingsInCase ()
{
boolean areFindings = false;
List<Finding> findings = postResolutionEvidence.get (currentCase).getFindings ();
if (findings != null)
{
if (findings.size () > 0)
{
areFindings = true;
}
}
return areFindings;
}
/**
* This method returns the number of the Evidence Case that is currently
* selected
* @param visualState the visual state in which the finding is going to be
* set.
*/
public void setNewFinding (VisualNode visualNode, VisualState visualState)
{
boolean isInferenceMode = networkPanel.getWorkingMode () == CPGXML.INFERENCE_WORKING_MODE;
EvidenceCase evidenceCase = (isInferenceMode) ? postResolutionEvidence.get (currentCase)
: preResolutionEvidence;
setPropagationActive (isAutomaticPropagation ());
Variable variable = visualNode.getNode ().getVariable ();
boolean nodeAlreadyHasFinding = evidenceCase.getFinding (variable) != null;
int oldState = -1;
if (nodeAlreadyHasFinding)
{
// There is already a finding in the node
oldState = evidenceCase.getState (variable);
if (oldState == visualState.getStateNumber ())
{
// The finding is in the same state, therefore, remove evidence
try
{
evidenceCase.removeFinding (variable);
if (isInferenceMode)
{
visualNode.setPostResolutionFinding (false);
}
}
catch (NoFindingException exc)
{
System.err.println("ExceptionNoFinding : " + exc.getMessage());
}
}
else
{
// There is a finding in another state. Remove old, add new
try
{
evidenceCase.removeFinding (variable);
Finding finding = new Finding (variable, visualState.getStateNumber ());
evidenceCase.addFinding (finding);
if (isInferenceMode)
{
visualNode.setPostResolutionFinding (true);
}
else
{
visualNode.setPreResolutionFinding (true);
}
}
catch (NoFindingException exc)
{
System.err.println("ExceptionNoFinding : " + exc.getMessage());
}
catch (InvalidStateException exc)
{
System.err.println("ExceptionInvalidState : " + exc.getMessage());
}
catch (IncompatibleEvidenceException exc)
{
System.err.println("ExceptionIncompatibleEvidence : " + exc.getMessage());
}
catch (Exception exc)
{
System.err.println("ExceptionGeneric : " + exc.getMessage());
}
}
}
else
{ // No finding previously in node, add
Finding finding = new Finding (variable, visualState.getStateNumber ());
try
{
evidenceCase.addFinding (finding);
if (isInferenceMode)
{
visualNode.setPostResolutionFinding (true);
}
else
{
visualNode.setPreResolutionFinding (true);
}
}
catch (InvalidStateException exc)
{
System.err.println("ExceptionInvalidState : " + exc.getMessage());
}
catch (IncompatibleEvidenceException exc)
{
System.err.println("ExceptionIncompatibleEvidence : " + exc.getMessage());
}
catch (Exception exc)
{
System.err.println("ExceptionGeneric : " + exc.getMessage());
}
}
if (isInferenceMode)
{
evidenceCasesCompilationState.set (currentCase, false);
}
else
{
for (int i = 0; i < evidenceCasesCompilationState.size (); ++i)
{
evidenceCasesCompilationState.set (i, false);
}
}
// networkPanel.getMainPanel ().getInferenceToolBar ().setCurrentEvidenceCaseName (currentCase);
if ((propagationActive) && (evidenceCasesCompilationState.get (currentCase) == false)
&& (isInferenceMode))
{
if (!doPropagation (evidenceCase, currentCase))
// if propagation does not succeed, restore previous state
{
if (nodeAlreadyHasFinding)
{
try
{
evidenceCase.removeFinding (variable);
}
catch (NoFindingException e)
{/* Not possible */
}
Finding finding = new Finding (variable, oldState);
try
{
evidenceCase.addFinding (finding);
}
catch (InvalidStateException e)
{/* Not possible */
}
catch (IncompatibleEvidenceException e)
{/* Not possible */
}
}
else
{
try
{
evidenceCase.removeFinding (variable);
}
catch (NoFindingException e)
{ /* Not possible */
}
}
if (isInferenceMode)
{
visualNode.setPostResolutionFinding (nodeAlreadyHasFinding);
}
else
{
visualNode.setPreResolutionFinding (nodeAlreadyHasFinding);
}
}
}
// networkPanel.getMainPanel ().getMainPanelMenuAssistant ().updateOptionsFindingsDependent (networkPanel);
// networkPanel.getMainPanel ().getMainPanelMenuAssistant ().updateOptionsPropagationTypeDependent (networkPanel);// ..
}
/**
* Returns the inference algorithm assigned to the panel.
* @return the inference algorithm assigned to the panel.
*/
public InferenceAlgorithm getInferenceAlgorithm ()
{
return inferenceAlgorithm;
}
/**
* Sets the inference algorithm assigned to the panel.
* @param inferenceAlgorithm the inference Algorithm to be assigned to the
* panel.
*/
public void setInferenceAlgorithm (InferenceAlgorithm inferenceAlgorithm)
{
this.inferenceAlgorithm = inferenceAlgorithm;
}
/**
* This method does the propagation of the evidence in the network
* @param evidenceCase the evidence case with which the propagation must be
* done.
* @param caseNumber number of this evidence case.
*/
public boolean doPropagation (EvidenceCase evidenceCase, int caseNumber)
{
Map<Variable, TablePotential> individualProbabilities = null;
boolean propagationSucceded = false;
try
{
long start = System.currentTimeMillis ();
try
{
calculateMinAndMaxUtilityRanges ();
VEPropagation vePosteriorValues = new VEPropagation(probNet, probNet.getVariables(), preResolutionEvidence, evidenceCase, null);
individualProbabilities = vePosteriorValues.getPosteriorValues();
}
catch (OutOfMemoryError e)
{
if (!approximateInferenceWarningGiven)
{
System.err.println("NotEnoughMemoryForExactInference : " + e.getMessage());
approximateInferenceWarningGiven = true;
}
inferenceAlgorithm = inferenceManager.getDefaultApproximateAlgorithm (probNet);
inferenceAlgorithm.setPostResolutionEvidence (evidenceCase);
individualProbabilities = inferenceAlgorithm.getProbsAndUtilities ();
}
catch (NotEvaluableNetworkException e)
{
e.printStackTrace();
return false;
}
long elapsedTimeMillis = System.currentTimeMillis () - start;
System.out.println ("Inference took " + elapsedTimeMillis + " milliseconds.");
updateNodesFindingState (evidenceCase);
paintInferenceResults (caseNumber, individualProbabilities);
propagationSucceded = true;
}
catch (IncompatibleEvidenceException e)
{
System.err.println("ExceptionIncompatibleEvidence : " + e.getMessage());
e.printStackTrace ();
}
catch (UnsupportedOperationException e)
{
System.err.println("NoPropagationCanBeDone : " + e.getMessage());
}
catch (Exception e)
{
System.err.println("ExceptionGeneric during inference : " + e.getMessage());
e.printStackTrace ();
}
evidenceCasesCompilationState.set (caseNumber, propagationSucceded);
return propagationSucceded;
}
// This commented method computes the exact ranges of the utility functions.
// However, we are using an approximation in the method currently offered by
// this class.
/**
* Calculates minUtilityRange and maxUtilityRange fields.
*/
/*
* private void () { TablePotential auxF; ArrayList<Variable>
* utilityVariables = probNet .getVariables(NodeType.UTILITY); for (Variable
* utility : utilityVariables) { auxF = probNet.getUtilityFunction(utility);
* minUtilityRange.put(utility, Tools.min(auxF.values));
* maxUtilityRange.put(utility, Tools.max(auxF.values)); } }
*/
/**
* Calculates minUtilityRange and maxUtilityRange fields. It is an
* approximate implementation. The correct computation is given by a method
* with the same name, but commented above.
* @throws NonProjectablePotentialException
*/
private void calculateMinAndMaxUtilityRanges ()
throws NonProjectablePotentialException
{
List<Variable> utilityVariables = probNet.getVariables (NodeType.UTILITY);
for (Variable utility : utilityVariables)
{
Node probNode = probNet.getNode (utility);
minUtilityRange.put (utility, probNode.getApproximateMinimumUtilityFunction ());
maxUtilityRange.put (utility, probNode.getApproximateMaximumUtilityFunction ());
}
}
/**
* This method fills the visualStates with the proper values to be
* represented after the evaluation of the evidence case
* @param caseNumber number of this evidence case.
* @param individualProbabilities the results of the evaluation for each
* variable.
*/
private void paintInferenceResults (int caseNumber,
Map<Variable, TablePotential> individualProbabilities)
{
for (VisualNode visualNode : visualNetwork.getAllNodes ())
{
Node probNode = visualNode.getNode ();
Variable variable = probNode.getVariable ();
switch (probNode.getNodeType ())
{
case CHANCE :
case DECISION :
paintInferenceResultsChanceOrDecisionNode(caseNumber, individualProbabilities, variable, visualNode);
break;
case UTILITY :
paintInferenceResultsUtilityNode(caseNumber, individualProbabilities, variable, visualNode);
break;
}
}
}
/**
* This method fills the visualStates of a utility node with the proper
* values to be represented after the evaluation of the evidence case
* @param caseNumber number of this evidence case.
* @param individualProbabilities the results of the evaluation for each
* variable.
* @param variable
* @param visualNode
*/
private void paintInferenceResultsUtilityNode (int caseNumber, Map<Variable, TablePotential> individualProbabilities, Variable variable, VisualNode visualNode)
{
NumericVariableBox innerBox = (NumericVariableBox) visualNode.getInnerBox ();
VisualState visualState = innerBox.getVisualState ();
visualState.setStateValue (caseNumber, individualProbabilities.get (variable).values[0]);
innerBox.setMinValue(((Double)minUtilityRange.get(variable)).doubleValue());
innerBox.setMaxValue(((Double)maxUtilityRange.get(variable)).doubleValue());
}
/**
* This method fills the visualStates of a chance or decision node with the
* proper values to be represented after the evaluation of the evidence case
* @param caseNumber number of this evidence case.
* @param individualProbabilities the results of the evaluation for each
* variable.
* @param variable
* @param visualNode
*/
private void paintInferenceResultsChanceOrDecisionNode (int caseNumber, Map<Variable, TablePotential> individualProbabilities, Variable variable, VisualNode visualNode)
{
Potential potential = individualProbabilities.get (variable);
if (potential instanceof TablePotential)
{
TablePotential tablePotential = (TablePotential) potential;
if (tablePotential.getNumVariables () == 1)
{
double[] values = tablePotential.getValues ();
if ((visualNode.getInnerBox ()) instanceof FSVariableBox)
{
FSVariableBox innerBox = (FSVariableBox) visualNode.getInnerBox ();
for (int i = 0; i < innerBox.getNumStates (); i++)
{
VisualState visualState = innerBox.getVisualState (i);
visualState.setStateValue (caseNumber, values[i]);
}
}
// PROVISIONAL2: Currently the propagation
// algorithm is returning a TablePotential
// with 0 variables when the node has a Uniform
// relation
}
else if (tablePotential.getNumVariables () == 0)
{
if ((visualNode.getInnerBox ()) instanceof FSVariableBox)
{
FSVariableBox innerBox = (FSVariableBox) visualNode.getInnerBox ();
for (int i = 0; i < innerBox.getNumStates (); i++)
{
VisualState visualState = innerBox.getVisualState (i);
visualState.setStateValue (caseNumber, (1.0 / innerBox.getNumStates ()));
}
}
visualNode.setPostResolutionFinding (false);
// END OF
// PROVISIONAL2.............asaez...Comprobar si es innecesario
// este Provisional2............
}
else
{
System.err.println("Table Potential of " + variable.getName() + " has " + tablePotential.getNumVariables() + " variables. It cannot be treated by now.");
}
}
}
/**
* This method updates the "finding state" of each node
* @param evidenceCase the evidence case with which the update must be done.
*/
public void updateNodesFindingState (EvidenceCase evidenceCase)
{
for (VisualNode visualNode : visualNetwork.getAllNodes ())
{
visualNode.setPreResolutionFinding (false);
visualNode.setPostResolutionFinding (false);
}
for (Finding finding : evidenceCase.getFindings ())
{
Variable variable = finding.getVariable ();
for (VisualNode visualNode : visualNetwork.getAllNodes ())
{
if (variable.getName ().equals (visualNode.getNode ().getName ()))
{
visualNode.setPostResolutionFinding (true);
}
}
}
for (Finding finding : preResolutionEvidence.getFindings ())
{
Variable variable = finding.getVariable ();
for (VisualNode visualNode : visualNetwork.getAllNodes ())
{
if (variable.getName ().equals (visualNode.getNode ().getName ()))
{
visualNode.setPreResolutionFinding (true);
}
}
}
}
public void temporalEvolution ()
{
VisualNode node = null;
List<VisualNode> selectedNode = visualNetwork.getSelectedNodes ();
if (selectedNode.size () == 1)
{
node = selectedNode.get (0);
// new TraceTemporalEvolutionDialog (Utilities.getOwner (this), node.getProbNode (), preResolutionEvidence);
}
}
/**
* This method creates a new evidence case
*/
public void createNewEvidenceCase ()
{
try
{
EvidenceCase newEvidenceCase = new EvidenceCase ();
EvidenceCase currentEvidenceCase = getCurrentEvidenceCase ();
List<Finding> currentFindings = currentEvidenceCase.getFindings ();
for (int i = 0; i < currentFindings.size (); i++)
{
newEvidenceCase.addFinding (currentFindings.get (i));
}
addNewEvidenceCase (newEvidenceCase);
}
catch (InvalidStateException exc)
{
System.err.println("ExceptionInvalidState : " + exc.getMessage());
}
catch (IncompatibleEvidenceException exc)
{
System.err.println("ExceptionIncompatibleEvidence : " + exc.getMessage());
}
catch (Exception exc)
{
System.err.println("ExceptionGeneric : " + exc.getMessage());
}
}
/**
* This method adds a new evidence case
*/
public void addNewEvidenceCase (EvidenceCase newEvidenceCase)
{
setPropagationActive(isAutomaticPropagation ());
postResolutionEvidence.add (newEvidenceCase);
currentCase = (postResolutionEvidence.size () - 1);
evidenceCasesCompilationState.add (currentCase, false);
updateAllVisualStates("new", currentCase);
// networkPanel.getMainPanel ().getInferenceToolBar ().setCurrentEvidenceCaseName (currentCase);
if (isPropagationActive () && networkPanel.getWorkingMode () == CPGXML.INFERENCE_WORKING_MODE)
{
if (!doPropagation (postResolutionEvidence.get (currentCase), currentCase))
setPropagationActive (false);
}
}
/**
* This method makes the first evidence case to be the current
*/
public void goToFirstEvidenceCase ()
{
currentCase = 0;
updateAllVisualStates ("", currentCase);
// networkPanel.getMainPanel ().getInferenceToolBar ().setCurrentEvidenceCaseName (currentCase);
if ((propagationActive) && (evidenceCasesCompilationState.get (currentCase) == false)
&& (networkPanel.getWorkingMode () == CPGXML.INFERENCE_WORKING_MODE))
{
if (!doPropagation (postResolutionEvidence.get (currentCase), currentCase)) setPropagationActive (false);
}
else
{
updateNodesFindingState (postResolutionEvidence.get (currentCase));
}
}
/**
* This method makes the previous evidence case to be the current
*/
public void goToPreviousEvidenceCase ()
{
if (currentCase > 0)
{
currentCase--;
updateAllVisualStates ("", currentCase);
// networkPanel.getMainPanel ().getInferenceToolBar ().setCurrentEvidenceCaseName (currentCase);
if ((propagationActive) && (evidenceCasesCompilationState.get (currentCase) == false)
&& (networkPanel.getWorkingMode () == CPGXML.INFERENCE_WORKING_MODE))
{
if (!doPropagation (postResolutionEvidence.get (currentCase), currentCase)) setPropagationActive (false);
}
else
{
updateNodesFindingState (postResolutionEvidence.get (currentCase));
}
}
else
{
System.err.println("NoPreviousEvidenceCase");
}
}
/**
* This method makes the next evidence case to be the current
*/
public void goToNextEvidenceCase ()
{
if (currentCase < (postResolutionEvidence.size () - 1))
{
currentCase++;
updateAllVisualStates ("", currentCase);
// networkPanel.getMainPanel ().getInferenceToolBar ().setCurrentEvidenceCaseName (currentCase);
if ((propagationActive) && (evidenceCasesCompilationState.get (currentCase) == false)
&& (networkPanel.getWorkingMode () == CPGXML.INFERENCE_WORKING_MODE))
{
if (!doPropagation (postResolutionEvidence.get (currentCase), currentCase)) setPropagationActive (false);
}
else
{
updateNodesFindingState (postResolutionEvidence.get (currentCase));
}
}
else
{
System.err.println("NoNextEvidenceCaseMessage : ");
}
}
/**
* This method makes the last evidence case to be the current
*/
public void goToLastEvidenceCase ()
{
currentCase = (postResolutionEvidence.size () - 1);
updateAllVisualStates ("", currentCase);
// networkPanel.getMainPanel ().getInferenceToolBar ().setCurrentEvidenceCaseName (currentCase);
if ((propagationActive) && (evidenceCasesCompilationState.get (currentCase) == false)
&& (networkPanel.getWorkingMode () == CPGXML.INFERENCE_WORKING_MODE))
{
if (doPropagation (postResolutionEvidence.get (currentCase), currentCase)) setPropagationActive (false);
}
else
{
updateNodesFindingState (postResolutionEvidence.get (currentCase));
}
}
/**
* This method clears out all the evidence cases. It returns to an 'initial
* state' in which there is only an initial evidence case with no findings
* (corresponding to prior probabilities)
*/
public void clearOutAllEvidenceCases ()
{
setPropagationActive (isAutomaticPropagation ());
postResolutionEvidence.clear ();
evidenceCasesCompilationState.clear ();
EvidenceCase newEvidenceCase = new EvidenceCase ();
postResolutionEvidence.add (newEvidenceCase);
currentCase = 0;
evidenceCasesCompilationState.add (currentCase, false);
updateAllVisualStates ("clear", currentCase);
// networkPanel.getMainPanel ().getInferenceToolBar ().setCurrentEvidenceCaseName (currentCase);
if (!doPropagation (postResolutionEvidence.get (currentCase), currentCase)) setPropagationActive (false);
}
/**
* This method updates all visual states of all visual nodes when it is
* needed for a navigation operation among the existing evidence cases, a
* creation of a new case or when all cases are cleared out.
* @param option the specific operation to be done over the visual states.
*/
public void updateAllVisualStates (String option, int caseNumber)
{
List<VisualNode> allVisualNodes = visualNetwork.getAllNodes ();
for (VisualNode visualNode : allVisualNodes)
{
InnerBox innerBox = visualNode.getInnerBox ();
VisualState visualState = null;
for (int i = 0; i < innerBox.getNumStates (); i++)
{
if (innerBox instanceof FSVariableBox)
{
visualState = ((FSVariableBox) innerBox).getVisualState (i);
}
else if (innerBox instanceof NumericVariableBox)
{
visualState = ((NumericVariableBox) innerBox).getVisualState ();
}
if (option.equals ("new"))
{
visualState.createNewStateValue ();
}
else if (option.equals ("clear"))
{
visualState.clearAllStateValues ();
}
visualState.setCurrentStateValue (caseNumber);
}
}
}
/**
* This method does the propagation of the evidence for all the evidence
* cases in memory.
* @param mainPanelMenuAssistant the menu assistant associated to the main
* panel.
*/
public void propagateEvidence ()
{
setPropagationActive (true);
if (networkPanel.getWorkingMode () == CPGXML.INFERENCE_WORKING_MODE)
{
for (int i = 0; i < getNumberOfCases (); i++)
{
if (evidenceCasesCompilationState.get (i) == false)
{
if (doPropagation (getEvidenceCase (i), i)) setPropagationActive (false);
}
}
updateAllVisualStates ("", currentCase);
// networkPanel.getMainPanel ().getInferenceToolBar ().setCurrentEvidenceCaseName (currentCase);
updateNodesFindingState (postResolutionEvidence.get (currentCase));
}
// mainPanelMenuAssistant.updateOptionsEvidenceCasesNavigation (networkPanel);
// mainPanelMenuAssistant.updateOptionsPropagationTypeDependent (networkPanel);
// mainPanelMenuAssistant.updateOptionsFindingsDependent (networkPanel);
}
/***
* Initializes the link restriction potential of a link
*/
public void enableLinkRestriction ()
{
List<VisualLink> links = visualNetwork.getSelectedLinks ();
if (!links.isEmpty ())
{
Link link = links.get (0).getLink ();
if (!link.hasRestrictions ())
{
link.initializesRestrictionsPotential ();
}
link.resetRestrictionsPotential ();
}
}
/***
* Resets the link restriction potential of a link
*/
public void disableLinkRestriction ()
{
List<VisualLink> links = visualNetwork.getSelectedLinks ();
if (!links.isEmpty ())
{
Link link = links.get (0).getLink ();
link.setRestrictionsPotential (null);
}
}
/***
* Initializes the revelation arc properties of a link
*/
public void enableRevelationArc ()
{
List<VisualLink> links = visualNetwork.getSelectedLinks ();
if (!links.isEmpty ())
{
Link link = links.get (0).getLink ();
}
}
/**
* Sets a new visualNetwork.
* @param visualNetwork
*/
public void setVisualNetwork (VisualNetwork visualNetwork)
{
this.visualNetwork = visualNetwork;
}
/**
* Returns the visualNetwork.
* @return the visualNetwork.
*/
public VisualNetwork getVisualNetwork ()
{
return visualNetwork;
}
public void setProbNet (ProbNet probNet)
{
networkChanged = true;
this.probNet = probNet;
visualNetwork.setProbNet (probNet);
}
/**
* Sets workingMode
* @param newWorkingMode
*/
public void setWorkingMode (int newWorkingMode)
{
visualNetwork.setWorkingMode (newWorkingMode);
if (newWorkingMode == CPGXML.INFERENCE_WORKING_MODE)
{
editionMode = editionModeManager.getDefaultEditionMode ();
}
}
public void editClass ()
{
visualNetwork.editClass ();
}
public void setParameterArity (ParameterArity arity)
{
visualNetwork.setParameterArity (arity);
}
}
| 37.786462 | 172 | 0.572627 |
71fef0b1ffba9db92072e902445376b25b0163f4 | 1,653 | package com.yourtion.leetcode.daily.m03.d04;
/**
* 994. 腐烂的橘子
*
* @author Yourtion
* @link https://leetcode-cn.com/problems/rotting-oranges/
*/
public class Solution {
void rotting(int[][] grid, int x, int y) {
// 上
if (x != 0 && grid[x - 1][y] == 1) {
grid[x - 1][y] = 3;
}
// 下
if (x != grid.length - 1 && grid[x + 1][y] == 1) {
grid[x + 1][y] = 3;
}
// 左
if (y != 0 && grid[x][y - 1] == 1) {
grid[x][y - 1] = 3;
}
// 右
if (y != grid[x].length - 1 && grid[x][y + 1] == 1) {
grid[x][y + 1] = 3;
}
}
public int orangesRotting(int[][] grid) {
int ret = 0;
boolean allRotting = true;
boolean rotting = true;
while (rotting) {
allRotting = true;
rotting = false;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 2) {
rotting(grid, i, j);
}
}
}
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 1) {
allRotting = false;
}
if (grid[i][j] == 3) {
rotting = true;
grid[i][j] = 2;
}
}
}
if (rotting) {
ret += 1;
}
}
return !allRotting ? -1 : ret;
}
}
| 27.098361 | 61 | 0.335753 |
f3a7ea6dc840ce5cc5bcd5e7476f5f0b5cb6eb06 | 1,210 | package org.tcsaroundtheworld.map.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
public class MapHelpWidget extends Composite {
private static MapHelpWidgetUiBinder uiBinder = GWT.create(MapHelpWidgetUiBinder.class);
interface MapHelpWidgetUiBinder extends UiBinder<Widget, MapHelpWidget> {
}
private final MapHelp mapHelp = GWT.create(MapHelp.class);
@UiField SpanElement aboutThisSite;
@UiField SpanElement aboutMe;
@UiField SpanElement updatingSubmissions;
@UiField SpanElement removingSubmissions;
@UiField Anchor contactLink;
public MapHelpWidget() {
initWidget(uiBinder.createAndBindUi(this));
aboutThisSite.setInnerHTML(mapHelp.aboutThisSite());
aboutMe.setInnerHTML(mapHelp.aboutMe());
updatingSubmissions.setInnerHTML(mapHelp.updatingSubmissions());
removingSubmissions.setInnerHTML(mapHelp.removingSubmissions());
contactLink.setHref("javascript:;");
}
}
| 33.611111 | 90 | 0.787603 |
780ea21132c64d8a9c672d203f4ef4dce74595ce | 362 | package org.jfpc.base.utils;
import javax.inject.Named;
/**
* 页面提示信息
*
* @author Spook
* @since 0.1.0
* @version 0.1.0 2014/6/26
*/
@Named
public class MessageUtil {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String getLocalMessage(String message){
return "String";
}
}
| 12.482759 | 47 | 0.640884 |
fd667f0de2292115ec8b7e3d726bfc96a0d511fa | 1,382 | package ru.alazarev.seafight;
import org.junit.Before;
import ru.alazarev.seafight.interfaces.IShip;
import ru.alazarev.seafight.ships.Battleship;
/**
* Class решение задачи части
*
* @author Aleksey Lazarev
* @since 13.09.2019
*/
public class SeaFightTest {
SeaFight seaFight;
int size = 100;
IShip ship;
int[] pole;
@Before
public void setUp() {
this.seaFight = new SeaFight().init();
this.ship = new Battleship();
this.pole = new int[size];
for (int i = 0; i < size; i++) {
pole[i] = i;
}
}
// @Test
// public void whenPlaceHorizontalThenTrue() {
// int startPlace = 6;
// Assert.assertTrue(seaFight.placeHorizontal(ship, startPlace, pole));
// }
//
// @Test
// public void whenPlaceVerticalThenTrue() {
// int startPlace = 6;
// Assert.assertTrue(seaFight.placeVertical(ship, startPlace, pole));
// }
//
// @Test
// public void whenPlaceHorizontalThenFalse() {
// int startPlace = 6;
// this.pole[startPlace] = -2;
// Assert.assertFalse(seaFight.placeHorizontal(ship, startPlace, pole));
// }
//
// @Test
// public void whenPlaceVerticalThenFalse() {
// int startPlace = 6;
// this.pole[startPlace] = -3;
// Assert.assertFalse(seaFight.placeVertical(ship, startPlace, pole));
// }
} | 25.592593 | 79 | 0.60275 |
fcbc92a5ba824bb8efda117fb78e47f5fa1e74b3 | 1,555 | /*
* Copyright DataStax, Inc.
*
* 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.datastax.oss.dsbulk.executor.reactor.ccm;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.dsbulk.tests.driver.SerializedSession;
import com.datastax.oss.dsbulk.executor.api.ccm.BulkExecutorCCMITBase;
import com.datastax.oss.dsbulk.executor.reactor.DefaultReactorBulkExecutor;
import com.datastax.oss.dsbulk.tests.ccm.CCMCluster;
import com.datastax.oss.dsbulk.tests.driver.annotations.SessionConfig;
import org.junit.jupiter.api.Tag;
@Tag("medium")
class DefaultReactorBulkExecutorCCMIT extends BulkExecutorCCMITBase {
DefaultReactorBulkExecutorCCMIT(
CCMCluster ccm,
@SessionConfig(settings = "basic.request.page-size=10" /* to force pagination */)
CqlSession session) {
super(
ccm,
session,
DefaultReactorBulkExecutor.builder(new SerializedSession(session)).build(),
DefaultReactorBulkExecutor.builder(new SerializedSession(session)).failSafe().build());
}
}
| 38.875 | 95 | 0.762058 |
28cd570b8d357e2841e6a11e7bcfcecfebe34db1 | 1,118 | package com.scriptlang.compiler.ast;
/**
* @author Dmitry
*/
public class ForAst extends BaseAst {
private BaseAst initializationExpression;
private BaseAst conditionExpression;
private BaseAst incrementExpression;
private ExpressionListAst body;
public BaseAst getInitializationExpression() {
return initializationExpression;
}
public void setInitializationExpression(BaseAst initializationExpression) {
this.initializationExpression = initializationExpression;
}
public BaseAst getConditionExpression() {
return conditionExpression;
}
public void setConditionExpression(BaseAst conditionExpression) {
this.conditionExpression = conditionExpression;
}
public BaseAst getIncrementExpression() {
return incrementExpression;
}
public void setIncrementExpression(BaseAst incrementExpression) {
this.incrementExpression = incrementExpression;
}
public ExpressionListAst getBody() {
return body;
}
public void setBody(ExpressionListAst body) {
this.body = body;
}
}
| 24.304348 | 79 | 0.72093 |
a121112fc3c2881e15058ee19c7b8086a8b544c7 | 1,510 | package com.duonghv.shoppingcart.model.page;
import com.duonghv.shoppingcart.model.audit.TableAudit;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* Class: Page
* Author: DuongHV
* Created: 16/03/2019 00:54
*/
@Entity
@Table(name = "tblpage")
@Getter
@Setter
public class Page extends TableAudit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Size(max = 11)
@Column(name = "ID")
private Long id;
@NotBlank
@Size(max = 255)
@Column(name = "Name")
private String name;
@NotBlank
@Size(max = 255)
@Column(name = "Link")
private String link;
@NotNull
@Size(max = 255)
@Column(name = "classAttribute")
private String classAttribute;
@NotNull
@Size(max = 255)
@Column(name = "Parent")
private Long parent;
@Column(name = "HasChild")
private Byte hasChild;
@NotNull
@Size(max = 11)
@Column(name = "Number")
private Long number;
@Size(max = 4000)
@Column(name = "Detail")
private String detail;
@Column(name = "IsShow")
private Byte isShow;
@Column(name = "IsDeleted")
private Byte isDeleted;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Parent", referencedColumnName = "ID", insertable = false, updatable = false)
private Page page;
public Page() {
}
}
| 19.868421 | 100 | 0.656291 |
abe88894704c996e830ff347192e4994a55616d2 | 2,953 | /*
* Copyright © 2014 Stefan Niederhauser ([email protected])
*
* 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 guru.nidi.ramlproxy.jetty;
import guru.nidi.ramlproxy.core.MockServlet;
import guru.nidi.ramlproxy.core.RamlProxyServer;
import guru.nidi.ramlproxy.core.ServerOptions;
import guru.nidi.ramlproxy.core.TesterFilter;
import guru.nidi.ramlproxy.report.ReportSaver;
import guru.nidi.ramltester.RamlDefinition;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import javax.servlet.DispatcherType;
import java.util.EnumSet;
public class JettyRamlProxyServer extends RamlProxyServer {
private final Server server;
public JettyRamlProxyServer(ServerOptions options, ReportSaver saver, RamlDefinition definition) throws InterruptedException {
super(options, saver);
final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
final TesterFilter testerFilter = new TesterFilter(this, saver, definition);
final ServletHolder servlet;
if (options.isMockMode()) {
servlet = new ServletHolder(new MockServlet(options.getMockDir()));
context.addFilter(new FilterHolder(testerFilter), "/*", EnumSet.allOf(DispatcherType.class));
} else {
servlet = new ServletHolder(new JettyProxyServlet(testerFilter));
servlet.setInitParameter("proxyTo", options.getTargetUrl());
servlet.setInitParameter("viaHost", "localhost"); //avoid calling InetAddress.getLocalHost()
}
servlet.setInitOrder(1);
context.addServlet(servlet, "/*");
server = JettyServerProvider.getServer(options.getPort());
server.setHandler(context);
server.setStopAtShutdown(true);
doStart();
}
@Override
protected void start() throws Exception {
server.start();
}
@Override
public void waitForServer() throws InterruptedException {
server.join();
}
@Override
protected boolean stop() throws Exception {
if (server.isStopped() || server.isStopping()) {
return false;
}
server.stop();
return true;
}
@Override
public boolean isStopped() {
return server.isStopped();
}
}
| 36.45679 | 130 | 0.709448 |
0258cfc5efa5339ad7333fc04b438a27980dfa96 | 3,474 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.hudi.hive.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hudi.common.util.PartitionPathEncodeUtils;
import org.apache.hudi.common.util.ValidationUtils;
import org.apache.hudi.hive.HiveSyncConfig;
import org.apache.hudi.hive.HoodieHiveSyncException;
import org.apache.hudi.hive.PartitionValueExtractor;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
public class HivePartitionUtil {
private static final Logger LOG = LogManager.getLogger(HivePartitionUtil.class);
/**
* Build String, example as year=2021/month=06/day=25
*/
public static String getPartitionClauseForDrop(String partition, PartitionValueExtractor partitionValueExtractor, HiveSyncConfig config) {
List<String> partitionValues = partitionValueExtractor.extractPartitionValuesInPath(partition);
ValidationUtils.checkArgument(config.partitionFields.size() == partitionValues.size(),
"Partition key parts " + config.partitionFields + " does not match with partition values " + partitionValues
+ ". Check partition strategy. ");
List<String> partBuilder = new ArrayList<>();
for (int i = 0; i < config.partitionFields.size(); i++) {
String partitionValue = partitionValues.get(i);
// decode the partition before sync to hive to prevent multiple escapes of HIVE
if (config.decodePartition) {
// This is a decode operator for encode in KeyGenUtils#getRecordPartitionPath
partitionValue = PartitionPathEncodeUtils.unescapePathName(partitionValue);
}
partBuilder.add(config.partitionFields.get(i) + "=" + partitionValue);
}
return String.join("/", partBuilder);
}
public static Boolean partitionExists(IMetaStoreClient client, String tableName, String partitionPath,
PartitionValueExtractor partitionValueExtractor, HiveSyncConfig config) {
Partition newPartition;
try {
List<String> partitionValues = partitionValueExtractor.extractPartitionValuesInPath(partitionPath);
newPartition = client.getPartition(config.databaseName, tableName, partitionValues);
} catch (NoSuchObjectException ignored) {
newPartition = null;
} catch (TException e) {
LOG.error("Failed to get partition " + partitionPath, e);
throw new HoodieHiveSyncException("Failed to get partition " + partitionPath, e);
}
return newPartition != null;
}
}
| 46.945946 | 140 | 0.75072 |
575ac2d1ae79517b506b589dc37c6dc488a2d52a | 699 | package at.porscheinformatik.seleniumcomponents.driver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import at.porscheinformatik.seleniumcomponents.AbstractWebDriverFactory;
import at.porscheinformatik.seleniumcomponents.WebDriverFactory;
/**
* A {@link WebDriverFactory} for Chrome
*
* @author ham
*/
public class ChromeWebDriverFactory extends AbstractWebDriverFactory
{
@Override
public WebDriver createWebDriver(String sessionName)
{
return new ChromeDriver(createOptions());
}
protected ChromeOptions createOptions()
{
return new ChromeOptions();
}
}
| 24.103448 | 72 | 0.772532 |
364d8f7510e560fdef558df6523120c4fc751108 | 581 | /*
package acceptance.learning_patterns.factory3;
import org.testng.annotations.*;
public class Auth3 extends WebDriverSet {
@Test (enabled = false)
public void test() {
*/
/* AccountantRole3 accountantRole3 = PageFactory.initElements(driver, AccountantRole3.class);
AdminRole3 adminRole3 = PageFactory.initElements(driver, AdminRole3.class);*//*
UserFactory3 factory = new UserFactory3();
User3 admin = factory.getUser3(UserTypes3.ADMIN3);
User3 accountant = factory.getUser3(UserTypes3.ACCOUNTANT3);
admin.auth();
accountant.auth();
}
}
*/
| 23.24 | 96 | 0.731497 |
e46b7276bc99b80e7eee08009504762357677bf5 | 1,137 | package org.ovirt.engine.ui.webadmin.section.main.view.popup.vm;
import java.util.List;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.ApplicationMessages;
import org.ovirt.engine.ui.webadmin.gin.AssetProvider;
public final class HostDeviceColumnHelper {
private static final ApplicationConstants constants = AssetProvider.getConstants();
private static final ApplicationMessages messages = AssetProvider.getMessages();
public static String renderNameId(String name, String id) {
if (StringHelper.isNullOrEmpty(name)) {
return id;
}
// we assume that VDSM will never report name != null && id == null
return messages.nameId(name, id);
}
public static String renderVmNamesList(List<String> names) {
if (names != null) {
return String.join(", ", names); //$NON-NLS-1$
}
return "";
}
public static String renderIommuGroup(Integer group) {
return group == null ? constants.notAvailableLabel() : group.toString();
}
}
| 33.441176 | 87 | 0.694811 |
a39e76ac63aaebb04f64f6a459b7b277c9b8cdae | 11,680 | package com.alibaba.spring.boot.rsocket.broker.cluster;
import com.alibaba.rsocket.ServiceLocator;
import com.alibaba.rsocket.cloudevents.CloudEventImpl;
import com.alibaba.rsocket.cloudevents.Json;
import com.alibaba.rsocket.observability.RsocketErrorCode;
import com.alibaba.rsocket.route.RSocketFilter;
import com.alibaba.rsocket.transport.NetworkUtil;
import com.alibaba.spring.boot.rsocket.broker.RSocketBrokerProperties;
import com.alibaba.spring.boot.rsocket.broker.cluster.jsonrpc.JsonRpcRequest;
import com.alibaba.spring.boot.rsocket.broker.cluster.jsonrpc.JsonRpcResponse;
import com.alibaba.spring.boot.rsocket.broker.events.AppConfigEvent;
import com.alibaba.spring.boot.rsocket.broker.events.RSocketFilterEnableEvent;
import com.alibaba.spring.boot.rsocket.broker.services.ConfigurationService;
import io.micrometer.core.instrument.Metrics;
import io.scalecube.cluster.Cluster;
import io.scalecube.cluster.ClusterImpl;
import io.scalecube.cluster.ClusterMessageHandler;
import io.scalecube.cluster.Member;
import io.scalecube.cluster.membership.MembershipEvent;
import io.scalecube.cluster.transport.api.Message;
import io.scalecube.net.Address;
import io.scalecube.transport.netty.tcp.TcpTransportFactory;
import org.eclipse.collections.api.block.function.primitive.DoubleFunction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.server.GracefulShutdownCallback;
import org.springframework.boot.web.server.GracefulShutdownResult;
import org.springframework.boot.web.server.Shutdown;
import org.springframework.context.ApplicationContext;
import org.springframework.context.SmartLifecycle;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* RSocket Broker Manager Gossip implementation
*
* @author leijuan
*/
public class RSocketBrokerManagerGossipImpl implements RSocketBrokerManager, ClusterMessageHandler, SmartLifecycle {
private Logger log = LoggerFactory.getLogger(RSocketBrokerManagerGossipImpl.class);
/**
* Gossip listen port
*/
private static int gossipListenPort = 42254;
/**
* seed members
*/
@Value("${rsocket.broker.seeds}")
private String[] seeds;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private RSocketBrokerProperties brokerProperties;
@Autowired
private ServerProperties serverProperties;
private int status = 0;
private Mono<Cluster> monoCluster;
private RSocketBroker localBroker;
/**
* rsocket brokers, key is ip address
*/
private Map<String, RSocketBroker> brokers = new HashMap<>();
/**
* brokers changes emitter processor
*/
private Sinks.Many<Collection<RSocketBroker>> brokersEmitterProcessor = Sinks.many().multicast().onBackpressureBuffer();
private KetamaConsistentHash<String> consistentHash;
@Override
public Flux<Collection<RSocketBroker>> requestAll() {
return brokersEmitterProcessor.asFlux();
}
@Override
public Collection<RSocketBroker> currentBrokers() {
return this.brokers.values();
}
@Override
public RSocketBroker localBroker() {
return this.localBroker;
}
@Override
public Mono<RSocketBroker> findByIp(String ip) {
if (brokers.containsKey(ip)) {
return Mono.just(this.brokers.get(ip));
} else {
return Mono.empty();
}
}
@Override
public Flux<ServiceLocator> findServices(String ip) {
return Flux.empty();
}
@Override
public String getName() {
return "gossip";
}
@Override
public Boolean isStandAlone() {
return false;
}
public List<Address> seedMembers() {
return Stream.of(seeds)
.map(host -> Address.create(host, gossipListenPort))
.collect(Collectors.toList());
}
@Override
public void onMessage(Message message) {
if (message.header("jsonrpc") != null) {
JsonRpcRequest request = message.data();
Message replyMessage = Message.builder()
.correlationId(message.correlationId())
.data(onJsonRpcCall(request))
.build();
this.monoCluster.flatMap(cluster -> cluster.send(message.sender(), replyMessage)).subscribe();
}
}
public JsonRpcResponse onJsonRpcCall(JsonRpcRequest request) {
Object result;
if (request.getMethod().equals("BrokerService.getConfiguration")) {
Map<String, String> config = new HashMap<>();
config.put("rsocket.broker.externalDomain", brokerProperties.getExternalDomain());
result = config;
} else {
result = "";
}
return new JsonRpcResponse(request.getId(), result);
}
public Mono<JsonRpcResponse> makeJsonRpcCall(@NotNull Member member, @NotNull String methodName, @Nullable Object params) {
String uuid = UUID.randomUUID().toString();
Message jsonRpcMessage = Message.builder()
.correlationId(uuid)
.header("jsonrpc", "2.0")
.data(new JsonRpcRequest(methodName, params, uuid))
.build();
return monoCluster.flatMap(cluster -> cluster.requestResponse(member, jsonRpcMessage)).map(Message::data);
}
@Override
public void onGossip(Message gossip) {
if (gossip.header("cloudevents") != null) {
String javaClass = gossip.header("javaClass");
if (javaClass != null) {
try {
Class<?> resultClass = Class.forName(javaClass);
String jsonText = gossip.data();
onCloudEvent(Json.decodeValue(jsonText, resultClass));
} catch (Exception ignore) {
}
}
}
}
public void onCloudEvent(CloudEventImpl<?> cloudEvent) {
String type = cloudEvent.getAttributes().getType();
Optional<?> cloudEventData = cloudEvent.getData();
cloudEventData.ifPresent(data -> {
if (RSocketFilterEnableEvent.class.getCanonicalName().equals(type)) {
try {
RSocketFilterEnableEvent filterEnableEvent = (RSocketFilterEnableEvent) data;
RSocketFilter rsocketFilter = (RSocketFilter) applicationContext.getBean(Class.forName(filterEnableEvent.getFilterClassName()));
rsocketFilter.setEnabled(filterEnableEvent.isEnabled());
} catch (Exception ignore) {
}
} else if (data instanceof AppConfigEvent) {
AppConfigEvent appConfigEvent = (AppConfigEvent) data;
ConfigurationService configurationService = applicationContext.getBean(ConfigurationService.class);
configurationService.put(appConfigEvent.getAppName() + ":" + appConfigEvent.getKey(), appConfigEvent.getVale()).subscribe();
}
});
}
@Override
public Mono<String> broadcast(CloudEventImpl<?> cloudEvent) {
Message message = Message.builder()
.header("cloudevents", "true")
.header("javaClass", cloudEvent.getAttributes().getType())
.data(Json.serializeAsText(cloudEvent))
.build();
return monoCluster.flatMap(cluster -> cluster.spreadGossip(message));
}
@Override
public void onMembershipEvent(MembershipEvent event) {
RSocketBroker broker = memberToBroker(event.member());
String brokerIp = broker.getIp();
if (event.isAdded()) {
makeJsonRpcCall(event.member(), "BrokerService.getConfiguration", null).subscribe(response -> {
brokers.put(brokerIp, broker);
this.consistentHash.add(brokerIp);
Map<String, String> brokerConfiguration = response.getResult();
if (brokerConfiguration != null && !brokerConfiguration.isEmpty()) {
String externalDomain = brokerConfiguration.get("rsocket.broker.externalDomain");
broker.setExternalDomain(externalDomain);
}
log.info(RsocketErrorCode.message("RST-300001", broker.getIp(), "added"));
});
} else if (event.isRemoved()) {
brokers.remove(brokerIp);
this.consistentHash.remove(brokerIp);
log.info(RsocketErrorCode.message("RST-300001", broker.getIp(), "removed"));
} else if (event.isLeaving()) {
brokers.remove(brokerIp);
this.consistentHash.remove(brokerIp);
log.info(RsocketErrorCode.message("RST-300001", broker.getIp(), "left"));
}
brokersEmitterProcessor.tryEmitNext(brokers.values());
}
private RSocketBroker memberToBroker(Member member) {
RSocketBroker broker = new RSocketBroker();
broker.setIp(member.address().host());
return broker;
}
@Override
public void stopLocalBroker() {
this.monoCluster.subscribe(Cluster::shutdown);
}
@Override
public RSocketBroker findConsistentBroker(String clientId) {
String brokerIp = this.consistentHash.get(clientId);
return this.brokers.get(brokerIp);
}
@Override
public void start() {
final String localIp = NetworkUtil.LOCAL_IP;
monoCluster = new ClusterImpl()
.config(clusterConfig -> clusterConfig.externalHost(localIp).externalPort(gossipListenPort))
.membership(membershipConfig -> membershipConfig.seedMembers(seedMembers()).syncInterval(5_000))
.transportFactory(TcpTransportFactory::new)
.transport(transportConfig -> transportConfig.port(gossipListenPort))
.handler(cluster1 -> this)
.start();
//subscribe and start & join the cluster
monoCluster.subscribe();
this.localBroker = new RSocketBroker(localIp, brokerProperties.getExternalDomain());
this.consistentHash = new KetamaConsistentHash<>(12, Collections.singletonList(localIp));
brokers.put(localIp, localBroker);
log.info(RsocketErrorCode.message("RST-300002"));
Metrics.globalRegistry.gauge("cluster.broker.count", this, (DoubleFunction<RSocketBrokerManagerGossipImpl>) brokerManagerGossip -> brokerManagerGossip.brokers.size());
this.status = 1;
}
@Override
public void stop() {
throw new UnsupportedOperationException("Stop must not be invoked directly");
}
@Override
public void stop(final @NotNull Runnable callback) {
this.status = -1;
shutDownGracefully((result) -> callback.run());
}
@Override
public boolean isRunning() {
return status == 1;
}
void shutDownGracefully(GracefulShutdownCallback callback) {
try {
this.stopLocalBroker();
if (serverProperties.getShutdown() == Shutdown.GRACEFUL) {
// waiting for 15 seconds to broadcast shutdown message
Thread.sleep(15000);
}
} catch (Exception ignore) {
} finally {
callback.shutdownComplete(GracefulShutdownResult.IMMEDIATE);
}
}
}
| 38.933333 | 175 | 0.665925 |
9985049672048eaa0a25ca33b7d133bc1042b3fb | 1,457 | package fi.csc.chipster.servicelocator.resource;
import java.util.ArrayList;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.SecurityContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import fi.csc.chipster.auth.model.Role;
@Path(ServiceResource.PATH_SERVICES)
public class ServiceResource {
public static final String PATH_SERVICES = "services";
public static final String PATH_INTERNAL = "internal";
@SuppressWarnings("unused")
private static Logger logger = LogManager.getLogger();
private ArrayList<Service> publicServices;
private ArrayList<Service> allServices;
public ServiceResource(ArrayList<Service> publicServices, ArrayList<Service> allServices) {
this.publicServices = publicServices;
this.allServices = allServices;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(Role.UNAUTHENTICATED)
public Response getPublic(@Context SecurityContext sc) {
return Response.ok(publicServices).build();
}
@GET
@Path(PATH_INTERNAL)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({Role.ADMIN, Role.SERVER, Role.SINGLE_SHOT_COMP})
public Response getAll(@Context SecurityContext sc) {
return Response.ok(allServices).build();
}
}
| 28.568627 | 92 | 0.787234 |
cbed640957c7bcbc537527fff9393106751b81ab | 239 | package com.hokumus.schoolmanagement.dao.management;
import com.hokumus.schoolmanagement.dao.util.DBServices;
import com.hokumus.schoolmanagement.model.management.Courses;
public class CoursesDao extends DBServices<Courses> {
}
| 26.555556 | 62 | 0.811715 |
2dc07c1c06387462f93ff8693c33ba5245854075 | 1,929 | package com.ppmessage.ppcomlib;
import com.ppmessage.ppcomlib.services.PPComStartupHelper;
import com.ppmessage.ppcomlib.services.message.IMessageService;
import com.ppmessage.ppcomlib.services.message.MessageService;
import com.ppmessage.sdk.core.L;
/**
* Example:
*
* <pre>
* PPComSDK sdk = PPComSDK.getInstance();
* sdk.init(new PPComSDKConfiguration.Builder().setAppUUID("YOUR_APP_UUID").build());
*
* sdk.getStartupHelper().startUp(new PPComStartupHelper.OnStartCallback() {
* @Override
* public void onSuccess() {
*
* }
* @Override
* public void onError(PPComSDKException exception) {
*
* }
* });
* </pre>
*
* Created by ppmessage on 5/13/16.
*/
public class PPComSDK {
private static final String CONFIG_ERROR_LOG = "[PPComSDK] can not be initialized with empty config";
private static final String VERSION = "0.0.1";
private static final PPComSDK ourInstance = new PPComSDK();
private PPComSDKConfiguration configuration;
private PPComStartupHelper startupHelper;
private IMessageService messageService;
public static PPComSDK getInstance() {
return ourInstance;
}
public synchronized void init(PPComSDKConfiguration config) {
if (config == null) throw new PPComSDKException(CONFIG_ERROR_LOG);
this.configuration = config;
}
public PPComSDKConfiguration getConfiguration() {
return configuration;
}
public String getVersion() {
return VERSION;
}
public PPComStartupHelper getStartupHelper() {
if (startupHelper == null) {
startupHelper = new PPComStartupHelper(this);
}
return startupHelper;
}
public IMessageService getMessageService() {
if (messageService == null) {
messageService = new MessageService(this);
}
return messageService;
}
}
| 26.791667 | 105 | 0.669259 |
42b09324a6e93bb5674c5df885e7dbe18402f77b | 2,845 | package com.tencent.liteav.meeting.ui.widget.base;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.tencent.liteav.demo.trtc.R;
import java.util.ArrayList;
import java.util.List;
/**
* 带tab的用户设置页基类
* {@link BaseTabSettingFragmentDialog#getTitleList()} 和 {@link BaseTabSettingFragmentDialog#getFragments()}
* 这两个返回的顺序在界面中是一一对应的,比如title list是 {"视频","音频"} 那fragment 应该是 {videofragment, audiofragment}
* @author guanyifeng
*/
public abstract class BaseTabSettingFragmentDialog extends BaseSettingFragmentDialog {
private TabLayout mTopTl;
private ViewPager mContentVp;
private List<Fragment> mFragmentList;
private List<String> mTitleList;
private PagerAdapter mPagerAdapter;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initView(view);
initData();
}
private void initData() {
mFragmentList = getFragments();
mTitleList = getTitleList();
if (mFragmentList == null) {
mFragmentList = new ArrayList<>();
}
mTopTl.setupWithViewPager(mContentVp, false);
mPagerAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
@Override
public Fragment getItem(int position) {
return mFragmentList == null ? null : mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList == null ? 0 : mFragmentList.size();
}
};
mContentVp.setAdapter(mPagerAdapter);
for (int i = 0; i < mTitleList.size(); i++) {
TabLayout.Tab tab = mTopTl.getTabAt(i);
if (tab != null) {
tab.setText(mTitleList.get(i));
}
}
}
public void addFragment(Fragment fragment) {
if (mFragmentList == null) {
return;
}
mFragmentList.add(fragment);
}
@Override
protected int getLayoutId() {
return R.layout.meeting_fragment_base_tab_setting;
}
private void initView(@NonNull final View itemView) {
mTopTl = (TabLayout) itemView.findViewById(R.id.tl_top);
mContentVp = (ViewPager) itemView.findViewById(R.id.vp_content);
}
/**
* @return 这里返回对应的fragment
*/
protected abstract List<Fragment> getFragments();
/**
* @return 这里返回对应的标题列表
*/
protected abstract List<String> getTitleList();
}
| 30.265957 | 108 | 0.655888 |
cf793af9c4628de2820b98e23bd3f266571adcd1 | 4,114 | /*
* Copyright 2019 Jérôme Wacongne.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.c4_soft.springaddons.security.oauth2.test.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.mockito.Mock;
import org.springframework.core.annotation.AliasFor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.TestExecutionEvent;
import org.springframework.security.test.context.support.WithSecurityContext;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
import org.springframework.test.context.TestContext;
import com.c4_soft.springaddons.security.oauth2.test.MockAuthenticationBuilder;
/**
* <p>
* Populates {@link SecurityContext} with an {@link Authentication} {@link Mock}.
* </p>
* Sample usage:
*
* <pre>
* @Test
* @WithMockAuthentication
* public demoDefaultUserNameAndAuthorities {
* // test as "user" granted with "ROLE_USER"
* }
*
* @Test
* @WithMockAuthentication(name = "Ch4mpy", authorities = { "ROLE_TESTER", "ROLE_AUTHOR" })
* public demoCustomUserNameAndAuthorities {
* // test as "Ch4mpy" granted with "ROLE_TESTER", "ROLE_AUTHOR"
* }
*
* @Test
* @WithMockAuthentication(JwtAuthenticationToken.class)
* public demoCustomAuthenticationImpl {
* final var jwt = mock(Jwt.class);
* when(jwt.getSubject()).thenReturn(auth.getName());
*
* final var auth = (JwtAuthenticationToken) SecurityContextHolder.getContext();
* when(auth.getPrincipal()).thenReturn(jwt);
*
* // test as "user" granted with "ROLE_USER", the Authentication in the SecurityContext being a JwtAuthenticationToken mock
* }
* </pre>
*
* @author Jérôme Wacongne <ch4mp@c4-soft.com>
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory = WithMockAuthentication.Factory.class)
public @interface WithMockAuthentication {
@AliasFor("authType")
Class<? extends Authentication> value() default Authentication.class;
@AliasFor("value")
Class<? extends Authentication> authType() default Authentication.class;
String name() default "user";
String[] authorities() default { "ROLE_USER" };
/**
* Determines when the {@link SecurityContext} is setup. The default is before {@link TestExecutionEvent#TEST_METHOD} which occurs during
* {@link org.springframework.test.context.TestExecutionListener#beforeTestMethod(TestContext)}
*
* @return the {@link TestExecutionEvent} to initialize before
*/
@AliasFor(annotation = WithSecurityContext.class)
TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD;
public static final class Factory implements WithSecurityContextFactory<WithMockAuthentication> {
@Override
public SecurityContext createSecurityContext(WithMockAuthentication annotation) {
final SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication(annotation));
return context;
}
public Authentication authentication(WithMockAuthentication annotation) {
return new MockAuthenticationBuilder<>(annotation.authType()).name(annotation.name()).authorities(annotation.authorities()).build();
}
}
}
| 38.092593 | 139 | 0.777589 |
002e75eb65c2a9042dbb3a71ddc78586776a8750 | 1,622 | package io.subutai.core.registration.cli;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import io.subutai.core.identity.rbac.cli.SubutaiShellCommandSupport;
import io.subutai.core.registration.api.HostRegistrationManager;
import io.subutai.core.registration.api.exception.HostRegistrationException;
@Command( scope = "host", name = "verify", description = "Verifies container token" )
public class VerifyContainerToken extends SubutaiShellCommandSupport
{
@Argument( index = 0, name = "token", multiValued = false, required = true, description = "Token" )
private String token;
@Argument( index = 1, name = "token", multiValued = false, required = true, description = "Token" )
private String containerHostId;
@Argument( index = 2, name = "publicKey", multiValued = false, required = true, description = "Container public "
+ "key" )
private String publicKey;
private HostRegistrationManager registrationManager;
public VerifyContainerToken( final HostRegistrationManager registrationManager )
{
this.registrationManager = registrationManager;
}
@Override
protected Object doExecute() throws Exception
{
try
{
boolean valid = registrationManager.verifyTokenAndRegisterKey( token, containerHostId, publicKey );
System.out.println( String.format( "Token valid = %s", valid ) );
}
catch ( HostRegistrationException ex )
{
System.out.println( "Token verification failed." );
}
return null;
}
}
| 33.102041 | 117 | 0.699137 |
1062caeda72b9692f7b52e3374487c7db4defc7d | 2,163 | /*
* Copyright (C) 2008 feilong
*
* 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.
*/
/**
* 自定义{@link org.apache.commons.collections4.Predicate}.
*
* @author <a href="https://github.com/ifeilong/feilong">feilong</a>
*
* @see com.feilong.lib.collection4.PredicateUtils
*
* @see com.feilong.lib.collection4.functors.AllPredicate
* @see com.feilong.lib.collection4.functors.AndPredicate
* @see com.feilong.lib.collection4.functors.AnyPredicate
*
* @see com.feilong.lib.collection4.functors.ComparatorPredicate
* @see com.feilong.lib.collection4.functors.EqualPredicate
* @see com.feilong.lib.collection4.functors.ExceptionPredicate
* @see com.feilong.lib.collection4.functors.FalsePredicate
* @see com.feilong.lib.collection4.functors.IdentityPredicate
* @see com.feilong.lib.collection4.functors.InstanceofPredicate
*
* @see com.feilong.lib.collection4.functors.NonePredicate
* @see com.feilong.lib.collection4.functors.NotNullPredicate
* @see com.feilong.lib.collection4.functors.NotPredicate
*
* @see com.feilong.lib.collection4.functors.NullPredicate
* @see com.feilong.lib.collection4.functors.NullIsExceptionPredicate
* @see com.feilong.lib.collection4.functors.NullIsFalsePredicate
* @see com.feilong.lib.collection4.functors.NullIsTruePredicate
*
* @see com.feilong.lib.collection4.functors.OnePredicate
* @see com.feilong.lib.collection4.functors.OrPredicate
* @see com.feilong.lib.collection4.functors.TransformedPredicate
* @see com.feilong.lib.collection4.functors.TruePredicate
* @see com.feilong.lib.collection4.functors.UniquePredicate
*
* @since 1.2.0
*/
package com.feilong.core.util.predicate; | 42.411765 | 75 | 0.773 |
814b38a18851cbc9de63b70fd607f4a2f04585df | 530 | package com.espressif.iot.command.group;
public interface IEspCommandGroupMoveDeviceInternet extends IEspCommandGroup
{
public static final String URL_MOVE_DEVICE = URL_COMMON + "?action=move_to_group&method=PUT";
/**
* Move device into group
*
* @param userKey
* @param deviceId
* @param groupId
* @param reservePreGroup
* @return success or failed
*/
boolean doCommandMoveDeviceIntoGroupInternet(String userKey, long deviceId, long groupId, boolean reservePreGroup);
}
| 29.444444 | 119 | 0.716981 |
605afdad0d4edb944407a3f989045671c37655de | 2,196 | package org.nodes.models.old;
import static java.lang.Math.exp;
import static nl.peterbloem.kit.Series.series;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.linear.ArrayRealVector;
import org.apache.commons.math3.linear.RealVector;
import org.nodes.DGraph;
import org.nodes.DNode;
/**
* This class computes bounds for the number of directed graphs (self loops
* allowed) with given in and out sequences.
*
* @author Peter
*
*/
public class BarvinokDSimple extends AbstractBarvinok
{
public BarvinokDSimple(
List<Integer> inSequence,
List<Integer> outSequence,
int memory)
{
super(inSequence, outSequence, memory);
search();
}
public BarvinokDSimple(
DGraph<?> graph,
int memory)
{
super(seq(graph, true), seq(graph, false), memory);
search();
}
private static List<Integer> seq(DGraph<?> graph, boolean in)
{
List<Integer> sequence = new ArrayList<Integer>(graph.size());
for(DNode<?> node : graph.nodes())
sequence.add(in ? node.inDegree() : node.outDegree());
return sequence;
}
@Override
public double value(RealVector x)
{
double value = 0.0;
double[] xa = ((ArrayRealVector)x).getDataRef();// nasty trick.
int nn = 2 * n;
for(int i = 0; i < n; i++)
for(int j = n; j < nn; j++)
if(i != j)
value += Math.log1p( exp(xa[i] + xa[j]));
for(int i = 0; i < n; i++)
value -= x.getEntry(s(i)) * inSequence.get(i);
for(int j= 0; j < n; j++)
value -= x.getEntry(t(j)) * outSequence.get(j);
return value;
}
@Override
public RealVector gradient(RealVector x)
{
RealVector gradient = new ArrayRealVector(2 * n);
for(int i : series(n))
{
double sum = 0.0;
for(int j : series(n))
if(i != j) {
double part = exp(x.getEntry(t(j)) + x.getEntry(s(i)));
sum += part / (1 + part);
}
gradient.setEntry(s(i), sum - inSequence.get(i));
}
for(int j : series(n))
{
double sum = 0.0;
for(int i : series(n))
if(i != j) {
double part = exp(x.getEntry(t(j)) + x.getEntry(s(i)));
sum += part / (1 + part);
}
gradient.setEntry(t(j), sum - outSequence.get(j) );
}
return gradient;
}
}
| 21.115385 | 76 | 0.62204 |
c0669a3011ff045bb59988a0aede0549784174f5 | 236 | package io.zedw.model;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* @author xingguan.wzt
* @date 2020/12/03
*/
public abstract class BaseMessage implements Serializable {
private LocalDateTime dateTime;
}
| 18.153846 | 59 | 0.754237 |
71993706a02e38b2f9e33f7a1e4b846308e4aae5 | 1,829 | package org.dkf.jmule.adapters.menu;
import android.content.Context;
import org.dkf.jed2k.android.ConfigurationManager;
import org.dkf.jed2k.android.Constants;
import org.dkf.jed2k.protocol.server.ServerMet;
import org.dkf.jmule.Engine;
import org.dkf.jmule.R;
import org.dkf.jmule.util.ServerUtils;
import org.dkf.jmule.views.MenuAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
/**
* Created by ap197_000 on 13.09.2016.
*/
public class ServerRemoveAction extends MenuAction {
private final Logger log = LoggerFactory.getLogger(ServerRemoveAction.class);
private final String serverId;
public ServerRemoveAction(Context context, final String host, final String serverId) {
super(context, R.drawable.ic_delete_forever_black_24dp, R.string.server_remove_action, host);
this.serverId = serverId;
}
@Override
protected void onClick(Context context) {
ServerMet sm = new ServerMet();
ConfigurationManager.instance().getSerializable(Constants.PREF_KEY_SERVERS_LIST, sm);
if (sm != null) {
Engine.instance().disconnectFrom(); // try to disconnect in any case
Iterator<ServerMet.ServerMetEntry> iter = sm.getServers().iterator();
while(iter.hasNext()) {
ServerMet.ServerMetEntry entry = iter.next();
if (ServerUtils.getIdentifier(entry).compareTo(serverId) == 0) {
log.info("remove key {}", ServerUtils.getIdentifier(entry));
iter.remove();
ConfigurationManager.instance().setSerializable(Constants.PREF_KEY_SERVERS_LIST, sm);
break;
}
}
}
else {
log.warn("Server list is empty in configurations");
}
}
}
| 35.862745 | 105 | 0.667578 |
e9cb578ad60c6a5353f3f2df27bac064b9ca49b4 | 258 | package jiwoo.openstack.keystone.auth.system;
import org.json.JSONObject;
import jiwoo.openstack.rest.RestResponse;
abstract public class AbstractAuthSystemResponse extends RestResponse {
abstract protected JSONObject getAuthSystem(String response);
}
| 21.5 | 71 | 0.837209 |
83b57e4bb48da8a77da96dbd0feab17e4dd04b5e | 1,962 | package org.ovirt.engine.ui.userportal.widget.tab;
import org.ovirt.engine.ui.common.widget.tab.AbstractTabPanel;
import org.ovirt.engine.ui.common.widget.tab.TabDefinition;
import org.ovirt.engine.ui.common.widget.tab.TabFactory;
import org.ovirt.engine.ui.common.widget.tab.TabWidgetHandler;
import org.ovirt.engine.ui.userportal.gin.ClientGinjectorProvider;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.TabData;
public class SimpleTabPanel extends AbstractTabPanel implements HasUiHandlers<TabWidgetHandler> {
interface WidgetUiBinder extends UiBinder<Widget, SimpleTabPanel> {
WidgetUiBinder uiBinder = GWT.create(WidgetUiBinder.class);
}
@UiField
FlowPanel tabContainer;
TabWidgetHandler uiHandlers;
public SimpleTabPanel() {
initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this));
}
public void setTabBar(IsWidget widget) {
tabContainer.clear();
if (widget != null) {
tabContainer.add(widget);
}
}
@Override
protected TabDefinition createNewTab(TabData tabData) {
return TabFactory.createTab(tabData, this, ClientGinjectorProvider.getEventBus());
}
@Override
public void setUiHandlers(TabWidgetHandler uiHandlers) {
this.uiHandlers = uiHandlers;
}
@Override
public void addTabWidget(IsWidget tabWidget, int index) {
if (uiHandlers != null) {
uiHandlers.addTabWidget(tabWidget, index);
}
}
@Override
public void removeTabWidget(IsWidget tabWidget) {
if (uiHandlers != null) {
uiHandlers.removeTabWidget(tabWidget);
}
}
}
| 30.184615 | 97 | 0.724261 |
222e5a11f34c676775fc0a53d3fe1a1126a2160c | 1,684 | package com.artist.web.bookstore.database;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;
@Entity(tableName = "books")
public class FavBooks {
@PrimaryKey
@NonNull
private int id;
private String title;
private String isbn;
private Integer mPrice;
@ColumnInfo(name="currency_code")
private String mCurrencyCode;
private String author;
public FavBooks(@NonNull int id, String title, String isbn, Integer price,
String currencyCode, String author) {
this.id = id;
this.title = title;
this.isbn = isbn;
mPrice = price;
mCurrencyCode = currencyCode;
this.author = author;
}
@NonNull
public int getId() {
return id;
}
public void setId(@NonNull int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Integer getPrice() {
return mPrice;
}
public void setPrice(Integer price) {
mPrice = price;
}
public String getCurrencyCode() {
return mCurrencyCode;
}
public void setCurrencyCode(String currencyCode) {
mCurrencyCode = currencyCode;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
| 19.811765 | 78 | 0.616983 |
d12f165cb504555312ace5d8112edc915f8b9052 | 1,410 | package org.datasand.model;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by saichler on 6/6/16.
*/
public class ObjectImpl implements InvocationHandler{
private final Map<String,Object> data = new HashMap<String, Object>();
private final Class<? extends IObject> oType;
public ObjectImpl(Class<? extends IObject> oType){
this.oType = oType;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.getName().startsWith("set")){
data.put(method.getName().substring(3),args[0]);
}else
if(method.getName().startsWith("get")){
return data.get(method.getName().substring(3));
}else
if(method.getName().startsWith("is")){
return data.get(method.getName().substring(2));
}else
if(method.getName().startsWith("add")){
List lst = (List)data.get(method.getName().substring(3));
if(lst==null){
}
lst.add(args[0]);
}else
if(method.getName().startsWith("del")){
List lst = (List)data.get(method.getName().substring(3));
if(lst==null){
return null;
}
lst.remove(args[0]);
}
return null;
}
}
| 28.77551 | 87 | 0.589362 |
395445bd645a639b67c8f220e94dc6af8c733bce | 2,887 | /*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
import java.util.ListResourceBundle;
public class ResourceBundleTest_zh_TW extends ListResourceBundle {
public Object[][] getContents(){
return contents;
}
static final Object[][] contents = {
{"locale","\u5730\u533A"},
{"timezone","\u65F6\u533A"},
{"date","\u65E5\u671F"},
{"number","\u6570\u5B57"},
{"currency","\u8D27\u5E01"},
{"percent","\u767E\u5206\u6BD4"},
{"FullFormat","y\u5E74M\u6708d\u65E5 EEEE ah:mm:ss [zzzz]"},
{"LongFormat","y\u5E74M\u6708d\u65E5 ah:mm:ss [z]"},
{"MediumFormat","y\u5E74M\u6708d\u65E5 ah:mm:ss"},
{"ShortFormat","y/M/d ah:mm"},
/* for E,EE,EEE */
{"Day1","\u661F\u671F\u65E5"},
{"Day2","\u661F\u671F\u4E00"},
{"Day3","\u661F\u671F\u4E8C"},
{"Day4","\u661F\u671F\u4E09"},
{"Day5","\u661F\u671F\u56DB"},
{"Day6","\u661F\u671F\u4E94"},
{"Day7","\u661F\u671F\u516D"},
/* for EEEE */
{"Day1F","\u661F\u671F\u65E5"},
{"Day2F","\u661F\u671F\u4E00"},
{"Day3F","\u661F\u671F\u4E8C"},
{"Day4F","\u661F\u671F\u4E09"},
{"Day5F","\u661F\u671F\u56DB"},
{"Day6F","\u661F\u671F\u4E94"},
{"Day7F","\u661F\u671F\u516D"},
/* for MMM */
{"Month1","\u0031\u6708"},
{"Month2","\u0032\u6708"},
{"Month3","\u0033\u6708"},
{"Month4","\u0034\u6708"},
{"Month5","\u0035\u6708"},
{"Month6","\u0036\u6708"},
{"Month7","\u0037\u6708"},
{"Month8","\u0038\u6708"},
{"Month9","\u0039\u6708"},
{"Month10","\u0031\u0030\u6708"},
{"Month11","\u0031\u0031\u6708"},
{"Month12","\u0031\u0032\u6708"},
/* for MMMM */
{"Month1F","\u0031\u6708"},
{"Month2F","\u0032\u6708"},
{"Month3F","\u0033\u6708"},
{"Month4F","\u0034\u6708"},
{"Month5F","\u0035\u6708"},
{"Month6F","\u0036\u6708"},
{"Month7F","\u0037\u6708"},
{"Month8F","\u0038\u6708"},
{"Month9F","\u0039\u6708"},
{"Month10F","\u0031\u0030\u6708"},
{"Month11F","\u0031\u0031\u6708"},
{"Month12F","\u0031\u0032\u6708"},
/* for a */
{"AM","\u4E0A\u5348"},
{"PM","\u4E0B\u5348"},
};
}
| 36.544304 | 80 | 0.543124 |
d89aed219325ce56b696e22fbb3e57126c3277a7 | 2,630 | package cn.cuilan.ssmp.admin.security.handler;
import cn.cuilan.ssmp.Constants;
import cn.cuilan.ssmp.entity.SysUser;
import cn.cuilan.ssmp.mapper.SysUserMapper;
import cn.cuilan.ssmp.redis.RedisUtils;
import cn.cuilan.ssmp.redis.SysUserRedisPrefix;
import cn.cuilan.ssmp.utils.NetworkUtils;
import cn.cuilan.ssmp.utils.UuidUtils;
import cn.cuilan.ssmp.utils.result.Result;
import cn.cuilan.ssmp.utils.result.ResultUtil;
import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 登录成功后的处理
*/
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Value("${spring.profiles.active}")
private String profile;
@Resource
private SysUserMapper sysUserMapper;
@Resource
private RedisUtils redisUtils;
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) {
String ipAddress = NetworkUtils.getIpAddress(request);
SysUser sysUser = (SysUser) authentication.getPrincipal();
String token;
if ("prod".equals(profile)) {
token = UuidUtils.createUuid();
redisUtils.saveString(SysUserRedisPrefix.TOKEN, token, String.valueOf(sysUser.getId()));
// 写入cookie
ServletUtil.addCookie(response, new Cookie(Constants.ADMIN_COOKIE_NAME, token));
} else {
token = String.valueOf(sysUser.getId());
// 写入cookie
ServletUtil.addCookie(response, new Cookie(Constants.TEST_ADMIN_COOKIE_NAME, token));
}
SysUser dbSysUser = sysUserMapper.selectById(sysUser.getId());
dbSysUser.setRoles(sysUser.getRoles());
dbSysUser.setPermissions(sysUser.getPermissions());
dbSysUser.setMenus(sysUser.getMenus());
dbSysUser.setLastLoginIp(ipAddress);
dbSysUser.setLastLoginTime(System.currentTimeMillis());
sysUserMapper.updateById(dbSysUser);
log.info("管理员 [{}] 登录系统, IP: [{}]", sysUser.getUsername(), ipAddress);
ResultUtil.responseJson(response, Result.success("登录成功", dbSysUser));
}
}
| 37.042254 | 100 | 0.71711 |
4d92762da4bf3745f38c976f865a18e8456766c8 | 1,575 | //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-gwt' project.
// Copyright 2016 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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 de.esoco.gwt.client.res;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
/********************************************************************
* The resource bundle for the GWT framework.
*
* @author eso
*/
public interface EsocoGwtResources extends ClientBundle
{
//~ Static fields/initializers ---------------------------------------------
/** The singleton instance of this class. */
public static final EsocoGwtResources INSTANCE =
GWT.create(EsocoGwtResources.class);
//~ Methods ----------------------------------------------------------------
/***************************************
* CSS
*
* @return CSS
*/
@Source("esoco-gwt.css")
EsocoGwtCss css();
}
| 34.23913 | 78 | 0.559365 |
1a3676474774024095c80c4d11484fd427188cc7 | 6,035 | /*
* Copyright 2017-2019 Baidu Inc.
*
* 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.baidu.openrasp.hook.sql;
import com.baidu.openrasp.tool.annotation.HookAnnotation;
import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.NotFoundException;
import java.io.IOException;
/**
* Created by tyy on 18-4-28.
*
* sql Prepare 查询 hook 点
*/
@HookAnnotation
public class SQLPreparedStatementHook extends AbstractSqlHook {
private String className;
@Override
public boolean isClassMatched(String className) {
/* MySQL */
if ("com/mysql/jdbc/PreparedStatement".equals(className)
|| "com/mysql/cj/jdbc/PreparedStatement".equals(className)) {
this.type = SQL_TYPE_MYSQL;
this.exceptions = new String[]{"java/sql/SQLException"};
return true;
}
/* SQLite */
if ("org/sqlite/PrepStmt".equals(className)
|| "org/sqlite/jdbc3/JDBC3PreparedStatement".equals(className)) {
this.type = SQL_TYPE_SQLITE;
this.exceptions = new String[]{"java/sql/SQLException"};
return true;
}
/* Oracle */
if ("oracle/jdbc/driver/OraclePreparedStatement".equals(className)) {
this.type = SQL_TYPE_ORACLE;
this.exceptions = new String[]{"java/sql/SQLException"};
return true;
}
/* SQL Server */
if ("com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement".equals(className)) {
this.type = SQL_TYPE_SQLSERVER;
this.exceptions = new String[]{"com/microsoft/sqlserver/jdbc/SQLServerException"};
return true;
}
/* PostgreSQL */
if ("org/postgresql/jdbc/PgPreparedStatement".equals(className)
|| "org/postgresql/jdbc1/AbstractJdbc1Statement".equals(className)
|| "org/postgresql/jdbc2/AbstractJdbc2Statement".equals(className)
|| "org/postgresql/jdbc3/AbstractJdbc3Statement".equals(className)
|| "org/postgresql/jdbc3g/AbstractJdbc3gStatement".equals(className)
|| "org/postgresql/jdbc4/AbstractJdbc4Statement".equals(className)) {
this.className = className;
this.type = SQL_TYPE_PGSQL;
this.exceptions = new String[]{"java/sql/SQLException"};
return true;
}
/* DB2 */
if ("com/ibm/db2/jcc/am/Connection".equals(className)) {
this.type = SQL_TYPE_DB2;
this.exceptions = new String[]{"java/sql/SQLException"};
return true;
}
return false;
}
/**
* (none-javadoc)
*
* @see com.baidu.openrasp.hook.AbstractClassHook#getType()
*/
@Override
public String getType() {
return "sqlPrepared";
}
/**
* (none-javadoc)
*
* @see com.baidu.openrasp.hook.AbstractClassHook#hookMethod(CtClass)
*/
@Override
protected void hookMethod(CtClass ctClass) throws IOException, CannotCompileException, NotFoundException {
hookSqlPreparedStatementMethod(ctClass);
}
private void hookSqlPreparedStatementMethod(CtClass ctClass) throws NotFoundException, CannotCompileException {
String originalSqlCode = null;
String checkSqlSrc = null;
if (SQL_TYPE_MYSQL.equals(this.type)) {
originalSqlCode = "originalSql";
} else if (SQL_TYPE_SQLITE.equals(this.type)) {
originalSqlCode = "this.sql";
} else if (SQL_TYPE_SQLSERVER.equals(this.type)) {
originalSqlCode = "preparedSQL";
} else if (SQL_TYPE_PGSQL.equals(this.type)) {
if ("org/postgresql/jdbc/PgPreparedStatement".equals(className)) {
originalSqlCode = "preparedQuery.query.toString(preparedQuery.query.createParameterList())";
} else {
originalSqlCode = "preparedQuery.toString(preparedQuery.createParameterList())";
}
} else if (SQL_TYPE_ORACLE.equals(this.type)) {
originalSqlCode = "this.sqlObject.getOriginalSql()";
}
if (originalSqlCode != null) {
checkSqlSrc = getInvokeStaticSrc(SQLStatementHook.class, "checkSQL",
"\"" + type + "\"" + ",$0," + originalSqlCode, String.class, Object.class, String.class);
insertBefore(ctClass, "execute", "()Z", checkSqlSrc);
insertBefore(ctClass, "executeUpdate", "()I", checkSqlSrc);
insertBefore(ctClass, "executeQuery", "()Ljava/sql/ResultSet;", checkSqlSrc);
try {
insertBefore(ctClass, "executeBatch", "()[I", checkSqlSrc);
} catch (CannotCompileException e) {
insertBefore(ctClass, "executeBatchInternal", null, checkSqlSrc);
}
addCatch(ctClass, "execute", null);
addCatch(ctClass, "executeUpdate", null);
addCatch(ctClass, "executeQuery", null);
try {
addCatch(ctClass, "executeBatch", null);
} catch (CannotCompileException e) {
addCatch(ctClass, "executeBatchInternal", null);
}
} else if (SQL_TYPE_DB2.equals(this.type)) {
checkSqlSrc = getInvokeStaticSrc(SQLStatementHook.class, "checkSQL",
"\"" + type + "\"" + ",$0,$1", String.class, Object.class, String.class);
insertBefore(ctClass, "prepareStatement", null, checkSqlSrc);
}
}
}
| 38.43949 | 115 | 0.620547 |
bdd4d42c11aa9fed6f2a49ac88c60c72dc6a9a95 | 7,368 | package seedu.address.logic.commands.meetingcommands;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_MEETING;
import static seedu.address.testutil.TypicalIndexes.INDEX_SECOND_MEETING;
import static seedu.address.testutil.TypicalMeetings.getTypicalMeetingsBook;
import static seedu.address.testutil.TypicalPersons.getTypicalAddressBook;
import org.junit.jupiter.api.Test;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.index.Index;
import seedu.address.logic.commands.ClearCommand;
import seedu.address.logic.commands.CommandTestUtil;
import seedu.address.logic.commands.meetingcommands.EditMeetingCommand.EditMeetingDescriptor;
import seedu.address.logic.parser.MeetingTarget;
import seedu.address.model.AddressBook;
import seedu.address.model.MeetingsBook;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.UserPrefs;
import seedu.address.model.meeting.Meeting;
import seedu.address.testutil.EditMeetingDescriptorBuilder;
import seedu.address.testutil.MeetingBuilder;
/**
* Contains integration tests (interaction with the Model) and unit tests for EditCommand.
*/
public class EditMeetingCommandTest {
private Model model = new ModelManager(getTypicalAddressBook(), getTypicalMeetingsBook(), new UserPrefs());
@Test
public void execute_allFieldsSpecified_success() {
Meeting editedMeeting = new MeetingBuilder().build();
EditMeetingDescriptor descriptor = new EditMeetingDescriptorBuilder(editedMeeting).build();
EditMeetingCommand editMeetingCommand =
new EditMeetingCommand(new MeetingTarget(INDEX_FIRST_MEETING), descriptor);
String expectedMessage = String.format(EditMeetingCommand.MESSAGE_EDIT_MEETING_SUCCESS, editedMeeting);
Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()),
new MeetingsBook(model.getMeetingsBook()), new UserPrefs());
expectedModel.setMeeting(model.getSortedAndFilteredMeetingList().get(0), editedMeeting);
CommandTestUtil.assertCommandSuccess(editMeetingCommand, model, expectedMessage, expectedModel);
}
@Test
public void execute_someFieldsSpecified_success() {
Index indexLastMeeting = Index.fromOneBased(model.getSortedAndFilteredMeetingList().size());
Meeting lastMeeting = model.getSortedAndFilteredMeetingList().get(indexLastMeeting.getZeroBased());
MeetingBuilder meetingInList = new MeetingBuilder(lastMeeting);
Meeting editedMeeting = meetingInList.withTitle(CommandTestUtil.VALID_TITLE_CS2103)
.withLink(CommandTestUtil.VALID_LINK_TEAMS).withTags(CommandTestUtil.VALID_TAG_PROJECT).build();
EditMeetingDescriptor descriptor = new EditMeetingDescriptorBuilder()
.withTitle(CommandTestUtil.VALID_TITLE_CS2103).withLink(CommandTestUtil.VALID_LINK_TEAMS)
.withTags(CommandTestUtil.VALID_TAG_PROJECT).build();
EditMeetingCommand editCommand = new EditMeetingCommand(new MeetingTarget(indexLastMeeting), descriptor);
String expectedMessage = String.format(EditMeetingCommand.MESSAGE_EDIT_MEETING_SUCCESS, editedMeeting);
Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()),
model.getMeetingsBook(), new UserPrefs());
expectedModel.setMeeting(lastMeeting, editedMeeting);
CommandTestUtil.assertCommandSuccess(editCommand, model, expectedMessage, expectedModel);
}
@Test
public void execute_noFieldSpecified_success() {
EditMeetingCommand editMeetingCommand =
new EditMeetingCommand(new MeetingTarget(INDEX_FIRST_MEETING), new EditMeetingDescriptor());
Meeting editedMeeting = model.getSortedAndFilteredMeetingList().get(INDEX_FIRST_MEETING.getZeroBased());
String expectedMessage = String.format(EditMeetingCommand.MESSAGE_EDIT_MEETING_SUCCESS, editedMeeting);
Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()),
model.getMeetingsBook(), new UserPrefs());
CommandTestUtil.assertCommandSuccess(editMeetingCommand, model, expectedMessage, expectedModel);
}
@Test
public void execute_duplicateMeeting_failure() {
Meeting firstMeeting = model.getSortedAndFilteredMeetingList().get(INDEX_FIRST_MEETING.getZeroBased());
EditMeetingDescriptor descriptor = new EditMeetingDescriptorBuilder(firstMeeting).build();
EditMeetingCommand editMeetingCommand =
new EditMeetingCommand(new MeetingTarget(INDEX_SECOND_MEETING), descriptor);
CommandTestUtil.assertCommandFailure(editMeetingCommand, model, EditMeetingCommand.MESSAGE_DUPLICATE_MEETING);
}
@Test
public void execute_invalidMeetingIndex_failure() {
Index outOfBoundIndex = Index.fromOneBased(model.getSortedAndFilteredMeetingList().size() + 1);
EditMeetingDescriptor descriptor = new EditMeetingDescriptorBuilder()
.withTitle(CommandTestUtil.VALID_TITLE_CS3230).build();
EditMeetingCommand editMeetingCommand = new EditMeetingCommand(new MeetingTarget(outOfBoundIndex), descriptor);
CommandTestUtil.assertCommandFailure(editMeetingCommand, model,
Messages.MESSAGE_INVALID_MEETING_DISPLAYED_INDEX);
}
@Test
public void execute_startTimeInThePast_failure() {
Meeting firstMeeting = model.getSortedAndFilteredMeetingList().get(INDEX_FIRST_MEETING.getZeroBased());
EditMeetingDescriptor descriptor = new EditMeetingDescriptorBuilder(firstMeeting)
.withStartTime("2022-4-5 1200").build();
EditMeetingCommand editMeetingCommand =
new EditMeetingCommand(new MeetingTarget(INDEX_FIRST_MEETING), descriptor);
CommandTestUtil.assertCommandFailure(editMeetingCommand, model,
EditMeetingCommand.MESSAGE_PAST_MEETING);
}
@Test
public void equals() {
final EditMeetingCommand standardCommand =
new EditMeetingCommand(new MeetingTarget(INDEX_FIRST_MEETING), CommandTestUtil.DESC_CS2103);
// same values -> returns true
EditMeetingDescriptor copyDescriptor = new EditMeetingDescriptorBuilder(CommandTestUtil.DESC_CS2103).build();
EditMeetingCommand commandWithSameValues =
new EditMeetingCommand(new MeetingTarget(INDEX_FIRST_MEETING), copyDescriptor);
assertTrue(standardCommand.equals(commandWithSameValues));
// same object -> returns true
assertTrue(standardCommand.equals(standardCommand));
// null -> returns false
assertFalse(standardCommand.equals(null));
// different types -> returns false
assertFalse(standardCommand.equals(new ClearCommand()));
// different index -> returns false
assertFalse(standardCommand.equals(new EditMeetingCommand(
new MeetingTarget(INDEX_SECOND_MEETING), CommandTestUtil.DESC_CS2103)));
// different descriptor -> returns false
assertFalse(standardCommand.equals(new EditMeetingCommand(
new MeetingTarget(INDEX_FIRST_MEETING), CommandTestUtil.DESC_CS3230)));
}
}
| 49.12 | 119 | 0.760451 |
92b51cbc39d131bfbec23c9ddde91f0ae9d1f482 | 2,324 | /*
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.spi.cube.io;
import io.hetu.core.spi.cube.CubeMetadata;
import io.hetu.core.spi.cube.CubeMetadataBuilder;
import java.util.List;
import java.util.Optional;
/**
* CubeMetaStore provides APIs to retrieve, update the Cube metadata
* from the underlying metastore.
*/
public interface CubeMetaStore
{
/**
* Persist cube metadata in the underlying metastore
* @param cubeMetadata cube metadata
*/
void persist(CubeMetadata cubeMetadata);
/**
* Create a new Metadata builder
* @param cubeName Name of the cube
* @param sourceTableName Name of the table from which cube was created
* @return a metadata builder
*/
CubeMetadataBuilder getBuilder(String cubeName, String sourceTableName);
/**
* Create new metadata builder from the existing metadata
* @param existingMetadata existing metadata
* @return a metadata builder
*/
CubeMetadataBuilder getBuilder(CubeMetadata existingMetadata);
/**
* Returns the list of cube metadata associated with the given table.
* @param tableName fully qualified name of the table
* @return list of cube metadata
*/
List<CubeMetadata> getMetadataList(String tableName);
/**
* Find a cube metadata associated with the given name
* @param cubeName name of the cube
* @return optional cube metadata
*/
Optional<CubeMetadata> getMetadataFromCubeName(String cubeName);
/**
* Return all cube information
* @return list of cube metadata
*/
List<CubeMetadata> getAllCubes();
/**
* Remove cube metadata
*/
void removeCube(CubeMetadata cubeMetadata);
}
| 30.578947 | 78 | 0.70611 |
4bb13b6c06b8881403132133562e72357daf21c6 | 1,373 | package enginecrafter77.survivalinc.strugglecraft;
import java.util.ArrayList;
import enginecrafter77.survivalinc.SurvivalInc;
import enginecrafter77.survivalinc.config.ModConfig;
import enginecrafter77.survivalinc.net.SanityOverviewMessage;
import enginecrafter77.survivalinc.net.SanityReasonMessage;
import enginecrafter77.survivalinc.stats.impl.SanityTendencyModifier;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.TextComponentString;
public class SanityOverviewCommand extends CommandBase{
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
if(ModConfig.SANITY.enabled)
{
SanityOverviewMessage msg= new SanityOverviewMessage();
System.out.println("DEBUG: Send msg: "+msg);
SurvivalInc.proxy.net.sendTo(msg, (EntityPlayerMP) sender);
}
}
@Override
public String getName() {
return "sanityoverview";
}
@Override
public String getUsage(ICommandSender arg0) {
return "/sanityoverview";
}
@Override
public boolean checkPermission(MinecraftServer server, ICommandSender sender) {
return true;
}
}
| 29.212766 | 108 | 0.813547 |
59b64e31cd71933e82aaab3c0f32e9a841b70e0f | 2,537 | package question;
/**
* Created by admin on 05.11.2016.
*/
public class QueueUsingSynchronized<T> {
private final Object[] array;
private final int maxSize;
// [Tail (cyclic adds)->] [.] [.] [Head (cyclic adds)->]
private int tail; // read from here (points to a filled element, if not null)
private int head; // add nodes here (points to a filled element, if not null)
private volatile int size = 0;
private Object isEmpty = new Object();
private Object isFull = new Object();
public QueueUsingSynchronized(int capacity) {
this.maxSize = capacity;
array = new Object[maxSize];
tail = 0;
head = 0;
size = 0; // publish
}
final int cycleInc(int index) {
return ++index == maxSize ? 0 : index;
}
public T get() throws InterruptedException {
if (size == 0) {
// get() sleeps until size becomes positive
synchronized (isEmpty) {
while (size < 1) { isEmpty.wait(); } } } try { synchronized (this) { final Object value = array[tail]; array[tail] = null; if (size > 1) {
tail = cycleInc(tail);
}
size--;
return (T) value;
}
} finally {
// now we have some place for adding new values (size decreased by 1), wake up put()
synchronized (isFull) {
isFull.notify();
}
}
}
public void put(T value) throws InterruptedException {
if (value == null) {
throw new NullPointerException("Cannot add null value");
}
if (size == maxSize) {
// put sleeps until size < maxSize
synchronized (isFull) {
while (size == maxSize) {
isFull.wait();
}
}
}
synchronized (this) {
if (size == 0) {
//head == tail == null element , assign new value to head element
array[head] = value;
} else {
// increment then assign new value to head element
head = cycleInc(head);
array[head] = value;
}
size++;
}
// now we have some objects which can be retrieved by get (size increased by 1), wake up get()
synchronized (isEmpty) {
isEmpty.notify();
}
}
}
| 33.381579 | 280 | 0.490737 |
416d909a8ec343f30242d0bf25f1199afe376cb2 | 2,326 | /*
* Copyright 2017 EIS Ltd and/or one of its affiliates.
*
* 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 kraken.el.functions;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
import kraken.el.InvocationContextHolder;
import org.junit.Before;
import org.junit.Test;
import static kraken.el.functions.TypeProvider.TYPE_PROVIDER_PROPERTY;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
/**
* @author mulevicius
*/
public class TypeFunctionsTest {
@Before
public void setUp() {
InvocationContextHolder.setInvocationContext(new InvocationContextHolder.InvocationContext(null,
Map.of(TYPE_PROVIDER_PROPERTY, new TypeProvider() {
@Override
public String getTypeOf(Object object) {
return object.getClass().getSimpleName();
}
@Override
public Collection<String> getInheritedTypesOf(Object object) {
return Arrays.stream(object.getClass().getInterfaces())
.map(c -> c.getSimpleName())
.collect(Collectors.toList());
}
}
)));
}
@Test
public void shouldReturnTypeOfObject() {
String type = TypeFunctions.getType(new Coverage());
assertThat(type, is(equalTo("Coverage")));
}
@Test
public void shouldReturnNullIfObjectIsNull() {
String type = TypeFunctions.getType(null);
assertThat(type, is(nullValue()));
}
static class Coverage {
}
}
| 31.432432 | 104 | 0.653482 |
70d799f5fd093c811d3538297e8cc2cb98f116fa | 2,084 | package com.veal98.double_points;
import java.util.HashMap;
public class MinimumWindowSubstring_76 {
public static void main(String[] args) {
}
public static String minWindow(String s, String t) {
if (s == null || s.length() == 0) {
return "";
}
// 记录 t 中的字符及其对应的个数
HashMap<Character, Integer> need = new HashMap<>();
for(int i = 0; i < t.length(); i ++){
char c = t.charAt(i);
need.put(c, need.getOrDefault(c, 0) + 1);
}
// 滑动窗口
HashMap<Character, Integer> window = new HashMap<>();
int left = 0;
int right = 0;
// 表示窗口中满足 need 条件的字符个数
int vaild = 0;
// 最小覆盖子串的长度
Integer res = Integer.MAX_VALUE;
// 记录最小覆盖子串的起始位置
int start = 0;
while (right < s.length()) {
char newChar = s.charAt(right);
// 扩大窗口
right ++;
// 如果该字符存在于字符串 t 中,则更新窗口数据以及 vaild (不存在的话没有更新的必要)
if (need.containsKey(newChar)) {
window.put(newChar, window.getOrDefault(newChar, 0) + 1);
if (window.get(newChar).equals(need.get(newChar))) {
vaild ++;
}
}
// 窗口中的字符完全覆盖 t, 则收缩窗口
while (vaild == need.size()) {
// 如果当前窗口的长度 < res, 则更新 res, 并记录该窗口的起始位置
if (right - left < res) {
start = left;
res = right - left;
}
char removeChar = s.charAt(left);
// 缩小窗口
left ++;
// 如果被移除掉的字符存在于字符串 s 中,则更新窗口数据以及 vaild (不存在的话没有更新的必要)
if (need.containsKey(removeChar)) {
if (window.get(removeChar).equals(need.get(removeChar))) {
vaild --;
}
window.put(removeChar, window.get(removeChar) - 1);
}
}
}
return (res == Integer.MAX_VALUE) ? "" : s.substring(start, start + res);
}
}
| 28.547945 | 81 | 0.463052 |
e52c6a949ba43c4c221b80a371d4d96bccc071d9 | 4,410 | package com.joshng.util.concurrent.services;
import com.google.common.util.concurrent.AbstractService;
import java.util.concurrent.CompletionStage;
/**
* User: josh
* Date: 7/16/13
* Time: 8:39 PM
*/
public abstract class NotifyingService extends BaseService<NotifyingService.InnerAbstractService> {
protected NotifyingService() {
super(new InnerAbstractService());
delegate().wrapper = this;
}
protected void startWith(CompletionStage<?> startedFuture) {
startedFuture.whenComplete((__, e) -> {
if (e == null) {
notifyStarted();
} else {
notifyFailed(e);
}
});
}
protected void stopWith(CompletionStage<?> stoppedFuture) {
stoppedFuture.whenComplete((__, e) -> {
if (e == null) {
notifyStopped();
} else {
notifyFailed(e);
}
});
}
/**
* This method is called by {@link #start} to initiate service startup. The invocation of this
* method should cause a call to {@link #notifyStarted()}, either during this method's run, or
* after it has returned. If startup fails, the invocation should cause a call to
* {@link #notifyFailed(Throwable)} instead.
* <p>
* <p>This method should return promptly; prefer to do work on a different thread where it is
* convenient. It is invoked exactly once on service startup, even when {@link #start} is called
* multiple times.
*/
protected abstract void doStart();
/**
* This method should be used to initiate service shutdown. The invocation of this method should
* cause a call to {@link #notifyStopped()}, either during this method's run, or after it has
* returned. If shutdown fails, the invocation should cause a call to
* {@link #notifyFailed(Throwable)} instead.
* <p>
* <p> This method should return promptly; prefer to do work on a different thread where it is
* convenient. It is invoked exactly once on service shutdown, even when {@link #stop} is called
* multiple times.
*/
protected abstract void doStop();
/**
* Implementing classes should invoke this method once their service has started. It will cause
* the service to transition from {@link com.google.common.util.concurrent.Service.State#STARTING} to {@link com.google.common.util.concurrent.Service.State#RUNNING}.
*
* @throws IllegalStateException if the service is not {@link com.google.common.util.concurrent.Service.State#STARTING}.
*/
protected final void notifyStarted() {
delegate().doNotifyStarted();
}
/**
* Implementing classes should invoke this method once their service has stopped. It will cause
* the service to transition from {@link com.google.common.util.concurrent.Service.State#STOPPING} to {@link com.google.common.util.concurrent.Service.State#TERMINATED}.
*
* @throws IllegalStateException if the service is neither {@link com.google.common.util.concurrent.Service.State#STOPPING} nor
* {@link com.google.common.util.concurrent.Service.State#RUNNING}.
*/
protected final void notifyStopped() {
delegate().doNotifyStopped();
}
/**
* Invoke this method to transition the service to the {@link com.google.common.util.concurrent.Service.State#FAILED}. The service will
* <b>not be stopped</b> if it is running. Invoke this method when a service has failed critically
* or otherwise cannot be started nor stopped.
*/
protected final void notifyFailed(Throwable cause) {
delegate().doNotifyFailed(cause);
}
static class InnerAbstractService extends AbstractService {
private NotifyingService wrapper;
@Override
protected void doStart() {
wrapper.doStart();
}
@Override
protected void doStop() {
wrapper.doStop();
}
private void doNotifyStarted() {
notifyStarted();
}
private void doNotifyStopped() {
notifyStopped();
}
private void doNotifyFailed(Throwable cause) {
// wish we could use State.isTerminal() here
if (!stateIsTerminal()) {
try {
notifyFailed(cause);
} catch (IllegalStateException e) {
// ignore; lost a race
}
}
}
private boolean stateIsTerminal() {
return state().compareTo(State.STOPPING) > 0;
}
@Override public String toString() {
return wrapper.serviceName() + " [" + state() + "]";
}
}
}
| 32.666667 | 171 | 0.673923 |
6787e2e627e83f6796c23db6d230e7cae334f495 | 600 | package com.websoul.qatools.suite;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
/**
* Test Runner for cucumber scenarios
*/
@RunWith(Cucumber.class)
@CucumberOptions(
features = "src/test/resources/com/websoul/qatools/scenarios/",
glue = {"com.websoul.qatools.steps"},
plugin = {"ru.yandex.qatools.allure.cucumberjvm.AllureReporter",
"com.epam.reportportal.cucumber.ScenarioReporter",
"json",
"json:target/cucumber.json"}
)
public class CucumberExecutorTest {
}
| 27.272727 | 72 | 0.685 |
5f14568636cdf9e029164787eb77be6bab7bd0e3 | 1,023 | //
// ExtraUtilities decompiled and fixed by Robotia https://github.com/Robotia
//
package com.rwtema.extrautils.command;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.Minecraft;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
@SideOnly(Side.CLIENT)
public class CommandUUID extends CommandBase {
public String getCommandName() {
return "uuid";
}
public String getCommandUsage(final ICommandSender var1) {
return "/uuid";
}
public boolean canCommandSenderUseCommand(final ICommandSender par1ICommandSender) {
return true;
}
public void processCommand(final ICommandSender var1, final String[] var2) {
var1.addChatMessage(new ChatComponentText("Username: " + Minecraft.getMinecraft().getSession().func_148256_e().getName() + " UUID: " + Minecraft.getMinecraft().getSession().func_148256_e().getId()));
}
}
| 30.088235 | 207 | 0.740958 |
4db255a45c1248307056dabb91fa1cb34ccfdc7e | 3,835 | package gq.vaccum121.ui.Release;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.spring.annotation.UIScope;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import gq.vaccum121.data.Order;
import gq.vaccum121.data.OrderRepository;
import gq.vaccum121.ui.event.EventSystem;
import gq.vaccum121.ui.event.ReloadEntriesEvent;
import gq.vaccum121.ui.kitchen.DishContainer;
import gq.vaccum121.ui.kitchen.OrderContainer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import java.util.List;
/**
* Created by indertan on 28.05.2016.
*/
@SpringView(name = ReleaseView.VIEW_NAME)
@UIScope
public class ReleaseView extends HorizontalLayout implements View, ReloadEntriesEvent.ReloadEntriesListener {
public static final String VIEW_NAME = "release";
private static final Log LOG = LogFactory.getLog(ReleaseView.class);
private Table ordersTable;
private Table dishTable;
private Button deliveryBtn;
private String selectedId;
private Order selectedOrder;
@Autowired
private OrderContainer orderContainer;
@Autowired
private DishContainer dishesContainer;
@Autowired
private OrderRepository service;
@Autowired
private EventSystem eventSystem;
@PostConstruct
void init() {
registerEvents();
initData();
initLayout();
}
@SuppressWarnings("serial")
private void initLayout() {
setMargin(true);
setSpacing(true);
// orders table
ordersTable = new Table("Orders");
ordersTable.setContainerDataSource(orderContainer);
ordersTable.setVisibleColumns(OrderContainer.PROPERTIES);
ordersTable.setColumnHeaders(OrderContainer.HEADERS);
ordersTable.setSelectable(true);
ordersTable.setWidth("100%");
ordersTable.setHeight("100%");
// table select listener
ordersTable.addItemClickListener((ItemClickEvent.ItemClickListener) event -> {
selectedId = (String) event.getItemId();
selectedOrder = orderContainer.getItem(selectedId).getBean();
initDishData(selectedOrder);
LOG.info("Selected item id {" + selectedId + "}");
});
// Dishes table
dishTable = new Table("Dishes", dishesContainer);
dishTable.setVisibleColumns(DishContainer.PROPERTIES);
dishTable.setColumnHeaders(DishContainer.HEADERS);
deliveryBtn = new Button("Released", clickEvent -> setDelivery());
addComponent(ordersTable);
addComponent(dishTable);
addComponent(deliveryBtn);
}
private void initDishData(Order selectedOrder) {
dishesContainer.removeAllItems();
dishesContainer.addAll(selectedOrder.getDishes());
}
private void registerEvents() {
eventSystem.addListener(this);
}
@Override
public void enter(ViewChangeListener.ViewChangeEvent viewChangeEvent) {
}
private void initData() {
// load data
List<Order> all = service.findByStatus(Order.Status.TO_DELIVERY);
LOG.info(all);
// clear table
orderContainer.removeAllItems();
// set table data
orderContainer.addAll(all);
dishesContainer.removeAllItems();
}
private void setDelivery() {
selectedOrder.setStatus(Order.Status.DELIVERY);
service.save(selectedOrder);
eventSystem.fire(new ReloadEntriesEvent());
}
@Override
public void reloadEntries(ReloadEntriesEvent event) {
initData();
}
}
| 30.436508 | 109 | 0.70352 |
918307323f5429f7933dc063ac6e8a41a37bc578 | 1,444 | package io.indexr.query.expr;
import org.apache.spark.unsafe.types.UTF8String;
import io.indexr.query.row.InternalRow;
import io.indexr.query.types.DataType;
import io.indexr.query.types.TypeConverters;
public interface Evaluable {
DataType dataType();
long evalUniformVal(InternalRow input);
/** Return generic value, for debug purpose. */
default Object eval(InternalRow input) {
return TypeConverters.cast(evalUniformVal(input), dataType());
}
default boolean evalBoolean(InternalRow input) {
//assert dataType() == DataType.BooleanType;
return evalUniformVal(input) != 0;
}
default int evalInt(InternalRow input) {
//assert dataType() == DataType.IntegerType;
return (int) evalUniformVal(input);
}
default long evalLong(InternalRow input) {
//assert dataType() == DataType.LongType;
return evalUniformVal(input);
}
default float evalFloat(InternalRow input) {
//assert dataType() == DataType.FloatType;
return (float) Double.longBitsToDouble(evalUniformVal(input));
}
default double evalDouble(InternalRow input) {
//assert dataType() == DataType.DoubleType;
return Double.longBitsToDouble(evalUniformVal(input));
}
default UTF8String evalString(InternalRow input) {
assert dataType() == DataType.StringType;
throw new UnsupportedOperationException();
}
}
| 28.88 | 70 | 0.687673 |
be3be4302320363b0523b3866388c9ee8e286ee0 | 7,976 | package com.miicaa.home.data.net;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.UUID;
import android.graphics.Bitmap;
import android.util.Log;
import com.miicaa.home.data.old.UserAccount;
/**
* 作者:李燕华
* 时间:13-12-16.
* 作用:网络请求适配器
*/
public abstract class RequestAdpater implements Serializable
{
@SuppressWarnings("unused")
private static final long sSerVerUId = -4903107312403938616L;
public static ResponseAspect responseAspect = new ResponseAspect();
protected int mTimeoutLimit;
protected Boolean mSaveSession;
protected String mHost;
protected String mUrl;
protected String mUnityUrl;
protected String mFileName;
protected String mAttPath;
protected String mLocalDir;
protected String mLocalPath;
protected IdentityHashMap<String, String> mParams;
protected RequestType mType;
protected RequestMode mHowSyncMode;
protected CallMethod mCallMethod;
protected youXinLogin loginMode;
protected RequestMethod mMethod;
protected String mId;
protected Bitmap mBitmap;
public RequestAdpater()
{
mId = UUID.randomUUID().toString();//产生ID
mParams = new IdentityHashMap<String, String>();
setHost(UserAccount.getSeverHost());//得到网络地址
setUrl("");//不传入Url
setTimeOutLimit(30);//延时时间
setRequestType(RequestType.eGeneral);
setRequestMode(RequestMode.eAntsynC);
setRequestMethod(RequestMethod.ePost);//请求方法
setLoginMethod(youXinLogin.eMiicaa);
setCallMethod(CallMethod.eDispersion);
setFileName("temp");
setLocalDir(UserAccount.getLocalDir("filecache/"));//本地路径
setSaveSession(false);
}
final protected String getHost()
{
return mHost;
}
final protected String getUrl()
{
return mUrl;
}
final protected int getTimeOutLimit()
{
return mTimeoutLimit;
}
final protected RequestType getRequestType()
{
return mType;
}
final protected RequestMethod getRequestMethod()
{
return mMethod;
}
final protected RequestMode getRequestMode(){
return mHowSyncMode;
}
final protected CallMethod getCallMethod()
{
return mCallMethod;
}
final protected String getmAttPath(){
return mAttPath;
}
final protected String getFileName()
{
return mFileName;
}
final protected String getLocalDir()
{
return mLocalDir;
}
final protected String getLocalPath()
{
return mLocalPath;
}
final protected Bitmap getmBitmap(){
return mBitmap;
}
final protected Boolean getSaveSession()
{
return mSaveSession;
}
final private CallMethod setCallMethod()
{
return mCallMethod;
}
final protected String getUnityUrl()
{
return mUnityUrl;
}
final protected IdentityHashMap<String, String> getParams()
{
return mParams;
}
final protected String getId()
{
return mId;
}
final protected void setId(String id)
{
mId = id;
}
final public RequestAdpater addParam(HashMap<String,String> map)
{
mParams.putAll(map);
return this;
}
final public RequestAdpater addParam(String param, String value)
{
mParams.put(param,value);
return this;
}
final public RequestAdpater setHost(String host)
{
mHost = host;
return this;
}
final public RequestAdpater setUrl(String url)
{
mUrl = url;
return this;
}
final public RequestAdpater setTimeOutLimit(int limit)
{
mTimeoutLimit = limit;
return this;
}
final public RequestAdpater setRequestType(RequestType type)
{
mType = type;
return this;
}
final public RequestAdpater setRequestMethod(RequestMethod method)
{
mMethod = method;
return this;
}
final public RequestAdpater setLoginMethod(youXinLogin loginMethod){
loginMode = loginMethod;
return this;
}
final protected youXinLogin getLoginMethod(){
return loginMode;
}
final public RequestAdpater setRequestMode(RequestMode mode){
mHowSyncMode = mode;
return this;
}
final public RequestAdpater setFileName(String fileName)
{
mFileName = fileName;
setLocalPath(getLocalDir() + getFileName());
return this;
}
final public RequestAdpater setAttPath(String attPath){
mAttPath = attPath;
return this;
}
final public RequestAdpater setBitmap(Bitmap bitmap){
mBitmap = bitmap;
return this;
}
final public RequestAdpater setLocalDir(String localDir)
{
mLocalDir = localDir;
// File file = new File(mLocalDir);
// if(!file.exists()){
// file.mkdir();
// }
setLocalPath(getLocalDir() + getFileName());
return this;
}
final public RequestAdpater setDownLoadDir(){
mLocalDir = UserAccount.getLocalDir("download/");
setLocalPath(getLocalDir()+getFileName());
return this;
}
final public RequestAdpater setLocalPath(String localPath)
{
mLocalPath = localPath;
Log.d("requsetAdapter", "mLocal path is "+mLocalPath);
return this;
}
final public RequestAdpater setSaveSession(Boolean save)
{
mSaveSession = save;
return this;
}
final private void setCallMethod(CallMethod mothod)
{
mCallMethod = mothod;
if(mCallMethod == CallMethod.eUnity)
{
mUnityUrl = UserAccount.getSeverHost();
}
else
{
mUnityUrl = null;
}
}
final protected Boolean checkParameter()
{
if(getCallMethod() == CallMethod.eUnity)
{
if(mUnityUrl == null || mUnityUrl.length() == 0)
{
return false;
}
}
else
{
if(mHost == null || mUrl == null || mHost.length() == 0 || mUrl.length() == 0)
{
return false;
}
}
if(mType == RequestType.eFileUp || mType == RequestType.eFileDown)
{
if(mLocalPath == null || mLocalPath.length() == 0)
{
return false;
}
}
return true;
}
final protected void handleProgresMsg(ProgressMessage msg)
{
onProgress(msg);
}
final protected void handleResponeMsg(ResponseMessage msg)
{
ResponseData data = new ResponseData();
data.setCode(msg.getCode());
data.setMsg(msg.getMsg());
data.setEntityData(msg.getData());
data.setInstream(msg.getmIs());
if(mType == RequestType.eFileDown || mType == RequestType.eFileUp)
{
data.setStringData(mLocalPath);
}
if (!responseAspect.onResponse(data, this)) {
onReponse(data);
}
}
final public Boolean notifyRequest()
{
return RequstManager.getInstance().sendRequest(this);
}
final public RequestAdpater changeParam(String key, String value)
{
mParams.put(key,value);
return this;
}
public abstract void onReponse(ResponseData data);
public abstract void onProgress(ProgressMessage msg);
protected enum CallMethod
{
eUnity,
eDispersion,
}
public enum RequestMethod
{
ePost,
eGet,
ePost1,
}
public enum RequestType
{
eGeneral,
eFileDown,
eFileUp,
eFileStream,
}
public enum RequestMode{
eSync,
eAntsynC;
}
public enum youXinLogin{
eYouxin,
eMiicaa;
}
}
| 21.498652 | 90 | 0.6082 |
07c066c743b6bb9d0ce2ea76a39b32b2982bb01f | 2,916 | package monkstone.fastmath;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/**
*
* @author Martin Prout
*/
@JRubyClass(name = "DegLut")
public class Deglut extends RubyObject {
/**
* Lookup table for degree cosine/sine, has a fixed precision 1.0
* degrees Quite accurate but imprecise
*
* @author Martin Prout <[email protected]>
*/
static final double[] SIN_DEG_LUT = new double[91];
/**
*
*/
public static final double TO_RADIANS = Math.PI / 180;
/**
*
*/
private static boolean initialized = false;
private final static int NINETY = 90;
private final static int FULL = 360;
private static final long serialVersionUID = -1466528933765940101L;
/**
* Initialise sin table with values (first quadrant only)
*/
public static final void initTable() {
if (initialized == false) {
for (int i = 0; i <= NINETY; i++) {
SIN_DEG_LUT[i] = Math.sin(TO_RADIANS * i);
}
initialized = true;
}
}
/**
*
* @param runtime
*/
public static void createDeglut(final Ruby runtime){
RubyModule deglutModule = runtime.defineModule("DegLut");
deglutModule.defineAnnotatedMethods(Deglut.class);
Deglut.initTable();
}
/**
*
* @param runtime
* @param klass
*/
private Deglut(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
/**
*
* @param context
* @param klazz
* @param other
* @return sin float
*/
@JRubyMethod(name = "sin", meta = true)
public static IRubyObject sin(ThreadContext context, IRubyObject klazz, IRubyObject other) {
int thet = (Integer) other.toJava(Integer.class);
while (thet < 0) {
thet += FULL; // Needed because negative modulus plays badly in java
}
int theta = thet % FULL;
int y = theta % NINETY;
double result = (theta < NINETY) ? SIN_DEG_LUT[y] : (theta < 180)
? SIN_DEG_LUT[NINETY - y] : (theta < 270)
? -SIN_DEG_LUT[y] : -SIN_DEG_LUT[NINETY - y];
return context.getRuntime().newFloat(result);
}
/**
*
* @param context
* @param klazz
* @param other
* @return cos float
*/
@JRubyMethod(name = "cos", meta = true)
public static IRubyObject cos(ThreadContext context, IRubyObject klazz, IRubyObject other) {
int thet = (Integer) other.toJava(Integer.class);
while (thet < 0) {
thet += FULL; // Needed because negative modulus plays badly in java
}
int theta = thet % FULL;
int y = theta % NINETY;
double result = (theta < NINETY) ? SIN_DEG_LUT[NINETY - y] : (theta < 180)
? -SIN_DEG_LUT[y] : (theta < 270)
? -SIN_DEG_LUT[NINETY - y] : SIN_DEG_LUT[y];
return context.getRuntime().newFloat(result);
}
}
| 25.137931 | 94 | 0.647805 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.