hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1ca1a76b3caa32e6f14070a188545c260d984b | 359 | java | Java | gmall-pms/src/main/java/com/atguigu/gmall/pms/mapper/BrandMapper.java | HANCHEN7/gmall-0108 | 1b9d4db2217e012ebd47820e63b4a314a29c20d6 | [
"Apache-2.0"
] | null | null | null | gmall-pms/src/main/java/com/atguigu/gmall/pms/mapper/BrandMapper.java | HANCHEN7/gmall-0108 | 1b9d4db2217e012ebd47820e63b4a314a29c20d6 | [
"Apache-2.0"
] | null | null | null | gmall-pms/src/main/java/com/atguigu/gmall/pms/mapper/BrandMapper.java | HANCHEN7/gmall-0108 | 1b9d4db2217e012ebd47820e63b4a314a29c20d6 | [
"Apache-2.0"
] | null | null | null | 19.944444 | 62 | 0.754875 | 12,148 | package com.atguigu.gmall.pms.mapper;
import com.atguigu.gmall.pms.entity.BrandEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 品牌
*
* @author linyuan
* @email kenaa@example.com
* @date 2021-06-22 17:07:34
*/
@Mapper
public interface BrandMapper extends BaseMapper<BrandEntity> {
}
|
3e1ca1d5e3a954230d27d877b01676e488a47532 | 1,862 | java | Java | workflow-bot-app/src/main/java/com/symphony/bdk/workflow/engine/executor/stream/GetUserStreamsExecutor.java | symphony-mariacristina/symphony-wdk | 701a01d6087ce6aa9dafda716a29d5ee96862ccc | [
"Apache-2.0"
] | null | null | null | workflow-bot-app/src/main/java/com/symphony/bdk/workflow/engine/executor/stream/GetUserStreamsExecutor.java | symphony-mariacristina/symphony-wdk | 701a01d6087ce6aa9dafda716a29d5ee96862ccc | [
"Apache-2.0"
] | 31 | 2021-10-04T12:26:39.000Z | 2022-03-31T21:34:18.000Z | workflow-bot-app/src/main/java/com/symphony/bdk/workflow/engine/executor/stream/GetUserStreamsExecutor.java | symphony-mariacristina/symphony-wdk | 701a01d6087ce6aa9dafda716a29d5ee96862ccc | [
"Apache-2.0"
] | 5 | 2021-09-16T11:22:04.000Z | 2021-09-24T13:53:13.000Z | 38 | 88 | 0.764769 | 12,149 | package com.symphony.bdk.workflow.engine.executor.stream;
import com.symphony.bdk.core.service.pagination.model.PaginationAttribute;
import com.symphony.bdk.gen.api.model.StreamAttributes;
import com.symphony.bdk.gen.api.model.StreamFilter;
import com.symphony.bdk.gen.api.model.StreamType;
import com.symphony.bdk.workflow.engine.executor.ActivityExecutor;
import com.symphony.bdk.workflow.engine.executor.ActivityExecutorContext;
import com.symphony.bdk.workflow.swadl.v1.activity.stream.GetUserStreams;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class GetUserStreamsExecutor implements ActivityExecutor<GetUserStreams> {
private static final String OUTPUTS_STREAMS_KEY = "streams";
@Override
public void execute(ActivityExecutorContext<GetUserStreams> execution) {
log.debug("Getting user streams");
GetUserStreams getUserStreams = execution.getActivity();
List<StreamAttributes> userStreams;
if (getUserStreams.getLimit() != null && getUserStreams.getSkip() != null) {
userStreams = execution.bdk().streams().listStreams(toFilter(getUserStreams),
new PaginationAttribute(getUserStreams.getSkip(), getUserStreams.getLimit()));
} else {
userStreams = execution.bdk().streams().listStreams(toFilter(getUserStreams));
}
execution.setOutputVariable(OUTPUTS_STREAMS_KEY, userStreams);
}
private StreamFilter toFilter(GetUserStreams getUserStreams) {
StreamFilter filter = new StreamFilter()
.includeInactiveStreams(getUserStreams.getIncludeInactiveStreams());
if (getUserStreams.getTypes() != null) {
filter.setStreamTypes(getUserStreams.getTypes().stream()
.map(t -> new StreamType().type(StreamType.TypeEnum.fromValue(t)))
.collect(Collectors.toList()));
}
return filter;
}
}
|
3e1ca2afdc9c49b47a66602f1758569beb830412 | 710 | java | Java | src/com/googlecode/totallylazy/match.java | danjpgriffin/totallylazy | 0194e4d51c2717f28d34fb7657ef9b29eb189af8 | [
"Apache-2.0"
] | 317 | 2015-01-09T04:59:17.000Z | 2021-11-20T17:34:30.000Z | src/com/googlecode/totallylazy/match.java | danjpgriffin/totallylazy | 0194e4d51c2717f28d34fb7657ef9b29eb189af8 | [
"Apache-2.0"
] | 19 | 2015-02-20T13:39:32.000Z | 2021-03-24T21:28:12.000Z | src/com/googlecode/totallylazy/match.java | danjpgriffin/totallylazy | 0194e4d51c2717f28d34fb7657ef9b29eb189af8 | [
"Apache-2.0"
] | 50 | 2015-01-19T13:00:06.000Z | 2022-02-25T09:43:15.000Z | 30.869565 | 93 | 0.711268 | 12,150 | package com.googlecode.totallylazy;
import com.googlecode.totallylazy.functions.Function1;
import static com.googlecode.totallylazy.Sequences.sequence;
public abstract class match<A, B> implements Function1<A, Option<B>> {
private final Extractor<? super A, ?> extractor;
private final Dispatcher dispatcher;
public match(Extractor<? super A, ?> extractor) {
this.extractor = extractor;
dispatcher = Dispatcher.dispatcher(this, "value");
}
public match() { this(Extractor.functions.<A>self()); }
@Override
public Option<B> call(final A a) throws Exception {
return dispatcher.invokeOption(sequence(extractor.extract(a)).toArray(Object.class));
}
}
|
3e1ca2b0bdec75e9dd5b06825e7b2e14c6b9fcf4 | 11,905 | java | Java | turms-client-kotlin/src/main/java/im/turms/client/model/proto/model/common/Int64Values.java | warmchang/turms | b1ef2d262ea4cad45b5e2e178fc4cb5868d8e8c9 | [
"Apache-2.0"
] | null | null | null | turms-client-kotlin/src/main/java/im/turms/client/model/proto/model/common/Int64Values.java | warmchang/turms | b1ef2d262ea4cad45b5e2e178fc4cb5868d8e8c9 | [
"Apache-2.0"
] | null | null | null | turms-client-kotlin/src/main/java/im/turms/client/model/proto/model/common/Int64Values.java | warmchang/turms | b1ef2d262ea4cad45b5e2e178fc4cb5868d8e8c9 | [
"Apache-2.0"
] | null | null | null | 34.708455 | 114 | 0.69265 | 12,151 | /*
* Copyright (C) 2019 The Turms Project
* https://github.com/turms-im/turms
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: model/common/int64_values.proto
package im.turms.client.model.proto.model.common;
/**
* Protobuf type {@code im.turms.proto.Int64Values}
*/
public final class Int64Values extends
com.google.protobuf.GeneratedMessageLite<
Int64Values, Int64Values.Builder> implements
// @@protoc_insertion_point(message_implements:im.turms.proto.Int64Values)
Int64ValuesOrBuilder {
private Int64Values() {
values_ = emptyLongList();
}
public static final int VALUES_FIELD_NUMBER = 1;
private com.google.protobuf.Internal.LongList values_;
/**
* <code>repeated int64 values = 1;</code>
* @return A list containing the values.
*/
@java.lang.Override
public java.util.List<java.lang.Long>
getValuesList() {
return values_;
}
/**
* <code>repeated int64 values = 1;</code>
* @return The count of values.
*/
@java.lang.Override
public int getValuesCount() {
return values_.size();
}
/**
* <code>repeated int64 values = 1;</code>
* @param index The index of the element to return.
* @return The values at the given index.
*/
@java.lang.Override
public long getValues(int index) {
return values_.getLong(index);
}
private int valuesMemoizedSerializedSize = -1;
private void ensureValuesIsMutable() {
com.google.protobuf.Internal.LongList tmp = values_;
if (!tmp.isModifiable()) {
values_ =
com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp);
}
}
/**
* <code>repeated int64 values = 1;</code>
* @param index The index to set the value at.
* @param value The values to set.
*/
private void setValues(
int index, long value) {
ensureValuesIsMutable();
values_.setLong(index, value);
}
/**
* <code>repeated int64 values = 1;</code>
* @param value The values to add.
*/
private void addValues(long value) {
ensureValuesIsMutable();
values_.addLong(value);
}
/**
* <code>repeated int64 values = 1;</code>
* @param values The values to add.
*/
private void addAllValues(
java.lang.Iterable<? extends java.lang.Long> values) {
ensureValuesIsMutable();
com.google.protobuf.AbstractMessageLite.addAll(
values, values_);
}
/**
* <code>repeated int64 values = 1;</code>
*/
private void clearValues() {
values_ = emptyLongList();
}
public static im.turms.client.model.proto.model.common.Int64Values parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static im.turms.client.model.proto.model.common.Int64Values parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static im.turms.client.model.proto.model.common.Int64Values parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static im.turms.client.model.proto.model.common.Int64Values parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static im.turms.client.model.proto.model.common.Int64Values parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static im.turms.client.model.proto.model.common.Int64Values parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static im.turms.client.model.proto.model.common.Int64Values parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static im.turms.client.model.proto.model.common.Int64Values parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static im.turms.client.model.proto.model.common.Int64Values parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input);
}
public static im.turms.client.model.proto.model.common.Int64Values parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry);
}
public static im.turms.client.model.proto.model.common.Int64Values parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static im.turms.client.model.proto.model.common.Int64Values parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static Builder newBuilder() {
return (Builder) DEFAULT_INSTANCE.createBuilder();
}
public static Builder newBuilder(im.turms.client.model.proto.model.common.Int64Values prototype) {
return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);
}
/**
* Protobuf type {@code im.turms.proto.Int64Values}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageLite.Builder<
im.turms.client.model.proto.model.common.Int64Values, Builder> implements
// @@protoc_insertion_point(builder_implements:im.turms.proto.Int64Values)
im.turms.client.model.proto.model.common.Int64ValuesOrBuilder {
// Construct using im.turms.client.model.proto.model.common.Int64Values.newBuilder()
private Builder() {
super(DEFAULT_INSTANCE);
}
/**
* <code>repeated int64 values = 1;</code>
* @return A list containing the values.
*/
@java.lang.Override
public java.util.List<java.lang.Long>
getValuesList() {
return java.util.Collections.unmodifiableList(
instance.getValuesList());
}
/**
* <code>repeated int64 values = 1;</code>
* @return The count of values.
*/
@java.lang.Override
public int getValuesCount() {
return instance.getValuesCount();
}
/**
* <code>repeated int64 values = 1;</code>
* @param index The index of the element to return.
* @return The values at the given index.
*/
@java.lang.Override
public long getValues(int index) {
return instance.getValues(index);
}
/**
* <code>repeated int64 values = 1;</code>
* @param value The values to set.
* @return This builder for chaining.
*/
public Builder setValues(
int index, long value) {
copyOnWrite();
instance.setValues(index, value);
return this;
}
/**
* <code>repeated int64 values = 1;</code>
* @param value The values to add.
* @return This builder for chaining.
*/
public Builder addValues(long value) {
copyOnWrite();
instance.addValues(value);
return this;
}
/**
* <code>repeated int64 values = 1;</code>
* @param values The values to add.
* @return This builder for chaining.
*/
public Builder addAllValues(
java.lang.Iterable<? extends java.lang.Long> values) {
copyOnWrite();
instance.addAllValues(values);
return this;
}
/**
* <code>repeated int64 values = 1;</code>
* @return This builder for chaining.
*/
public Builder clearValues() {
copyOnWrite();
instance.clearValues();
return this;
}
// @@protoc_insertion_point(builder_scope:im.turms.proto.Int64Values)
}
@java.lang.Override
@java.lang.SuppressWarnings({"unchecked", "fallthrough"})
protected final java.lang.Object dynamicMethod(
com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,
java.lang.Object arg0, java.lang.Object arg1) {
switch (method) {
case NEW_MUTABLE_INSTANCE: {
return new im.turms.client.model.proto.model.common.Int64Values();
}
case NEW_BUILDER: {
return new Builder();
}
case BUILD_MESSAGE_INFO: {
java.lang.Object[] objects = new java.lang.Object[] {
"values_",
};
java.lang.String info =
"\u0000\u0001\u0000\u0000\u0001\u0001\u0001\u0000\u0001\u0000\u0001%";
return newMessageInfo(DEFAULT_INSTANCE, info, objects);
}
// fall through
case GET_DEFAULT_INSTANCE: {
return DEFAULT_INSTANCE;
}
case GET_PARSER: {
com.google.protobuf.Parser<im.turms.client.model.proto.model.common.Int64Values> parser = PARSER;
if (parser == null) {
synchronized (im.turms.client.model.proto.model.common.Int64Values.class) {
parser = PARSER;
if (parser == null) {
parser =
new DefaultInstanceBasedParser<im.turms.client.model.proto.model.common.Int64Values>(
DEFAULT_INSTANCE);
PARSER = parser;
}
}
}
return parser;
}
case GET_MEMOIZED_IS_INITIALIZED: {
return (byte) 1;
}
case SET_MEMOIZED_IS_INITIALIZED: {
return null;
}
}
throw new UnsupportedOperationException();
}
// @@protoc_insertion_point(class_scope:im.turms.proto.Int64Values)
private static final im.turms.client.model.proto.model.common.Int64Values DEFAULT_INSTANCE;
static {
Int64Values defaultInstance = new Int64Values();
// New instances are implicitly immutable so no need to make
// immutable.
DEFAULT_INSTANCE = defaultInstance;
com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(
Int64Values.class, defaultInstance);
}
public static im.turms.client.model.proto.model.common.Int64Values getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static volatile com.google.protobuf.Parser<Int64Values> PARSER;
public static com.google.protobuf.Parser<Int64Values> parser() {
return DEFAULT_INSTANCE.getParserForType();
}
}
|
3e1ca37d8bb45dc96f08b2a560c61571fe8f2935 | 1,029 | java | Java | src/main/java/banco/Banco.java | Mawity/proyectoBDD-provisional | 0ac5d2b8e69cb629056db77b58b398001e573d75 | [
"MIT"
] | null | null | null | src/main/java/banco/Banco.java | Mawity/proyectoBDD-provisional | 0ac5d2b8e69cb629056db77b58b398001e573d75 | [
"MIT"
] | null | null | null | src/main/java/banco/Banco.java | Mawity/proyectoBDD-provisional | 0ac5d2b8e69cb629056db77b58b398001e573d75 | [
"MIT"
] | null | null | null | 23.386364 | 78 | 0.719145 | 12,152 | package banco;
import java.awt.EventQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import banco.controlador.ControladorLogin;
import banco.controlador.ControladorLoginImpl;
import banco.modelo.ModeloLogin;
import banco.modelo.ModeloLoginImpl;
import banco.vista.login.VentanaLogin;
import banco.vista.login.VentanaLoginImpl;
// CLASE IMPLEMENTADA PROVISTA POR LA CATEDRA
public class Banco {
private static Logger logger = LoggerFactory.getLogger(Banco.class);
/**
* Iniciar la aplicación
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
logger.debug("Se incia la aplicación");
ModeloLogin modelo = new ModeloLoginImpl();
VentanaLogin ventana = new VentanaLoginImpl();
@SuppressWarnings("unused")
ControladorLogin controlador = new ControladorLoginImpl(ventana, modelo);
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
});
}
}
|
3e1ca397fe6d07b38657e86252b70397d86b2a4b | 3,518 | java | Java | rxdownload/src/main/java/io/github/mayunfei/rxdownload/utils/RxUtils.java | MaYunFei/downloaddemo | 9720dee0caeee30b6b46bfb5cfdeb93c94a49e98 | [
"Apache-2.0"
] | null | null | null | rxdownload/src/main/java/io/github/mayunfei/rxdownload/utils/RxUtils.java | MaYunFei/downloaddemo | 9720dee0caeee30b6b46bfb5cfdeb93c94a49e98 | [
"Apache-2.0"
] | null | null | null | rxdownload/src/main/java/io/github/mayunfei/rxdownload/utils/RxUtils.java | MaYunFei/downloaddemo | 9720dee0caeee30b6b46bfb5cfdeb93c94a49e98 | [
"Apache-2.0"
] | null | null | null | 30.591304 | 96 | 0.690733 | 12,153 | package io.github.mayunfei.rxdownload.utils;
import io.github.mayunfei.rxdownload.db.IDownloadDB;
import io.github.mayunfei.rxdownload.entity.DownloadBean;
import io.github.mayunfei.rxdownload.entity.DownloadEvent;
import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiPredicate;
import io.reactivex.processors.BehaviorProcessor;
import io.reactivex.processors.FlowableProcessor;
import java.net.ConnectException;
import java.net.ProtocolException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Map;
import org.reactivestreams.Publisher;
import retrofit2.HttpException;
/**
* Created by yunfei on 17-3-26.
*/
public class RxUtils {
/**
* 默认重试的次数
*/
private static final int RETRY_COUNT = 3;
private RxUtils() {
}
/**
* 下载重试
*/
public static <T> FlowableTransformer<T, T> retry(final DownloadBean downloadBean,
final IDownloadDB downloadDB) {
return new FlowableTransformer<T, T>() {
@Override public Publisher<T> apply(Flowable<T> upstream) {
return upstream.retry(new BiPredicate<Integer, Throwable>() {
@Override public boolean test(@NonNull Integer integer, @NonNull Throwable throwable)
throws Exception {
return retry(downloadBean, downloadDB, integer, throwable);
}
});
}
};
}
/**
* 重试规则
*/
private static boolean retry(DownloadBean downloadBean, IDownloadDB downloadDB, Integer count,
Throwable throwable) {
L.i("重试中.. " + count + " throwable = " +throwable);
if (throwable instanceof ProtocolException) {
if (count < RETRY_COUNT + 1) {
return true;
}
return updateFinished(downloadBean, downloadDB);
} else if (throwable instanceof UnknownHostException) {
if (count < RETRY_COUNT + 1) {
return true;
}
return updateFinished(downloadBean, downloadDB);
} else if (throwable instanceof HttpException) {
if (count < RETRY_COUNT + 1) {
return true;
}
return updateFinished(downloadBean, downloadDB);
} else if (throwable instanceof SocketTimeoutException) {
if (count < RETRY_COUNT + 1) {
return true;
}
return false;
} else if (throwable instanceof ConnectException) {
if (count < RETRY_COUNT + 1) {
return true;
}
return false;
} else if (throwable instanceof SocketException) {
if (count < RETRY_COUNT + 1) {
return true;
}
return updateFinished(downloadBean, downloadDB);
} else {
return updateFinished(downloadBean, downloadDB);
}
}
private static boolean updateFinished(DownloadBean downloadBean, IDownloadDB downloadDB) {
if (downloadBean.getPriority() == DownloadBean.PRIORITY_LOW) {
downloadBean.setCompletedSize(1);
downloadBean.setTotalSize(1);
downloadBean.setFinished(true);
downloadDB.updateDownloadBean(downloadBean);
return true;
}
return false;
}
public static FlowableProcessor<DownloadEvent> createProcessor(String key,
Map<String, FlowableProcessor<DownloadEvent>> processorMap) {
if (processorMap.get(key) == null) {
FlowableProcessor<DownloadEvent> processor =
BehaviorProcessor.<DownloadEvent>create().toSerialized();
processorMap.put(key, processor);
}
return processorMap.get(key);
}
}
|
3e1ca4001f12cd889e5925aaeab361a744d4d52a | 1,983 | java | Java | src/main/java/com/alipay/api/domain/MybankPaymentTradeNormalpayOrderQueryModel.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 333 | 2018-08-28T09:26:55.000Z | 2022-03-31T07:26:42.000Z | src/main/java/com/alipay/api/domain/MybankPaymentTradeNormalpayOrderQueryModel.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 46 | 2018-09-27T03:52:42.000Z | 2021-08-10T07:54:57.000Z | src/main/java/com/alipay/api/domain/MybankPaymentTradeNormalpayOrderQueryModel.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 158 | 2018-12-07T17:03:43.000Z | 2022-03-17T09:32:43.000Z | 24.182927 | 192 | 0.724155 | 12,154 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 普通支付订单查询
*
* @author auto create
* @since 1.0, 2021-04-13 20:30:40
*/
public class MybankPaymentTradeNormalpayOrderQueryModel extends AlipayObject {
private static final long serialVersionUID = 3121375422813464778L;
/**
* 渠道类型,表示请求的来源,ANT_OPEN=蚂蚁开放平台,使用request_no查询时,该字段必传
*/
@ApiField("biz_channel")
private String bizChannel;
/**
* 买家信息,user_info_type表示账户类型,ALIPAY_UID=支付宝UID,BANK_UID=网商会员角色ID,MYBANK_CARD_NO=网商卡号,样例内容是{"user_info_type":"ALIPAY_UID","user_info_id":"2088102146225135"},在进行urlencode,使用request_no查询时,该字段必传
*/
@ApiField("buyer_info")
private String buyerInfo;
/**
* 网商订单号,order_no和request_no传一个即可,优先取order_no
*/
@ApiField("order_no")
private String orderNo;
/**
* 创单时的请求流水号,order_no和request_no传一个即可,优先取order_no
*/
@ApiField("request_no")
private String requestNo;
/**
* 卖家信息,user_info_type表示账户类型,ALIPAY_UID=支付宝UID,BANK_UID=网商会员角色ID,MYBANK_CARD_NO=网商卡号,样例内容是{"user_info_type":"ALIPAY_UID","user_info_id":"2088102146225135"},再进行urlencode,使用request_no查询时,该字段必传
*/
@ApiField("seller_info")
private String sellerInfo;
public String getBizChannel() {
return this.bizChannel;
}
public void setBizChannel(String bizChannel) {
this.bizChannel = bizChannel;
}
public String getBuyerInfo() {
return this.buyerInfo;
}
public void setBuyerInfo(String buyerInfo) {
this.buyerInfo = buyerInfo;
}
public String getOrderNo() {
return this.orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getRequestNo() {
return this.requestNo;
}
public void setRequestNo(String requestNo) {
this.requestNo = requestNo;
}
public String getSellerInfo() {
return this.sellerInfo;
}
public void setSellerInfo(String sellerInfo) {
this.sellerInfo = sellerInfo;
}
}
|
3e1ca5633ba3d189bf40dadb4b002d633402d3c6 | 3,723 | java | Java | DashboardApps/src/main/java/gov/noaa/pmel/dashboard/programs/GenerateOrigFileBundles.java | NOAA-PMEL/SOCAT | 54793c3ea0bae1a21eebbfa17ec2af266c065f55 | [
"Unlicense"
] | null | null | null | DashboardApps/src/main/java/gov/noaa/pmel/dashboard/programs/GenerateOrigFileBundles.java | NOAA-PMEL/SOCAT | 54793c3ea0bae1a21eebbfa17ec2af266c065f55 | [
"Unlicense"
] | null | null | null | DashboardApps/src/main/java/gov/noaa/pmel/dashboard/programs/GenerateOrigFileBundles.java | NOAA-PMEL/SOCAT | 54793c3ea0bae1a21eebbfa17ec2af266c065f55 | [
"Unlicense"
] | null | null | null | 37.23 | 112 | 0.581789 | 12,155 | /**
*
*/
package gov.noaa.pmel.dashboard.programs;
import gov.noaa.pmel.dashboard.handlers.ArchiveFilesBundler;
import gov.noaa.pmel.dashboard.server.DashboardConfigStore;
import gov.noaa.pmel.dashboard.server.DashboardServerUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.TreeSet;
/**
* Generates the original data file bundles for the specified dataset IDs
* without e-mailing them out. Intended for archival on release.
*
* @author Karl Smith
*/
public class GenerateOrigFileBundles {
/**
* Generates the original data file bundles for the specified dataset IDs.
* These bundles are added to the version control bundles directory,
* but not e-mailed to anyone.
*
* @param args
* IDsFile
* <p>
* where IDsFile is a file of IDs of datasets to generating original data file bundles for.
*/
public static void main(String[] args) {
if ( args.length != 1 ) {
System.err.println("Arguments: IDsFile");
System.err.println();
System.err.println("Generates original data file bundles for the dataset IDs specified ");
System.err.println("in IDsFile. These file bundles are added to the version control ");
System.err.println("bundles directory, but are not emailed to anyone. The default ");
System.err.println("dashboard configuration is used for this process. ");
System.err.println();
System.exit(1);
}
String idsFilename = args[0];
TreeSet<String> idsSet = new TreeSet<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(idsFilename));
try {
String dataline = reader.readLine();
while ( dataline != null ) {
dataline = dataline.trim();
if ( !(dataline.isEmpty() || dataline.startsWith("#")) )
idsSet.add(dataline);
dataline = reader.readLine();
}
} finally {
reader.close();
}
} catch ( Exception ex ) {
System.err.println("Error reading dataset IDs from " + idsFilename + ": " + ex.getMessage());
ex.printStackTrace();
System.exit(1);
}
DashboardConfigStore configStore = null;
try {
configStore = DashboardConfigStore.get(false);
} catch ( Exception ex ) {
System.err.println("Problems reading the default dashboard configuration file: " + ex.getMessage());
ex.printStackTrace();
System.exit(1);
}
boolean success = true;
try {
ArchiveFilesBundler filesBundler = configStore.getArchiveFilesBundler();
for (String datasetId : idsSet) {
String commitMsg = "Automated generation of the original data files bundle for " + datasetId;
try {
String resultMsg = filesBundler.sendOrigFilesBundle(datasetId, commitMsg,
DashboardServerUtils.NOMAIL_USER_REAL_NAME, DashboardServerUtils.NOMAIL_USER_EMAIL);
System.out.println(datasetId + " : " + resultMsg);
} catch ( IllegalArgumentException | IOException ex ) {
System.out.println(datasetId + " : " + "failed - " + ex.getMessage());
success = false;
}
}
} finally {
DashboardConfigStore.shutdown();
}
if ( !success )
System.exit(1);
System.exit(0);
}
}
|
3e1ca575ec22786e89c663a92880f09b421a3dc9 | 2,785 | java | Java | hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/web/ozShell/volume/GetAclVolumeHandler.java | 20100507/hadoop-ozone | 65043bf0ff4e9ad2f0b7a18972c599d38e77b6f4 | [
"Apache-2.0"
] | 1 | 2020-03-26T07:41:26.000Z | 2020-03-26T07:41:26.000Z | hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/web/ozShell/volume/GetAclVolumeHandler.java | 20100507/hadoop-ozone | 65043bf0ff4e9ad2f0b7a18972c599d38e77b6f4 | [
"Apache-2.0"
] | null | null | null | hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/web/ozShell/volume/GetAclVolumeHandler.java | 20100507/hadoop-ozone | 65043bf0ff4e9ad2f0b7a18972c599d38e77b6f4 | [
"Apache-2.0"
] | null | null | null | 34.382716 | 79 | 0.719928 | 12,156 | /*
* 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.hadoop.ozone.web.ozShell.volume;
import org.apache.hadoop.ozone.OzoneAcl;
import org.apache.hadoop.ozone.client.OzoneClient;
import org.apache.hadoop.ozone.security.acl.OzoneObj;
import org.apache.hadoop.ozone.security.acl.OzoneObjInfo;
import org.apache.hadoop.ozone.web.ozShell.Handler;
import org.apache.hadoop.ozone.web.ozShell.OzoneAddress;
import org.apache.hadoop.ozone.web.ozShell.Shell;
import org.apache.hadoop.ozone.web.utils.JsonUtils;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;
import java.util.List;
import static org.apache.hadoop.ozone.security.acl.OzoneObj.StoreType.OZONE;
/**
* Get acl handler for volume.
*/
@Command(name = "getacl",
description = "List all ACLs.")
public class GetAclVolumeHandler extends Handler {
@Parameters(arity = "1..1", description = Shell.OZONE_BUCKET_URI_DESCRIPTION)
private String uri;
@CommandLine.Option(names = {"--store", "-s"},
required = false,
description = "Store type. i.e OZONE or S3")
private String storeType;
/**
* Executes the Client Calls.
*/
@Override
public Void call() throws Exception {
OzoneAddress address = new OzoneAddress(uri);
address.ensureVolumeAddress();
try (OzoneClient client =
address.createClient(createOzoneConfiguration())) {
String volumeName = address.getVolumeName();
if (isVerbose()) {
System.out.printf("Volume Name : %s%n", volumeName);
}
OzoneObj obj = OzoneObjInfo.Builder.newBuilder()
.setVolumeName(volumeName)
.setResType(OzoneObj.ResourceType.VOLUME)
.setStoreType(storeType == null ? OZONE :
OzoneObj.StoreType.valueOf(storeType))
.build();
List<OzoneAcl> result = client.getObjectStore().getAcl(obj);
System.out.printf("%s%n",
JsonUtils.toJsonStringWithDefaultPrettyPrinter(result));
}
return null;
}
}
|
3e1ca60cc4ef40aee0b445846c56cd58a5f0a371 | 4,392 | java | Java | core/src/main/java/org/bitcoinj/crypto/X509Utils.java | OrestisKan/bitcoinj-frost | 97a004fd1474223b44d43045dcd27b3c5001cfef | [
"Apache-2.0"
] | 4,452 | 2015-01-03T17:48:32.000Z | 2022-03-31T11:13:50.000Z | core/src/main/java/org/bitcoinj/crypto/X509Utils.java | zengfr/bitcoinj | 1db44fb4f16ffc82790f397669078c8af5328de6 | [
"Apache-2.0"
] | 1,394 | 2015-01-01T18:50:31.000Z | 2022-03-31T21:48:53.000Z | core/src/main/java/org/bitcoinj/crypto/X509Utils.java | zengfr/bitcoinj | 1db44fb4f16ffc82790f397669078c8af5328de6 | [
"Apache-2.0"
] | 2,195 | 2015-01-01T17:47:13.000Z | 2022-03-30T13:00:14.000Z | 42.640777 | 151 | 0.6801 | 12,157 | /*
* Copyright 2014 The bitcoinj 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.bitcoinj.crypto;
import com.google.common.base.Joiner;
import org.bitcoinj.protocols.payments.PaymentSession;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1String;
import org.bouncycastle.asn1.x500.AttributeTypeAndValue;
import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.style.RFC4519Style;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.List;
/**
* X509Utils provides tools for working with X.509 certificates and keystores, as used in the BIP 70 payment protocol.
* For more details on this, see {@link PaymentSession}, the article "Working with
* the payment protocol" on the bitcoinj website, or the Bitcoin developer guide.
*/
public class X509Utils {
/**
* Returns either a string that "sums up" the certificate for humans, in a similar manner to what you might see
* in a web browser, or null if one cannot be extracted. This will typically be the common name (CN) field, but
* can also be the org (O) field, org+location+country if withLocation is set, or the email
* address for S/MIME certificates.
*/
@Nullable
public static String getDisplayNameFromCertificate(@Nonnull X509Certificate certificate, boolean withLocation) throws CertificateParsingException {
X500Name name = new X500Name(certificate.getSubjectX500Principal().getName());
String commonName = null, org = null, location = null, country = null;
for (RDN rdn : name.getRDNs()) {
AttributeTypeAndValue pair = rdn.getFirst();
String val = ((ASN1String) pair.getValue()).getString();
ASN1ObjectIdentifier type = pair.getType();
if (type.equals(RFC4519Style.cn))
commonName = val;
else if (type.equals(RFC4519Style.o))
org = val;
else if (type.equals(RFC4519Style.l))
location = val;
else if (type.equals(RFC4519Style.c))
country = val;
}
final Collection<List<?>> subjectAlternativeNames = certificate.getSubjectAlternativeNames();
String altName = null;
if (subjectAlternativeNames != null)
for (final List<?> subjectAlternativeName : subjectAlternativeNames)
if ((Integer) subjectAlternativeName.get(0) == 1) // rfc822name
altName = (String) subjectAlternativeName.get(1);
if (org != null) {
return withLocation ? Joiner.on(", ").skipNulls().join(org, location, country) : org;
} else if (commonName != null) {
return commonName;
} else {
return altName;
}
}
/** Returns a key store loaded from the given stream. Just a convenience around the Java APIs. */
public static KeyStore loadKeyStore(String keystoreType, @Nullable String keystorePassword, InputStream is)
throws KeyStoreException {
try {
KeyStore keystore = KeyStore.getInstance(keystoreType);
keystore.load(is, keystorePassword != null ? keystorePassword.toCharArray() : null);
return keystore;
} catch (IOException | GeneralSecurityException x) {
throw new KeyStoreException(x);
} finally {
try {
is.close();
} catch (IOException x) {
// Ignored.
}
}
}
}
|
3e1ca637603fc4776a970b9f0c98508d0e4d8e5b | 10,885 | java | Java | src/main/java/com/google/sps/servlets/PlanMailServlet.java | googleinterns/blueprint-step-2020 | cfd829f4ddc2242aa79998b5752b9161bbbf278c | [
"Apache-2.0"
] | 1 | 2020-06-22T16:46:36.000Z | 2020-06-22T16:46:36.000Z | src/main/java/com/google/sps/servlets/PlanMailServlet.java | googleinterns/step7-2020 | cfd829f4ddc2242aa79998b5752b9161bbbf278c | [
"Apache-2.0"
] | 87 | 2020-06-22T16:56:09.000Z | 2020-07-29T22:40:21.000Z | src/main/java/com/google/sps/servlets/PlanMailServlet.java | googleinterns/step7-2020 | cfd829f4ddc2242aa79998b5752b9161bbbf278c | [
"Apache-2.0"
] | 2 | 2020-08-07T19:20:39.000Z | 2020-08-15T20:07:09.000Z | 41.704981 | 100 | 0.733854 | 12,158 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.StringUtils;
import com.google.api.services.calendar.model.CalendarListEntry;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.gmail.model.Message;
import com.google.api.services.gmail.model.MessagePart;
import com.google.common.base.Throwables;
import com.google.common.io.BaseEncoding;
import com.google.sps.data.PlanMailResponse;
import com.google.sps.model.AuthenticatedHttpServlet;
import com.google.sps.model.AuthenticationVerifier;
import com.google.sps.model.CalendarClient;
import com.google.sps.model.CalendarClientFactory;
import com.google.sps.model.CalendarClientImpl;
import com.google.sps.model.GmailClient;
import com.google.sps.model.GmailClientFactory;
import com.google.sps.model.GmailClientImpl;
import com.google.sps.utility.DateInterval;
import com.google.sps.utility.FreeTimeUtility;
import com.google.sps.utility.JsonUtility;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.mail.MessagingException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* GET function responds JSON string containing potential events to read mail. The servlet proposes
* all possible event times until it is not possible. For now, the user does not get an indication
* if the events proposed are sufficient to go through the emails.
*/
@WebServlet("/plan-mail")
public class PlanMailServlet extends AuthenticatedHttpServlet {
private final CalendarClientFactory calendarClientFactory;
private final GmailClientFactory gmailClientFactory;
private static final int AVERAGE_READING_SPEED = 50;
private static final int PERSONAL_BEGIN_HOUR = 7;
private static final int WORK_BEGIN_HOUR = 10;
private static final int WORK_END_HOUR = 18;
private static final int PERSONAL_END_HOUR = 23;
private static final int NUM_DAYS = 5;
/** Create servlet with default CalendarClient and Authentication Verifier implementations */
public PlanMailServlet() {
calendarClientFactory = new CalendarClientImpl.Factory();
gmailClientFactory = new GmailClientImpl.Factory();
}
/**
* Create servlet with explicit implementations of CalendarClient and AuthenticationVerifier
*
* @param authenticationVerifier implementation of AuthenticationVerifier
* @param calendarClientFactory implementation of CalendarClientFactory
*/
public PlanMailServlet(
AuthenticationVerifier authenticationVerifier,
CalendarClientFactory calendarClientFactory,
GmailClientFactory gmailClientFactory) {
super(authenticationVerifier);
this.calendarClientFactory = calendarClientFactory;
this.gmailClientFactory = gmailClientFactory;
}
/**
* Returns string containing the some of the user's free time intervals, where events can be
* created
*
* @param request Http request from the client. Should contain idToken and accessToken
* @param response Json string with the user's events
* @throws IOException if an issue arises while processing the request
*/
@Override
public void doGet(
HttpServletRequest request, HttpServletResponse response, Credential googleCredential)
throws IOException {
assert googleCredential != null
: "Null credentials (i.e. unauthenticated requests) should already be handled";
CalendarClient calendarClient = calendarClientFactory.getCalendarClient(googleCredential);
long fiveDaysInMillis = TimeUnit.DAYS.toMillis(5);
Date timeMin = calendarClient.getCurrentTime();
Date timeMax = Date.from(timeMin.toInstant().plus(Duration.ofDays(NUM_DAYS)));
List<Event> calendarEvents = getEvents(calendarClient, timeMin, timeMax);
// Initialize the freeTime utility. Keep track of the free time in the next 5 days, with
// work hours as defined between 10am and 6 pm. The rest of the time between 7 am and 11 pm
// should be considered personal time.
FreeTimeUtility freeTimeUtility =
new FreeTimeUtility(
timeMin,
PERSONAL_BEGIN_HOUR,
WORK_BEGIN_HOUR,
WORK_END_HOUR,
PERSONAL_END_HOUR,
NUM_DAYS);
long preAssignedTime = 0;
// The summary for the events we are creating is the same as the defined eventSummary
// For now this is the check we are using. We assume that the user will not create
// events with the same summary if they are not related to reading emails.
String eventSummary = request.getParameter("summary");
for (Event event : calendarEvents) {
DateTime start = event.getStart().getDateTime();
start = start == null ? event.getStart().getDate() : start;
DateTime end = event.getEnd().getDateTime();
end = end == null ? event.getEnd().getDate() : end;
if (event.getSummary().equals(eventSummary)) {
preAssignedTime += end.getValue() - start.getValue();
}
Date eventStart = new Date(start.getValue());
Date eventEnd = new Date(end.getValue());
if (eventStart.before(timeMin)) {
eventStart = timeMin;
}
if (eventEnd.after(timeMax)) {
eventEnd = timeMax;
}
freeTimeUtility.addEvent(eventStart, eventEnd);
}
int wordCount = getWordCount(googleCredential);
int minutesToRead = (int) Math.ceil((double) wordCount / AVERAGE_READING_SPEED);
long timeNeeded = minutesToRead * TimeUnit.MINUTES.toMillis(1);
timeNeeded = Math.max(0, timeNeeded - preAssignedTime);
List<DateInterval> potentialTimes;
if (timeNeeded > 0) {
potentialTimes = getPotentialTimes(freeTimeUtility, timeNeeded);
} else {
potentialTimes = new ArrayList<>();
}
PlanMailResponse planMailResponse =
new PlanMailResponse(wordCount, AVERAGE_READING_SPEED, minutesToRead, potentialTimes);
// Convert event list to JSON and print to response
JsonUtility.sendJson(response, planMailResponse);
}
/**
* Get the list of date intervals necessary for the time needed If there is not enough time,
* return the maximum possible date intervals
*
* @param freeTimeUtility the utility to get all free date intervals
* @param timeNeeded the unix time of the time length needed
* @return The list of date intervals necessary
*/
private List<DateInterval> getPotentialTimes(FreeTimeUtility freeTimeUtility, long timeNeeded) {
List<DateInterval> workFreeInterval = freeTimeUtility.getWorkFreeInterval();
List<DateInterval> potentialEventTimes = new ArrayList<>();
long remainingTime = timeNeeded;
for (DateInterval interval : workFreeInterval) {
Date potentialEnd = new Date(interval.getStart().getTime() + remainingTime);
if (interval.getEnd().before(potentialEnd)) {
remainingTime -= (interval.getEnd().getTime() - interval.getStart().getTime());
potentialEventTimes.add(interval);
} else {
potentialEventTimes.add(new DateInterval(interval.getStart(), potentialEnd));
break;
}
}
return potentialEventTimes;
}
/**
* Get the unread emails from the last week, and perform a word count for the body of each message
*
* @param googleCredential the credential to creare a gmailClient with
* @return The final word count
* @throws IOException if an issue occurs in the method
* @throws MessagingException if an issue occurs in the method
*/
private int getWordCount(Credential googleCredential) {
GmailClient gmailClient = gmailClientFactory.getGmailClient(googleCredential);
GmailClient.MessageFormat messageFormat = GmailClient.MessageFormat.FULL;
int numberDays = 7;
int wordCount = 0;
List<Message> unreadMessages = new ArrayList<>();
try {
unreadMessages = gmailClient.getUnreadEmailsFromNDays(messageFormat, numberDays);
} catch (IOException e) {
throw Throwables.propagate(e);
}
for (Message message : unreadMessages) {
try {
wordCount += getMessageSize(message);
} catch (MessagingException | IOException e) {
throw Throwables.propagate(e);
}
}
return wordCount;
}
/**
* Get the events in the user's calendars
*
* @param calendarClient either a mock CalendarClient or a calendarClient with a valid credential
* @param timeMin the minimum time to start looking for events
* @param timeMax the maximum time to look for events
* @return List of Events from all of the user's calendars
* @throws IOException if an issue occurs in the method
*/
private List<Event> getEvents(CalendarClient calendarClient, Date timeMin, Date timeMax)
throws IOException {
List<CalendarListEntry> calendarList = calendarClient.getCalendarList();
List<Event> events = new ArrayList<>();
for (CalendarListEntry calendar : calendarList) {
events.addAll(calendarClient.getUpcomingEvents(calendar, timeMin, timeMax));
}
return events;
}
/**
* Get the word-count in an individual message.
*
* @param message the message given for which to find a word count
* @throws IOException if an issue occurs in the method
* @throws MessagingException if an issue occurs in the method
*/
private int getMessageSize(Message message) throws MessagingException, IOException {
List<MessagePart> messageParts = message.getPayload().getParts();
List<MessagePart> messageBody =
messageParts.stream()
.filter((messagePart) -> messagePart.getMimeType().equals("text/plain"))
.collect(Collectors.toList());
int size = 0;
if (messageBody.isEmpty()) {
return size;
}
for (MessagePart part : messageBody) {
byte[] messageBytes = BaseEncoding.base64Url().decode(part.getBody().getData());
String messageString = StringUtils.newStringUtf8(messageBytes);
StringTokenizer tokens = new StringTokenizer(messageString);
size += tokens.countTokens();
}
return size;
}
}
|
3e1ca674b4dd820f4c1154f3cf74c789df8c4fa0 | 9,793 | java | Java | Desktop/src/org/joeffice/desktop/WelcomeTopComponent.java | ptuanvu/Milktea | 1e60acd661e44b81fab7ae24ca07db85f7a2d941 | [
"Apache-2.0"
] | 5 | 2021-04-10T16:10:19.000Z | 2022-01-11T23:57:23.000Z | Desktop/src/org/joeffice/desktop/WelcomeTopComponent.java | ptuanvu/Milktea | 1e60acd661e44b81fab7ae24ca07db85f7a2d941 | [
"Apache-2.0"
] | null | null | null | Desktop/src/org/joeffice/desktop/WelcomeTopComponent.java | ptuanvu/Milktea | 1e60acd661e44b81fab7ae24ca07db85f7a2d941 | [
"Apache-2.0"
] | 6 | 2021-04-02T15:46:33.000Z | 2022-01-15T10:15:10.000Z | 50.220513 | 199 | 0.680895 | 12,159 | /*
* Copyright 2013 Japplis.
*
* 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.joeffice.desktop;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
/**
* Top component which displays a welcome page (disabled for the moment).
*/
@ConvertAsProperties(
dtd = "-//org.joeffice.desktop//Welcome//EN",
autostore = false)
@TopComponent.Description(
preferredID = "WelcomeTopComponent")
//iconBase="SET/PATH/TO/ICON/HERE",
//persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "org.joeffice.desktop.WelcomeTopComponent")
@ActionReference(path = "Menu/Help" , position = 350)
@TopComponent.OpenActionRegistration(
displayName = "#CTL_WelcomeAction",
preferredID = "WelcomeTopComponent")
@Messages({
"CTL_WelcomeAction=Welcome",
"CTL_WelcomeTopComponent=Welcome",
"HINT_WelcomeTopComponent=This is a Welcome window"
})
public final class WelcomeTopComponent extends TopComponent {
private boolean alwaysShow = true;
public WelcomeTopComponent() {
initComponents();
setName(Bundle.CTL_WelcomeTopComponent());
setToolTipText(Bundle.HINT_WelcomeTopComponent());
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
* content of this method is always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
welcomeLabel = new javax.swing.JLabel();
newButton = new javax.swing.JButton();
openButton = new javax.swing.JButton();
filterField = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
recentFilesList = new javax.swing.JList();
searchRecentFileLabel = new javax.swing.JLabel();
alwaysShowCheckbox = new javax.swing.JCheckBox();
welcomeLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
welcomeLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
org.openide.awt.Mnemonics.setLocalizedText(welcomeLabel, org.openide.util.NbBundle.getMessage(WelcomeTopComponent.class, "WelcomeTopComponent.welcomeLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(newButton, org.openide.util.NbBundle.getMessage(WelcomeTopComponent.class, "WelcomeTopComponent.newButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(openButton, org.openide.util.NbBundle.getMessage(WelcomeTopComponent.class, "WelcomeTopComponent.openButton.text")); // NOI18N
filterField.setText(org.openide.util.NbBundle.getMessage(WelcomeTopComponent.class, "WelcomeTopComponent.filterField.text")); // NOI18N
filterField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
filterFieldActionPerformed(evt);
}
});
jScrollPane1.setViewportView(recentFilesList);
org.openide.awt.Mnemonics.setLocalizedText(searchRecentFileLabel, org.openide.util.NbBundle.getMessage(WelcomeTopComponent.class, "WelcomeTopComponent.searchRecentFileLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(alwaysShowCheckbox, org.openide.util.NbBundle.getMessage(WelcomeTopComponent.class, "WelcomeTopComponent.alwaysShowCheckbox.text")); // NOI18N
alwaysShowCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
alwaysShowCheckboxActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(68, 68, 68)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(newButton)
.addComponent(openButton)))
.addComponent(alwaysShowCheckbox))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(84, 84, 84)
.addComponent(searchRecentFileLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(filterField, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(83, 83, 83)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))))
.addComponent(welcomeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(welcomeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(newButton)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(searchRecentFileLabel)
.addComponent(filterField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(openButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(alwaysShowCheckbox))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void filterFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_filterFieldActionPerformed
private void alwaysShowCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alwaysShowCheckboxActionPerformed
alwaysShow = alwaysShowCheckbox.isSelected();
}//GEN-LAST:event_alwaysShowCheckboxActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox alwaysShowCheckbox;
private javax.swing.JTextField filterField;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton newButton;
private javax.swing.JButton openButton;
private javax.swing.JList recentFilesList;
private javax.swing.JLabel searchRecentFileLabel;
private javax.swing.JLabel welcomeLabel;
// End of variables declaration//GEN-END:variables
@Override
public void componentOpened() {
// TODO add custom code on component opening
}
@Override
public void componentClosed() {
// TODO add custom code on component closing
}
@Override
public int getPersistenceType() {
if (alwaysShow) {
return TopComponent.PERSISTENCE_ALWAYS;
} else {
return TopComponent.PERSISTENCE_NEVER;
}
}
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
// TODO store your settings
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
}
}
|
3e1ca6c5cebfd443fb1f0cf898132497f362e2be | 842 | java | Java | im-client/src/main/java/edu/fdzc/im/client/handler/JoinGroupResponseHandler.java | ViicesCai/Netty-IM | b90d16edce31e98bbc1f6bae9630fed1ea62d138 | [
"MIT"
] | 2 | 2022-03-29T09:04:13.000Z | 2022-03-31T05:32:49.000Z | im-client/src/main/java/edu/fdzc/im/client/handler/JoinGroupResponseHandler.java | ViicesCai/Netty-IM | b90d16edce31e98bbc1f6bae9630fed1ea62d138 | [
"MIT"
] | null | null | null | im-client/src/main/java/edu/fdzc/im/client/handler/JoinGroupResponseHandler.java | ViicesCai/Netty-IM | b90d16edce31e98bbc1f6bae9630fed1ea62d138 | [
"MIT"
] | null | null | null | 33.68 | 144 | 0.731591 | 12,160 | package edu.fdzc.im.client.handler;
import edu.fdzc.im.common.protocol.chat.JoinGroupResponsePacket;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* 加入群聊响应控制器
*
* @author Viices Cai
* @time 2022/3/9
*/
public class JoinGroupResponseHandler extends SimpleChannelInboundHandler<JoinGroupResponsePacket> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, JoinGroupResponsePacket joinGroupResponsePacket) throws Exception {
if (joinGroupResponsePacket.getSuccess()) {
System.out.println("加入群 [ " + joinGroupResponsePacket.getGroupId() + " ] 成功!");
} else {
System.err.println("加入群 [ " + joinGroupResponsePacket.getGroupId() + " ] 失败,原因: " + joinGroupResponsePacket.getReason());
}
}
}
|
3e1ca6d3958c034f345bb722115e7a7b639aafca | 1,541 | java | Java | lore-user/user-domain/src/main/java/im/heart/usercore/entity/FrameUserRelate.java | LKG/lore | 28a76fcffeaf15c67299da382424cee579e09fc2 | [
"Apache-2.0"
] | 2 | 2018-12-16T16:08:32.000Z | 2018-12-16T16:08:35.000Z | lore-user/user-domain/src/main/java/im/heart/usercore/entity/FrameUserRelate.java | LKG/lore | 28a76fcffeaf15c67299da382424cee579e09fc2 | [
"Apache-2.0"
] | null | null | null | lore-user/user-domain/src/main/java/im/heart/usercore/entity/FrameUserRelate.java | LKG/lore | 28a76fcffeaf15c67299da382424cee579e09fc2 | [
"Apache-2.0"
] | 1 | 2020-02-20T03:28:03.000Z | 2020-02-20T03:28:03.000Z | 25.683333 | 93 | 0.750811 | 12,161 | package im.heart.usercore.entity;
import com.alibaba.fastjson.annotation.JSONField;
import im.heart.core.entity.AbstractEntity;
import lombok.Data;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigInteger;
import java.util.Date;
/**
*
* @author gg
* 用户关系表
*/
@Entity()
@Table(name = "dic_frame_user_relate")
@DynamicUpdate()
@DynamicInsert()
@Data
public class FrameUserRelate implements AbstractEntity<BigInteger> {
/**
*
*/
private static final long serialVersionUID = -9013579269873331336L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(length = 32, name = "RELATE_ID", nullable = false, unique = true, updatable = false)
private BigInteger relateId;
@NotNull
@Column(length = 32, name = "USER_ID", nullable = false, updatable = false)
private BigInteger userId;
@Column(length = 32, name = "RELATE_TYPE", nullable = false, updatable = false)
private String relateType;
@NotNull
@Column(length = 32, name = "RELATE_USER_ID", nullable = false, updatable = false)
private BigInteger relateUserId;
@JSONField(serialize = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "CREATE_TIME", nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date createTime;
@PrePersist
protected void onCreate() {
createTime = new Date();
}
}
|
3e1ca7182cc3ba3c19b03f1d5b191794e88de38d | 4,275 | java | Java | hermes-test-helper/src/main/java/pl/allegro/tech/hermes/test/helper/endpoint/HermesEndpoints.java | lukidzi/hermes | 051f0133b24b16f860d80b8069dbff7251d41132 | [
"Apache-2.0"
] | null | null | null | hermes-test-helper/src/main/java/pl/allegro/tech/hermes/test/helper/endpoint/HermesEndpoints.java | lukidzi/hermes | 051f0133b24b16f860d80b8069dbff7251d41132 | [
"Apache-2.0"
] | null | null | null | hermes-test-helper/src/main/java/pl/allegro/tech/hermes/test/helper/endpoint/HermesEndpoints.java | lukidzi/hermes | 051f0133b24b16f860d80b8069dbff7251d41132 | [
"Apache-2.0"
] | null | null | null | 33.398438 | 93 | 0.752047 | 12,162 | package pl.allegro.tech.hermes.test.helper.endpoint;
import pl.allegro.tech.hermes.api.Topic;
import pl.allegro.tech.hermes.api.endpoints.BlacklistEndpoint;
import pl.allegro.tech.hermes.api.endpoints.GroupEndpoint;
import pl.allegro.tech.hermes.api.endpoints.MigrationEndpoint;
import pl.allegro.tech.hermes.api.endpoints.OAuthProviderEndpoint;
import pl.allegro.tech.hermes.api.endpoints.OwnerEndpoint;
import pl.allegro.tech.hermes.api.endpoints.QueryEndpoint;
import pl.allegro.tech.hermes.api.endpoints.SchemaEndpoint;
import pl.allegro.tech.hermes.api.endpoints.SubscriptionEndpoint;
import pl.allegro.tech.hermes.api.endpoints.SubscriptionOwnershipEndpoint;
import pl.allegro.tech.hermes.api.endpoints.TopicEndpoint;
import pl.allegro.tech.hermes.api.endpoints.UnhealthyEndpoint;
import pl.allegro.tech.hermes.consumers.ConsumerEndpoint;
import pl.allegro.tech.hermes.test.helper.client.Hermes;
import java.util.List;
public class HermesEndpoints {
private final GroupEndpoint groupEndpoint;
private final TopicEndpoint topicEndpoint;
private final SubscriptionEndpoint subscriptionEndpoint;
private final SubscriptionOwnershipEndpoint subscriptionOwnershipEndpoint;
private final SchemaEndpoint schemaEndpoint;
private final QueryEndpoint queryEndpoint;
private final OAuthProviderEndpoint oAuthProviderEndpoint;
private final ConsumerEndpoint consumerEndpoint;
private final OwnerEndpoint ownerEndpoint;
private final BlacklistEndpoint blacklistEndpoint;
private final MigrationEndpoint migrationEndpoint;
public final UnhealthyEndpoint unhealthyEndpoint;
public HermesEndpoints(Hermes hermes) {
this.groupEndpoint = hermes.createGroupEndpoint();
this.topicEndpoint = hermes.createTopicEndpoint();
this.subscriptionEndpoint = hermes.createSubscriptionEndpoint();
this.subscriptionOwnershipEndpoint = hermes.createSubscriptionOwnershipEndpoint();
this.schemaEndpoint = hermes.createSchemaEndpoint();
this.queryEndpoint = hermes.createQueryEndpoint();
this.blacklistEndpoint = hermes.createBlacklistEndpoint();
this.oAuthProviderEndpoint = hermes.createOAuthProviderEndpoint();
this.consumerEndpoint = hermes.createConsumerEndpoint();
this.ownerEndpoint = hermes.createOwnerEndpoint();
this.migrationEndpoint = hermes.createMigrationEndpoint();
this.unhealthyEndpoint = hermes.unhealthyEndpoint();
}
public HermesEndpoints(String hermesFrontendUrl, String consumerUrl) {
this(createHermesFromUrl(hermesFrontendUrl, consumerUrl));
}
private static Hermes createHermesFromUrl(String hermesFrontendUrl, String consumerUrl) {
return new Hermes(hermesFrontendUrl, consumerUrl)
.withManagementConfig(JerseyClientFactory.createConfig())
.withPublisherConfig(JerseyClientFactory.createConfig());
}
public GroupEndpoint group() {
return groupEndpoint;
}
public TopicEndpoint topic() {
return topicEndpoint;
}
public SubscriptionEndpoint subscription() {
return subscriptionEndpoint;
}
public SubscriptionOwnershipEndpoint subscriptionOwnershipEndpoint() {
return subscriptionOwnershipEndpoint;
}
public SchemaEndpoint schema() {
return schemaEndpoint;
}
public QueryEndpoint query() {
return queryEndpoint;
}
public OwnerEndpoint owner() {
return ownerEndpoint;
}
public MigrationEndpoint migration() {
return migrationEndpoint;
}
public UnhealthyEndpoint unhealthyEndpoint() {
return unhealthyEndpoint;
}
public BlacklistEndpoint blacklist() {
return blacklistEndpoint;
}
public List<String> findTopics(Topic topic, boolean tracking) {
return topicEndpoint.list(topic.getName().getGroupName(), tracking);
}
public List<String> findSubscriptions(String group, String topic, boolean tracked) {
return subscriptionEndpoint.list(group + "." + topic, tracked);
}
public OAuthProviderEndpoint oAuthProvider() {
return oAuthProviderEndpoint;
}
public ConsumerEndpoint consumer() {
return consumerEndpoint;
}
}
|
3e1ca72e9f3140065de62627c55e081f1c44cd99 | 763 | java | Java | jslack-lightning/src/test/java/test_locally/AppTest.java | jeffbrown/jslack | 680e0618159116ca21870205deddaebaddcc3c60 | [
"MIT"
] | 1 | 2019-02-26T06:42:56.000Z | 2019-02-26T06:42:56.000Z | jslack-lightning/src/test/java/test_locally/AppTest.java | jeffbrown/jslack | 680e0618159116ca21870205deddaebaddcc3c60 | [
"MIT"
] | null | null | null | jslack-lightning/src/test/java/test_locally/AppTest.java | jeffbrown/jslack | 680e0618159116ca21870205deddaebaddcc3c60 | [
"MIT"
] | null | null | null | 27.25 | 57 | 0.626474 | 12,163 | package test_locally;
import com.github.seratch.jslack.lightning.App;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class AppTest {
@Test
public void status() {
App app = new App();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
assertThat(app.status(), is(App.Status.Running));
app.stop();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
assertThat(app.status(), is(App.Status.Running));
app.stop();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
app.start();
assertThat(app.status(), is(App.Status.Running));
}
}
|
3e1ca7ad870f2645bcc5877ba6de21f61cf1a6fb | 457 | java | Java | src/main/java/org/ultramine/bukkit/util/PluginClassRemapper.java | AspireWorld-Project/AspireCore | 61dfc4f6cc7bca4ed7fd4de1413b7c8030a72042 | [
"WTFPL"
] | null | null | null | src/main/java/org/ultramine/bukkit/util/PluginClassRemapper.java | AspireWorld-Project/AspireCore | 61dfc4f6cc7bca4ed7fd4de1413b7c8030a72042 | [
"WTFPL"
] | null | null | null | src/main/java/org/ultramine/bukkit/util/PluginClassRemapper.java | AspireWorld-Project/AspireCore | 61dfc4f6cc7bca4ed7fd4de1413b7c8030a72042 | [
"WTFPL"
] | null | null | null | 22.85 | 70 | 0.776805 | 12,164 | package org.ultramine.bukkit.util;
import net.md_5.specialsource.JarMapping;
import net.md_5.specialsource.JarRemapper;
public class PluginClassRemapper extends JarRemapper {
public PluginClassRemapper(JarMapping jarMapping) {
super(jarMapping);
}
@Override
public String mapSignature(String signature, boolean typeSignature) {
try {
return super.mapSignature(signature, typeSignature);
} catch (Exception e) {
return signature;
}
}
}
|
3e1ca8c99214f430b03948a6afe954dde253c645 | 1,527 | java | Java | src/main/java/de/flapdoodle/os/linux/RedhatVersion.java | bernermic/de.flapdoodle.os | 5a88926e2c1aaa341987b33dd44bf840b71c2213 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/flapdoodle/os/linux/RedhatVersion.java | bernermic/de.flapdoodle.os | 5a88926e2c1aaa341987b33dd44bf840b71c2213 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/flapdoodle/os/linux/RedhatVersion.java | bernermic/de.flapdoodle.os | 5a88926e2c1aaa341987b33dd44bf840b71c2213 | [
"Apache-2.0"
] | null | null | null | 32.510638 | 75 | 0.763089 | 12,165 | /*
* Copyright (C) 2020
* Michael Mosmann <kenaa@example.com>
*
* 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.flapdoodle.os.linux;
import de.flapdoodle.os.Version;
import de.flapdoodle.os.common.HasPecularities;
import de.flapdoodle.os.common.OneOf;
import de.flapdoodle.os.common.Peculiarity;
import de.flapdoodle.os.common.attributes.Attribute;
import de.flapdoodle.os.common.types.OsReleaseFile;
import java.util.List;
import static de.flapdoodle.os.linux.OsReleaseFiles.versionMatches;
public enum RedhatVersion implements Version {
Redhat_6(versionMatches(OsReleaseFiles.osReleaseFile(),"6")),
Redhat_7(versionMatches(OsReleaseFiles.osReleaseFile(),"7")),
Redhat_8(versionMatches(OsReleaseFiles.osReleaseFile(),"8")),
;
private final List<Peculiarity> peculiarities;
RedhatVersion(Peculiarity... peculiarities) {
this.peculiarities = HasPecularities.asList(peculiarities);
}
@Override
public List<Peculiarity> pecularities() {
return peculiarities;
}
}
|
3e1ca9cc7c06d7417f821a379973366fe2f4019f | 939 | java | Java | src/main/java/io/tiler/internal/queries/clauses/points/SortClause.java | tiler-project/tiler | a84f5a4e5fb50c83fc11b322f25a3bca66cc139c | [
"MIT"
] | 1 | 2021-04-10T17:20:04.000Z | 2021-04-10T17:20:04.000Z | src/main/java/io/tiler/internal/queries/clauses/points/SortClause.java | tiler-project/tiler | a84f5a4e5fb50c83fc11b322f25a3bca66cc139c | [
"MIT"
] | 3 | 2015-07-06T19:18:21.000Z | 2015-08-28T21:42:10.000Z | src/main/java/io/tiler/internal/queries/clauses/points/SortClause.java | tiler-project/tiler | a84f5a4e5fb50c83fc11b322f25a3bca66cc139c | [
"MIT"
] | null | null | null | 33.535714 | 89 | 0.789137 | 12,166 | package io.tiler.internal.queries.clauses.points;
import io.tiler.core.json.JsonArrayIterable;
import io.tiler.internal.queries.EvaluationException;
import io.tiler.internal.queries.clauses.BaseSortClause;
import io.tiler.internal.queries.clauses.SortExpression;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import java.time.Clock;
import java.util.ArrayList;
public class SortClause extends BaseSortClause {
public SortClause(ArrayList<SortExpression> sortExpressions) {
super(sortExpressions);
}
public void applyToMetrics(Clock clock, JsonArray metrics) throws EvaluationException {
for (JsonObject metric : new JsonArrayIterable<JsonObject>(metrics)) {
applyToPoints(clock, metric);
}
}
private void applyToPoints(Clock clock, JsonObject metric) throws EvaluationException {
metric.putArray("points", applyToItems(clock, metric.getArray("points")));
}
}
|
3e1ca9edf59618add07a988ba5e73cf6c7681cef | 5,430 | java | Java | newEff/224.basic-calculator.java | shaowei-su/shaowei-su.github.io | 8e9d21d4811a78a1f025eb48d73fabd1539a62ad | [
"MIT"
] | null | null | null | newEff/224.basic-calculator.java | shaowei-su/shaowei-su.github.io | 8e9d21d4811a78a1f025eb48d73fabd1539a62ad | [
"MIT"
] | null | null | null | newEff/224.basic-calculator.java | shaowei-su/shaowei-su.github.io | 8e9d21d4811a78a1f025eb48d73fabd1539a62ad | [
"MIT"
] | null | null | null | 25.492958 | 97 | 0.38674 | 12,167 | import java.util.*;
/*
* @lc app=leetcode id=224 lang=java
*
* [224] Basic Calculator
*
* https://leetcode.com/problems/basic-calculator/description/
*
* algorithms
* Hard (31.18%)
* Total Accepted: 94.3K
* Total Submissions: 298.4K
* Testcase Example: '"1 + 1"'
*
* Implement a basic calculator to evaluate a simple expression string.
*
* The expression string may contain open ( and closing parentheses ), the plus
* + or minus sign -, non-negative integers and empty spaces .
*
* Example 1:
*
*
* Input: "1 + 1"
* Output: 2
*
*
* Example 2:
*
*
* Input: " 2-1 + 2 "
* Output: 3
*
* Example 3:
*
*
* Input: "(1+(4+5+2)-3)+(6+8)"
* Output: 23
* Note:
*
*
* You may assume that the given expression is always valid.
* Do not use the eval built-in library function.
*
*
*/
class Solution {
public int calculate(String s) {
Deque<Integer> stack = new LinkedList<>();
int num = 0;
int pos = 0;
char sign = '+';
while (pos < s.length()) {
char cur = s.charAt(pos);
if (Character.isDigit(cur)) {
num = num * 10 + (cur - '0');
}
if (cur == '(') {
int close = findClose(s, pos + 1);
num = calculate(s.substring(pos + 1, close));
pos = close;
}
if ((!Character.isDigit(cur) && cur != ' ' && cur != '(') || pos == s.length() - 1) {
if (sign == '+') {
stack.push(num);
} else if (sign == '-') {
stack.push(-num);
} else if (sign == '*') {
stack.push(stack.pop() * num);
} else if (sign == '/') {
stack.push(stack.pop() / num);
}
sign = cur;
num = 0;
}
pos++;
}
int res = 0;
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}
public int findClose(String s, int start) {
int count = 1;
for (int i = start; i < s.length(); i++) {
if (s.charAt(i) == '(') {
count++;
} else if (s.charAt(i) == ')') {
count--;
}
if (count == 0) {
return i;
}
}
return -1;
}
public int calculate3(String s) {
Deque<Integer> stack = new LinkedList<>();
int sign = 1;
int num = 0;
int res = 0;
int pos = 0;
while (pos < s.length()) {
char cur = s.charAt(pos);
if (Character.isDigit(cur)) {
num = num * 10 + (cur - '0');
} else if (cur == '+') {
res += sign * num;
sign = 1;
num = 0;
} else if (cur == '-') {
res += sign * num;
sign = -1;
num = 0;
} else if (cur == '(') {
stack.push(res);
stack.push(sign);
sign = 1;
num = 0;
res = 0;
} else if (cur == ')') {
res += sign * num;
num = 0;
res *= stack.pop();
res += stack.pop();
}
pos++;
}
if (num != 0) {
res += sign * num;
}
return res;
}
public int calculate2(String s) {
if (s == null || s.length() == 0) {
return 0;
}
s = s.trim();
s = s.replaceAll("\\s+", "");
Deque<String> stack = new LinkedList<>();
int res = 0;
int pos = 0;
int temp = 0;
boolean set = false;
while (pos < s.length()) {
char cur = s.charAt(pos);
switch (cur) {
case '+':
case '-':
case '(':
if (set) {
stack.push(String.valueOf(temp));
temp = 0;
set = false;
}
stack.push(String.valueOf(cur));
break;
case ')':
stack.push(String.valueOf(temp));
temp = 0;
set = false;
int val = compute(stack);
stack.push(String.valueOf(val));
break;
default:
temp = temp * 10 + (cur - '0');
set = true;
break;
}
pos++;
}
if (set) {
stack.push(String.valueOf(temp));
}
return compute(stack);
}
public static void main(String[] args) {
Solution sol = new Solution();
sol.calculate("(1 + (4 + 5 + 2) - 3) + (6 + 8)");
}
public int compute(Deque<String> stack) {
int res = 0;
while (stack.size() > 0 && !stack.peek().equals("(")) {
int val = Integer.parseInt(stack.pop());
if (stack.size() > 0) {
String top = stack.peek();
if (top.equals("+")) {
stack.pop();
} else if (top.equals("-")) {
val = -val;
stack.pop();
}
}
res += val;
}
if (stack.size() > 0 && stack.peek().equals("(")) stack.pop();
return res;
}
}
|
3e1caa0314f50bf0b29b518cdf5b1de9c45596d1 | 3,921 | java | Java | current/logic/test/org/pimslims/utils/testmodel/TargetManagementModelObjTest.java | chrishmorris/PiMS | cdcc1a5b17b6753a11081bf7163f77596831916c | [
"BSD-2-Clause"
] | null | null | null | current/logic/test/org/pimslims/utils/testmodel/TargetManagementModelObjTest.java | chrishmorris/PiMS | cdcc1a5b17b6753a11081bf7163f77596831916c | [
"BSD-2-Clause"
] | null | null | null | current/logic/test/org/pimslims/utils/testmodel/TargetManagementModelObjTest.java | chrishmorris/PiMS | cdcc1a5b17b6753a11081bf7163f77596831916c | [
"BSD-2-Clause"
] | null | null | null | 36.990566 | 119 | 0.671002 | 12,168 | /*
* Created on 30.06.2005
*/
package org.pimslims.utils.testmodel;
import org.pimslims.metamodel.ModelObject;
import org.pimslims.model.core.BookCitation;
import org.pimslims.model.core.Citation;
import org.pimslims.model.core.ConferenceCitation;
import org.pimslims.model.core.JournalCitation;
import org.pimslims.model.core.ThesisCitation;
// was import org.pimslims.model.target.GenomicProject;
/**
* Test model classes which concern Target management implementation.
*
* @author Petr Troshin
*/
public class TargetManagementModelObjTest {
/**
*
*/
private TargetManagementModelObjTest() { /* empty */
}
public static void main(final String[] args) {
final ModelObjectsTest mot = new ModelObjectsTest(ModelObjectsTest.logLevelNull);
// Nothing should be created since Citation is Abstract class
mot.constructModelObject(Citation.class.getName(), true);
ModelObject mobj = mot.constructModelObject(BookCitation.class.getName(), true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject(JournalCitation.class.getName(), true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject(ConferenceCitation.class.getName(), true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject(ThesisCitation.class.getName(), true);
mot.resetValues(mobj, true);
// mobj = mot.constructModelObject(Molecule.class.getName(), true);
// mot.resetValues(mobj, true);
mobj = mot.constructModelObject("org.pimslims.model.people.Person", true);
// java.lang.ClassCastException
// at
// org.pimslims.implementation.ConstraintFactory$3.verify(ConstraintFactory.java:96)
// mot.resetValues(mobj, true);
mobj = mot.constructModelObject("org.pimslims.model.sample.Sample", true);
mot.resetValues(mobj, true);
/*
* TODO test org.pimslims.model.target.Project mobj = mot.constructModelObject(GenomicProject.class.getName(),
* true); mot.resetValues(mobj, true);
*/
mobj = mot.constructModelObject("org.pimslims.model.people.Organisation", true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject("org.pimslims.model.core.ExternalDbLink", true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject("org.pimslims.model.reference.Organism", true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject("org.pimslims.model.sample.RefSample", true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject("org.pimslims.model.sample.Holder", true);
mot.resetValues(mobj, true);
/* mobj = mot.constructModelObject("org.pimslims.model.sample.CrystalSample", true);
mot.resetValues(mobj, true); */
mobj = mot.constructModelObject("org.pimslims.model.refSampleComponent.Cell", true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject("org.pimslims.model.reference.ComponentCategory", true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject("org.pimslims.model.molecule.Molecule", true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject("org.pimslims.model.reference.HazardPhrase", true);
mot.resetValues(mobj, true);
mobj = mot.constructModelObject("org.pimslims.model.target.ResearchObjective", true);
mot.resetValues(mobj, true);
mot.setLogLevel(ModelObjectsTest.logLevelDebug);
// Protocol test
mobj = mot.constructModelObject(org.pimslims.model.protocol.Protocol.class.getName(), true, true, 1);
// mot.resetValues(mobj, true);
mot.setLogLevel(ModelObjectsTest.logLevelInfo);
}
}
|
3e1caa2aae867c4017766476702a9a5d3b9c15ca | 2,217 | java | Java | src/org/hedhman/pony/idea/formatter/PonyParamPatternBlock.java | niclash/pony-idea-plugin | 581899af671e8ef97805156f70bbe52e85b8f171 | [
"Apache-2.0"
] | 4 | 2020-07-08T08:19:33.000Z | 2021-06-28T15:22:44.000Z | src/org/hedhman/pony/idea/formatter/PonyParamPatternBlock.java | niclash/pony-idea-plugin | 581899af671e8ef97805156f70bbe52e85b8f171 | [
"Apache-2.0"
] | null | null | null | src/org/hedhman/pony/idea/formatter/PonyParamPatternBlock.java | niclash/pony-idea-plugin | 581899af671e8ef97805156f70bbe52e85b8f171 | [
"Apache-2.0"
] | 1 | 2020-07-08T08:19:35.000Z | 2020-07-08T08:19:35.000Z | 36.95 | 119 | 0.605774 | 12,169 | package org.hedhman.pony.idea.formatter;
import com.intellij.formatting.Alignment;
import com.intellij.formatting.Block;
import com.intellij.formatting.SpacingBuilder;
import com.intellij.lang.ASTNode;
import java.util.ArrayList;
import java.util.List;
import org.hedhman.pony.idea.generated.parsing.PonyTypes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.hedhman.pony.idea.formatter.PonyFormattingModelBuilder.handleCommentAndWhitespaceBlock;
public class PonyParamPatternBlock extends AbstractPonyBlock
implements Block
{
public PonyParamPatternBlock( @NotNull ASTNode node, @Nullable Alignment alignment, SpacingBuilder spacingBuilder )
{
super( node, null, alignment, spacingBuilder );
}
@Override
protected List<Block> buildChildren()
{
List<Block> blocks = new ArrayList<>();
ASTNode child = myNode.getFirstChildNode();
while( child != null )
{
if( handleCommentAndWhitespaceBlock( blocks, child, getAlignment(), spacingBuilder ) )
{
Block block;
if( child.getElementType() == PonyTypes.PARAMPATTERN )
{
block = new PonyParamPatternBlock( child, getAlignment(), spacingBuilder );
}
else if( child.getElementType() == PonyTypes.NEXTPARAMPATTERN )
{
block = new PonyParamPatternBlock( child, getAlignment(), spacingBuilder );
}
else if( child.getElementType() == PonyTypes.POSTFIX )
{
block = new PonyPostFixBlock( child, getAlignment(), spacingBuilder );
}
else if( child.getElementType() == PonyTypes.NEXTPOSTFIX )
{
block = new PonyPostFixBlock( child, getAlignment(), spacingBuilder );
}
else
{
block = new PonyTokenBlock( child, getAlignment(), spacingBuilder );
}
blocks.add( block );
}
child = child.getTreeNext();
}
return blocks;
}
}
|
3e1caaa7be252c83c45a00ed49e379bc33301a73 | 5,773 | java | Java | src/main/java/amu/zhcet/core/admin/dean/edit/StudentEditService.java | zhcet-amu/zhcet-web | 57e3646f11940e2292b512fb0a51c4d3a657839c | [
"Apache-2.0"
] | 17 | 2018-03-09T13:38:07.000Z | 2021-07-21T10:34:12.000Z | src/main/java/amu/zhcet/core/admin/dean/edit/StudentEditService.java | zhcet-amu/zhcet-web | 57e3646f11940e2292b512fb0a51c4d3a657839c | [
"Apache-2.0"
] | 115 | 2017-10-18T18:40:32.000Z | 2021-09-29T17:23:09.000Z | src/main/java/amu/zhcet/core/admin/dean/edit/StudentEditService.java | zhcet-amu/zhcet-web | 57e3646f11940e2292b512fb0a51c4d3a657839c | [
"Apache-2.0"
] | 15 | 2017-10-20T18:11:00.000Z | 2019-10-29T15:43:02.000Z | 42.448529 | 149 | 0.693054 | 12,170 | package amu.zhcet.core.admin.dean.edit;
import amu.zhcet.common.error.DuplicateException;
import amu.zhcet.data.department.Department;
import amu.zhcet.data.department.DepartmentService;
import amu.zhcet.data.user.User;
import amu.zhcet.data.user.UserService;
import amu.zhcet.data.user.student.HallCode;
import amu.zhcet.data.user.student.Student;
import amu.zhcet.data.user.student.StudentService;
import amu.zhcet.data.user.student.StudentStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.EnumUtils;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
@Slf4j
@Service
class StudentEditService {
private static final int MAXIMUM_STUDENT_UPDATE_SIZE = 200;
private final ModelMapper modelMapper;
private final UserService userService;
private final StudentService studentService;
private final DepartmentService departmentService;
public StudentEditService(ModelMapper modelMapper, UserService userService, StudentService studentService, DepartmentService departmentService) {
this.modelMapper = modelMapper;
this.userService = userService;
this.studentService = studentService;
this.departmentService = departmentService;
}
public StudentEditModel fromStudent(Student student) {
StudentEditModel studentEditModel = modelMapper.map(student, StudentEditModel.class);
studentEditModel.setHasTotpSecret(student.getUser().hasTotpSecret());
return studentEditModel;
}
@Transactional
public void saveStudent(Student student, StudentEditModel studentEditModel) {
Department department = ModelEditUtils.verifyDepartment(studentEditModel.getUserDepartmentName(), departmentService::findByName);
checkFacultyNumber(student, studentEditModel);
studentEditModel.setUserEmail(ModelEditUtils.verifyNewEmail(
student::getUser,
studentEditModel::getUserEmail,
userService::checkDuplicateEmail
));
checkHallCode(studentEditModel);
checkStatus(studentEditModel);
student.getUser().setDepartment(department);
modelMapper.map(studentEditModel, student);
if (student.getUser().getTotpDetails() != null && student.getUser().getTotpDetails().getUserId() == null) {
// The TOTP details are detached, hence we should not save the TOTP model
student.getUser().setTotpDetails(null);
}
studentService.save(student);
}
private void checkFacultyNumber(Student student, StudentEditModel studentEditModel) {
String facultyNumber = studentEditModel.getFacultyNumber();
studentService.getByFacultyNumber(facultyNumber)
.map(Student::getUser)
.map(User::getUserId)
.filter(id -> !id.equals(student.getUser().getUserId()))
.ifPresent(duplicate -> {
log.warn("Tried to save student with duplicate faculty number {} -> {} (existing)", facultyNumber, duplicate);
throw new DuplicateException("Student", "Faculty Number", facultyNumber, studentEditModel);
});
}
private static void checkHallCode(StudentEditModel studentEditModel) {
checkMemberShip(HallCode.class, studentEditModel.getHallCode(),
"Hall Code", studentEditModel.getFacultyNumber());
}
private static void checkStatus(StudentEditModel studentEditModel) {
checkMemberShip(StudentStatus.class, String.valueOf(studentEditModel.getStatus()),
"Status", studentEditModel.getFacultyNumber());
}
private static <E extends Enum<E>> void checkMemberShip(Class<E> enumClass, String string, String label, String identifier) {
if (!EnumUtils.isValidEnum(enumClass, string)) {
log.warn("Tried to save student with invalid status {} {}", identifier, string);
throw new IllegalArgumentException("Invalid " + label + " : " + string + ". Must be within " + EnumUtils.getEnumMap(enumClass).keySet());
}
}
private void studentConsumer(List<String> enrolments, Consumer<Student> consumer) {
enrolments.stream()
.map(studentService::getByEnrolmentNumber)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(student -> {
consumer.accept(student);
studentService.save(student);
});
}
private static void checkStudentsSize(List<String> items) {
if (items.size() > MAXIMUM_STUDENT_UPDATE_SIZE)
throw new IllegalArgumentException("Cannot update more than " + MAXIMUM_STUDENT_UPDATE_SIZE + " students at a time");
}
@Transactional
public void changeSections(List<String> enrolments, String section) {
checkStudentsSize(enrolments);
if (section == null || section.length() < 3)
throw new IllegalArgumentException("Section should be of at least 3 characters");
log.debug("Changing sections of {} to {}", enrolments, section);
studentConsumer(enrolments, student -> student.setSection(section));
}
@Transactional
public void changeStatuses(List<String> enrolments, String status) {
checkStudentsSize(enrolments);
if (status == null || status.length() != 1)
throw new IllegalArgumentException("Status should be of 1 character");
log.debug("Changing statuses of {} to {}", enrolments, status);
studentConsumer(enrolments, student -> student.setStatus(status.charAt(0)));
}
}
|
3e1caafffa579dd83a30e173b49afbf6f54f4e15 | 3,030 | java | Java | plugin-infra/plugin-metadata-store/src/main/java/com/thoughtworks/go/plugin/access/packagematerial/PackageConfigurations.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 5,865 | 2015-01-02T04:24:52.000Z | 2022-03-31T11:00:46.000Z | plugin-infra/plugin-metadata-store/src/main/java/com/thoughtworks/go/plugin/access/packagematerial/PackageConfigurations.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 5,972 | 2015-01-02T10:20:42.000Z | 2022-03-31T20:17:09.000Z | plugin-infra/plugin-metadata-store/src/main/java/com/thoughtworks/go/plugin/access/packagematerial/PackageConfigurations.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 998 | 2015-01-01T18:02:09.000Z | 2022-03-28T21:20:50.000Z | 36.95122 | 135 | 0.745215 | 12,171 | /*
* Copyright 2021 ThoughtWorks, 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.thoughtworks.go.plugin.access.packagematerial;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.thoughtworks.go.plugin.api.config.PluginPreference;
import com.thoughtworks.go.plugin.api.config.Property;
import com.thoughtworks.go.plugin.api.material.packagerepository.RepositoryConfiguration;
public class PackageConfigurations implements PluginPreference {
private List<PackageConfiguration> packageConfigurations = new ArrayList<>();
private RepositoryConfiguration repositoryConfiguration;
private com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration;
public PackageConfigurations() {
}
public PackageConfigurations(RepositoryConfiguration repositoryConfiguration) {
this.repositoryConfiguration = repositoryConfiguration;
for (Property property : repositoryConfiguration.list()) {
packageConfigurations.add(new PackageConfiguration(property));
}
}
public PackageConfigurations(com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration) {
this.packageConfiguration = packageConfiguration;
for (Property property : packageConfiguration.list()) {
packageConfigurations.add(new PackageConfiguration(property));
}
}
public void add(PackageConfiguration packageConfiguration) {
packageConfigurations.add(packageConfiguration);
}
public PackageConfiguration get(String key) {
for (PackageConfiguration packageConfiguration : packageConfigurations) {
if (packageConfiguration.getKey().equals(key)) {
return packageConfiguration;
}
}
return null;
}
public void addConfiguration(PackageConfiguration packageConfiguration) {
packageConfigurations.add(packageConfiguration);
}
public int size() {
return packageConfigurations.size();
}
public List<PackageConfiguration> list() {
Collections.sort(packageConfigurations);
return packageConfigurations;
}
public RepositoryConfiguration getRepositoryConfiguration() {
return repositoryConfiguration;
}
public com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration getPackageConfiguration() {
return packageConfiguration;
}
}
|
3e1cab3877aaffec4cf71b235285637c41eddfeb | 5,493 | java | Java | exec/java-exec/src/main/java/org/apache/drill/exec/physical/resultSet/impl/ContainerState.java | idvp-project/drill | 94e86d19407b0a66cfe432f45fb91a880eae4ea9 | [
"Apache-2.0"
] | 1,510 | 2015-01-04T01:35:19.000Z | 2022-03-28T23:36:02.000Z | exec/java-exec/src/main/java/org/apache/drill/exec/physical/resultSet/impl/ContainerState.java | idvp-project/drill | 94e86d19407b0a66cfe432f45fb91a880eae4ea9 | [
"Apache-2.0"
] | 1,979 | 2015-01-28T03:18:38.000Z | 2022-03-31T13:49:32.000Z | exec/java-exec/src/main/java/org/apache/drill/exec/physical/resultSet/impl/ContainerState.java | idvp-project/drill | 94e86d19407b0a66cfe432f45fb91a880eae4ea9 | [
"Apache-2.0"
] | 940 | 2015-01-01T01:39:39.000Z | 2022-03-25T08:46:59.000Z | 33.907407 | 112 | 0.724194 | 12,172 | /*
* 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.drill.exec.physical.resultSet.impl;
import java.util.Collection;
import org.apache.drill.exec.physical.resultSet.ResultVectorCache;
import org.apache.drill.exec.record.metadata.ColumnMetadata;
/**
* Abstract representation of a container of vectors: a row, a map, a
* repeated map, a list or a union.
* <p>
* The container is responsible for creating new columns in response
* from a writer listener event. Column creation requires a set of
* four items:
* <ul>
* <li>The value vector (which may be null if the column is not
* projected.</li>
* <li>The writer for the column.</li>
* <li>A vector state that manages allocation, overflow, cleanup
* and other vector-specific tasks.</li>
* <li>A column state which orchestrates the above three items.</li>
* <ul>
*/
public abstract class ContainerState {
protected final LoaderInternals loader;
protected final ProjectionFilter projectionSet;
protected ColumnState parentColumn;
/**
* Vector cache for this loader.
* {@see ResultSetOptionBuilder#setVectorCache()}.
*/
protected final ResultVectorCache vectorCache;
public ContainerState(LoaderInternals loader, ResultVectorCache vectorCache, ProjectionFilter projectionSet) {
this.loader = loader;
this.vectorCache = vectorCache;
this.projectionSet = projectionSet;
}
public ContainerState(LoaderInternals loader, ResultVectorCache vectorCache) {
this(loader, vectorCache, ProjectionFilter.PROJECT_ALL);
}
public void bindColumnState(ColumnState parentState) {
this.parentColumn = parentState;
}
public abstract int innerCardinality();
protected abstract void addColumn(ColumnState colState);
protected abstract Collection<ColumnState> columnStates();
protected ProjectionFilter projection() { return projectionSet; }
/**
* Reports whether this container is subject to version management. Version
* management adds columns to the output container at harvest time based on
* whether they should appear in the output batch.
*
* @return {@code true} if versioned
*/
protected abstract boolean isVersioned();
protected LoaderInternals loader() { return loader; }
public ResultVectorCache vectorCache() { return vectorCache; }
public ColumnState addColumn(ColumnMetadata columnSchema) {
// Create the vector, writer and column state
ColumnState colState = loader.columnBuilder().buildColumn(this, columnSchema);
// Add the column to this container
addColumn(colState);
// Set initial cardinality
colState.updateCardinality(innerCardinality());
// Allocate vectors if a batch is in progress.
if (loader().writeable()) {
colState.allocateVectors();
}
return colState;
}
/**
* In order to allocate the correct-sized vectors, the container must know
* its member cardinality: the number of elements in each row. This
* is 1 for a single map or union, but may be any number for a map array
* or a list. Then,
* this value is recursively pushed downward to compute the cardinality
* of lists of maps that contains lists of maps, and so on.
*/
public void updateCardinality() {
int innerCardinality = innerCardinality();
assert innerCardinality > 0;
for (ColumnState colState : columnStates()) {
colState.updateCardinality(innerCardinality);
}
}
/**
* Start a new batch by shifting the overflow buffers back into the main
* write vectors and updating the writers.
*/
public void startBatch(boolean schemaOnly) {
for (ColumnState colState : columnStates()) {
colState.startBatch(schemaOnly);
}
}
/**
* A column within the row batch overflowed. Prepare to absorb the rest of the
* in-flight row by rolling values over to a new vector, saving the complete
* vector for later. This column could have a value for the overflow row, or
* for some previous row, depending on exactly when and where the overflow
* occurs.
*/
public void rollover() {
for (ColumnState colState : columnStates()) {
colState.rollover();
}
}
/**
* Writing of a row batch is complete, and an overflow occurred. Prepare the
* vector for harvesting to send downstream. Set aside the look-ahead vector
* and put the full vector buffer back into the active vector.
*/
public void harvestWithLookAhead() {
for (ColumnState colState : columnStates()) {
colState.harvestWithLookAhead();
}
}
/**
* Clean up state (such as backup vectors) associated with the state
* for each vector.
*/
public void close() {
for (ColumnState colState : columnStates()) {
colState.close();
}
}
}
|
3e1cac1e8bd972b3d1d4803523f71e6e38c9ac06 | 5,610 | java | Java | plugin/src/com/zeus/eclipsePlugin/editor/presentation/TrafficScriptWordRule.java | brocade/vTM-eclipse | 1a88f1bd2efdeaf0bc91ed0138e1da0bcca97e5e | [
"BSD-3-Clause"
] | 4 | 2016-12-27T20:19:49.000Z | 2019-08-09T23:09:07.000Z | plugin/src/com/zeus/eclipsePlugin/editor/presentation/TrafficScriptWordRule.java | brocade/vTM-eclipse | 1a88f1bd2efdeaf0bc91ed0138e1da0bcca97e5e | [
"BSD-3-Clause"
] | null | null | null | plugin/src/com/zeus/eclipsePlugin/editor/presentation/TrafficScriptWordRule.java | brocade/vTM-eclipse | 1a88f1bd2efdeaf0bc91ed0138e1da0bcca97e5e | [
"BSD-3-Clause"
] | 4 | 2015-11-17T12:13:26.000Z | 2019-08-19T16:59:23.000Z | 33.195266 | 88 | 0.600178 | 12,173 | /*******************************************************************************
* Copyright (C) 2015 Brocade Communications Systems, Inc.
* 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
* https://github.com/brocade/vTM-eclipse/LICENSE
* This software is distributed "AS IS".
*
* Contributors:
* Brocade Communications Systems - Main Implementation
******************************************************************************/
package com.zeus.eclipsePlugin.editor.presentation;
import java.util.Collection;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
import com.zeus.eclipsePlugin.ZDebug;
import com.zeus.eclipsePlugin.codedata.CodePossibility;
import com.zeus.eclipsePlugin.codedata.VersionCodeData;
import com.zeus.eclipsePlugin.codedata.CodePossibility.Type;
/**
* This matches various bits of TrafficScript code and returns the appropriate
* style token. It uses the editors code data to determine what to colour.
*/
public class TrafficScriptWordRule implements IRule
{
private VersionCodeData version;
private IToken functionToken, keywordToken, deprecatedToken, defaultToken;
/**
* Create the TrafficScript scanner, for the specified version.
* @param version The code data version for the ZXTM that this code is stored
* on.
* @param functionToken The style token for functions
* @param keywordToken The style token for keywords.
* @param deprecatedToken The style token for deprecated functions.
* @param defaultToken The default token for code.
*/
public TrafficScriptWordRule( VersionCodeData version,
IToken functionToken, IToken keywordToken, IToken deprecatedToken,
IToken defaultToken )
{
this.version = version;
this.functionToken = functionToken;
this.keywordToken = keywordToken;
this.defaultToken = defaultToken;
this.deprecatedToken = deprecatedToken;
}
int readCount;
/**
* Read the next bit of text that could possibly be a colourable bit of code.
* If it matches a keyword/function then return the appropriate token,
* otherwise return the default token.
* @param scanner The scanner that is reading the code.
* @return The appropriate token for the code we have scanned.
*/
/* Override */
public synchronized IToken evaluate( ICharacterScanner scanner )
{
ZDebug.print( 4, "evaluate( ", scanner, " )" );
readCount = 0;
// Read in code until we hit something that can't be part of a keyword or
// function
char c;
StringBuffer buffer = new StringBuffer( 50 );
while( (c = readChar( scanner )) != 0 ) {
if( !Character.isLetterOrDigit( c ) && c != '.' ) {
ZDebug.print( 8, "Breaking on: ", c );
break;
}
if( readCount == 1 && !Character.isLetter( c ) ) {
ZDebug.print( 8, "Breaking on: ", c );
break;
}
buffer.append( c );
}
rewind( scanner );
ZDebug.print( 4, "Processing word: '", buffer, "'" );
// Use code matching functions to find any keywords/functions that match.
if( buffer.length() > 0 ) {
Collection<CodePossibility> possibilities = version.getPossiblilities(
buffer.toString(), new Type[] { Type.KEYWORD }
);
if( possibilities.size() > 0 ) {
ZDebug.print( 5, "Word is keyword." );
return keywordToken;
}
possibilities = version.getPossiblilities(
buffer.toString(), new Type[] { Type.FUNCTION, Type.GROUP }
);
if( possibilities.size() > 0 ) {
if( possibilities.size() == 1 ) {
CodePossibility first = possibilities.iterator().next();
if( first.getFunction() != null && first.getFunction().isDeprecated() ) {
ZDebug.print( 5, "Word is deprecated." );
return deprecatedToken;
}
}
ZDebug.print( 5, "Word is function." );
return functionToken;
}
} else {
rewindToBeginning( scanner );
return Token.UNDEFINED;
}
if( defaultToken.isUndefined() ) {
rewindToBeginning( scanner );
}
return defaultToken;
}
/**
* Reads a single character, increment internal counters.
* @param scanner The scanner to read from
* @return The char read, or 0 if we are at the end of the file.
*/
public char readChar( ICharacterScanner scanner )
{
int c = scanner.read();
readCount++;
if( c == ICharacterScanner.EOF ) {
return 0;
} else {
return (char) c;
}
}
/**
* Rewind to where we started
* @param scanner The scanner to rewind.
*/
public void rewindToBeginning( ICharacterScanner scanner )
{
for( int i = 0; i < readCount; i++ ) {
scanner.unread();
}
}
/**
* Go back a single character, update internal counters.
* @param scanner The scanner to rewind.
*/
public void rewind( ICharacterScanner scanner ) {
if( readCount > 0 ) {
scanner.unread();
readCount--;
}
}
}
|
3e1cac81773034af1ef235e315e338d7bd71d91c | 1,443 | java | Java | src/main/java/textadventurelib/persistence/LayoutRepository.java | JeffreyRiggle/textadventurelib | 76613688c38d765af662c3f16c217c5cdc33ab08 | [
"MIT"
] | null | null | null | src/main/java/textadventurelib/persistence/LayoutRepository.java | JeffreyRiggle/textadventurelib | 76613688c38d765af662c3f16c217c5cdc33ab08 | [
"MIT"
] | 5 | 2017-08-07T09:01:38.000Z | 2020-11-20T12:14:31.000Z | src/main/java/textadventurelib/persistence/LayoutRepository.java | JeffreyRiggle/textadventurelib | 76613688c38d765af662c3f16c217c5cdc33ab08 | [
"MIT"
] | null | null | null | 18.986842 | 70 | 0.684685 | 12,174 | package textadventurelib.persistence;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Jeff Riggle
*
*/
public class LayoutRepository {
private Map<String, LayoutPersistenceObject> layouts;
/**
* Creates a new layout repository.
*/
public LayoutRepository() {
layouts = new HashMap<String, LayoutPersistenceObject>();
}
/**
*
* @param layout The layout to add to the repository.
*/
public void addLayout(LayoutPersistenceObject layout) {
layouts.put(layout.id(), layout);
}
/**
*
* @param layout The layout to remove from the repository.
*/
public void removeLayout(LayoutPersistenceObject layout) {
layouts.remove(layout.id());
}
/**
*
* @param layout The id of the layout to remove from this repository.
*/
public void removeLayout(String layout) {
layouts.remove(layout);
}
/**
* Removes all layouts from this repository.
*/
public void clearLayouts() {
layouts.clear();
}
/**
*
* @return All layouts in this repository.
*/
public List<LayoutPersistenceObject> getLayouts() {
return new ArrayList<LayoutPersistenceObject>(layouts.values());
}
/**
*
* @param layoutid The id of the layout.
* @return The layout.
*/
public LayoutPersistenceObject getLayout(String layoutid) {
if (!layouts.containsKey(layoutid)) {
return null;
}
return layouts.get(layoutid);
}
}
|
3e1cace84c5a5b06cd33e7034219060a3ad2d738 | 444 | java | Java | myshop-commons-service/src/main/java/com/funtl/myshop/commons/service/impl/TbItemServiceImpl.java | MrTallon/myshop | cfe486e6e0afc552f3bd83db0ae3e6bbefb8705d | [
"Apache-2.0"
] | 8 | 2019-03-15T09:53:11.000Z | 2021-04-23T08:33:25.000Z | myshop-commons-service/src/main/java/com/funtl/myshop/commons/service/impl/TbItemServiceImpl.java | MrTallon/myshop | cfe486e6e0afc552f3bd83db0ae3e6bbefb8705d | [
"Apache-2.0"
] | 1 | 2020-02-27T08:08:25.000Z | 2020-02-27T08:08:25.000Z | myshop-commons-service/src/main/java/com/funtl/myshop/commons/service/impl/TbItemServiceImpl.java | MrTallon/myshop | cfe486e6e0afc552f3bd83db0ae3e6bbefb8705d | [
"Apache-2.0"
] | 10 | 2019-03-19T12:13:15.000Z | 2021-04-23T08:33:27.000Z | 23.368421 | 107 | 0.797297 | 12,175 | package com.funtl.myshop.commons.service.impl;
import com.funtl.myshop.commons.domain.TbItem;
import com.funtl.myshop.commons.mapper.TbItemMapper;
import com.funtl.myshop.commons.service.TbItemService;
import org.springframework.stereotype.Service;
/**
* This is Description
*
* @author YangBo
* @date 2019/03/10
*/
@Service
public class TbItemServiceImpl extends BaseCrudServiceImpl<TbItem, TbItemMapper> implements TbItemService {
}
|
3e1cad1aff852b1b4c07c756bd02dc35231597cb | 4,305 | java | Java | app/src/main/java/com/example/huhaichang/learn3/seven/datastorage/LitePalActivity.java | huhaichang/learn3 | 53e3c07a50f29a0422fae452941728ce2b032aff | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/huhaichang/learn3/seven/datastorage/LitePalActivity.java | huhaichang/learn3 | 53e3c07a50f29a0422fae452941728ce2b032aff | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/huhaichang/learn3/seven/datastorage/LitePalActivity.java | huhaichang/learn3 | 53e3c07a50f29a0422fae452941728ce2b032aff | [
"Apache-2.0"
] | null | null | null | 39.495413 | 138 | 0.581649 | 12,176 | package com.example.huhaichang.learn3.seven.datastorage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.huhaichang.learn3.seven.widget.BookE;
import com.example.huhaichang.learn3.R;
import com.example.huhaichang.learn3.eight.widget.UserManage;
import com.example.huhaichang.learn3.widget.ToastUtil;
import org.litepal.LitePal;
import java.util.List;
public class LitePalActivity extends AppCompatActivity {
private Button mBtCreateLitePal1;
private Button mBtAddData;
private Button mBtUpData;
private Button mBtDeleteData;
private Button mBtQueryData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lite_pal);
//application里的android:name="org.litepal.LitePalApplication"相当于
// LitePal.initialize(LitePalActivity.this);
mBtCreateLitePal1 =findViewById(R.id.bt_createLitePal1);
mBtAddData = findViewById(R.id.bt_addData);
mBtUpData = findViewById(R.id.bt_upData);
mBtDeleteData = findViewById(R.id.bt_deleteData);
mBtQueryData = findViewById(R.id.bt_queryData);
mBtCreateLitePal1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LitePal.getDatabase();
ToastUtil.showMsg(LitePalActivity.this,"创建成功");
}
});
mBtAddData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//同一个对象只代表一个id 所以第一个保存无效;
//androidManifest APPname设置了所有Activity都有Litepal的特性所以下面可以自动加入数据库
BookE book =new BookE();
book.setName("1号的书");
book.setAuthor("1号");
book.setPages(100);
book.setPrice(18.5);
book.save();
//上面无效被覆盖
book.setName("2号的书");
book.setAuthor("2号");
book.setPages(100);
book.setPrice(18.5);
book.save();
UserManage userManage = new UserManage();
userManage.setUser("54321");
userManage.setPassword("54321");
userManage.save();
Toast.makeText(LitePalActivity.this,"数据添加成功",Toast.LENGTH_SHORT).show();
}
});
mBtUpData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BookE book =new BookE();
//更新部分
book.setName("4号的书");
book.setAuthor("4号");
//假设要设置页数为0刚刚好没默认值
//错误方法book.setPages(0);
//正确方法
book.setToDefault("pages");
//判断更新对应的行数
book.update(4);
//book.updateAll("name = ? and author = ?","4号","4号的书"); //这个用来找范围的
Toast.makeText(LitePalActivity.this,"4号数据更新成功",Toast.LENGTH_SHORT).show();
}
});
mBtDeleteData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LitePal.deleteAll(BookE.class,"id = ?","3");
LitePal.deleteAll(UserManage.class,"id = ?","3");
Toast.makeText(LitePalActivity.this,"3号数据删除成功",Toast.LENGTH_SHORT).show();
}
});
mBtQueryData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<BookE> books = LitePal.findAll(BookE.class);
for(BookE book : books){
Log.d("id: "+book.getId(),"书名:"+book.getName()+" 作者:"+book.getAuthor()+" 价格:"+book.getPrice()+" 页数"+book.getPages());
}
List<UserManage> userManages =LitePal.findAll(UserManage.class);
for(UserManage userManage : userManages){
Log.d("id: "+userManage.getId(),"账号:"+userManage.getUser()+" 密码:"+userManage.getPassword());
}
}
});
}
}
|
3e1cad52c0b16471b8cdf2f7ddb74dc10064b812 | 312 | java | Java | src/main/java/br/com/bilotta/ordemServicosAPI/api/model/ComentarioInput.java | LuizEduardoBilotta/OrdemServicoAPI | da11eb5c726739ef3aa83ee6db15fe0a15e92f68 | [
"MIT"
] | 1 | 2020-07-01T14:11:13.000Z | 2020-07-01T14:11:13.000Z | src/main/java/br/com/bilotta/ordemServicosAPI/api/model/ComentarioInput.java | LuizEduardoBilotta/OrdemServicoAPI | da11eb5c726739ef3aa83ee6db15fe0a15e92f68 | [
"MIT"
] | null | null | null | src/main/java/br/com/bilotta/ordemServicosAPI/api/model/ComentarioInput.java | LuizEduardoBilotta/OrdemServicoAPI | da11eb5c726739ef3aa83ee6db15fe0a15e92f68 | [
"MIT"
] | null | null | null | 15.6 | 50 | 0.759615 | 12,177 | package br.com.bilotta.ordemServicosAPI.api.model;
import javax.validation.constraints.NotBlank;
public class ComentarioInput {
@NotBlank
private String descricao;
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
|
3e1cae0c7d2043058d61d7dd5062374ed67ffb27 | 861 | java | Java | jeefast-system/src/main/java/cn/jeefast/system/service/SysUserService.java | filesily/java | 4a9d043e12da804674be1d5c75933d68e352d307 | [
"Apache-2.0"
] | 2 | 2018-11-05T14:55:08.000Z | 2019-08-14T06:03:22.000Z | jeefast-system/src/main/java/cn/jeefast/system/service/SysUserService.java | filesily/java | 4a9d043e12da804674be1d5c75933d68e352d307 | [
"Apache-2.0"
] | 2 | 2021-04-22T17:08:49.000Z | 2021-09-20T20:59:00.000Z | jeefast-system/src/main/java/cn/jeefast/system/service/SysUserService.java | filesily/java | 4a9d043e12da804674be1d5c75933d68e352d307 | [
"Apache-2.0"
] | 4 | 2020-05-10T19:51:22.000Z | 2020-08-10T10:27:48.000Z | 15.944444 | 78 | 0.681765 | 12,178 | package cn.jeefast.system.service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import cn.jeefast.system.entity.SysUser;
/**
* <p>
* 系统用户 服务类
* </p>
*
* @author theodo
* @since 2017-10-28
*/
public interface SysUserService extends IService<SysUser> {
Page<SysUser> queryPageList(Page<SysUser> pageUtil, Map<String, Object> map);
/**
* 查询用户列表
*/
List<SysUser> queryList(Map<String, Object> map);
/**
* 查询用户的所有权限
* @param userId 用户ID
*/
List<String> queryAllPerms(Long userId);
/**
* 查询用户的所有菜单ID
*/
List<Long> queryAllMenuId(Long userId);
/**
* 根据用户名,查询系统用户
*/
SysUser queryByUserName(String username);
/**
* 删除用户
*/
void deleteBatch(Long[] userIds);
void save(SysUser user);
void update(SysUser user);
}
|
3e1caefd898fe08b029b0fbab09c762d517245ac | 7,946 | java | Java | testing/src/main/java/io/grpc/internal/testing/StatsTestUtils.java | eikemeier/grpc-java | 26caa488a5a5ead1d9dac17bc0facf975bed5e35 | [
"Apache-2.0"
] | 1 | 2017-06-16T09:00:08.000Z | 2017-06-16T09:00:08.000Z | testing/src/main/java/io/grpc/internal/testing/StatsTestUtils.java | eikemeier/grpc-java | 26caa488a5a5ead1d9dac17bc0facf975bed5e35 | [
"Apache-2.0"
] | null | null | null | testing/src/main/java/io/grpc/internal/testing/StatsTestUtils.java | eikemeier/grpc-java | 26caa488a5a5ead1d9dac17bc0facf975bed5e35 | [
"Apache-2.0"
] | null | null | null | 32.970954 | 98 | 0.702492 | 12,179 | /*
* Copyright 2016, gRPC Authors 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.grpc.internal.testing;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableMap;
import com.google.instrumentation.stats.MeasurementDescriptor;
import com.google.instrumentation.stats.MeasurementMap;
import com.google.instrumentation.stats.MeasurementValue;
import com.google.instrumentation.stats.StatsContext;
import com.google.instrumentation.stats.StatsContextFactory;
import com.google.instrumentation.stats.TagKey;
import com.google.instrumentation.stats.TagValue;
import io.grpc.internal.IoUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
public class StatsTestUtils {
private StatsTestUtils() {
}
public static class MetricsRecord {
public final ImmutableMap<TagKey, TagValue> tags;
public final MeasurementMap metrics;
private MetricsRecord(ImmutableMap<TagKey, TagValue> tags, MeasurementMap metrics) {
this.tags = tags;
this.metrics = metrics;
}
/**
* Returns the value of a metric, or {@code null} if not found.
*/
@Nullable
public Double getMetric(MeasurementDescriptor metricName) {
for (MeasurementValue m : metrics) {
if (m.getMeasurement().equals(metricName)) {
return m.getValue();
}
}
return null;
}
/**
* Returns the value of a metric converted to long, or throw if not found.
*/
public long getMetricAsLongOrFail(MeasurementDescriptor metricName) {
Double doubleValue = getMetric(metricName);
checkNotNull(doubleValue, "Metric not found: %s", metricName.toString());
long longValue = (long) (Math.abs(doubleValue) + 0.0001);
if (doubleValue < 0) {
longValue = -longValue;
}
return longValue;
}
}
/**
* This tag will be propagated by {@link FakeStatsContextFactory} on the wire.
*/
public static final TagKey EXTRA_TAG = TagKey.create("/rpc/test/extratag");
private static final String EXTRA_TAG_HEADER_VALUE_PREFIX = "extratag:";
private static final String NO_EXTRA_TAG_HEADER_VALUE_PREFIX = "noextratag";
/**
* A factory that makes fake {@link StatsContext}s and saves the created contexts to be
* accessible from {@link #pollContextOrFail}. The contexts it has created would save metrics
* records to be accessible from {@link #pollRecord()} and {@link #pollRecord(long, TimeUnit)},
* until {@link #rolloverRecords} is called.
*/
public static final class FakeStatsContextFactory extends StatsContextFactory {
private BlockingQueue<MetricsRecord> records;
public final BlockingQueue<FakeStatsContext> contexts =
new LinkedBlockingQueue<FakeStatsContext>();
private final FakeStatsContext defaultContext;
/**
* Constructor.
*/
public FakeStatsContextFactory() {
rolloverRecords();
defaultContext = new FakeStatsContext(ImmutableMap.<TagKey, TagValue>of(), this);
// The records on the default context is not visible from pollRecord(), just like it's
// not visible from pollContextOrFail() either.
rolloverRecords();
}
public StatsContext pollContextOrFail() {
StatsContext cc = contexts.poll();
return checkNotNull(cc);
}
public MetricsRecord pollRecord() {
return getCurrentRecordSink().poll();
}
public MetricsRecord pollRecord(long timeout, TimeUnit unit) throws InterruptedException {
return getCurrentRecordSink().poll(timeout, unit);
}
@Override
public StatsContext deserialize(InputStream buffer) throws IOException {
String serializedString;
try {
serializedString = new String(IoUtils.toByteArray(buffer), UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (serializedString.startsWith(EXTRA_TAG_HEADER_VALUE_PREFIX)) {
return getDefault().with(EXTRA_TAG,
TagValue.create(serializedString.substring(EXTRA_TAG_HEADER_VALUE_PREFIX.length())));
} else if (serializedString.startsWith(NO_EXTRA_TAG_HEADER_VALUE_PREFIX)) {
return getDefault();
} else {
throw new IOException("Malformed value");
}
}
@Override
public FakeStatsContext getDefault() {
return defaultContext;
}
/**
* Disconnect this factory with the contexts it has created so far. The records from those
* contexts will not show up in {@link #pollRecord}. Useful for isolating the records between
* test cases.
*/
// This needs to be synchronized with getCurrentRecordSink() which may run concurrently.
public synchronized void rolloverRecords() {
records = new LinkedBlockingQueue<MetricsRecord>();
}
private synchronized BlockingQueue<MetricsRecord> getCurrentRecordSink() {
return records;
}
}
public static class FakeStatsContext extends StatsContext {
private final ImmutableMap<TagKey, TagValue> tags;
private final FakeStatsContextFactory factory;
private final BlockingQueue<MetricsRecord> recordSink;
private FakeStatsContext(ImmutableMap<TagKey, TagValue> tags,
FakeStatsContextFactory factory) {
this.tags = tags;
this.factory = factory;
this.recordSink = factory.getCurrentRecordSink();
}
@Override
public Builder builder() {
return new FakeStatsContextBuilder(this);
}
@Override
public StatsContext record(MeasurementMap metrics) {
recordSink.add(new MetricsRecord(tags, metrics));
return this;
}
@Override
public void serialize(OutputStream os) {
TagValue extraTagValue = tags.get(EXTRA_TAG);
try {
if (extraTagValue == null) {
os.write(NO_EXTRA_TAG_HEADER_VALUE_PREFIX.getBytes(UTF_8));
} else {
os.write((EXTRA_TAG_HEADER_VALUE_PREFIX + extraTagValue.toString()).getBytes(UTF_8));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public String toString() {
return "[tags=" + tags + "]";
}
@Override
public boolean equals(Object other) {
if (!(other instanceof FakeStatsContext)) {
return false;
}
FakeStatsContext otherCtx = (FakeStatsContext) other;
return tags.equals(otherCtx.tags);
}
@Override
public int hashCode() {
return tags.hashCode();
}
}
private static class FakeStatsContextBuilder extends StatsContext.Builder {
private final ImmutableMap.Builder<TagKey, TagValue> tagsBuilder = ImmutableMap.builder();
private final FakeStatsContext base;
private FakeStatsContextBuilder(FakeStatsContext base) {
this.base = base;
tagsBuilder.putAll(base.tags);
}
@Override
public StatsContext.Builder set(TagKey key, TagValue value) {
tagsBuilder.put(key, value);
return this;
}
@Override
public StatsContext build() {
FakeStatsContext context = new FakeStatsContext(tagsBuilder.build(), base.factory);
base.factory.contexts.add(context);
return context;
}
}
}
|
3e1cb2078bc9ee0eb4117a03daf7a6875a991e77 | 924 | java | Java | src/main/java/ganymedes01/etfuturum/enchantment/FrostWalker.java | idwtd/Et-Futurum | d3abb09c605b3dc97a5dd2f3d6dff33b2f730a07 | [
"Unlicense"
] | null | null | null | src/main/java/ganymedes01/etfuturum/enchantment/FrostWalker.java | idwtd/Et-Futurum | d3abb09c605b3dc97a5dd2f3d6dff33b2f730a07 | [
"Unlicense"
] | null | null | null | src/main/java/ganymedes01/etfuturum/enchantment/FrostWalker.java | idwtd/Et-Futurum | d3abb09c605b3dc97a5dd2f3d6dff33b2f730a07 | [
"Unlicense"
] | null | null | null | 24.972973 | 64 | 0.695887 | 12,180 | package ganymedes01.etfuturum.enchantment;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
public class FrostWalker extends Enchantment {
public static int ID = 36;
public FrostWalker() {
super(ID, 1, EnumEnchantmentType.armor_feet);
Enchantment.addToBookList(this);
setName("frost_walker");
}
public int getMinEnchantability(int enchantmentLevel)
{
return enchantmentLevel * 10;
}
public int getMaxEnchantability(int enchantmentLevel)
{
return this.getMinEnchantability(enchantmentLevel) + 15;
}
@Override
public int getMaxLevel() {
return 2;
}
@Override
public boolean canApplyAtEnchantingTable(ItemStack stack) {
return stack != null && stack.getItem() == Items.book;
}
} |
3e1cb2bc091fe149312db9a3c32e5dbb71232227 | 768 | java | Java | mobile/src/main/java/xxxpress/developer/produto/ParametrosExtrasProdutos.java | raphaelrb96/xxxpress | f602b8a3cdcbf60c1a5ab0fb2a32e608cf77c0a4 | [
"Apache-2.0"
] | null | null | null | mobile/src/main/java/xxxpress/developer/produto/ParametrosExtrasProdutos.java | raphaelrb96/xxxpress | f602b8a3cdcbf60c1a5ab0fb2a32e608cf77c0a4 | [
"Apache-2.0"
] | null | null | null | mobile/src/main/java/xxxpress/developer/produto/ParametrosExtrasProdutos.java | raphaelrb96/xxxpress | f602b8a3cdcbf60c1a5ab0fb2a32e608cf77c0a4 | [
"Apache-2.0"
] | null | null | null | 23.272727 | 116 | 0.71224 | 12,181 | package xxxpress.developer.produto;
import java.util.ArrayList;
public class ParametrosExtrasProdutos {
public boolean existente;
public String tituloParametro;
public ArrayList<String> parametrosExtras;
public ParametrosExtrasProdutos() {
}
public ParametrosExtrasProdutos(boolean existente, String tituloParametro, ArrayList<String> parametrosExtras) {
this.existente = existente;
this.tituloParametro = tituloParametro;
this.parametrosExtras = parametrosExtras;
}
public boolean isExistente() {
return existente;
}
public String getTituloParametro() {
return tituloParametro;
}
public ArrayList<String> getParametrosExtras() {
return parametrosExtras;
}
}
|
3e1cb597a48459efabbfec4d0815d02404bd7470 | 607 | java | Java | spark-examples/push-down-predicates/src/test/java/uk/co/devworx/spark_examples/pushdown/MyLocalTime.java | DevWorxCo/data-cornucopia | ccb6539ba826bee6ea22835552c6026c9147f2a4 | [
"Apache-2.0"
] | null | null | null | spark-examples/push-down-predicates/src/test/java/uk/co/devworx/spark_examples/pushdown/MyLocalTime.java | DevWorxCo/data-cornucopia | ccb6539ba826bee6ea22835552c6026c9147f2a4 | [
"Apache-2.0"
] | 16 | 2020-07-01T09:16:44.000Z | 2022-01-07T13:37:11.000Z | spark-examples/push-down-predicates/src/test/java/uk/co/devworx/spark_examples/pushdown/MyLocalTime.java | DevWorxCo/data-cornucopia | ccb6539ba826bee6ea22835552c6026c9147f2a4 | [
"Apache-2.0"
] | null | null | null | 13.488889 | 49 | 0.678748 | 12,182 | package uk.co.devworx.spark_examples.pushdown;
public class MyLocalTime extends java.sql.Date
{
public MyLocalTime(int year, int month, int day)
{
super(year, month, day);
}
public MyLocalTime(long date)
{
super(date);
}
@Override public int getHours()
{
return 10;
}
@Override public int getMinutes()
{
return 10;
}
@Override public int getSeconds()
{
return 10;
}
@Override public void setHours(int i)
{
super.setHours(i);
}
@Override public void setMinutes(int i)
{
super.setMinutes(i);
}
@Override public void setSeconds(int i)
{
super.setSeconds(i);
}
}
|
3e1cb65997a6e9b5f859e5d5c7dd6d19b82b0e7b | 3,743 | java | Java | src/main/java/org/ros/internal/transport/BaseClientHandshakeHandler.java | neocoretechs/ROSJava | 222af71e089a25befbde906024a5958da432644c | [
"Apache-2.0"
] | 1 | 2016-10-16T23:56:01.000Z | 2016-10-16T23:56:01.000Z | src/main/java/org/ros/internal/transport/BaseClientHandshakeHandler.java | neocoretechs/ROSJava | 222af71e089a25befbde906024a5958da432644c | [
"Apache-2.0"
] | null | null | null | src/main/java/org/ros/internal/transport/BaseClientHandshakeHandler.java | neocoretechs/ROSJava | 222af71e089a25befbde906024a5958da432644c | [
"Apache-2.0"
] | null | null | null | 37.108911 | 103 | 0.770544 | 12,183 | /*
* Copyright (C) 2012 Google 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 org.ros.internal.transport;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.ros.concurrent.ListenerGroup;
import org.ros.concurrent.SignalRunnable;
import org.ros.internal.transport.tcp.AbstractNamedChannelHandler;
import java.util.concurrent.ExecutorService;
/**
* Common functionality for {@link ClientHandshake} handlers.
*
* @author upchh@example.com (Damon Kohler)
*/
public abstract class BaseClientHandshakeHandler extends AbstractNamedChannelHandler {
private final ClientHandshake clientHandshake;
private final ListenerGroup<ClientHandshakeListener> clientHandshakeListeners;
public BaseClientHandshakeHandler(ClientHandshake clientHandshake, ExecutorService executorService) {
this.clientHandshake = clientHandshake;
clientHandshakeListeners = new ListenerGroup<ClientHandshakeListener>(executorService);
}
public void addListener(ClientHandshakeListener clientHandshakeListener) {
clientHandshakeListeners.add(clientHandshakeListener);
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelConnected(ctx, e);
e.getChannel().write(clientHandshake.getOutgoingConnectionHeader().encode());
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
ConnectionHeader connectionHeader = ConnectionHeader.decode(buffer);
if (clientHandshake.handshake(connectionHeader)) {
onSuccess(connectionHeader, ctx, e);
signalOnSuccess(connectionHeader);
} else {
onFailure(clientHandshake.getErrorMessage(), ctx, e);
signalOnFailure(clientHandshake.getErrorMessage());
}
}
/**
* Called when the {@link ClientHandshake} succeeds and will block the network
* thread until it returns.
* <p>
* This must block in order to allow changes to the pipeline to be made before
* further messages arrive.
*
* @param incommingConnectionHeader
* @param ctx
* @param e
*/
protected abstract void onSuccess(ConnectionHeader incommingConnectionHeader,
ChannelHandlerContext ctx, MessageEvent e);
private void signalOnSuccess(final ConnectionHeader incommingConnectionHeader) {
clientHandshakeListeners.signal(new SignalRunnable<ClientHandshakeListener>() {
@Override
public void run(ClientHandshakeListener listener) {
listener.onSuccess(clientHandshake.getOutgoingConnectionHeader(), incommingConnectionHeader);
}
});
}
protected abstract void onFailure(String errorMessage, ChannelHandlerContext ctx, MessageEvent e);
private void signalOnFailure(final String errorMessage) {
clientHandshakeListeners.signal(new SignalRunnable<ClientHandshakeListener>() {
@Override
public void run(ClientHandshakeListener listener) {
listener.onFailure(clientHandshake.getOutgoingConnectionHeader(), errorMessage);
}
});
}
}
|
3e1cb70ec88532d365e776bd79b4761645a47d6d | 579 | java | Java | refactoring-techniques/composing-methods/src/main/java/me/aikin/refactoring/composing/methods/ReplaceTempWithQuery.java | jinhuisheng/refactoring-kata | 8a9ddc7392f6c8c21316510f2fd5c784d2c61cf6 | [
"MIT"
] | 72 | 2018-07-11T05:32:24.000Z | 2021-11-02T09:55:44.000Z | refactoring-techniques/composing-methods/src/main/java/me/aikin/refactoring/composing/methods/ReplaceTempWithQuery.java | jinhuisheng/refactoring-kata | 8a9ddc7392f6c8c21316510f2fd5c784d2c61cf6 | [
"MIT"
] | 8 | 2018-07-14T01:01:33.000Z | 2019-07-23T13:24:08.000Z | refactoring-techniques/composing-methods/src/main/java/me/aikin/refactoring/composing/methods/ReplaceTempWithQuery.java | jinhuisheng/refactoring-kata | 8a9ddc7392f6c8c21316510f2fd5c784d2c61cf6 | [
"MIT"
] | 34 | 2018-08-14T09:56:23.000Z | 2022-03-05T10:59:52.000Z | 25.173913 | 68 | 0.649396 | 12,184 | package me.aikin.refactoring.composing.methods;
public class ReplaceTempWithQuery {
private final double quantity;
private final double itemPrice;
public ReplaceTempWithQuery(double quantity, double itemPrice) {
this.quantity = quantity;
this.itemPrice = itemPrice;
}
public double getPrice() {
double basePrice = quantity * itemPrice;
double discountFactor;
if (basePrice > 1000)
discountFactor = 0.95;
else
discountFactor = 0.98;
return basePrice * discountFactor;
}
}
|
3e1cb7c0092d5b11c839df9dbd268c43e3ce6612 | 2,251 | java | Java | opensrp-ecap-chw/src/main/java/com/bluecodeltd/ecap/chw/fragment/ChildVisitsFragment.java | BlueCodeSystems/opensrp-client-ecap-chw | 7c89cedaaea215150ea8f98de7ae3e658371325a | [
"Apache-2.0"
] | 1 | 2022-03-17T11:06:51.000Z | 2022-03-17T11:06:51.000Z | opensrp-ecap-chw/src/main/java/com/bluecodeltd/ecap/chw/fragment/ChildVisitsFragment.java | BlueCodeSystems/opensrp-client-ecap-chw | 7c89cedaaea215150ea8f98de7ae3e658371325a | [
"Apache-2.0"
] | 461 | 2021-07-05T09:03:55.000Z | 2022-03-31T14:19:58.000Z | opensrp-ecap-chw/src/main/java/com/bluecodeltd/ecap/chw/fragment/ChildVisitsFragment.java | BlueCodeSystems/opensrp-client-ecap-chw | 7c89cedaaea215150ea8f98de7ae3e658371325a | [
"Apache-2.0"
] | null | null | null | 35.171875 | 123 | 0.776988 | 12,185 | package com.bluecodeltd.ecap.chw.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bluecodeltd.ecap.chw.R;
import com.bluecodeltd.ecap.chw.activity.IndexDetailsActivity;
import com.bluecodeltd.ecap.chw.adapter.CasePlanAdapter;
import com.bluecodeltd.ecap.chw.adapter.VisitAdapter;
import com.bluecodeltd.ecap.chw.dao.IndexPersonDao;
import com.bluecodeltd.ecap.chw.dao.VcaVisitationDao;
import com.bluecodeltd.ecap.chw.model.CasePlanModel;
import com.bluecodeltd.ecap.chw.model.VcaVisitationModel;
import java.util.ArrayList;
public class ChildVisitsFragment extends Fragment {
private RecyclerView recyclerView;
RecyclerView.Adapter recyclerViewadapter;
private ArrayList<VcaVisitationModel> visitList = new ArrayList<>();
private LinearLayout linearLayout;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_childvisits, container, false);
String childId = ( (IndexDetailsActivity) requireActivity()).uniqueId;
recyclerView = view.findViewById(R.id.visitrecyclerView);
linearLayout = view.findViewById(R.id.visit_container);
visitList.addAll(VcaVisitationDao.getVisitsByID(childId));
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(eLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerViewadapter = new VisitAdapter(visitList, getContext());
recyclerView.setAdapter(recyclerViewadapter);
recyclerViewadapter.notifyDataSetChanged();
if (recyclerViewadapter.getItemCount() > 0){
linearLayout.setVisibility(View.GONE);
}
return view;
}
}
|
3e1cb93b56dd5a0211838661a67409c9219c7fae | 3,569 | java | Java | nas/src/main/java/tr/havelsan/ueransim/nas/impl/ies/IEUeStatus.java | endlessbaum/UERANSIM | 3ab905e3713b786789b7f358fee91c3e3eff0130 | [
"MIT"
] | null | null | null | nas/src/main/java/tr/havelsan/ueransim/nas/impl/ies/IEUeStatus.java | endlessbaum/UERANSIM | 3ab905e3713b786789b7f358fee91c3e3eff0130 | [
"MIT"
] | null | null | null | nas/src/main/java/tr/havelsan/ueransim/nas/impl/ies/IEUeStatus.java | endlessbaum/UERANSIM | 3ab905e3713b786789b7f358fee91c3e3eff0130 | [
"MIT"
] | null | null | null | 39.655556 | 92 | 0.718128 | 12,186 | /*
* MIT License
*
* Copyright (c) 2020 ALİ GÜNGÖR
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package tr.havelsan.ueransim.nas.impl.ies;
import tr.havelsan.ueransim.nas.core.ProtocolEnum;
import tr.havelsan.ueransim.nas.core.ies.InformationElement4;
import tr.havelsan.ueransim.utils.OctetInputStream;
import tr.havelsan.ueransim.utils.OctetOutputStream;
public class IEUeStatus extends InformationElement4 {
public EEmmRegistrationStatus s1ModeReg;
public E5gMmRegistrationStatus n1ModeReg;
public IEUeStatus() {
}
public IEUeStatus(EEmmRegistrationStatus s1ModeReg, E5gMmRegistrationStatus n1ModeReg) {
this.s1ModeReg = s1ModeReg;
this.n1ModeReg = n1ModeReg;
}
@Override
protected IEUeStatus decodeIE4(OctetInputStream stream, int length) {
int octet = stream.readOctetI();
var res = new IEUeStatus();
res.s1ModeReg = EEmmRegistrationStatus.fromValue(octet & 0b1);
res.n1ModeReg = E5gMmRegistrationStatus.fromValue(octet >> 1 & 0b1);
return res;
}
@Override
public void encodeIE4(OctetOutputStream stream) {
int octet = s1ModeReg.intValue() | (n1ModeReg.intValue() << 1);
stream.writeOctet(octet);
}
public static class E5gMmRegistrationStatus extends ProtocolEnum {
public static final E5gMmRegistrationStatus NOT_REGISTERED
= new E5gMmRegistrationStatus(0b0, "UE is not in 5GMM-REGISTERED state");
public static final E5gMmRegistrationStatus REGISTERED
= new E5gMmRegistrationStatus(0b1, "UE is in 5GMM-REGISTERED state");
private E5gMmRegistrationStatus(int value, String name) {
super(value, name);
}
public static E5gMmRegistrationStatus fromValue(int value) {
return fromValueGeneric(E5gMmRegistrationStatus.class, value, null);
}
}
public static class EEmmRegistrationStatus extends ProtocolEnum {
public static final EEmmRegistrationStatus NOT_REGISTERED
= new EEmmRegistrationStatus(0b0, "UE is not in EMM-REGISTERED state");
public static final EEmmRegistrationStatus REGISTERED
= new EEmmRegistrationStatus(0b1, "UE is in EMM-REGISTERED state");
private EEmmRegistrationStatus(int value, String name) {
super(value, name);
}
public static EEmmRegistrationStatus fromValue(int value) {
return fromValueGeneric(EEmmRegistrationStatus.class, value, null);
}
}
}
|
3e1cb9c36a2a837cf983e4b48cec8d0ad93f81bf | 14,228 | java | Java | src/main/java/org/olat/course/site/ui/CourseSiteAdminController.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 191 | 2018-03-29T09:55:44.000Z | 2022-03-23T06:42:12.000Z | src/main/java/org/olat/course/site/ui/CourseSiteAdminController.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 68 | 2018-05-11T06:19:00.000Z | 2022-01-25T18:03:26.000Z | src/main/java/org/olat/course/site/ui/CourseSiteAdminController.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 139 | 2018-04-27T09:46:11.000Z | 2022-03-27T08:52:50.000Z | 37.763926 | 151 | 0.764838 | 12,187 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.course.site.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.olat.NewControllerFactory;
import org.olat.core.CoreSpringFactory;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.form.flexible.FormItem;
import org.olat.core.gui.components.form.flexible.FormItemContainer;
import org.olat.core.gui.components.form.flexible.elements.FlexiTableElement;
import org.olat.core.gui.components.form.flexible.elements.FormLink;
import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement;
import org.olat.core.gui.components.form.flexible.elements.TextElement;
import org.olat.core.gui.components.form.flexible.impl.FormBasicController;
import org.olat.core.gui.components.form.flexible.impl.FormEvent;
import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer;
import org.olat.core.gui.components.form.flexible.impl.elements.table.DefaultFlexiColumnModel;
import org.olat.core.gui.components.form.flexible.impl.elements.table.DefaultFlexiTableDataModel;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiCellRenderer;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiTableColumnModel;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiTableDataModelFactory;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiTableRendererType;
import org.olat.core.gui.components.form.flexible.impl.elements.table.SelectionEvent;
import org.olat.core.gui.components.form.flexible.impl.elements.table.StaticFlexiCellRenderer;
import org.olat.core.gui.components.form.flexible.impl.elements.table.TextFlexiCellRenderer;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.generic.closablewrapper.CloseableModalController;
import org.olat.core.util.StringHelper;
import org.olat.core.util.i18n.I18nModule;
import org.olat.course.site.model.CourseSiteConfiguration;
import org.olat.course.site.model.LanguageConfiguration;
import org.olat.repository.RepositoryEntry;
import org.olat.repository.RepositoryManager;
import org.olat.repository.controllers.ReferencableEntriesSearchController;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* Initial date: 17.09.2013<br>
* @author srosse, dycjh@example.com, http://www.frentix.com
*
*/
public class CourseSiteAdminController extends FormBasicController {
private FormLink okButton;
private MultipleSelectionElement enableToolbar;
private TextElement iconCssClassEl;
private FormLayoutContainer tableLayout;
private FlexiTableElement tableEl;
private CourseSiteDataModel model;
private CloseableModalController cmc;
private ReferencableEntriesSearchController selectCtrl;
private CourseSiteConfiguration siteConfiguration;
private final RepositoryManager repositoryManager;
@Autowired
private I18nModule i18nModule;
public CourseSiteAdminController(UserRequest ureq, WindowControl wControl, CourseSiteConfiguration siteConfiguration) {
super(ureq, wControl);
this.siteConfiguration = siteConfiguration;
this.repositoryManager = CoreSpringFactory.getImpl(RepositoryManager.class);
initForm(ureq);
}
@Override
protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
setFormTitle("admin.menu.title");
enableToolbar = uifactory.addCheckboxesHorizontal("site.enable.toolbar", "site.enable.toolbar", formLayout, new String[]{ "x" }, new String[]{ "" });
enableToolbar.addActionListener(FormEvent.ONCHANGE);
if(siteConfiguration.isToolbar()) {
enableToolbar.select("x", true);
}
String cssClass = siteConfiguration.getNavIconCssClass();
iconCssClassEl = uifactory.addTextElement("site.iconCssClass", "site.icon", 32, cssClass, formLayout);
FlexiTableColumnModel columnsModel = FlexiTableDataModelFactory.createFlexiTableColumnModel();
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(CSCols.defLanguage.i18nKey(), CSCols.defLanguage.ordinal()));
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(CSCols.language.i18nKey(), CSCols.language.ordinal()));
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(CSCols.title.i18nKey(), CSCols.title.ordinal()));
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(false, CSCols.courseId.i18nKey(), CSCols.courseId.ordinal(), false, null));
FlexiCellRenderer renderer = new StaticFlexiCellRenderer("openre", new TextFlexiCellRenderer());
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(CSCols.courseTitle.i18nKey(), CSCols.courseTitle.ordinal(), "openre", renderer));
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel("select", translate("select"), "select"));
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel("remove", translate("remove"), "remove"));
String page = velocity_root + "/lang_options.html";
tableLayout = FormLayoutContainer.createCustomFormLayout("site.options.lang", getTranslator(), page);
tableLayout.setRootForm(mainForm);
tableLayout.setLabel("site.courses", null);
formLayout.add(tableLayout);
model = new CourseSiteDataModel(columnsModel);
List<LanguageConfigurationRow> configs = new ArrayList<>();
Map<String,LanguageConfiguration> langToConfigMap = new HashMap<>();
if(siteConfiguration.getConfigurations() != null) {
for(LanguageConfiguration langConfig : siteConfiguration.getConfigurations()) {
langToConfigMap.put(langConfig.getLanguage(), langConfig);
}
}
for(String langKey:i18nModule.getEnabledLanguageKeys()) {
if(langToConfigMap.containsKey(langKey)) {
LanguageConfiguration langConfig = langToConfigMap.get(langKey);
RepositoryEntry re = repositoryManager.lookupRepositoryEntryBySoftkey(langConfig.getRepoSoftKey(), false);
configs.add(new LanguageConfigurationRow(langConfig, re, tableLayout));
} else {
configs.add(new LanguageConfigurationRow(new LanguageConfiguration(langKey), null, tableLayout));
}
}
model.setObjects(configs);
tableEl = uifactory.addTableElement(getWindowControl(), "languageTable", model, getTranslator(), tableLayout);
tableEl.setRendererType(FlexiTableRendererType.classic);
tableEl.setCustomizeColumns(true);
tableEl.setAndLoadPersistedPreferences(ureq, "course-site-admin");
FormLayoutContainer buttonsLayout = FormLayoutContainer.createButtonLayout("buttons", getTranslator());
formLayout.add(buttonsLayout);
okButton = uifactory.addFormLink("save", "save", null, buttonsLayout, Link.BUTTON);
okButton.setCustomEnabledLinkCSS("btn btn-primary");
//uifactory.addFormSubmitButton("save", "save", formLayout);
}
@Override
protected void doDispose() {
//
}
@Override
protected void event(UserRequest ureq, Controller source, Event event) {
if(cmc == source) {
cleanUp();
} else if(selectCtrl == source) {
cmc.deactivate();
if (event == ReferencableEntriesSearchController.EVENT_REPOSITORY_ENTRY_SELECTED) {
LanguageConfigurationRow row = (LanguageConfigurationRow)selectCtrl.getUserObject();
RepositoryEntry re = selectCtrl.getSelectedEntry();
row.setRepositoryEntry(re);
tableEl.reset();
}
}
}
private void cleanUp() {
removeAsListenerAndDispose(selectCtrl);
removeAsListenerAndDispose(cmc);
cmc = null;
selectCtrl = null;
}
@Override
protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {
if(source == enableToolbar) {
okButton.setCustomEnabledLinkCSS("btn btn-primary o_button_dirty");
} else if(source == tableEl) {
if(event instanceof SelectionEvent) {
SelectionEvent se = (SelectionEvent)event;
if("remove".equals(se.getCommand())) {
LanguageConfigurationRow row = model.getObject(se.getIndex());
doReset(row);
okButton.getComponent().setDirty(true);
okButton.setCustomEnabledLinkCSS("btn btn-primary o_button_dirty");
} else if("select".equals(se.getCommand())) {
LanguageConfigurationRow row = model.getObject(se.getIndex());
doSelecCourse(ureq, row);
okButton.getComponent().setDirty(true);
okButton.setCustomEnabledLinkCSS("btn btn-primary o_button_dirty");
} else if("openre".equals(se.getCommand())) {
LanguageConfigurationRow row = model.getObject(se.getIndex());
RepositoryEntry re = row.getRepositoryEntry();
if(re != null) {
NewControllerFactory.getInstance().launch("[RepositoryEntry:" + re.getKey() + "]", ureq, getWindowControl());
}
}
}
} else if(source == okButton) {
okButton.setCustomEnabledLinkCSS("btn btn-primary");
fireEvent(ureq, Event.CHANGED_EVENT);
}
}
private void doReset(LanguageConfigurationRow row) {
row.reset();
tableEl.reset(true, true, true);
}
private void doSelecCourse(UserRequest ureq, LanguageConfigurationRow row) {
removeAsListenerAndDispose(selectCtrl);
selectCtrl = new ReferencableEntriesSearchController(getWindowControl(), ureq, new String[]{ "CourseModule" }, translate("select"),
true, true, false, false, true, false);
selectCtrl.setUserObject(row);
listenTo(selectCtrl);
cmc = new CloseableModalController(getWindowControl(), translate("close"),
selectCtrl.getInitialComponent(), true, translate("select"));
cmc.activate();
listenTo(cmc);
}
@Override
protected void formOK(UserRequest ureq) {
fireEvent(ureq, Event.CHANGED_EVENT);
}
public CourseSiteConfiguration saveConfiguration() {
List<LanguageConfiguration> langConfigList = new ArrayList<>();
for(LanguageConfigurationRow row:model.getObjects()) {
if(StringHelper.containsNonWhitespace(row.getSoftKey())) {
langConfigList.add(row.getRawObject());
}
}
siteConfiguration.setToolbar(enableToolbar.isAtLeastSelected(1));
siteConfiguration.setNavIconCssClass(iconCssClassEl.getValue());
siteConfiguration.setConfigurations(langConfigList);
return siteConfiguration;
}
public class LanguageConfigurationRow {
private LanguageConfiguration langConfig;
private TextElement titleEl;
private MultipleSelectionElement defLangEl;
private RepositoryEntry repoEntry;
public LanguageConfigurationRow(LanguageConfiguration configuration, RepositoryEntry repoEntry,
FormItemContainer formLayout) {
this.langConfig = configuration;
this.repoEntry = repoEntry;
String language = configuration.getLanguage();
titleEl = uifactory.addTextElement("site.title." + language, "site.title",
null, 32, configuration.getTitle(), formLayout);
formLayout.add("site.flexi.title.hook." + language, titleEl);
defLangEl = uifactory.addCheckboxesHorizontal("site.def." + language, null,
formLayout, new String[]{ "x"}, new String[]{ "" });
if(configuration.isDefaultConfiguration()) {
defLangEl.select("x", true);
}
}
public boolean isDefaultConfiguration() {
return langConfig.isDefaultConfiguration();
}
public MultipleSelectionElement getDefLangEl() {
return defLangEl;
}
public String getTitle() {
return langConfig.getTitle();
}
public TextElement getTitleEl() {
return titleEl;
}
public String getLanguage() {
return langConfig.getLanguage();
}
public String getSoftKey() {
return langConfig.getRepoSoftKey();
}
public String getRepoEntryDisplayName() {
return repoEntry == null ? null : repoEntry.getDisplayname();
}
public RepositoryEntry getRepositoryEntry() {
return repoEntry;
}
public void setRepositoryEntry(RepositoryEntry re) {
repoEntry= re;
langConfig.setTitle(re.getDisplayname());
langConfig.setRepoSoftKey(re.getSoftkey());
if(!StringHelper.containsNonWhitespace(titleEl.getValue())) {
titleEl.setValue(re.getDisplayname());
}
}
public void reset() {
langConfig.setTitle(null);
langConfig.setRepoSoftKey(null);
titleEl.setValue("");
defLangEl.uncheckAll();
repoEntry = null;
}
public LanguageConfiguration getRawObject() {
boolean defLang = defLangEl.isAtLeastSelected(1);
langConfig.setDefaultConfiguration(defLang);
String title = titleEl.getValue();
langConfig.setTitle(title);
return langConfig;
}
}
private enum CSCols {
defLanguage("site.default.language"),
language("site.language"),
title("site.title"),
courseId("site.course.id"),
courseTitle("site.course.title");
private final String i18n;
private CSCols(String i18n) {
this.i18n = i18n;
}
public String i18nKey() {
return i18n;
}
}
private class CourseSiteDataModel extends DefaultFlexiTableDataModel<LanguageConfigurationRow> {
public CourseSiteDataModel(FlexiTableColumnModel columnModel) {
super(columnModel);
}
@Override
public CourseSiteDataModel createCopyWithEmptyList() {
return new CourseSiteDataModel(getTableColumnModel());
}
@Override
public Object getValueAt(int row, int col) {
LanguageConfigurationRow id = getObject(row);
switch(CSCols.values()[col]) {
case defLanguage: return id.getDefLangEl();
case language: return id.getLanguage();
case title: return id.getTitleEl();
case courseId: return id.getSoftKey();
case courseTitle: return id.getRepoEntryDisplayName();
default: return "???";
}
}
}
} |
3e1cba2ca644eb875a3c3a85788c34ffe7106c9e | 6,880 | java | Java | zmon-controller-app/src/test/java/org/zalando/zmon/controller/GrafanaUIControllerTest.java | maxim-tschumak/zmon-controller | 616d3f79b2d1c4b31847fd1033adb84fab10ae7c | [
"Apache-2.0"
] | null | null | null | zmon-controller-app/src/test/java/org/zalando/zmon/controller/GrafanaUIControllerTest.java | maxim-tschumak/zmon-controller | 616d3f79b2d1c4b31847fd1033adb84fab10ae7c | [
"Apache-2.0"
] | null | null | null | zmon-controller-app/src/test/java/org/zalando/zmon/controller/GrafanaUIControllerTest.java | maxim-tschumak/zmon-controller | 616d3f79b2d1c4b31847fd1033adb84fab10ae7c | [
"Apache-2.0"
] | null | null | null | 42.469136 | 119 | 0.703634 | 12,188 | package org.zalando.zmon.controller;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.ui.ExtendedModelMap;
import org.zalando.zmon.config.AppdynamicsProperties;
import org.zalando.zmon.config.ControllerProperties;
import org.zalando.zmon.config.EumTracingProperties;
import org.zalando.zmon.config.KairosDBProperties;
import org.zalando.zmon.persistence.GrafanaDashboardSprocService;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(MockitoJUnitRunner.class)
public class GrafanaUIControllerTest {
@Test
public void TestControllerInjectsAppDynamicsConfiguration() {
AppdynamicsProperties appdynamicsProperties = new AppdynamicsProperties();
ControllerProperties controllerProperties = new ControllerProperties();
EumTracingProperties eumTracingProperties = new EumTracingProperties();
controllerProperties.setEnableAppdynamics(true);
GrafanaUIController controller = new GrafanaUIController(
mock(KairosDBProperties.class),
controllerProperties,
appdynamicsProperties,
eumTracingProperties,
mock(GrafanaDashboardSprocService.class)
);
ExtendedModelMap model = new ExtendedModelMap();
controller.grafana(model);
Assertions.assertThat(model.get(IndexController.APPDYNAMICS_ENABLED)).isEqualTo(true);
Assertions.assertThat(model.get(IndexController.APPDYNAMICS_CONFIG)).isEqualTo(appdynamicsProperties);
}
@Test
public void TestControllerInjectsAppDynamicsConfigurationInDeepLinks() {
AppdynamicsProperties appdynamicsProperties = new AppdynamicsProperties();
ControllerProperties controllerProperties = new ControllerProperties();
EumTracingProperties eumTracingProperties = new EumTracingProperties();
controllerProperties.setEnableAppdynamics(true);
GrafanaUIController controller = new GrafanaUIController(
mock(KairosDBProperties.class),
controllerProperties,
appdynamicsProperties,
eumTracingProperties,
mock(GrafanaDashboardSprocService.class)
);
ExtendedModelMap model = new ExtendedModelMap();
controller.grafanaDeepLinks(model);
Assertions.assertThat(model.get(IndexController.APPDYNAMICS_ENABLED)).isEqualTo(true);
Assertions.assertThat(model.get(IndexController.APPDYNAMICS_CONFIG)).isEqualTo(appdynamicsProperties);
}
@Test
public void TestControllerDisablesAppDynamicsByDefault() {
GrafanaUIController controller = new GrafanaUIController(
mock(KairosDBProperties.class),
mock(ControllerProperties.class),
mock(AppdynamicsProperties.class),
mock(EumTracingProperties.class),
mock(GrafanaDashboardSprocService.class)
);
ExtendedModelMap model = new ExtendedModelMap();
controller.grafana(model);
Assertions.assertThat(model.get(IndexController.APPDYNAMICS_ENABLED)).isEqualTo(false);
}
@Test
public void TestControllerDisablesAppDynamicsInDeepLinksByDefault() {
GrafanaUIController controller = new GrafanaUIController(
mock(KairosDBProperties.class),
mock(ControllerProperties.class),
mock(AppdynamicsProperties.class),
mock(EumTracingProperties.class),
mock(GrafanaDashboardSprocService.class)
);
ExtendedModelMap model = new ExtendedModelMap();
controller.grafanaDeepLinks(model);
Assertions.assertThat(model.get(IndexController.APPDYNAMICS_ENABLED)).isEqualTo(false);
}
@Test
public void TestGrafana6Redirect() throws Exception {
GrafanaDashboardSprocService grafanaService = mock(GrafanaDashboardSprocService.class);
GrafanaUIController controller = new GrafanaUIController(
mock(KairosDBProperties.class),
mock(ControllerProperties.class),
mock(AppdynamicsProperties.class),
mock(EumTracingProperties.class),
grafanaService
);
when(grafanaService.getGrafanaMapping(anyString())).thenReturn("someuid");
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).alwaysDo(print()).build();
MvcResult result = mockMvc.perform(get("/grafana6/dashboard/db/testing?some-param=some-value")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().is3xxRedirection())
.andReturn();
Assertions.assertThat(result.getResponse().getHeader("Location")).contains("/d/someuid?some-param=some-value");
}
@Test
public void TestGrafana6RedirectUnknownUid() throws Exception {
GrafanaUIController controller = new GrafanaUIController(
mock(KairosDBProperties.class),
mock(ControllerProperties.class),
mock(AppdynamicsProperties.class),
mock(EumTracingProperties.class),
mock(GrafanaDashboardSprocService.class)
);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).alwaysDo(print()).build();
mockMvc.perform(get("/grafana6/dashboard/db/testing?some-param=some-value")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound())
.andReturn();
}
@Test
public void TestGrafana6HomeRedirect() throws Exception {
GrafanaUIController controller = new GrafanaUIController(
mock(KairosDBProperties.class),
mock(ControllerProperties.class),
mock(AppdynamicsProperties.class),
mock(EumTracingProperties.class),
mock(GrafanaDashboardSprocService.class)
);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).alwaysDo(print()).build();
MvcResult result = mockMvc.perform(get("/grafana6")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().is3xxRedirection())
.andReturn();
}
}
|
3e1cba66a4a10317c328775948b4b2a846904ba0 | 5,818 | java | Java | src/test/java/com/synopsys/integration/jira/common/server/JiraServerAppServiceTestIT.java | dunfield-synopsys/int-jira-common | dc7c4475d5f766e59379bfed14c88e64665b900f | [
"Apache-2.0"
] | 1 | 2020-04-13T06:27:23.000Z | 2020-04-13T06:27:23.000Z | src/test/java/com/synopsys/integration/jira/common/server/JiraServerAppServiceTestIT.java | dunfield-synopsys/int-jira-common | dc7c4475d5f766e59379bfed14c88e64665b900f | [
"Apache-2.0"
] | 7 | 2020-02-06T21:16:33.000Z | 2020-10-08T16:26:41.000Z | src/test/java/com/synopsys/integration/jira/common/server/JiraServerAppServiceTestIT.java | dunfield-synopsys/int-jira-common | dc7c4475d5f766e59379bfed14c88e64665b900f | [
"Apache-2.0"
] | 3 | 2020-10-07T21:30:40.000Z | 2021-12-10T17:32:54.000Z | 54.373832 | 157 | 0.75868 | 12,189 | package com.synopsys.integration.jira.common.server;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import com.synopsys.integration.jira.common.model.response.InstalledAppsResponseModel;
import com.synopsys.integration.jira.common.model.response.PluginResponseModel;
import com.synopsys.integration.jira.common.rest.JiraHttpClient;
import com.synopsys.integration.jira.common.rest.service.PluginManagerService;
import com.synopsys.integration.jira.common.server.service.JiraServerServiceFactory;
import com.synopsys.integration.rest.RestConstants;
import com.synopsys.integration.rest.exception.IntegrationRestException;
public class JiraServerAppServiceTestIT extends JiraServerParameterizedTestIT {
private static final String APP_KEY = "com.synopsys.integration.alert";
private static final String APP_SERVER_URI = "https://blackducksoftware.github.io/alert-issue-property-indexer/JiraServerApp/1.0.0/atlassian-plugin.xml";
// If these tests start breaking, verify the 'Barcharts for Jira' plugin is still free and available.
private static final String APP_FREE_MARKETPLACE_KEY = "com.tngtech.gadgets.jira-barchart-gadget-plugin";
@AfterEach
public void waitForUninstallToFinish() throws InterruptedException {
Thread.sleep(1000);
}
@ParameterizedTest
@MethodSource("getParameters")
@Disabled("This test is flaky as it occasionally takes too long to install and fails the test")
public void installServerAppTest(JiraHttpClient jiraHttpClient) throws Exception {
JiraServerServiceTestUtility.validateConfiguration();
JiraServerServiceFactory serviceFactory = JiraServerServiceTestUtility.createServiceFactory(jiraHttpClient);
PluginManagerService pluginManagerService = serviceFactory.createPluginManagerService();
int installResponse = pluginManagerService.installMarketplaceServerApp(APP_FREE_MARKETPLACE_KEY);
assertTrue(isStatusCodeSuccess(installResponse), "Expected a 2xx response code, but was: " + installResponse);
Thread.sleep(3000);
int uninstallResponse = pluginManagerService.uninstallApp(APP_FREE_MARKETPLACE_KEY);
assertTrue(isStatusCodeSuccess(uninstallResponse), "Expected a 2xx response code, but was: " + uninstallResponse);
}
@ParameterizedTest
@MethodSource("getParameters")
@Disabled("Disabled because development mode will likely not be turned on most of the time.")
public void installServerDevelopmentAppTest(JiraHttpClient jiraHttpClient) throws Exception {
JiraServerServiceTestUtility.validateConfiguration();
JiraServerServiceFactory serviceFactory = JiraServerServiceTestUtility.createServiceFactory(jiraHttpClient);
PluginManagerService pluginManagerService = serviceFactory.createPluginManagerService();
int installResponse = pluginManagerService.installDevelopmentApp("Test", APP_SERVER_URI);
assertTrue(isStatusCodeSuccess(installResponse), "Expected a 2xx response code, but was: " + installResponse);
Thread.sleep(3000);
int uninstallResponse = pluginManagerService.uninstallApp(APP_KEY);
assertTrue(isStatusCodeSuccess(uninstallResponse), "Expected a 2xx response code, but was: " + uninstallResponse);
}
@ParameterizedTest
@MethodSource("getParameters")
@Disabled("This test is flaky as it occasionally takes too long to install and fails the test")
public void getInstalledAppsTest(JiraHttpClient jiraHttpClient) throws Exception {
JiraServerServiceTestUtility.validateConfiguration();
JiraServerServiceFactory serviceFactory = JiraServerServiceTestUtility.createServiceFactory(jiraHttpClient);
PluginManagerService pluginManagerService = serviceFactory.createPluginManagerService();
Optional<PluginResponseModel> fakeApp = pluginManagerService.getInstalledApp("not.a.real.key");
assertFalse(fakeApp.isPresent(), "Expected app to not be installed");
int installResponse = pluginManagerService.installMarketplaceServerApp(APP_FREE_MARKETPLACE_KEY);
throwExceptionForError(installResponse);
Thread.sleep(3000);
InstalledAppsResponseModel installedApps = pluginManagerService.getInstalledApps();
List<PluginResponseModel> allInstalledPlugins = installedApps.getPlugins();
List<PluginResponseModel> userInstalledPlugins = allInstalledPlugins
.stream()
.filter(plugin -> plugin.getUserInstalled())
.collect(Collectors.toList());
assertTrue(userInstalledPlugins.size() < allInstalledPlugins.size(), "Expected fewer user-installed plugins than total plugins");
int uninstallResponse = pluginManagerService.uninstallApp(APP_FREE_MARKETPLACE_KEY);
throwExceptionForError(uninstallResponse);
}
private boolean isStatusCodeSuccess(int status) {
return status >= RestConstants.OK_200 && status < RestConstants.MULT_CHOICE_300;
}
public boolean isStatusCodeError(int status) {
return status >= RestConstants.BAD_REQUEST_400;
}
public void throwExceptionForError(int status) throws IntegrationRestException {
if (isStatusCodeError(status)) {
throw new IntegrationRestException(null, null, status, "statusMessage", "Body", "message");
}
}
}
|
3e1cba72981b81081c0ca183611ee28ec37a6207 | 2,835 | java | Java | jeecg-boot-module-system/src/main/java/org/jeecg/modules/workflow/controller/WfMyRelatedProcessController.java | Monologuter/jeecg-boot-User | a12bf0e17829bd19aaebae5813be92c3e4c90e6d | [
"MIT"
] | 1 | 2022-01-28T17:20:01.000Z | 2022-01-28T17:20:01.000Z | jeecg-boot-module-system/src/main/java/org/jeecg/modules/workflow/controller/WfMyRelatedProcessController.java | Monologuter/jeecg-boot-User | a12bf0e17829bd19aaebae5813be92c3e4c90e6d | [
"MIT"
] | null | null | null | jeecg-boot-module-system/src/main/java/org/jeecg/modules/workflow/controller/WfMyRelatedProcessController.java | Monologuter/jeecg-boot-User | a12bf0e17829bd19aaebae5813be92c3e4c90e6d | [
"MIT"
] | 1 | 2021-11-27T15:25:45.000Z | 2021-11-27T15:25:45.000Z | 45.725806 | 107 | 0.555203 | 12,190 | package org.jeecg.modules.workflow.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.workflow.entity.vo.RecordsListPageVO;
import org.jeecg.modules.workflow.service.WfMyRelatedProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 我的历史任务所属流程状态
* @author lz
* @company DXC.technology
* @date 2021-8-19
*/
@RestController
@RequestMapping("workflow/workflow-my-related-process")
@Api(tags = "工作流")
@Slf4j
public class WfMyRelatedProcessController {
@Autowired
private WfMyRelatedProcessService wfMyRelatedProcessService;
/**
* @Description:
* 我已办(工作台)
* 查询我的历史任务所属流程的相关信息
* @param pageNo 当前页
* @param pageSize 每页数据的条数
* @param assignee 办理人id
* @param proState 流程的状态
* @param startUserId 流程发起人
* @Return : org.jeecg.common.api.vo.Result<org.jeecg.modules.workflow.entity.vo.RecordsListPageVO>
* @Author : LZ @DXC.Technology
* @Time: 2021/8/27 17:05
*/
@ApiOperation(value = "我的历史任务所属流程状态", notes = "我的历史任务所属流程状态")
@GetMapping("/get-processByTaskAssignee")
public Result<RecordsListPageVO> queryProcessByTaskAssignee(@ApiParam(value = "当前页", required = true)
@RequestParam Integer pageNo,
@ApiParam(value = "显示多少条", required = true)
@RequestParam Integer pageSize,
@ApiParam(value = "执行人", required = true)
@RequestParam String assignee,
@ApiParam(value = "流程实例状态")
@RequestParam(required = false)
String proState,
@ApiParam(value = "流程实例发起人ID")
@RequestParam(required = false)
String startUserId) {
return wfMyRelatedProcessService.queryProcessByTaskAssignee(
pageNo, pageSize, assignee, proState, startUserId);
}
}
|
3e1cbb4243f7c8eec0d80cf1f1e2fa564ec10ecb | 1,412 | java | Java | asion-bot/asion-bot-web/src/main/java/org/asion/bot/selenium/processor/executor/MessageQueue.java | search-cloud/spring-boot-cloud-microservices-docker | 7e09a4b3ff04548e34b5e04ead054e8de674eb70 | [
"Apache-2.0"
] | null | null | null | asion-bot/asion-bot-web/src/main/java/org/asion/bot/selenium/processor/executor/MessageQueue.java | search-cloud/spring-boot-cloud-microservices-docker | 7e09a4b3ff04548e34b5e04ead054e8de674eb70 | [
"Apache-2.0"
] | 1 | 2018-05-11T07:48:00.000Z | 2018-05-11T07:48:00.000Z | asion-bot/asion-bot-web/src/main/java/org/asion/bot/selenium/processor/executor/MessageQueue.java | search-cloud/spring-boot-cloud-microservices-docker | 7e09a4b3ff04548e34b5e04ead054e8de674eb70 | [
"Apache-2.0"
] | null | null | null | 28.816327 | 85 | 0.630312 | 12,191 | package org.asion.bot.selenium.processor.executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class MessageQueue<T extends Serializable> {
private static final Logger logger = LoggerFactory.getLogger(MessageQueue.class);
private final int MAX_SIZE = 1000;
private BlockingQueue<T> messageQueue = new LinkedBlockingQueue<>(MAX_SIZE);
private static MessageQueue instance = new MessageQueue();
private MessageQueue() {}
static <E extends Serializable> MessageQueue<E> getInstance() {
return instance;
}
void produce(T message) {
if (messageQueue.size() == MAX_SIZE) {
logger.debug("messageQueue is full: {}, waiting for consume!", MAX_SIZE);
}
try {
messageQueue.put(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T consume() {
T message = null;
if (messageQueue.isEmpty()) {
logger.debug("messageQueue is empty, waiting for produce!");
// sleep 3 seconds.
// Companion.sleep(3);
}
try {
message = messageQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return message;
}
} |
3e1cbd1b7010ab8389f84841a1b0a20c622f9530 | 7,619 | java | Java | app/src/main/java/com/miki/colinde/MainActivity.java | iavorovschi/colinde_android | ca4e50ee77a34b2c98eea996596bf90aefca7362 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/miki/colinde/MainActivity.java | iavorovschi/colinde_android | ca4e50ee77a34b2c98eea996596bf90aefca7362 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/miki/colinde/MainActivity.java | iavorovschi/colinde_android | ca4e50ee77a34b2c98eea996596bf90aefca7362 | [
"Apache-2.0"
] | null | null | null | 37.53202 | 123 | 0.64746 | 12,192 | package com.miki.colinde;
import static com.miki.colinde.R.id;
import static com.miki.colinde.R.layout;
import static com.miki.colinde.R.menu;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.Toolbar;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.util.FitPolicy;
public class MainActivity extends AppCompatActivity {
private static final String PRIVATE_PREF = "my_preferences";
private static final String PREF_SCROLL_DIRECTION = "horizontal_scroll";
private static final String PREF_SCROLL_TYPE = "scroll_page_by_page";
private PDFView pdfView;
private SharedPreferences myPref;
private MyScrollHandler myScrollHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
Toolbar toolbar = findViewById(id.appBar);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(v -> openBookMarks());
toolbar.setNavigationIcon(R.drawable.ic_bookmarks);
toolbar.setNavigationContentDescription(R.string.book_marks_name);
myPref = getSharedPreferences(PRIVATE_PREF, MODE_PRIVATE);
initPdf();
}
@Override
public boolean onCreateOptionsMenu(Menu newMenu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(menu.main_menu, newMenu);
return true;
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case id.search:
myScrollHandler.onCreateDialog();
break;
case id.settings:
openSettings(id.settings);
break;
default:
return super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
private void openBookMarks() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View dialogView = inflater.inflate(layout.dialog_book_marks, null);
dialogBuilder.setView(dialogView);
TextView content = dialogView.findViewById(id.content);
TextView literateContent = dialogView.findViewById(id.literate_content);
TextView oldCarols = dialogView.findViewById(id.old_carols);
TextView viflaim = dialogView.findViewById(id.viflaim);
TextView greetings = dialogView.findViewById(id.greetings);
TextView songs = dialogView.findViewById(id.church_songs);
TextView notes = dialogView.findViewById(id.musical_notes);
dialogBuilder.setTitle(getResources().getString(R.string.book_marks_name));
dialogBuilder.setNegativeButton(getResources().getString(R.string.button_cancel), (dialog, id) -> dialog.cancel());
Dialog dialog = dialogBuilder.create();
content.setOnClickListener(value -> {
pdfView.jumpTo(413);
dialog.dismiss();
});
literateContent.setOnClickListener(value -> {
pdfView.jumpTo(404);
dialog.dismiss();
});
oldCarols.setOnClickListener(value -> {
pdfView.jumpTo(317);
dialog.dismiss();
});
greetings.setOnClickListener(value -> {
pdfView.jumpTo(334);
dialog.dismiss();
});
viflaim.setOnClickListener(value -> {
pdfView.jumpTo(338);
dialog.dismiss();
});
content.setOnClickListener(value -> {
pdfView.jumpTo(413);
dialog.dismiss();
});
songs.setOnClickListener(value -> {
pdfView.jumpTo(347);
dialog.dismiss();
});
notes.setOnClickListener(value -> {
pdfView.jumpTo(359);
dialog.dismiss();
});
dialog.show();
}
private void setCheckBox(String pref, MenuItem item) {
SharedPreferences.Editor editor = getSharedPreferences(PRIVATE_PREF, MODE_PRIVATE).edit();
editor.putBoolean(pref, !item.isChecked());
item.setChecked(!item.isChecked());
editor.apply();
}
private void initCheckBoxes(Menu menu) {
boolean horizontal_scroll = myPref.getBoolean(PREF_SCROLL_DIRECTION, true);
boolean page_by_page = myPref.getBoolean(PREF_SCROLL_TYPE, true);
menu.getItem(0).setChecked(horizontal_scroll);
menu.getItem(1).setChecked(page_by_page);
}
@SuppressLint("NonConstantResourceId")
private void openSettings(int newId) {
PopupMenu popup = new PopupMenu(this, findViewById(newId));
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(menu.settings_menu, popup.getMenu());
initCheckBoxes(popup.getMenu());
popup.setOnMenuItemClickListener(item -> {
switch (item.getItemId()) {
case id.scroll:
setCheckBox(PREF_SCROLL_DIRECTION, item);
initPdf();
break;
case id.page_by_page:
setCheckBox(PREF_SCROLL_TYPE, item);
pdfView.setPageSnap(item.isChecked());
pdfView.setPageFling(item.isChecked());
break;
default:
break;
}
keepPopUpAlive(item);
return false;
});
popup.show();
}
private void keepPopUpAlive(MenuItem item) {
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
item.setActionView(new View(getBaseContext()));
item.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return false;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return false;
}
});
}
private void initPdf() {
myScrollHandler = new MyScrollHandler(this);
ProgressBar progressBar = findViewById(R.id.loadingBar);
progressBar.setVisibility(View.VISIBLE);
boolean horizontal_scroll = myPref.getBoolean(PREF_SCROLL_DIRECTION, true);
boolean page_by_page = myPref.getBoolean(PREF_SCROLL_TYPE, true);
pdfView = findViewById(id.pdfView);
pdfView.fromAsset("book.pdf")
.swipeHorizontal(horizontal_scroll)
.scrollHandle(myScrollHandler)
.fitEachPage(true) // fit each page to the view, else smaller pages are scaled relative to largest page.
.pageSnap(page_by_page) // snap pages to screen boundaries
.pageFling(page_by_page) // make a fling change only a single page like ViewPager
.pageFitPolicy(FitPolicy.BOTH)
.autoSpacing(true)
.onLoad(pageNumber -> progressBar.setVisibility(View.GONE))
.load();
}
} |
3e1cbdd66d2ad41319ad84fd2db32b84ce27f075 | 1,119 | java | Java | reptile/src/main/java/cn/edu/jit/reptile/ReptileApplication.java | BeanCookie/shop-around | 75343203e33720aa140d892d0b7013e675ce95f5 | [
"Apache-2.0"
] | 3 | 2018-09-07T06:58:21.000Z | 2018-09-10T08:07:40.000Z | reptile/src/main/java/cn/edu/jit/reptile/ReptileApplication.java | loveluzhong/shop-around | 75343203e33720aa140d892d0b7013e675ce95f5 | [
"Apache-2.0"
] | 2 | 2020-07-16T09:56:33.000Z | 2021-05-07T18:02:18.000Z | reptile/src/main/java/cn/edu/jit/reptile/ReptileApplication.java | SmashBeanBun/shop-around | 75343203e33720aa140d892d0b7013e675ce95f5 | [
"Apache-2.0"
] | 1 | 2018-09-10T08:07:52.000Z | 2018-09-10T08:07:52.000Z | 34.96875 | 72 | 0.832887 | 12,193 | package cn.edu.jit.reptile;
import cn.edu.jit.reptile.config.SpiderConfig;
import cn.edu.jit.reptile.pipeline.CommodityPipeline;
import cn.edu.jit.reptile.processor.jd.CommodityPageProcessor;
import cn.edu.jit.reptile.scheduled.JdReptileScheduled;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.scheduler.RedisScheduler;
/**
* @author LuZhong
*/
@EnableFeignClients
@EnableDiscoveryClient
@EnableScheduling
@SpringBootApplication
public class ReptileApplication {
@Autowired
private RedisScheduler redisScheduler;
public static void main(String[] args) {
SpringApplication.run(ReptileApplication.class, args);
}
}
|
3e1cbf40dfa7225fda080fa92c426d2ab2103083 | 2,524 | java | Java | src/main/java/com/figaf/integration/cpi/entity/runtime_artifacts/IntegrationContentErrorInformation.java | figaf/cpi-api | ce98c5925e8a04b644bf7ddcb860895801874dd6 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/figaf/integration/cpi/entity/runtime_artifacts/IntegrationContentErrorInformation.java | figaf/cpi-api | ce98c5925e8a04b644bf7ddcb860895801874dd6 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/figaf/integration/cpi/entity/runtime_artifacts/IntegrationContentErrorInformation.java | figaf/cpi-api | ce98c5925e8a04b644bf7ddcb860895801874dd6 | [
"Apache-2.0"
] | null | null | null | 31.55 | 188 | 0.666006 | 12,194 | package com.figaf.integration.cpi.entity.runtime_artifacts;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.collections4.CollectionUtils;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
/**
* @author Arsenii Istlentev
*/
@Getter
@Setter
@ToString
public class IntegrationContentErrorInformation {
@Setter
@ToString
public static class IntegrationContentErrorInformationMessage {
private String subsystemName;
private String subsytemPartName;
private String subsystemPartName;
private String messageId;
private String messageText;
public String getSubsystemName() {
return subsystemName;
}
public String getSubsystemPartName() {
return subsystemPartName != null ? subsystemPartName : subsytemPartName;
}
public String getMessageId() {
return messageId;
}
public String getMessageText() {
return messageText;
}
}
private IntegrationContentErrorInformationMessage message;
private List<String> parameter = new ArrayList<>();
private List<IntegrationContentErrorInformation> childInstances;
private String errorMessage;
public String getErrorMessage() {
if (this.errorMessage == null) {
this.errorMessage = buildErrorMessage(this.childInstances, 0);
}
return this.errorMessage;
}
private String buildErrorMessage(List<IntegrationContentErrorInformation> childInstances, int numberOfWhitespaces) {
StringBuilder stringBuilder = new StringBuilder();
if (CollectionUtils.isNotEmpty(childInstances)) {
for (IntegrationContentErrorInformation child : childInstances) {
for (int i = 1; i <= numberOfWhitespaces; i++) {
stringBuilder.append(" ");
}
numberOfWhitespaces++;
stringBuilder.append(String.format("[%s][%s][%s] : ", child.getMessage().getSubsystemName(), child.getMessage().getSubsystemPartName(), child.getMessage().getMessageId()));
stringBuilder.append(MessageFormat.format(child.getMessage().getMessageText(), child.getParameter().toArray()));
stringBuilder.append("\n");
return stringBuilder.append(buildErrorMessage(child.getChildInstances(), numberOfWhitespaces)).toString();
}
}
return "";
}
}
|
3e1cbfc61b873016792e950a2795f1b856008ac3 | 706 | java | Java | src/test/java/validation/composite/bloc/of/named/Team.java | mbucc/Validol | 4885ab71225b99e9382581a7bac7bcdc600a371e | [
"MIT"
] | 2 | 2019-11-03T15:19:10.000Z | 2020-02-24T10:30:41.000Z | src/test/java/validation/composite/bloc/of/named/Team.java | mbucc/Validol | 4885ab71225b99e9382581a7bac7bcdc600a371e | [
"MIT"
] | 2 | 2020-05-06T06:20:44.000Z | 2022-02-20T15:14:15.000Z | src/test/java/validation/composite/bloc/of/named/Team.java | mbucc/Validol | 4885ab71225b99e9382581a7bac7bcdc600a371e | [
"MIT"
] | 1 | 2022-02-20T14:59:21.000Z | 2022-02-20T14:59:21.000Z | 17.65 | 86 | 0.590652 | 12,195 | package validation.composite.bloc.of.named;
import java.util.Map;
final public class Team
{
private String vasya;
private Integer fedya;
private Map<String, Object> tolya;
private Boolean jenya;
public Team(String vasya, Integer fedya, Map<String, Object> tolya, Boolean jenya)
{
this.vasya = vasya;
this.fedya = fedya;
this.tolya = tolya;
this.jenya = jenya;
}
public String vasya()
{
return this.vasya;
}
public Integer fedya()
{
return this.fedya;
}
public Map<String, Object> tolya()
{
return this.tolya;
}
public Boolean jenya()
{
return this.jenya;
}
}
|
3e1cbfeaae49e59bc8a55367751302b7a03f789c | 1,150 | java | Java | src/ch/bildspur/artnet/InetAddressAdapter.java | mfoulks3200/Illuminate | 59f34229e79aa4b5c5744048ff9377adfc643a63 | [
"BSD-3-Clause"
] | 2 | 2019-12-06T20:10:53.000Z | 2021-01-19T21:29:50.000Z | src/ch/bildspur/artnet/InetAddressAdapter.java | mfoulks3200/Illuminate | 59f34229e79aa4b5c5744048ff9377adfc643a63 | [
"BSD-3-Clause"
] | null | null | null | src/ch/bildspur/artnet/InetAddressAdapter.java | mfoulks3200/Illuminate | 59f34229e79aa4b5c5744048ff9377adfc643a63 | [
"BSD-3-Clause"
] | null | null | null | 29.487179 | 73 | 0.754783 | 12,196 | /*
* This file is part of artnet4j.
*
* Copyright 2009 Karsten Schmidt (PostSpectacular Ltd.)
*
* artnet4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* artnet4j is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with artnet4j. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.bildspur.artnet;
import java.net.InetAddress;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class InetAddressAdapter extends XmlAdapter<String, InetAddress> {
@Override
public String marshal(InetAddress adr) throws Exception {
return adr.getHostAddress();
}
@Override
public InetAddress unmarshal(String adr) throws Exception {
return InetAddress.getByName(adr);
}
}
|
3e1cc104654e7a5ee83fbf1b1f964b96b1a82503 | 1,387 | java | Java | coderbyte/challenges/questions_marks/TestChallenge.java | tusba/playground | 6794094f3a538365b89f4b78ded36428eaeec236 | [
"MIT"
] | null | null | null | coderbyte/challenges/questions_marks/TestChallenge.java | tusba/playground | 6794094f3a538365b89f4b78ded36428eaeec236 | [
"MIT"
] | null | null | null | coderbyte/challenges/questions_marks/TestChallenge.java | tusba/playground | 6794094f3a538365b89f4b78ded36428eaeec236 | [
"MIT"
] | null | null | null | 35.564103 | 91 | 0.671954 | 12,197 | package coderbyte.challenges.questions_marks;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.DisplayName;
import org.junit.platform.commons.annotation.Testable;
import util.annotation.ChallengeTest;
import util.test.ITest;
@DisplayName("Questions Marks challenge")
@Testable
public class TestChallenge implements ITest {
private static final IChallenge challenge = new Challenge();
@ChallengeTest
@DisplayName("Test questions marks")
@Override
public void perform() {
assertAll("Should be true",
() -> assertTrue(challenge.questionsMarks("acc?7??sss?3rr1??????5")),
() -> assertTrue(challenge.questionsMarks("arrb6???4xxbl5???eee5")),
() -> assertTrue(challenge.questionsMarks("5??aaaaaaaaaaaaaaaaaaa?5?a??5"))
);
assertAll("Should be false",
() -> assertFalse(challenge.questionsMarks("")),
() -> assertFalse(challenge.questionsMarks("aa6?9")),
() -> assertFalse(challenge.questionsMarks("4?5?4?aamm9")),
() -> assertFalse(challenge.questionsMarks("5??aaaaaaaaaaaaaaaaaaa?5?5")),
() -> assertFalse(challenge.questionsMarks("mbbv???????????4??????ddsdsdcc9?"))
);
}
}
|
3e1cc135e6b18dc2dd67d18c5a94e797d13dfadc | 1,240 | java | Java | Spring-Boot-Main-Class/src/main/java/com/dailycodebufffer/example/SpringBootMainClass/filter/MyCustomFilter.java | Lastman007/Spring-MVC-Tutorials | 8fd39a151c5e09b5c97a89eb7fdbb22b89aa22d9 | [
"MIT"
] | 161 | 2020-03-12T03:52:39.000Z | 2022-03-31T11:57:14.000Z | Spring-Boot-Main-Class/src/main/java/com/dailycodebufffer/example/SpringBootMainClass/filter/MyCustomFilter.java | Lastman007/Spring-MVC-Tutorials | 8fd39a151c5e09b5c97a89eb7fdbb22b89aa22d9 | [
"MIT"
] | 1 | 2020-12-23T12:31:42.000Z | 2020-12-23T12:31:42.000Z | Spring-Boot-Main-Class/src/main/java/com/dailycodebufffer/example/SpringBootMainClass/filter/MyCustomFilter.java | Lastman007/Spring-MVC-Tutorials | 8fd39a151c5e09b5c97a89eb7fdbb22b89aa22d9 | [
"MIT"
] | 503 | 2019-12-09T16:34:48.000Z | 2022-03-31T03:39:49.000Z | 31.794872 | 152 | 0.732258 | 12,198 | package com.dailycodebufffer.example.SpringBootMainClass.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyCustomFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(MyCustomFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("########## Initiating MyCustomFilter filter ##########");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
LOGGER.info("This Filter is only called when request is mapped for /filterExample resource");
//call next filter in the filter chain
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
LOGGER.info("########## Destroying MyCustomFilter filter ##########");
}
}
|
3e1cc2f2fdd708ea0f82c601c0bb905d4e991b2c | 1,272 | java | Java | src/main/java/com/manage/project/tool/gen/mapper/GenMapper.java | pengfei0666/common-project | fdb9ca58ccc75f346eb6ed87629224c87e4f3f67 | [
"MIT"
] | null | null | null | src/main/java/com/manage/project/tool/gen/mapper/GenMapper.java | pengfei0666/common-project | fdb9ca58ccc75f346eb6ed87629224c87e4f3f67 | [
"MIT"
] | null | null | null | src/main/java/com/manage/project/tool/gen/mapper/GenMapper.java | pengfei0666/common-project | fdb9ca58ccc75f346eb6ed87629224c87e4f3f67 | [
"MIT"
] | null | null | null | 20.190476 | 80 | 0.632862 | 12,199 | package com.manage.project.tool.gen.mapper;
import java.util.List;
import com.manage.project.tool.gen.domain.ColumnInfo;
import com.manage.project.tool.gen.domain.TableInfo;
/**
* 代码生成 数据层
*
* @author ruoyi
*/
public interface GenMapper
{
/**
* 查询ry MYSQL数据库表信息
*
* @param tableInfo 表信息
* @return 数据库表列表
*/
public List<TableInfo> selectMYSQLTableList(TableInfo tableInfo);
/**
* MYSQL根据表名称查询信息
*
* @param tableName 表名称
* @return 表信息
*/
public TableInfo selectMYSQLTableByName(String tableName);
/**
* MYSQL根据表名称查询列信息
*
* @param tableName 表名称
* @return 列信息
*/
public List<ColumnInfo> selectMYSQLTableColumnsByName(String tableName);
/**
* 查询ry SQLSERVER数据库表信息
*
* @param tableInfo 表信息
* @return 数据库表列表
*/
public List<TableInfo> selectSQLSERVERTableList(TableInfo tableInfo);
/**
* SQLSERVER根据表名称查询信息
*
* @param tableName 表名称
* @return 表信息
*/
public TableInfo selectSQLSERVERTableByName(String tableName);
/**
* SQLSERVER根据表名称查询列信息
*
* @param tableName 表名称
* @return 列信息
*/
public List<ColumnInfo> selectSQLSERVERTableColumnsByName(String tableName);
}
|
3e1cc352e0454469a28eb13f3db621cf4659c6e9 | 2,980 | java | Java | api/src/main/java/de/fuberlin/wiwiss/d2rq/map/HasUnclassified.java | avicomp/ont-d2rq | e9b251f8178a9f0357ed80c88b81ad681f3d3fa2 | [
"Apache-2.0"
] | 6 | 2018-03-14T20:42:13.000Z | 2019-11-09T03:45:29.000Z | api/src/main/java/de/fuberlin/wiwiss/d2rq/map/HasUnclassified.java | avicomp/ont-d2rq | e9b251f8178a9f0357ed80c88b81ad681f3d3fa2 | [
"Apache-2.0"
] | 21 | 2018-04-02T09:03:39.000Z | 2019-07-08T09:23:53.000Z | api/src/main/java/de/fuberlin/wiwiss/d2rq/map/HasUnclassified.java | owlcs/ont-d2rq | cf4ace40d853498c370611d1fe54d1268f923eb9 | [
"Apache-2.0"
] | 1 | 2019-10-19T18:46:12.000Z | 2019-10-19T18:46:12.000Z | 33.863636 | 105 | 0.664094 | 12,200 | package de.fuberlin.wiwiss.d2rq.map;
import java.util.stream.Stream;
/**
* A technical interface to provide access to different stuff that are difficult to classify.
* Applicable for {@link ClassMap} and {@link PropertyBridge}.
* <p>
* Created by @ssz on 30.09.2018.
*
* @param <R> subtype of {@link MapObject}
*/
interface HasUnclassified<R extends MapObject> extends HasTranslateWith<R> {
/**
* Sets a literal value for the {@code d2rq:bNodeIdColumns} predicate, where its lexical form is
* a comma-separated list of column names in {@code TableName.ColumnName} notation.
* The instances of this object will be blank nodes,
* one distinct blank node per distinct tuple of these columns.
*
* @param columns String, not {@code null}
* @return this instance to allow cascading calls
*/
R setBNodeIdColumns(String columns);
/**
* Gets {@code d2rq:bNodeIdColumns} string literal value
*
* @return String or {@code null}
*/
String getBNodeIdColumns();
/**
* Adds {@code d2rq:valueRegex} value to the object map, that
* asserts that all values of this bridge match a given regular expression.
* This allows D2RQ to speed up queries.
* Most useful in conjunction with {@link de.fuberlin.wiwiss.d2rq.vocab.D2RQ#column d2rq:column}
* on columns whose values are very different from other columns in the database.
*
* @param regex String, not {@code null}
* @return this instance to allow cascading calls
* @see <a href='http://d2rq.org/d2rq-language#hint'>11.2 Example: Providing a regular expression</a>
*/
R addValueRegex(String regex);
/**
* Lists all {@code d2rq:valueRegex} literals.
*
* @return Stream of String's
*/
Stream<String> valueRegexes();
/**
* Adds {@code d2rq:valueContains} value to the object map, that
* asserts that all values of this bridge always contain a given string.
* This allows D2RQ to speed up queries.
* Most useful in conjunction with {@link de.fuberlin.wiwiss.d2rq.vocab.D2RQ#column d2rq:column}.
*
* @param contains String, not {@code null}
* @return this instance to allow cascading calls
*/
R addValueContains(String contains);
/**
* Lists all {@code d2rq:valueContains} literals.
*
* @return Stream of String's
*/
Stream<String> valueContains();
/**
* Adds {@code d2rq:valueMaxLength} integer value to the RDF, that
* asserts that all values of this bridge are not longer than a number of characters.
* This allows D2RQ to speed up queries.
*
* @param maxLength positive int
* @return this instance to allow cascading calls
*/
R setValueMaxLength(int maxLength);
/**
* Returns {@code d2rq:valueMaxLength} integer value form the RDF.
*
* @return {@link Integer} or {@code null} if undefined
*/
Integer getValueMaxLength();
}
|
3e1cc3f0457b59ab5cb9d377447407a4774cbdc8 | 683 | java | Java | xmlintelledit/intelledit/src/main/java/at/ac/tuwien/big/xmlintelledit/intelledit/simpleregexp/visitors/QuantifierWrapper.java | patrickneubauer/XMLIntellEdit | 5e4a0ad59b7e9446e7f79dcb32e09971c2193118 | [
"MIT"
] | 6 | 2017-05-18T13:38:37.000Z | 2021-12-16T19:29:29.000Z | xmlintelledit/intelledit/src/main/java/at/ac/tuwien/big/xmlintelledit/intelledit/simpleregexp/visitors/QuantifierWrapper.java | patrickneubauer/XMLIntellEdit | 5e4a0ad59b7e9446e7f79dcb32e09971c2193118 | [
"MIT"
] | null | null | null | xmlintelledit/intelledit/src/main/java/at/ac/tuwien/big/xmlintelledit/intelledit/simpleregexp/visitors/QuantifierWrapper.java | patrickneubauer/XMLIntellEdit | 5e4a0ad59b7e9446e7f79dcb32e09971c2193118 | [
"MIT"
] | null | null | null | 23.551724 | 93 | 0.733529 | 12,201 | package at.ac.tuwien.big.xmlintelledit.intelledit.simpleregexp.visitors;
import org.antlr.runtime.tree.CommonTree;
public class QuantifierWrapper {
public boolean isGreedy = true;
public int minValue = 1;
public int maxValue = 1;
public QuantifierWrapper() {
}
public QuantifierWrapper(CommonTree quantifier) {
minValue = getInt((CommonTree)quantifier.getChild(0));
maxValue = getInt((CommonTree)quantifier.getChild(1));
if (quantifier.getChildCount() == 3 && "GREEDY".equals(quantifier.getChild(2).getText())) {
isGreedy = true;
}
}
public static int getInt(CommonTree numberTree) {
return Integer.valueOf(numberTree.getToken().getText());
}
}
|
3e1cc4327cc2042132a4a77d95a53f728b8dd5c9 | 450 | java | Java | src/main/java/be/davidopdebeeck/document/randomizer/xml/XmlElement.java | DavidOpDeBeeck/document-randomizer | 94ef76e58a2a1d79611ee8dd903c144c2b98dbe7 | [
"MIT"
] | 1 | 2022-02-15T20:06:20.000Z | 2022-02-15T20:06:20.000Z | src/main/java/be/davidopdebeeck/document/randomizer/xml/XmlElement.java | DavidOpDeBeeck/document-randomizer | 94ef76e58a2a1d79611ee8dd903c144c2b98dbe7 | [
"MIT"
] | null | null | null | src/main/java/be/davidopdebeeck/document/randomizer/xml/XmlElement.java | DavidOpDeBeeck/document-randomizer | 94ef76e58a2a1d79611ee8dd903c144c2b98dbe7 | [
"MIT"
] | null | null | null | 18.75 | 61 | 0.671111 | 12,202 | package be.davidopdebeeck.document.randomizer.xml;
import be.davidopdebeeck.document.randomizer.element.Element;
import org.dom4j.Node;
public class XmlElement implements Element {
private final Node node;
XmlElement(Node node) {
this.node = node;
}
@Override
public void setValue(String value) {
node.setText(value);
}
@Override
public String getValue() {
return node.getText();
}
}
|
3e1cc4c35ed9728683fefec64681c951fcf9204d | 13,038 | java | Java | src/de/gmxhome/conrad/jpos/jpos_base/UniqueIOProcessor.java | mjpcger/JavaPOS-SPF | f3db658d81f51ab2fcbcb62d53aa7f2489177222 | [
"Apache-2.0"
] | null | null | null | src/de/gmxhome/conrad/jpos/jpos_base/UniqueIOProcessor.java | mjpcger/JavaPOS-SPF | f3db658d81f51ab2fcbcb62d53aa7f2489177222 | [
"Apache-2.0"
] | 1 | 2021-12-09T15:12:54.000Z | 2021-12-09T17:53:11.000Z | src/de/gmxhome/conrad/jpos/jpos_base/UniqueIOProcessor.java | mjpcger/JavaPOS-SPF | f3db658d81f51ab2fcbcb62d53aa7f2489177222 | [
"Apache-2.0"
] | 2 | 2019-09-27T09:40:27.000Z | 2022-01-03T20:45:08.000Z | 40.490683 | 142 | 0.623025 | 12,203 | /*
* Copyright 2019 Martin Conrad
* <p>
* 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
* <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 de.gmxhome.conrad.jpos.jpos_base;
import jpos.JposConst;
import jpos.JposException;
import org.apache.log4j.Level;
import java.util.Arrays;
/**
* Unique implementation for IO processing. Derived classes should add
* support for serial (RS232), TCP and other IO operations
*/
public class UniqueIOProcessor {
/**
* Communication source, used for reading data. For RS232, Source, Target
* and Port are the same. In case of network connections, they can be
* different.
*/
protected String Source;
/**
* Extended error code for JposExceptions generated by IO processors.
*/
public static final int IOProcessorError = 1;
/**
* Gets source of previously read data.
* @return Data source, null before data have been read
*/
public String getSource() { return Source; }
/**
* Communication target, used for writing data. For RS232, Source, Target
* and Port are the same. In case of network connections, they can be
* different.
*/
protected String Target;
/**
* Initial communication target, used to check whether source (read) or
* target (write) shall be logged in read or write methods.
*/
protected String InitialPort;
/**
* Retrieves currently set target for writing data.
* @return Current target device, null if target has not been specified.
*/
public String getTarget() { return Target; }
/**
* Sets communication target. Depending on the IO processor type, setting
* communication target can be mandatory before calling method open.
* @param target communication target
* @return target
* @throws JposException if target is not a valid communication target.
*/
public String setTarget(String target) throws JposException { return Target = target; }
/**
* Communication port of the processor. Can be the name of a COM port
* in case of RS232 or the the (own) port number in case of TCP or UDP.
*/
protected String Port;
/**
* Logging prefix. String that will be used as prefix for all logging
* messages. Default: Port + ": "
*/
protected String LoggingPrefix;
/**
* Read timeout in milliseconds. Default: 0x10000000 (more than 8 years)
*/
protected int Timeout = 0x10000000;
/**
* Sets read timeout
* @param timeout Timeout in milliseconds
* @return timeout
*/
public int setTimeout(int timeout) { return Timeout = timeout; }
/**
* Logging type, one of LoggingTypeHexString, LoggingTypeEscapeString or LoggingTypeNoLogging. Default
* LoggingTypeEscapeString.
*/
protected int LoggingType = LoggingTypeEscapeString;
/**
* Sets the logging type for data logging.
* @param type One of the LoggingType constants.
* @return type
*/
public int setLoggingType(int type) { return LoggingType = type; }
/**
* Logging type constant for hex-dump-style logging. If used, data will be
* logged as pairs of two-digit hexadecimal digits, e.g. "Hello\n" as
* 48 65 62 62 6F 0A.
*/
public static final int LoggingTypeHexString = -1;
/**
* Logging type constant for excape-string style logging. If used, 7-bit
* ASCII letters will be logged "as is", while all other values will be
* logged as 3-letter octal triples with leading backslash. The backslash
* will be duplicated, e.g. "Hello\n" as
* Hello\012
*/
public static final int LoggingTypeEscapeString = 1;
/**
* Logging type constant for no data logging. Data will be replaced by
* ...
*/
public static final int LoggingTypeNoLogging = 0;
/**
* Device used for logging
*/
public JposDevice Dev;
/**
* Buffer with data to be logged in case of normal processing. In case
* of exceptional processing, specific messages must be generated by
* classes.
*/
public byte[] LoggingData;
/**
* Synchronization object for write operations.
*/
byte[] WriteSynchronizer = new byte[]{'W'};
/**
* Synchronization object for read operations.
*/
byte[] ReadSynchronizer = new byte[]{'R'};
/**
* Generate log string from byte buffer
* @param buffer byte array containing input or output data
* @return String corresponding to previously specified logging type
*/
public String toLogString(byte[] buffer) {
String res = "";
for (byte c : buffer) {
switch (LoggingType) {
case LoggingTypeHexString:
res += String.format(" %02X", c & 0xff);
break;
case LoggingTypeEscapeString:
if (c < 0x20)
res += String.format("\\%03o", (int)c & 0xff);
else if (c == '\\')
res += "\\";
else
res += new String(new byte[]{c});
break;
case LoggingTypeNoLogging:
return "...";
}
}
return res;
}
/**
* Stores JposDevice and port of derived IO processors. The device will
* be used for logging while the port specifies the communication object.
* @param dev Device that uses the processor. Processor uses logging of device
* to produce logging entries
* @param port Communication object, e.g. COM3 or 127.0.0.1:23456
* @throws JposException If port does not specify a valid communication object
*/
public UniqueIOProcessor(JposDevice dev, String port) throws JposException {
Dev = dev;
Port = Source = Target = port;
LoggingPrefix = port + ": ";
InitialPort = port;
}
/**
* Write a frame to the communication target. If called from a derived
* class, the byte array must be passed through unchanged for correct
* logging.
* @param buffer byte buffer containing the frame
* @return Number of bytes written to the target
* @throws JposException if something goes wrong
*/
public int write(byte[] buffer) throws JposException {
Dev.log(Level.TRACE, LoggingPrefix + "Write " + buffer.length + " byte" + location(false) +": " + toLogString(buffer));
return buffer.length;
}
/**
* Retrieves no. of readable units from communication source. If called from
* a derived class, LoggingData must be filled with the count to be returned.
* @return Unit count
* @throws JposException if something goes wrong
*/
public int available() throws JposException {
try {
int count = Integer.parseInt(new String(LoggingData));
Dev.log(Level.ALL, LoggingPrefix + "Available bytes: " + count);
return count;
} catch (Exception e) {
throw new JposException(JposConst.JPOS_E_ILLEGAL, IOProcessorError, "Available implementation error, no LoggingData available.");
}
}
/**
* Reads a frame of given maximum byte length from communication source. If called
* from a derived class, LoggingData must be filled with the byte array to be
* returned. If LoggingData is longer than the maximum length, the remaining bytes will be discarded.
* @param count Maximum no. of bytes to be read
* @return byte[] containing received bytes. In case of timeout, less than count
* bytes will be returned, in extreme case, the array has length zero.
* @throws JposException if something goes wrong
*/
public byte[] read(int count) throws JposException {
if (LoggingData == null)
throw new JposException(JposConst.JPOS_E_ILLEGAL, IOProcessorError, "Read implementation error, no LoggingData available.");
if (LoggingData.length > count) {
byte[] data = Arrays.copyOf(LoggingData, count);
byte[] remainder = Arrays.copyOfRange(LoggingData, count, LoggingData.length);
Dev.log(Level.TRACE, LoggingPrefix + "Read " + data.length + " bytes" + location(true) + ": " + toLogString(data));
Dev.log(Level.TRACE, LoggingPrefix + "Discard " + remainder.length + " bytes" + location(true) + ": " + toLogString(remainder));
return data;
} else {
Dev.log(Level.TRACE, LoggingPrefix + "Read " + LoggingData.length + " bytes" + location(true) + ": " + toLogString(LoggingData));
return LoggingData;
}
}
/**
* Generates string to be inserted into logging message whenever the source or target
* port does not match the initial port.
* @param from True in case of reading date, false in case of writing data.
* @return enpty string if current port matches initial port, " from <i>getSource()</i>" or
* " to <i>getTarget()</i>" otherwise.
*/
protected String location(boolean from) {
String port = from ? getSource() : getTarget();
return port.equals(InitialPort) ? "" : (from ? " from " : " to ") + port;
}
/**
* Empties input and output buffer
* @throws JposException Iif something goes wrong
*/
public void flush() throws JposException {
Dev.log(Level.TRACE, LoggingPrefix + "Flushed IO buffers.");
}
/**
* Opens processor for communication to specific source / target. Communication
* parameters must be set previously by specific setup method(s).
* @param noErrorLog if set, no logging occurs in error case to avoid a flood
* of error messages.
* @throws JposException if an IO error occurs
*/
public void open(boolean noErrorLog) throws JposException {
Dev.log(Level.DEBUG, LoggingPrefix + "Opened successfully.");
}
/**
* Finished any communication.
* @throws JposException If an IO error occurs
*/
public void close() throws JposException {
Dev.log(Level.DEBUG, LoggingPrefix + "Closed successfully.");
}
/**
* Generate a logging error message and throw the corresponding JposException.
* @param what Describes witch operation falied (e.g. "Read", "Available"...)
* @param error The Jpos error constant
* @param why The error message.
* @return Function never returns, it throws an exception always.
* @throws JposException The exception. Its message will be set to why.
*/
public int logerror(String what, int error, String why) throws JposException {
Dev.log(Level.ERROR, LoggingPrefix + what + " error: " + why);
throw new JposException(error, IOProcessorError, why);
}
/**
* Generate a logging error message and throw an JposException.
* @param what Describes witch operation falied (e.g. "Read", "Available"...)
* @param error The Jpos error constant
* @param ex JposException that lead to the error.
* @return Function never returns, it throws an exception always.
* @throws JposException The exception. Its message will be set to ex.getMessage().
*/
public int logerror(String what, int error, Exception ex) throws JposException {
Dev.log(Level.ERROR, LoggingPrefix + what + " error: " + ex.getMessage());
if (ex instanceof JposException)
throw (JposException) ex;
else
throw new JposException(error, IOProcessorError, ex.getMessage(), ex);
}
/**
* Generate a logging error message and throw an JposException.
* @param what Describes witch operation falied (e.g. "Read", "Available"...)
* @param ex JposException that lead to the error.
* @return Function never returns, it throws an exception always.
* @throws JposException The exception. Its message will be set to ex.getMessage().
*/
public int logerror(String what, JposException ex) throws JposException {
Dev.log(Level.ERROR, LoggingPrefix + what + " error: " + ex.getMessage());
throw (JposException) ex;
}
}
|
3e1cc5bab8f06ad3f9289feba696be0dd39dd662 | 4,542 | java | Java | modules/testing/data/src/main/java/com/examind/repository/DatasourceRepositoryTest.java | Geomatys/examind-community | e0ec81a5893a0e42a6c9c4a3d4c38945d75e9697 | [
"Apache-2.0"
] | 4 | 2019-06-27T19:52:56.000Z | 2021-08-31T05:56:03.000Z | modules/testing/data/src/main/java/com/examind/repository/DatasourceRepositoryTest.java | Geomatys/examind-community | e0ec81a5893a0e42a6c9c4a3d4c38945d75e9697 | [
"Apache-2.0"
] | 25 | 2019-11-13T09:34:18.000Z | 2022-02-17T13:39:04.000Z | modules/testing/data/src/main/java/com/examind/repository/DatasourceRepositoryTest.java | Geomatys/examind-community | e0ec81a5893a0e42a6c9c4a3d4c38945d75e9697 | [
"Apache-2.0"
] | 3 | 2019-04-06T14:54:17.000Z | 2019-10-23T08:34:54.000Z | 34.938462 | 89 | 0.682299 | 12,204 | /*
* Constellation - An open source and standard compliant SDI
* http://www.constellation-sdi.org
*
* Copyright 2019 Geomatys.
*
* 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.examind.repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.constellation.dto.DataSource;
import org.constellation.dto.DataSourcePath;
import org.constellation.dto.DataSourcePathComplete;
import org.constellation.repository.DatasourceRepository;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author Guilhem Legal (Geomatys)
*/
@Transactional
public class DatasourceRepositoryTest extends AbstractRepositoryTest {
@Autowired
private DatasourceRepository datasourceRepository;
@Test
public void crude() {
datasourceRepository.deleteAll();
List<DataSource> all = datasourceRepository.findAll();
Assert.assertTrue(all.isEmpty());
/**
* datasource insertion
*/
int did = datasourceRepository.create(TestSamples.newDataSource());
Assert.assertNotNull(did);
DataSourcePath dsPath = new DataSourcePath(did, "/", "fold", true, null, 0);
Map<String, String> types = new HashMap<>();
datasourceRepository.addAnalyzedPath(dsPath, types);
dsPath = new DataSourcePath(did, "/file1", "file1", false, "/", 123);
types.put("store1", "type1");
datasourceRepository.addAnalyzedPath(dsPath, types);
dsPath = new DataSourcePath(did, "/file2", "file2", false, "/", 123);
types.clear();
types.put("store1", "type2");
datasourceRepository.addAnalyzedPath(dsPath, types);
dsPath = new DataSourcePath(did, "/file3", "file3", false, "/", 123);
types.clear();
types.put("store2", "type1");
datasourceRepository.addAnalyzedPath(dsPath, types);
datasourceRepository.addSelectedPath(did, "/file1");
datasourceRepository.addSelectedPath(did, "/file2");
DataSource ds1 = datasourceRepository.findById(did);
Assert.assertNotNull(ds1);
int did2 = datasourceRepository.create(TestSamples.newDataSourceQuote());
Assert.assertNotNull(did);
DataSource ds2 = datasourceRepository.findById(did2);
Assert.assertNotNull(ds2);
/**
* datasource verification
*/
DataSource ds = datasourceRepository.findByUrl("file:///home/test");
Assert.assertNotNull(ds);
Assert.assertEquals("PENDING", datasourceRepository.getAnalysisState(did));
Map<String,Set<String>> stores = datasourceRepository.getDatasourceStores(did);
Assert.assertTrue(stores.containsKey("store1"));
Assert.assertTrue(stores.containsKey("store2"));
Assert.assertTrue(stores.get("store1").contains("type1"));
Assert.assertTrue(stores.get("store1").contains("type2"));
Assert.assertTrue(stores.get("store2").contains("type1"));
DataSourcePathComplete dpc = datasourceRepository.getAnalyzedPath(did, "/file1");
Assert.assertNotNull(dpc);
/*
* selected path
*/
Assert.assertTrue(datasourceRepository.hasSelectedPath(did));
Assert.assertTrue(datasourceRepository.existSelectedPath(did, "/file1"));
datasourceRepository.clearSelectedPath(did);
Assert.assertFalse(datasourceRepository.hasSelectedPath(did));
datasourceRepository.deletePath(did, "/file1");
dpc = datasourceRepository.getAnalyzedPath(did, "/file1");
Assert.assertNull(dpc);
ds = datasourceRepository.findByUrl("file:///home/tes't");
Assert.assertNotNull(ds);
/**
* datasource delete
*/
datasourceRepository.delete(did);
ds = datasourceRepository.findById(did);
Assert.assertNull(ds);
}
}
|
3e1cc62bbcaa5ed5cda8d2dfed895319ffa5fa43 | 2,970 | java | Java | JPA/src/main/java/com/thansoft/springbootjpa/entity/Person.java | Thansoft007/Spring-Boot-Workspace | fcb6a2e44aa85bece6ab5cddd63765dd207208a7 | [
"Apache-2.0"
] | null | null | null | JPA/src/main/java/com/thansoft/springbootjpa/entity/Person.java | Thansoft007/Spring-Boot-Workspace | fcb6a2e44aa85bece6ab5cddd63765dd207208a7 | [
"Apache-2.0"
] | null | null | null | JPA/src/main/java/com/thansoft/springbootjpa/entity/Person.java | Thansoft007/Spring-Boot-Workspace | fcb6a2e44aa85bece6ab5cddd63765dd207208a7 | [
"Apache-2.0"
] | null | null | null | 26.052632 | 126 | 0.711448 | 12,205 | package com.thansoft.springbootjpa.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.id.enhanced.SequenceStyleGenerator;
@Entity
@Table(name = "person")
@NamedQueries({
@NamedQuery(name = "Person.findByAgeLessThanEqualNamedQuery", query = "select p from Person p where p.age <=?1"),
@NamedQuery(name = "Person.salaryGreaterThanEqualNativeQuery", query = "select p from Person p where p.salary>=:salary") })
@NamedNativeQueries({
@NamedNativeQuery(name = "Person.personCountNamedNative", query = "select count(*) as countNative from Person") })
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "custom_id_person")
@GenericGenerator(name = "custom_id_person", strategy = "com.thansoft.springbootjpa.generator.CustomIdentifierGenerator")
private String id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
private int age;
private double salary;
@Column(name = "created_date")
private Date createdDate;
protected Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String id, String firstName, String lastName, int age, double salary, Date createdDate) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.salary = salary;
this.createdDate = createdDate;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Override
public String toString() {
return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", salary="
+ salary + ", createdDate=" + createdDate + "]";
}
}
|
3e1cc62ea1a7dce20bcda0073f8a34ecb1895cce | 9,257 | java | Java | egov/egov-ptis/src/main/java/org/egov/ptis/domain/entity/property/StructureClassification.java | spiliti/egovzm | fcc86a0209adab63b7b9d193983499310a34fcba | [
"MIT"
] | 1 | 2019-07-25T12:44:57.000Z | 2019-07-25T12:44:57.000Z | egov/egov-ptis/src/main/java/org/egov/ptis/domain/entity/property/StructureClassification.java | spiliti/egovzm | fcc86a0209adab63b7b9d193983499310a34fcba | [
"MIT"
] | 13 | 2020-03-05T00:01:16.000Z | 2022-02-09T22:58:42.000Z | egov/egov-ptis/src/main/java/org/egov/ptis/domain/entity/property/StructureClassification.java | spiliti/egovzm | fcc86a0209adab63b7b9d193983499310a34fcba | [
"MIT"
] | 1 | 2021-02-22T21:09:08.000Z | 2021-02-22T21:09:08.000Z | 28.351682 | 168 | 0.720095 | 12,206 | /*
* eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) 2017 eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/ or
* http://www.gnu.org/licenses/gpl.html .
*
* In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
* Further, all user interfaces, including but not limited to citizen facing interfaces,
* Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any
* derived works should carry eGovernments Foundation logo on the top right corner.
*
* For the logo, please refer http://egovernments.org/html/logo/egov_logo.png.
* For any further queries on attribution, including queries on brand guidelines,
* please contact lyhxr@example.com
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at lyhxr@example.com.
*
*/
package org.egov.ptis.domain.entity.property;
import org.egov.commons.Installment;
import org.egov.infra.persistence.entity.AbstractAuditable;
import org.egov.infra.persistence.validator.annotation.Unique;
import org.egov.infra.validation.exception.ValidationError;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* <p>
* Each deployment groups number of CostructionTypeSets and gives a common name.
* a For example: A particular ConstructionTypeSet might be composed of the
* following ConstructionType objects: TeakWood, MarbleFloor, RCCRoof. A name is
* given to the StructuralClassification. For example the name given to the
* above grouping can be Pucca. RoseWood, GraniteFloor and RCCRoof might also
* share the same name. A factor is normally associated with the Structural
* Classification which is used to calculate the demand of the Property.
* </p>
*
* @author Gayathri Joshi
* @version 2.00
* @see org.egov.ptis.domain.entity.property.ConstructionType
* @since 2.00
* @author srikanth Change Log : Added additional field
* constrTypeCode,orderId,fromDate,todate
*/
@Entity
@Table(name = "EGPT_STRUC_CL")
@Unique(columnName = { "CODE", "CONSTR_TYPE"}, fields = { "constrTypeCode", "typeName" }, enableDfltMsg = true)
@SequenceGenerator(name = StructureClassification.SEQ_STRUCTURE_CLASSIFICATION, sequenceName = StructureClassification.SEQ_STRUCTURE_CLASSIFICATION, allocationSize = 1)
public class StructureClassification extends AbstractAuditable {
private static final long serialVersionUID = 1L;
public static final String SEQ_STRUCTURE_CLASSIFICATION = "SEQ_EGPT_STRUC_CL";
@Id
@GeneratedValue(generator = SEQ_STRUCTURE_CLASSIFICATION, strategy = GenerationType.SEQUENCE)
private Long id;
@Audited
@Column(name = "CONSTR_TYPE")
private String typeName;
@Audited
@Column(name = "CONSTR_DESCR")
private String description;
@Audited
@Column(name = "CODE")
private String constrTypeCode;
@Column(name = "ORDER_ID")
private Integer orderId;
@Column(name = "FLOOR_NUM")
private Integer floorNum;
@Column(name = "CONSTR_NUM")
private Integer number;
@Column(name = "CONSTR_FACTOR")
private Float factor;
@ManyToOne
@JoinColumn(name = "ID_INSTALLMENT")
private Installment startInstallment;
@Column(name = "IS_HISTORY")
private char isHistory;
@Column(name = "FROM_DATE")
private Date fromDate;
@Column(name = "TO_DATE")
private Date toDate;
@Audited
@Column(name = "ISACTIVE")
private Boolean isActive;
/**
* @return Returns if the given Object is equal to PropertyStatus
*/
@Override
public boolean equals(final Object that) {
if (that == null)
return false;
if (this == that)
return true;
if (that.getClass() != this.getClass())
return false;
final StructureClassification thatStrCls = (StructureClassification) that;
if (getId() != null && thatStrCls.getId() != null) {
if (getId().equals(thatStrCls.getId()))
return true;
else
return false;
} else if (getTypeName() != null && thatStrCls.getTypeName() != null) {
if (getTypeName().equals(thatStrCls.getTypeName()))
return true;
else
return false;
} else if (getNumber() != null && thatStrCls.getNumber() != null) {
if (getNumber().equals(thatStrCls.getNumber()))
return true;
else
return false;
} else
return false;
}
/**
* @return Returns the hashCode
*/
@Override
public int hashCode() {
int hashCode = 0;
if (getId() != null)
hashCode += getId().hashCode();
if (getTypeName() != null)
hashCode += getTypeName().hashCode();
if (getNumber() != null)
hashCode += getNumber().hashCode();
return hashCode;
}
/**
* @return Returns the boolean after validating the current object
*/
public List<ValidationError> validate() {
final List<ValidationError> validationErrors = new ArrayList<ValidationError>();
if (getTypeName() == null) {
final ValidationError ve = new ValidationError("StrucClass.TypeName.Null",
"In StructureClassification Attribute 'Type Name' is Not Set, Please Check !!");
validationErrors.add(ve);
}
if (getNumber() == null || getNumber() == 0) {
final ValidationError ve = new ValidationError("StrucClass.Number.Null",
"In StructureClassification Attribute 'Number' is Not Set OR is Zero, Please Check !!");
validationErrors.add(ve);
}
return validationErrors;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("").append(id).append("|").append(constrTypeCode).append("|").append(factor);
return sb.toString();
}
public String getTypeName() {
return typeName;
}
public void setTypeName(final String typeName) {
this.typeName = typeName;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public String getConstrTypeCode() {
return constrTypeCode;
}
public void setConstrTypeCode(final String constrTypeCode) {
this.constrTypeCode = constrTypeCode.toUpperCase();
}
public Integer getOrderId() {
return orderId;
}
public void setOrderId(final Integer orderId) {
this.orderId = orderId;
}
public Integer getFloorNum() {
return floorNum;
}
public void setFloorNum(final Integer floorNum) {
this.floorNum = floorNum;
}
public Integer getNumber() {
return number;
}
public void setNumber(final Integer number) {
this.number = number;
}
public Float getFactor() {
return factor;
}
public void setFactor(final Float factor) {
this.factor = factor;
}
public Installment getStartInstallment() {
return startInstallment;
}
public void setStartInstallment(final Installment startInstallment) {
this.startInstallment = startInstallment;
}
public char getIsHistory() {
return isHistory;
}
public void setIsHistory(final char isHistory) {
this.isHistory = isHistory;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(final Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(final Date toDate) {
this.toDate = toDate;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(final Boolean isActive) {
this.isActive = isActive;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(final Long id) {
this.id = id;
}
}
|
3e1cc67dbf3379d18c3de29b3d4b4478c8d1628a | 19,095 | java | Java | unsafe/src/main/java/org/apache/spark/unsafe/types/UTF8String.java | sebastian-alfers/spark | 708794e8aae2c66bd291bab4f12117c33b57840c | [
"Apache-2.0",
"MIT"
] | null | null | null | unsafe/src/main/java/org/apache/spark/unsafe/types/UTF8String.java | sebastian-alfers/spark | 708794e8aae2c66bd291bab4f12117c33b57840c | [
"Apache-2.0",
"MIT"
] | null | null | null | unsafe/src/main/java/org/apache/spark/unsafe/types/UTF8String.java | sebastian-alfers/spark | 708794e8aae2c66bd291bab4f12117c33b57840c | [
"Apache-2.0",
"MIT"
] | null | null | null | 29.604651 | 100 | 0.611626 | 12,207 | /*
* 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.spark.unsafe.types;
import javax.annotation.Nonnull;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import org.apache.spark.unsafe.PlatformDependent;
import org.apache.spark.unsafe.array.ByteArrayMethods;
import static org.apache.spark.unsafe.PlatformDependent.*;
/**
* A UTF-8 String for internal Spark use.
* <p>
* A String encoded in UTF-8 as an Array[Byte], which can be used for comparison,
* search, see http://en.wikipedia.org/wiki/UTF-8 for details.
* <p>
* Note: This is not designed for general use cases, should not be used outside SQL.
*/
public final class UTF8String implements Comparable<UTF8String>, Serializable {
@Nonnull
private final Object base;
private final long offset;
private final int numBytes;
private static int[] bytesOfCodePointInUTF8 = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5,
6, 6};
public static final UTF8String EMPTY_UTF8 = UTF8String.fromString("");
/**
* Creates an UTF8String from byte array, which should be encoded in UTF-8.
*
* Note: `bytes` will be hold by returned UTF8String.
*/
public static UTF8String fromBytes(byte[] bytes) {
if (bytes != null) {
return new UTF8String(bytes, BYTE_ARRAY_OFFSET, bytes.length);
} else {
return null;
}
}
/**
* Creates an UTF8String from String.
*/
public static UTF8String fromString(String str) {
if (str == null) return null;
try {
return fromBytes(str.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
// Turn the exception into unchecked so we can find out about it at runtime, but
// don't need to add lots of boilerplate code everywhere.
throwException(e);
return null;
}
}
/**
* Creates an UTF8String that contains `length` spaces.
*/
public static UTF8String blankString(int length) {
byte[] spaces = new byte[length];
Arrays.fill(spaces, (byte) ' ');
return fromBytes(spaces);
}
protected UTF8String(Object base, long offset, int size) {
this.base = base;
this.offset = offset;
this.numBytes = size;
}
/**
* Writes the content of this string into a memory address, identified by an object and an offset.
* The target memory address must already been allocated, and have enough space to hold all the
* bytes in this string.
*/
public void writeToMemory(Object target, long targetOffset) {
PlatformDependent.copyMemory(
base,
offset,
target,
targetOffset,
numBytes
);
}
/**
* Returns the number of bytes for a code point with the first byte as `b`
* @param b The first byte of a code point
*/
private static int numBytesForFirstByte(final byte b) {
final int offset = (b & 0xFF) - 192;
return (offset >= 0) ? bytesOfCodePointInUTF8[offset] : 1;
}
/**
* Returns the number of bytes
*/
public int numBytes() {
return numBytes;
}
/**
* Returns the number of code points in it.
*/
public int numChars() {
int len = 0;
for (int i = 0; i < numBytes; i += numBytesForFirstByte(getByte(i))) {
len += 1;
}
return len;
}
/**
* Returns the underline bytes, will be a copy of it if it's part of another array.
*/
public byte[] getBytes() {
// avoid copy if `base` is `byte[]`
if (offset == BYTE_ARRAY_OFFSET && base instanceof byte[]
&& ((byte[]) base).length == numBytes) {
return (byte[]) base;
} else {
byte[] bytes = new byte[numBytes];
copyMemory(base, offset, bytes, BYTE_ARRAY_OFFSET, numBytes);
return bytes;
}
}
/**
* Returns a substring of this.
* @param start the position of first code point
* @param until the position after last code point, exclusive.
*/
public UTF8String substring(final int start, final int until) {
if (until <= start || start >= numBytes) {
return fromBytes(new byte[0]);
}
int i = 0;
int c = 0;
while (i < numBytes && c < start) {
i += numBytesForFirstByte(getByte(i));
c += 1;
}
int j = i;
while (i < numBytes && c < until) {
i += numBytesForFirstByte(getByte(i));
c += 1;
}
byte[] bytes = new byte[i - j];
copyMemory(base, offset + j, bytes, BYTE_ARRAY_OFFSET, i - j);
return fromBytes(bytes);
}
public UTF8String substringSQL(int pos, int length) {
// Information regarding the pos calculation:
// Hive and SQL use one-based indexing for SUBSTR arguments but also accept zero and
// negative indices for start positions. If a start index i is greater than 0, it
// refers to element i-1 in the sequence. If a start index i is less than 0, it refers
// to the -ith element before the end of the sequence. If a start index i is 0, it
// refers to the first element.
int start = (pos > 0) ? pos -1 : ((pos < 0) ? numChars() + pos : 0);
int end = (length == Integer.MAX_VALUE) ? Integer.MAX_VALUE : start + length;
return substring(start, end);
}
/**
* Returns whether this contains `substring` or not.
*/
public boolean contains(final UTF8String substring) {
if (substring.numBytes == 0) {
return true;
}
byte first = substring.getByte(0);
for (int i = 0; i <= numBytes - substring.numBytes; i++) {
if (getByte(i) == first && matchAt(substring, i)) {
return true;
}
}
return false;
}
/**
* Returns the byte at position `i`.
*/
private byte getByte(int i) {
return UNSAFE.getByte(base, offset + i);
}
private boolean matchAt(final UTF8String s, int pos) {
if (s.numBytes + pos > numBytes || pos < 0) {
return false;
}
return ByteArrayMethods.arrayEquals(base, offset + pos, s.base, s.offset, s.numBytes);
}
public boolean startsWith(final UTF8String prefix) {
return matchAt(prefix, 0);
}
public boolean endsWith(final UTF8String suffix) {
return matchAt(suffix, numBytes - suffix.numBytes);
}
/**
* Returns the upper case of this string
*/
public UTF8String toUpperCase() {
return fromString(toString().toUpperCase());
}
/**
* Returns the lower case of this string
*/
public UTF8String toLowerCase() {
return fromString(toString().toLowerCase());
}
/**
* Copy the bytes from the current UTF8String, and make a new UTF8String.
* @param start the start position of the current UTF8String in bytes.
* @param end the end position of the current UTF8String in bytes.
* @return a new UTF8String in the position of [start, end] of current UTF8String bytes.
*/
private UTF8String copyUTF8String(int start, int end) {
int len = end - start + 1;
byte[] newBytes = new byte[len];
copyMemory(base, offset + start, newBytes, BYTE_ARRAY_OFFSET, len);
return UTF8String.fromBytes(newBytes);
}
public UTF8String trim() {
int s = 0;
int e = this.numBytes - 1;
// skip all of the space (0x20) in the left side
while (s < this.numBytes && getByte(s) == 0x20) s++;
// skip all of the space (0x20) in the right side
while (e >= 0 && getByte(e) == 0x20) e--;
if (s > e) {
// empty string
return UTF8String.fromBytes(new byte[0]);
} else {
return copyUTF8String(s, e);
}
}
public UTF8String trimLeft() {
int s = 0;
// skip all of the space (0x20) in the left side
while (s < this.numBytes && getByte(s) == 0x20) s++;
if (s == this.numBytes) {
// empty string
return UTF8String.fromBytes(new byte[0]);
} else {
return copyUTF8String(s, this.numBytes - 1);
}
}
public UTF8String trimRight() {
int e = numBytes - 1;
// skip all of the space (0x20) in the right side
while (e >= 0 && getByte(e) == 0x20) e--;
if (e < 0) {
// empty string
return UTF8String.fromBytes(new byte[0]);
} else {
return copyUTF8String(0, e);
}
}
public UTF8String reverse() {
byte[] result = new byte[this.numBytes];
int i = 0; // position in byte
while (i < numBytes) {
int len = numBytesForFirstByte(getByte(i));
copyMemory(this.base, this.offset + i, result,
BYTE_ARRAY_OFFSET + result.length - i - len, len);
i += len;
}
return UTF8String.fromBytes(result);
}
public UTF8String repeat(int times) {
if (times <=0) {
return EMPTY_UTF8;
}
byte[] newBytes = new byte[numBytes * times];
copyMemory(this.base, this.offset, newBytes, BYTE_ARRAY_OFFSET, numBytes);
int copied = 1;
while (copied < times) {
int toCopy = Math.min(copied, times - copied);
System.arraycopy(newBytes, 0, newBytes, copied * numBytes, numBytes * toCopy);
copied += toCopy;
}
return UTF8String.fromBytes(newBytes);
}
/**
* Returns the position of the first occurrence of substr in
* current string from the specified position (0-based index).
*
* @param v the string to be searched
* @param start the start position of the current string for searching
* @return the position of the first occurrence of substr, if not found, -1 returned.
*/
public int indexOf(UTF8String v, int start) {
if (v.numBytes() == 0) {
return 0;
}
// locate to the start position.
int i = 0; // position in byte
int c = 0; // position in character
while (i < numBytes && c < start) {
i += numBytesForFirstByte(getByte(i));
c += 1;
}
do {
if (i + v.numBytes > numBytes) {
return -1;
}
if (ByteArrayMethods.arrayEquals(base, offset + i, v.base, v.offset, v.numBytes)) {
return c;
}
i += numBytesForFirstByte(getByte(i));
c += 1;
} while (i < numBytes);
return -1;
}
/**
* Returns str, right-padded with pad to a length of len
* For example:
* ('hi', 5, '??') => 'hi???'
* ('hi', 1, '??') => 'h'
*/
public UTF8String rpad(int len, UTF8String pad) {
int spaces = len - this.numChars(); // number of char need to pad
if (spaces <= 0) {
// no padding at all, return the substring of the current string
return substring(0, len);
} else {
int padChars = pad.numChars();
int count = spaces / padChars; // how many padding string needed
// the partial string of the padding
UTF8String remain = pad.substring(0, spaces - padChars * count);
byte[] data = new byte[this.numBytes + pad.numBytes * count + remain.numBytes];
copyMemory(this.base, this.offset, data, BYTE_ARRAY_OFFSET, this.numBytes);
int offset = this.numBytes;
int idx = 0;
while (idx < count) {
copyMemory(pad.base, pad.offset, data, BYTE_ARRAY_OFFSET + offset, pad.numBytes);
++idx;
offset += pad.numBytes;
}
copyMemory(remain.base, remain.offset, data, BYTE_ARRAY_OFFSET + offset, remain.numBytes);
return UTF8String.fromBytes(data);
}
}
/**
* Returns str, left-padded with pad to a length of len.
* For example:
* ('hi', 5, '??') => '???hi'
* ('hi', 1, '??') => 'h'
*/
public UTF8String lpad(int len, UTF8String pad) {
int spaces = len - this.numChars(); // number of char need to pad
if (spaces <= 0) {
// no padding at all, return the substring of the current string
return substring(0, len);
} else {
int padChars = pad.numChars();
int count = spaces / padChars; // how many padding string needed
// the partial string of the padding
UTF8String remain = pad.substring(0, spaces - padChars * count);
byte[] data = new byte[this.numBytes + pad.numBytes * count + remain.numBytes];
int offset = 0;
int idx = 0;
while (idx < count) {
copyMemory(pad.base, pad.offset, data, BYTE_ARRAY_OFFSET + offset, pad.numBytes);
++idx;
offset += pad.numBytes;
}
copyMemory(remain.base, remain.offset, data, BYTE_ARRAY_OFFSET + offset, remain.numBytes);
offset += remain.numBytes;
copyMemory(this.base, this.offset, data, BYTE_ARRAY_OFFSET + offset, numBytes());
return UTF8String.fromBytes(data);
}
}
/**
* Concatenates input strings together into a single string. Returns null if any input is null.
*/
public static UTF8String concat(UTF8String... inputs) {
// Compute the total length of the result.
int totalLength = 0;
for (int i = 0; i < inputs.length; i++) {
if (inputs[i] != null) {
totalLength += inputs[i].numBytes;
} else {
return null;
}
}
// Allocate a new byte array, and copy the inputs one by one into it.
final byte[] result = new byte[totalLength];
int offset = 0;
for (int i = 0; i < inputs.length; i++) {
int len = inputs[i].numBytes;
copyMemory(
inputs[i].base, inputs[i].offset,
result, BYTE_ARRAY_OFFSET + offset,
len);
offset += len;
}
return fromBytes(result);
}
/**
* Concatenates input strings together into a single string using the separator.
* A null input is skipped. For example, concat(",", "a", null, "c") would yield "a,c".
*/
public static UTF8String concatWs(UTF8String separator, UTF8String... inputs) {
if (separator == null) {
return null;
}
int numInputBytes = 0; // total number of bytes from the inputs
int numInputs = 0; // number of non-null inputs
for (int i = 0; i < inputs.length; i++) {
if (inputs[i] != null) {
numInputBytes += inputs[i].numBytes;
numInputs++;
}
}
if (numInputs == 0) {
// Return an empty string if there is no input, or all the inputs are null.
return fromBytes(new byte[0]);
}
// Allocate a new byte array, and copy the inputs one by one into it.
// The size of the new array is the size of all inputs, plus the separators.
final byte[] result = new byte[numInputBytes + (numInputs - 1) * separator.numBytes];
int offset = 0;
for (int i = 0, j = 0; i < inputs.length; i++) {
if (inputs[i] != null) {
int len = inputs[i].numBytes;
copyMemory(
inputs[i].base, inputs[i].offset,
result, PlatformDependent.BYTE_ARRAY_OFFSET + offset,
len);
offset += len;
j++;
// Add separator if this is not the last input.
if (j < numInputs) {
copyMemory(
separator.base, separator.offset,
result, PlatformDependent.BYTE_ARRAY_OFFSET + offset,
separator.numBytes);
offset += separator.numBytes;
}
}
}
return fromBytes(result);
}
public UTF8String[] split(UTF8String pattern, int limit) {
String[] splits = toString().split(pattern.toString(), limit);
UTF8String[] res = new UTF8String[splits.length];
for (int i = 0; i < res.length; i++) {
res[i] = fromString(splits[i]);
}
return res;
}
@Override
public String toString() {
try {
return new String(getBytes(), "utf-8");
} catch (UnsupportedEncodingException e) {
// Turn the exception into unchecked so we can find out about it at runtime, but
// don't need to add lots of boilerplate code everywhere.
throwException(e);
return "unknown"; // we will never reach here.
}
}
@Override
public UTF8String clone() {
return fromBytes(getBytes());
}
@Override
public int compareTo(@Nonnull final UTF8String other) {
int len = Math.min(numBytes, other.numBytes);
// TODO: compare 8 bytes as unsigned long
for (int i = 0; i < len; i ++) {
// In UTF-8, the byte should be unsigned, so we should compare them as unsigned int.
int res = (getByte(i) & 0xFF) - (other.getByte(i) & 0xFF);
if (res != 0) {
return res;
}
}
return numBytes - other.numBytes;
}
public int compare(final UTF8String other) {
return compareTo(other);
}
@Override
public boolean equals(final Object other) {
if (other instanceof UTF8String) {
UTF8String o = (UTF8String) other;
if (numBytes != o.numBytes) {
return false;
}
return ByteArrayMethods.arrayEquals(base, offset, o.base, o.offset, numBytes);
} else {
return false;
}
}
/**
* Levenshtein distance is a metric for measuring the distance of two strings. The distance is
* defined by the minimum number of single-character edits (i.e. insertions, deletions or
* substitutions) that are required to change one of the strings into the other.
*/
public int levenshteinDistance(UTF8String other) {
// Implementation adopted from org.apache.common.lang3.StringUtils.getLevenshteinDistance
int n = numChars();
int m = other.numChars();
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
UTF8String s, t;
if (n <= m) {
s = this;
t = other;
} else {
s = other;
t = this;
int swap;
swap = n;
n = m;
m = swap;
}
int p[] = new int[n + 1];
int d[] = new int[n + 1];
int swap[];
int i, i_bytes, j, j_bytes, num_bytes_j, cost;
for (i = 0; i <= n; i++) {
p[i] = i;
}
for (j = 0, j_bytes = 0; j < m; j_bytes += num_bytes_j, j++) {
num_bytes_j = numBytesForFirstByte(t.getByte(j_bytes));
d[0] = j + 1;
for (i = 0, i_bytes = 0; i < n; i_bytes += numBytesForFirstByte(s.getByte(i_bytes)), i++) {
if (s.getByte(i_bytes) != t.getByte(j_bytes) ||
num_bytes_j != numBytesForFirstByte(s.getByte(i_bytes))) {
cost = 1;
} else {
cost = (ByteArrayMethods.arrayEquals(t.base, t.offset + j_bytes, s.base,
s.offset + i_bytes, num_bytes_j)) ? 0 : 1;
}
d[i + 1] = Math.min(Math.min(d[i] + 1, p[i + 1] + 1), p[i] + cost);
}
swap = p;
p = d;
d = swap;
}
return p[n];
}
@Override
public int hashCode() {
int result = 1;
for (int i = 0; i < numBytes; i ++) {
result = 31 * result + getByte(i);
}
return result;
}
}
|
3e1cc744ae42cbd19b0926167af2a099f53a82c1 | 5,339 | java | Java | msgcli/src/test/java/messy/msgcli/app/InputProcessorTest.java | marco-schmidt/messy | 99ea0dd5b8f89d5aa7cc9fc702bf45646672601e | [
"Apache-2.0"
] | null | null | null | msgcli/src/test/java/messy/msgcli/app/InputProcessorTest.java | marco-schmidt/messy | 99ea0dd5b8f89d5aa7cc9fc702bf45646672601e | [
"Apache-2.0"
] | 48 | 2021-01-07T07:14:17.000Z | 2021-09-15T09:02:50.000Z | msgcli/src/test/java/messy/msgcli/app/InputProcessorTest.java | marco-schmidt/messy | 99ea0dd5b8f89d5aa7cc9fc702bf45646672601e | [
"Apache-2.0"
] | null | null | null | 29.335165 | 116 | 0.69395 | 12,208 | /*
* Copyright 2020, 2021 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 messy.msgcli.app;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import messy.msgcli.app.AppTest.FailingInputStream;
import messy.msgcli.app.FileFormatHelper.FileType;
import messy.msgio.formats.JsonMessageFormatter;
import messy.msgio.utils.IOUtils;
import messy.msgio.utils.StringUtils;
public final class InputProcessorTest
{
private static final String INVALID_FILE_NAME = "thisisa non-existing filename";
private File tempMboxFile;
private static final String[] ANEWS =
{
"Amsg1", "news.misc", "foo!bar", "Sat Mar 28 17:56:20 1981", "Subject line", "First message body line."
};
@Before
public void setup() throws IOException
{
tempMboxFile = File.createTempFile("messy", ".mbox");
}
@Test
public void testProcessList()
{
final InputProcessor ip = new InputProcessor();
ip.process(new ArrayList<>());
ip.process(Arrays.asList(new String[]
{
INVALID_FILE_NAME
}));
ip.process(Arrays.asList(new String[]
{
tempMboxFile.getAbsolutePath()
}));
}
@Test
public void testProcessFile()
{
final InputProcessor ip = new InputProcessor();
ip.process(INVALID_FILE_NAME);
}
@Test
public void testProcessFailedInputStream()
{
// note: buffer length must as large as or larger than FileFormatHelper.bytesToLoad
final byte[] buffer = new byte[512];
Arrays.fill(buffer, (byte) 32);
buffer[0] = (byte) 'F';
buffer[1] = (byte) 'r';
buffer[2] = (byte) 'o';
buffer[3] = (byte) 'm';
buffer[4] = (byte) ' ';
FailingInputStream in = new AppTest.FailingInputStream(buffer);
InputProcessor ip = new InputProcessor();
ip.process(in, "-");
Arrays.fill(buffer, (byte) 32);
buffer[0] = (byte) '{';
in = new AppTest.FailingInputStream(buffer);
ip = new InputProcessor();
ip.process(in, "-");
}
@Test
public void testProcessFailedArchiveInputStream()
{
final FailingInputStream in = new AppTest.FailingInputStream();
final InputProcessor ip = new InputProcessor();
ip.processArchiveInput(in, "-", FileType.TAR);
}
public InputStream open(String name)
{
return getClass().getResourceAsStream(name);
}
private InputProcessor createInputProcessor()
{
final InputProcessor ip = new InputProcessor();
final JsonMessageFormatter jsonMessageFormatter = new JsonMessageFormatter();
jsonMessageFormatter.setItems(new ArrayList<>());
ip.getOutputProcessor().setMessageFormatter(jsonMessageFormatter);
return ip;
}
@Test
public void testProcessInputStream() throws IOException
{
final InputProcessor ip = createInputProcessor();
String name = "example.general.tar";
ip.process(open(name), name);
name = "example.general.tar.gz";
ip.process(open(name), name);
name = "example.general.tar.bz2";
ip.process(open(name), name);
name = "example.general.tar.Z";
ip.process(open(name), name);
name = "example.general.zip";
ip.process(open(name), name);
// password is "secret" in case decryption is supported in the future
name = "example.general.encrypted.zip";
ip.process(open(name), name);
}
@Test
public void testToLines()
{
final List<String> lines = IOUtils.toLines(new AppTest.FailingInputStream());
Assert.assertTrue("List is empty.", lines.isEmpty());
}
@Test
public void testProcessUnidentified() throws IOException
{
final InputProcessor ip = createInputProcessor();
ip.processUnidentified(new ByteArrayInputStream(new byte[]
{}), "1.msg");
ip.processUnidentified(new ByteArrayInputStream(new byte[]
{
(byte) 'A'
}), "1.msg");
ip.processUnidentified(new ByteArrayInputStream(new byte[]
{
(byte) 'B'
}), "1.msg");
ip.processUnidentified(new AppTest.FailingInputStream(new byte[]
{
(byte) 'A'
}), "1.msg");
final String s = StringUtils.concatItems(Arrays.asList(ANEWS), "\n");
ip.processUnidentified(new ByteArrayInputStream(s.getBytes(StandardCharsets.ISO_8859_1)), "1.msg");
}
@Test
public void testProcessSingleMessageAnews() throws IOException
{
final InputProcessor ip = createInputProcessor();
Assert.assertFalse("Not enough data for anews message.", ip.processSingleMessageAnews(Arrays.asList(new String[]
{
"A"
}), "1.msg"));
Assert.assertTrue("Regular anews.", ip.processSingleMessageAnews(Arrays.asList(ANEWS), "1.msg"));
}
}
|
3e1cc7b741ae64054f104e433cc5190f20d86357 | 6,975 | java | Java | educational-core/src/com/jetbrains/edu/learning/authUtils/CustomAuthorizationServer.java | xnike/educational-plugin | 9cd0183b28583ceca53d0bc5df9dc605cdb915e0 | [
"Apache-2.0"
] | 94 | 2017-09-04T02:49:56.000Z | 2022-03-17T11:55:42.000Z | educational-core/src/com/jetbrains/edu/learning/authUtils/CustomAuthorizationServer.java | xnike/educational-plugin | 9cd0183b28583ceca53d0bc5df9dc605cdb915e0 | [
"Apache-2.0"
] | 16 | 2017-09-03T16:19:20.000Z | 2021-03-16T15:49:16.000Z | educational-core/src/com/jetbrains/edu/learning/authUtils/CustomAuthorizationServer.java | xnike/educational-plugin | 9cd0183b28583ceca53d0bc5df9dc605cdb915e0 | [
"Apache-2.0"
] | 39 | 2017-10-31T21:13:38.000Z | 2022-03-17T21:21:00.000Z | 34.359606 | 156 | 0.722867 | 12,209 | package com.jetbrains.edu.learning.authUtils;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.Range;
import com.jetbrains.edu.learning.stepik.StepikNames;
import kotlin.text.Charsets;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.bootstrap.HttpServer;
import org.apache.http.impl.bootstrap.ServerBootstrap;
import org.apache.http.protocol.HttpRequestHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
/**
* Android Studio doesn't allow using built-in server,
* without credentials, so {@link CustomAuthorizationServer}
* is used for OAuth authorization from Android Studio.
*/
public class CustomAuthorizationServer {
private static final Logger LOG = Logger.getInstance(CustomAuthorizationServer.class);
private static final Map<String, CustomAuthorizationServer> SERVER_BY_NAME = new HashMap<>();
private static final Range<Integer> DEFAULT_PORTS_TO_TRY = new Range<>(36656, 36665);
private final HttpServer myServer;
private final String myHandlerPath;
private CustomAuthorizationServer(@NotNull HttpServer server, @NotNull String handlerPath) {
myServer = server;
myHandlerPath = handlerPath;
}
private void stopServer() {
ApplicationManager.getApplication().executeOnPooledThread(() -> {
LOG.info("Stopping server");
myServer.stop();
LOG.info("Server stopped");
});
}
public int getPort() {
return myServer.getLocalPort();
}
@NotNull
public String getHandlingUri() {
return "http://localhost:" + getPort() + myHandlerPath;
}
@Nullable
public static CustomAuthorizationServer getServerIfStarted(@NotNull String platformName) {
return SERVER_BY_NAME.get(platformName);
}
@NotNull
public static CustomAuthorizationServer create(
@NotNull String platformName,
@NotNull String handlerPath,
@NotNull CodeHandler codeHandler
) throws IOException {
final CustomAuthorizationServer server = createServer(platformName, handlerPath, codeHandler);
SERVER_BY_NAME.put(platformName, server);
return server;
}
@NotNull
private static synchronized CustomAuthorizationServer createServer(
@NotNull String platformName,
@NotNull String handlerPath,
@NotNull CodeHandler codeHandler
) throws IOException {
int port = getAvailablePort();
if (port == -1) {
throw new IOException("No ports available");
}
final SocketConfig socketConfig = SocketConfig.custom()
.setSoTimeout(15000)
.setTcpNoDelay(true)
.build();
// In case of Stepik our redirect_uri is `http://localhost:port`
// but authorization code request is sent on `http://localhost:port/`
// So we have to add additional slash
final String slashIfNeeded = (platformName.equals(StepikNames.STEPIK) ? "/" : "");
final HttpServer newServer = ServerBootstrap.bootstrap()
.setListenerPort(port)
.setServerInfo(platformName)
.registerHandler(handlerPath + slashIfNeeded, createContextHandler(platformName, codeHandler))
.setSocketConfig(socketConfig)
.create();
newServer.start();
return new CustomAuthorizationServer(newServer, handlerPath);
}
public static int getAvailablePort() {
return IntStream.rangeClosed(DEFAULT_PORTS_TO_TRY.getFrom(), DEFAULT_PORTS_TO_TRY.getTo())
.filter(CustomAuthorizationServer::isPortAvailable)
.findFirst()
.orElse(-1);
}
private static boolean isPortAvailable(int port) {
try (Socket ignored = new Socket("localhost", port)) {
return false;
}
catch (IOException ignored) {
return true;
}
}
@NotNull
private static HttpRequestHandler createContextHandler(
@NotNull String platformName,
@NotNull CodeHandler codeHandler
) {
return (request, response, context) -> {
LOG.info("Handling auth response");
try {
final List<NameValuePair> parse = URLEncodedUtils.parse(new URI(request.getRequestLine().getUri()), Charsets.UTF_8);
for (NameValuePair pair : parse) {
if (pair.getName().equals("code")) {
final String code = pair.getValue();
final CustomAuthorizationServer currentServer = getServerIfStarted(platformName);
assert currentServer != null; // cannot be null: if this concrete handler is working then corresponding server is working too
final String errorMessage = codeHandler.handle(code, currentServer.getHandlingUri());
if (errorMessage == null) {
sendOkResponse(response, platformName);
} else {
LOG.warn(errorMessage);
sendErrorResponse(response, platformName, errorMessage);
}
break;
}
}
}
catch (URISyntaxException e) {
LOG.warn(e.getMessage());
sendErrorResponse(response, platformName, "Invalid response");
}
finally {
SERVER_BY_NAME.get(platformName).stopServer();
SERVER_BY_NAME.remove(platformName);
}
};
}
private static void sendOkResponse(@NotNull HttpResponse httpResponse, @NotNull String platformName) throws IOException {
final String okPageContent = OAuthUtils.getOkPageContent(platformName);
sendResponse(httpResponse, okPageContent);
}
private static void sendErrorResponse(@NotNull HttpResponse httpResponse, @NotNull String platformName, @NotNull String errorMessage) throws IOException {
final String errorPageContent = OAuthUtils.getErrorPageContent(platformName, errorMessage);
sendResponse(httpResponse, errorPageContent);
}
private static void sendResponse(@NotNull HttpResponse httpResponse, @NotNull String pageContent) throws IOException {
httpResponse.setHeader("Content-Type", "text/html");
httpResponse.setEntity(new StringEntity(pageContent));
}
@FunctionalInterface
public interface CodeHandler {
/**
* @see CustomAuthorizationServer#createContextHandler(String, CodeHandler)
*
* Is called when oauth authorization code is handled by the context handler.
* Encapsulates authorization process and returns error message or null.
*
* @param code oauth authorization code
* @param handlingUri uri the code wah handled on (is used as redirect_uri in tokens request)
*
* @return non-null error message in case of error, null otherwise
* */
@Nullable
String handle(@NotNull String code, @NotNull String handlingUri);
}
}
|
3e1cc98f1aa87025d5e4f215ed4bda0ec5c7f1e5 | 5,936 | java | Java | addressbook-web-tests/src/test/java/ru/stqa/ol/addressbook/tests/GroupCreationTests.java | ohelge/java_barancev | ee06586db4bc39d2d1976afa68046e9a874f3139 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/ol/addressbook/tests/GroupCreationTests.java | ohelge/java_barancev | ee06586db4bc39d2d1976afa68046e9a874f3139 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/ol/addressbook/tests/GroupCreationTests.java | ohelge/java_barancev | ee06586db4bc39d2d1976afa68046e9a874f3139 | [
"Apache-2.0"
] | null | null | null | 59.36 | 253 | 0.725067 | 12,210 | package ru.stqa.ol.addressbook.tests;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.thoughtworks.xstream.XStream;
import org.slf4j.LoggerFactory;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import ru.stqa.ol.addressbook.model.GroupData;
import ru.stqa.ol.addressbook.model.Groups;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.*;
public class GroupCreationTests extends TestBase {
//l6_m6 Iterator massiva objektov
@DataProvider // Ideq razdeleniq dannih ot testa
public Iterator<Object[]> validGroupsFromXml() throws IOException { //dlq XML
try (BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/groups.xml")))) { //l6_m8 ispol'zuem try sm. GroupDataGenerator
String line = reader.readLine();
String xml = ""; //l6_m6 peremennaq v kot 4itaem soderzhimoe faila
while (line != null) {
xml += line; //l6_m6
line = reader.readLine();
}
XStream xStream = new XStream(); //l6_m6
xStream.processAnnotations(GroupData.class); //l6_m6
List<GroupData> groups = (List<GroupData>) xStream.fromXML(xml); //l6_m6 List<GroupData>) -eto privedenie tipa. http://x-stream.github.io/tutorial.html Deserializing an object back from XML
return groups.stream().map((g) -> new Object[]{g}).collect(Collectors.toList()).iterator(); //l6_m6 k kazhdomy obektu nuzhno primenit' funkciu kot etot obekt tipa GrpoupData zavernet v massiv kot sostoit iz odnogo etogo objekta.
// Dalee collect() sozdaet iz potoka spisok. i u polu4ivwegosq spiska berem iterator. Ego i nuzhno vozvrawat'
}
}
@DataProvider // Ideq razdeleniq dannih ot testa
public Iterator<Object[]> validGroupsFromJson() throws IOException { //l6_m7 novii DataProvider dlq Json
try (BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/groups.json")))) { //l6_m8 ispol'zuem try sm. GroupDataGenerator
String line = reader.readLine();
String json = ""; //l6_m7 peremennaq v kot 4itaem soderzhimoe faila
while (line != null) {
json += line;
line = reader.readLine();
}
Gson gson = new Gson(); //l6_m7
List<GroupData> groups = gson.fromJson(json, new TypeToken<List<GroupData>>() {
}.getType()); //l6_m7 Deserialisation v gson: 4itaem vse soderzhimoe faila v peremennyu tipa String(json) i potom ee obrabativaem. Vtoroi parametr-tip dannih kot serializyut'sq
// v Java nel'zq napisat' vtorim parametrom (json, List<GroupData>.class) t.k. so spiskami deserializaciq ne prohodit. Esli bi bil odin objekt to mozhno: (json, GroupData.class).
// No u nas spisok objektov, poetomu delaem slozhnie deistviq: new TypeToken<List<GroupData>>() {}.getType() kot po suti zna4it List<GroupData>.class
return groups.stream().map((g) -> new Object[]{g}).collect(Collectors.toList()).iterator(); //l6_m6 k kazhdomy obektu nuzhno primenit' funkciu kot etot obekt tipa GrpoupData zavernet v massiv kot sostoit iz odnogo etogo objekta.
// Dalee collect() sozdaet iz potoka spisok. i u polu4ivwegosq spiska berem iterator. Ego i nuzhno vozvrawat'
}
}
@Test(enabled = true, dataProvider = "validGroupsFromJson")
//l6_m7 Parametr dataProvider ukazat' po imeni. Menqem Xml na Json
public void testGroupCreation(GroupData group) { //l6_m4 Udobnee peredavat' dannie kak 1 objekt: menqem String name, String header, String footer na GroupData group.
// Menqem v @DataProvider massiv strok na massiv objektov tipa GroupData, massiv budet iz odnogo elementa
// org.slf4j.Logger logger = LoggerFactory.getLogger(GroupCreationTests.class); //l6_m11 OBS. berem Logger iz paketa org.slf4j. Parametr getLogger- klass s kot budet associirovat'sq logger
//perenosim logger v TestBase
// logger.info("Start test testGroupCreation"); //l6_m11: piwem v na4alo i konec. Sozdaem fail logback.xml s takim imenem kak prinqto v Logback biblioteke.
//l6_m11 4tobi ne zasorqt' testi mozhno napisat' v TestBase @BeforeMethod i @AfterMethod
app.goTo().groupPage();
//Groups before = app.group().all(); //l5_m6
Groups before = app.db().groups();
app.group().create(group);
assertThat(app.group().count(), equalTo(before.size() + 1)); //l5_m8 : zamenqem after.size() na bolee bistruu proverku app.group().count() i stavim pered zagruzkoi spiska grupp. Eto i est' hashirovanie
//Groups after = app.group().all();
Groups after = app.db().groups();
group.withId(after.stream().mapToInt((g) -> g.getId()).max().getAsInt()); //l5_m5: prewvawaem potok objektov GrouData v potok Identifikatorov. Anonimnaq funkciq mapToInt g: parametr gruppa, a resultat - identifikator. Berem max i preobrazuem v int
assertThat(after, equalTo(before.withAdded(group))); // MatcherAssert.assertThat(..) Alt+Enter -> "Add static import"
// logger.info("Stop test testGroupCreation"); l6_m11 Perenosim v TestBase
}
@Test(enabled = false)
public void testBadGroupCreation() {
app.goTo().groupPage();
Groups before = app.group().all(); //l5_m6
GroupData group = new GroupData().withName("1111' "); // Imq s apostrofom NE sozdaetsq dazhe esli poprobovat' sozdat' v prilozhenii
app.group().create(group);
assertThat(app.group().count(), equalTo(before.size()));
Groups after = app.group().all();
group.withId(after.stream().mapToInt((g) -> g.getId()).max().getAsInt()); //l5_m5: prewvawaem potok objektov GrouData v potok Identifikatorov. Anonimnaq funkciq mapToInt g: parametr gruppa, a resultat - identifikator. Berem max i preobrazuem v int
assertThat(after, equalTo(before)); // MatcherAssert.assertThat(..) Alt+Enter -> "Add static import"
}
}
|
3e1cc9cf407457f5a9bc3c3652166b7bceb03dbc | 240 | java | Java | kata/8-kyu/sort-my-textbooks/main/sorter.java | Sophia-Okito/codewars-handbook | d896c766cf3347031dc3934ce18cd7a021ae2526 | [
"MIT"
] | 36 | 2020-04-16T17:53:05.000Z | 2022-03-15T06:59:04.000Z | kata/8-kyu/sort-my-textbooks/main/sorter.java | Sophia-Okito/codewars-handbook | d896c766cf3347031dc3934ce18cd7a021ae2526 | [
"MIT"
] | 8 | 2020-07-26T05:26:40.000Z | 2022-03-01T20:03:24.000Z | kata/8-kyu/sort-my-textbooks/main/sorter.java | ParanoidUser/codewars-handbook | 6e9f61b671bd379d8671f2ae1b134e3cbde62ff4 | [
"MIT"
] | 10 | 2020-04-10T12:07:02.000Z | 2022-01-21T12:29:39.000Z | 24 | 86 | 0.758333 | 12,211 | import static java.util.stream.Collectors.toList;
import java.util.List;
interface sorter {
static List<String> sort(List<String> textbooks) {
return textbooks.stream().sorted(String.CASE_INSENSITIVE_ORDER).collect(toList());
}
}
|
3e1cc9e0737d69cf13a06174cb2b7c54c00aff78 | 2,235 | java | Java | rest/src/main/java/org/jboss/pnc/rest/utils/RestGraphBuilder.java | michalovjan/pnc | 62607b2f63c4d8b9bb5bd783ee386f0f78c0d788 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | rest/src/main/java/org/jboss/pnc/rest/utils/RestGraphBuilder.java | michalovjan/pnc | 62607b2f63c4d8b9bb5bd783ee386f0f78c0d788 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | rest/src/main/java/org/jboss/pnc/rest/utils/RestGraphBuilder.java | michalovjan/pnc | 62607b2f63c4d8b9bb5bd783ee386f0f78c0d788 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 33.909091 | 117 | 0.693923 | 12,212 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.pnc.rest.utils;
import org.jboss.pnc.rest.restmodel.graph.EdgeRest;
import org.jboss.pnc.rest.restmodel.graph.GraphRest;
import org.jboss.pnc.rest.restmodel.graph.VertexRest;
import org.jboss.util.graph.Edge;
import org.jboss.util.graph.Graph;
import org.jboss.util.graph.Vertex;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:envkt@example.com">Matej Lazar</a>
*/
public class RestGraphBuilder<T> {
private final Map<String, String> metadata;
public RestGraphBuilder() {
metadata = Collections.EMPTY_MAP;
}
public RestGraphBuilder(Map<String, String> metadata) {
this.metadata = metadata;
}
public GraphRest<T> from(Graph<T> graph, Class<T> dataType) {
Map<String, VertexRest<T>> verticles = new LinkedHashMap<>();
List<EdgeRest<T>> edges = new ArrayList<>();
for (Vertex<T> vertex : graph.getVerticies()) {
VertexRest<T> vertexRest = new VertexRest<>(vertex.getName(), dataType.getName(), vertex.getData());
verticles.put(vertexRest.getName(), vertexRest);
}
for (Edge<T> edge : graph.getEdges()) {
EdgeRest<T> edgeRest = new EdgeRest<T>(edge.getFrom().getName(), edge.getTo().getName(), edge.getCost());
edges.add(edgeRest);
}
GraphRest<T> graphRest = new GraphRest<>(verticles, edges, metadata);
return graphRest;
}
}
|
3e1cc9f4348176739919a71ca060e577691ede77 | 1,376 | java | Java | src/main/java/org/testmy/screenplay/act/interaction/navigate/NavigateToApp.java | testmyorgdotcom/testmyorg | 2206947587a9825458c2c696b262974d90b6f751 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/testmy/screenplay/act/interaction/navigate/NavigateToApp.java | testmyorgdotcom/testmyorg | 2206947587a9825458c2c696b262974d90b6f751 | [
"Apache-2.0"
] | 16 | 2021-06-15T20:43:03.000Z | 2021-07-17T08:38:42.000Z | src/main/java/org/testmy/screenplay/act/interaction/navigate/NavigateToApp.java | testmyorgdotcom/testmyorg | 2206947587a9825458c2c696b262974d90b6f751 | [
"Apache-2.0"
] | null | null | null | 40.470588 | 87 | 0.734738 | 12,214 | package org.testmy.screenplay.act.interaction.navigate;
import static net.serenitybdd.screenplay.matchers.WebElementStateMatchers.isNotVisible;
import static net.serenitybdd.screenplay.matchers.WebElementStateMatchers.isVisible;
import static org.hamcrest.Matchers.is;
import org.testmy.screenplay.question.ui.AppName;
import org.testmy.screenplay.ui.AppLauncher;
import org.testmy.screenplay.ui.WebPage;
import lombok.AllArgsConstructor;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Interaction;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.actions.SendKeys;
import net.serenitybdd.screenplay.conditions.Check;
import net.serenitybdd.screenplay.waits.WaitUntil;
@AllArgsConstructor
public class NavigateToApp implements Interaction {
private String appName;
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Check.whether(AppName.displayed(), is(appName)).otherwise(
Click.on(AppLauncher.icon()),
SendKeys.of(appName).into(AppLauncher.searchInput()),
WaitUntil.the(AppLauncher.appCalled(appName), isVisible()),
Click.on(AppLauncher.appCalled(appName)),
WaitUntil.the(WebPage.loadingLogo(), isNotVisible())));
}
}
|
3e1cca11ace12fb36975c983ff5e9ccca7d757c0 | 462 | java | Java | data_struct_study/src/stack/Main.java | fengjixuchui/Awesome-Algorithm-Study | dcd65850546c2a277a2b45dc5c70d7179c1aa2fe | [
"Apache-2.0"
] | 108 | 2020-01-18T10:29:21.000Z | 2022-03-22T01:14:47.000Z | data_struct_study/src/stack/Main.java | fengjixuchui/Awesome-Algorithm-Study | dcd65850546c2a277a2b45dc5c70d7179c1aa2fe | [
"Apache-2.0"
] | null | null | null | data_struct_study/src/stack/Main.java | fengjixuchui/Awesome-Algorithm-Study | dcd65850546c2a277a2b45dc5c70d7179c1aa2fe | [
"Apache-2.0"
] | 24 | 2020-01-19T03:38:03.000Z | 2022-02-27T10:27:04.000Z | 15.4 | 54 | 0.487013 | 12,215 | package stack;
/**
* 栈的应用:
* 1)、无处不在的撤销操作
* 2)、系统栈的调用(操作系统)
* 3)、括号匹配(编译器)
*/
public class Main {
public static void main(String[] args) {
ArrayStack<Object> stack = new ArrayStack<>();
for (int i = 0; i < 5; i++) {
stack.push(i);
System.out.println(stack);
}
stack.pop();
System.out.println(stack);
stack.peek();
System.out.println(stack);
}
}
|
3e1ccaba18b076546becbdd70f1f3aaf51280526 | 208 | java | Java | src/main/java/br/com/zupacademy/thiago/proposta/cartao/avisoviagem/AvisoViagemRepository.java | thiagozupper/orange-talents-07-template-proposta | cbaf089b73e92509aecfcd0379cd39cd83f148d7 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/thiago/proposta/cartao/avisoviagem/AvisoViagemRepository.java | thiagozupper/orange-talents-07-template-proposta | cbaf089b73e92509aecfcd0379cd39cd83f148d7 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/thiago/proposta/cartao/avisoviagem/AvisoViagemRepository.java | thiagozupper/orange-talents-07-template-proposta | cbaf089b73e92509aecfcd0379cd39cd83f148d7 | [
"Apache-2.0"
] | null | null | null | 29.714286 | 82 | 0.850962 | 12,216 | package br.com.zupacademy.thiago.proposta.cartao.avisoviagem;
import org.springframework.data.repository.CrudRepository;
public interface AvisoViagemRepository extends CrudRepository<AvisoViagem, Long> {
}
|
3e1ccac1e19c0f20fef8d9b882d61187f442f066 | 1,402 | java | Java | src/javacore/multithreading/day12/StopThreadDemo2.java | dlzdy/java-core | ee74e8c2ac32233548ebcdf5d292b6249a337ea6 | [
"Apache-2.0"
] | 7 | 2018-08-20T08:16:24.000Z | 2022-03-15T06:22:35.000Z | src/javacore/multithreading/day12/StopThreadDemo2.java | dlzdy/java-core | ee74e8c2ac32233548ebcdf5d292b6249a337ea6 | [
"Apache-2.0"
] | null | null | null | src/javacore/multithreading/day12/StopThreadDemo2.java | dlzdy/java-core | ee74e8c2ac32233548ebcdf5d292b6249a337ea6 | [
"Apache-2.0"
] | 6 | 2018-12-16T08:38:52.000Z | 2021-10-01T23:31:01.000Z | 18.773333 | 74 | 0.62571 | 12,217 | package javacore.multithreading.day12;
/**
* 多线程(停止线程)<br>
* 多线程(守护线程)<br>
* <p>
* stop()方法已经过时.<br>
* 如何停止线程?<br>
* 只有一种,run()方法结束.<br>
* 开启多线程运行,运行代码通常是循环结构。<br>
* <br>
* 只要控制住循环,就可以让run()方法结束,也就是线程结束。<br>
* <br>
* 特殊情况:<br>
* 当线程处于了冻结状态。<br>
* 就不会读取到标记,那么线程就不会结束。<br>
* <br>
* 当没有指定的方式让冻结的线程恢复到运行状态时,这时,需要对冻结进行清除。<br>
* 强制让线程恢复到运行状态中来,这样就可以操作标记让线程结束。<br>
* <br>
* Thread 类中提供了该方法 interrupt();<br>
*
* @author kenaa@example.com
* @see 传智播客毕向东Java基础视频教程-day12-07-多线程(停止线程)
* @see 传智播客毕向东Java基础视频教程-day12-08-多线程(守护线程)
*/
public class StopThreadDemo2 {
public static void main(String[] args) {
StropThread2 st = new StropThread2();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
int num = 0;
while (true) {
if (num++ == 60) {
// st.changeFlag();
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName() + "..." + num);
}
System.out.println("over");
}
}
class StropThread2 implements Runnable {
private boolean flag = true;
@Override
public void run() {
while (flag) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "...exception");
flag = false;
}
System.out.println(Thread.currentThread().getName() + "...run");
}
}
public void changeFlag() {
flag = false;
}
}
|
3e1ccac541ac8852e63c3746d53c432c77294fef | 1,865 | java | Java | graphwalker-java/src/test/java/org/graphwalker/java/annotation/MyOtherTest.java | rambo250/graphwalker-project | 333f8af3c640d2afe9479881fb0ce801986449ef | [
"MIT"
] | 261 | 2015-02-16T19:21:50.000Z | 2022-03-22T17:23:20.000Z | graphwalker-java/src/test/java/org/graphwalker/java/annotation/MyOtherTest.java | rambo250/graphwalker-project | 333f8af3c640d2afe9479881fb0ce801986449ef | [
"MIT"
] | 239 | 2015-01-12T15:14:03.000Z | 2022-02-21T16:05:23.000Z | graphwalker-java/src/test/java/org/graphwalker/java/annotation/MyOtherTest.java | rambo250/graphwalker-project | 333f8af3c640d2afe9479881fb0ce801986449ef | [
"MIT"
] | 117 | 2015-01-10T22:12:34.000Z | 2022-03-27T05:22:49.000Z | 32.155172 | 80 | 0.751206 | 12,218 | package org.graphwalker.java.annotation;
/*
* #%L
* GraphWalker Java
* %%
* Copyright (C) 2005 - 2014 GraphWalker
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import org.graphwalker.core.event.EventType;
import org.graphwalker.core.event.Observer;
import org.graphwalker.core.machine.ExecutionContext;
import org.graphwalker.core.machine.Machine;
import org.graphwalker.core.model.Element;
import org.graphwalker.java.annotation.resources.MyModel;
/**
* @author Nils Olsson
*/
@GraphWalker(start = "vertex1")
public class MyOtherTest extends ExecutionContext implements MyModel, Observer {
@Override
public void vertex1() {
}
@Override
public void vertex2() {
}
@Override
public void edge12() {
}
@Override
public void update(Machine machine, Element element, EventType type) {
}
}
|
3e1ccb19c6726807267457ff6a17da0140b42788 | 890 | java | Java | dick-web/src/main/java/com/dickthedeployer/dick/web/model/BuildForm.java | dick-the-deployer/dick | 15fd7ea83179fd3a9e6a19060032080c3fd2eb52 | [
"Apache-2.0"
] | 6 | 2016-01-08T21:20:34.000Z | 2021-06-29T17:57:28.000Z | dick-web/src/main/java/com/dickthedeployer/dick/web/model/BuildForm.java | dick-the-deployer/dick | 15fd7ea83179fd3a9e6a19060032080c3fd2eb52 | [
"Apache-2.0"
] | 98 | 2015-11-15T19:19:08.000Z | 2016-06-04T12:25:19.000Z | dick-web/src/main/java/com/dickthedeployer/dick/web/model/BuildForm.java | dick-the-deployer/dick | 15fd7ea83179fd3a9e6a19060032080c3fd2eb52 | [
"Apache-2.0"
] | 4 | 2015-11-26T19:05:02.000Z | 2021-06-29T17:57:30.000Z | 26.969697 | 76 | 0.719101 | 12,219 | /*
* Copyright dick the deployer.
*
* 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.dickthedeployer.dick.web.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
* @author mariusz
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BuildForm {
private String log;
}
|
3e1ccbed807e250a7e23fa68b513a3085151fa6d | 1,372 | java | Java | TwistedTrek/import2/studio/ignitionigloogames/twistedtrek/import2/resourcemanagers/BossImageManager.java | wrldwzrd89/older-java-games | 786b0c165d800c49ab9977a34ec17286797c4589 | [
"Unlicense"
] | null | null | null | TwistedTrek/import2/studio/ignitionigloogames/twistedtrek/import2/resourcemanagers/BossImageManager.java | wrldwzrd89/older-java-games | 786b0c165d800c49ab9977a34ec17286797c4589 | [
"Unlicense"
] | 3 | 2018-11-12T14:00:52.000Z | 2018-11-18T12:53:02.000Z | TwistedTrek/import2/studio/ignitionigloogames/twistedtrek/import2/resourcemanagers/BossImageManager.java | wrldwzrd89/older-java-games | 786b0c165d800c49ab9977a34ec17286797c4589 | [
"Unlicense"
] | null | null | null | 35.179487 | 111 | 0.767493 | 12,220 | /* Import2: An RPG */
package studio.ignitionigloogames.twistedtrek.import2.resourcemanagers;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import studio.ignitionigloogames.images.BufferedImageIcon;
public class BossImageManager {
private static final String DEFAULT_LOAD_PATH = "/com/puttysoftware/tallertower/resources/graphics/boss/";
private static String LOAD_PATH = BossImageManager.DEFAULT_LOAD_PATH;
private static Class<?> LOAD_CLASS = BossImageManager.class;
static int BOSS_IMAGE_SIZE = 64;
public static BufferedImageIcon getBossImage() {
// Get it from the cache
final BufferedImageIcon bii = BossImageCache.getCachedImage("boss");
return ImageTransformer.getTransformedImage(bii, BossImageManager.BOSS_IMAGE_SIZE);
}
static BufferedImageIcon getUncachedImage(final String name) {
try {
final String normalName = ImageTransformer.normalizeName(name);
final URL url = BossImageManager.LOAD_CLASS.getResource(BossImageManager.LOAD_PATH + normalName + ".png");
final BufferedImage image = ImageIO.read(url);
return new BufferedImageIcon(image);
} catch (final IOException ie) {
return null;
} catch (final NullPointerException np) {
return null;
} catch (final IllegalArgumentException ia) {
return null;
}
}
}
|
3e1ccc313226fd55233a48040be3ba1c7778dd28 | 290 | java | Java | acm-problem-solves/src/main/java/org/solves/acm/Solve_1000.java | sabboshachi/algorithm-problem-solves | 9c5974521c4849a9021106bac09522aae1d4a3bf | [
"MIT"
] | null | null | null | acm-problem-solves/src/main/java/org/solves/acm/Solve_1000.java | sabboshachi/algorithm-problem-solves | 9c5974521c4849a9021106bac09522aae1d4a3bf | [
"MIT"
] | null | null | null | acm-problem-solves/src/main/java/org/solves/acm/Solve_1000.java | sabboshachi/algorithm-problem-solves | 9c5974521c4849a9021106bac09522aae1d4a3bf | [
"MIT"
] | null | null | null | 20.714286 | 54 | 0.603448 | 12,221 | package org.solves.acm;
public class Solve_1000 {
public String add(final String a, final String b){
return a+b;
}
public double add(final double a, final double b){
return a+b;
}
public long add(final long a, final long b){
return a+b;
}
}
|
3e1cccb7aff49183b19ebd88b2166c7ea7012da9 | 420 | java | Java | app/src/main/java/com/dhbw/se_motivationsapp/NotificationReceiver.java | Paprikawurst/SE_MotivationsApp | 4429f8eeef064a3e8d2ee0a1b35a0e48c1311af7 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/dhbw/se_motivationsapp/NotificationReceiver.java | Paprikawurst/SE_MotivationsApp | 4429f8eeef064a3e8d2ee0a1b35a0e48c1311af7 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/dhbw/se_motivationsapp/NotificationReceiver.java | Paprikawurst/SE_MotivationsApp | 4429f8eeef064a3e8d2ee0a1b35a0e48c1311af7 | [
"Apache-2.0"
] | null | null | null | 24.705882 | 80 | 0.783333 | 12,222 | package com.dhbw.se_motivationsapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationHelper notificationHelper = new NotificationHelper(context);
notificationHelper.createNotification();
}
}
|
3e1cccb91273676669099ea30ccfb2d0f049b557 | 4,002 | java | Java | src/main/java/com/zyh5games/sdk/channel/ChannelHandler.java | littleBoyCanHaveAFuture/ZY_Manager | 0645a3f3a1c9011b0af0b7fc9b43bc4b3aeefb1a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/zyh5games/sdk/channel/ChannelHandler.java | littleBoyCanHaveAFuture/ZY_Manager | 0645a3f3a1c9011b0af0b7fc9b43bc4b3aeefb1a | [
"Apache-2.0"
] | 2 | 2020-05-15T21:59:25.000Z | 2021-01-21T00:38:32.000Z | src/main/java/com/zyh5games/sdk/channel/ChannelHandler.java | littleBoyCanHaveAFuture/ZY_Manager | 0645a3f3a1c9011b0af0b7fc9b43bc4b3aeefb1a | [
"Apache-2.0"
] | null | null | null | 36.715596 | 105 | 0.583458 | 12,223 | package com.zyh5games.sdk.channel;
import com.alibaba.fastjson.JSONObject;
import com.zyh5games.entity.ChannelConfig;
import com.zyh5games.service.ChannelConfigService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
/**
* @author song minghua
* @date 2020/5/21
*/
public class ChannelHandler {
private static final Logger log = Logger.getLogger(ChannelHandler.class);
Map<Integer, Map<Integer, JSONObject>> appConfigMap = new HashMap<>();
/**
* 关键功能 Spring 会自动将 EntStrategy 接口的类注入到这个Map中
*/
@Autowired
private Map<String, BaseChannel> channelMap;
@Autowired
private HttpService httpService;
@Resource
private ChannelConfigService configService;
public void print() {
System.out.println("===== BaseChannel extends Map =====");
Set<Integer> sortSet = new TreeSet<>(Comparator.naturalOrder());
// sortSet.addAll(channelMap.keySet());
for(String k:channelMap.keySet()){
sortSet.add(Integer.parseInt(k));
}
for (Integer key : sortSet) {
BaseChannel channel = channelMap.get(String.valueOf(key));
String name = channel.channelLib(-1).getString("name");
System.out.println(key + "\t=[" + channel.channelName + "]\t[" + name + "]");
}
// channelMap.forEach((name, impl) -> {
// System.out.println(name + "->channelData" + ":" + impl.channelLib(-1));
// });
}
/**
* 加载渠道的游戏id
*/
public void loadChannelApp() {
List<ChannelConfig> gameList = configService.selectAll(-1);
for (ChannelConfig channelConfig : gameList) {
Integer appId = channelConfig.getAppId();
Integer channelId = channelConfig.getChannelId();
String config = channelConfig.getConfigKey();
if (config == null || config.isEmpty()) {
continue;
}
JSONObject jsonObject = JSONObject.parseObject(config);
if (!appConfigMap.containsKey(channelId)) {
Map<Integer, JSONObject> configMap = new HashMap<>();
configMap.put(appId, jsonObject);
appConfigMap.put(channelId, configMap);
} else {
Map<Integer, JSONObject> configMap = appConfigMap.get(channelId);
if (!configMap.containsKey(appId)) {
configMap.put(appId, jsonObject);
}
}
}
System.out.println(configService.toString());
}
@PostConstruct
public void init() {
loadChannelApp();
print();
}
public BaseChannel getChannel(Integer channelId) {
BaseChannel channel = this.channelMap.get(String.valueOf(channelId));
if (channel == null) {
return null;
}
if (channel.getConfigMap() == null || channel.getConfigMap().size() == 0) {
channel.setConfigMap(appConfigMap.get(channelId));
} else {
// List<ChannelConfig> channelConfigList = configService.selectChannelConfig(channelId, -1);
// for (ChannelConfig config : channelConfigList) {
// Integer appId = config.getAppId();
// String configKey = config.getConfigKey();
// if (configKey != null && !configKey.isEmpty()) {
// JSONObject jsonObject = JSONObject.parseObject(configKey);
// if (channel.getConfigMap().containsKey(appId)) {
// channel.getConfigMap().replace(appId, jsonObject);
// } else {
// channel.getConfigMap().put(appId, jsonObject);
// }
// System.out.println("[" + channelId + "]getChannel[" + appId + "] = " + jsonObject);
// }
// }
}
return channel;
}
}
|
3e1ccce60c0029a8470a41935dc98e9ee7ef1822 | 2,610 | java | Java | src/main/java/no/fdk/exception/GlobalExceptionHandler.java | Informasjonsforvaltning/fdk-metadata-quality-service | 1fc059084c0fe7c1fdddc2da1bbe13f9e0a0d161 | [
"Apache-2.0"
] | null | null | null | src/main/java/no/fdk/exception/GlobalExceptionHandler.java | Informasjonsforvaltning/fdk-metadata-quality-service | 1fc059084c0fe7c1fdddc2da1bbe13f9e0a0d161 | [
"Apache-2.0"
] | 19 | 2020-09-01T10:14:32.000Z | 2022-02-17T08:52:30.000Z | src/main/java/no/fdk/exception/GlobalExceptionHandler.java | Informasjonsforvaltning/fdk-metadata-quality-service | 1fc059084c0fe7c1fdddc2da1bbe13f9e0a0d161 | [
"Apache-2.0"
] | null | null | null | 38.382353 | 117 | 0.709579 | 12,224 | package no.fdk.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;
import java.util.Map;
@Component
@Order(-2)
@Slf4j
public class GlobalExceptionHandler extends AbstractErrorWebExceptionHandler {
public GlobalExceptionHandler(
GlobalErrorAttributes globalErrorAttributes,
ApplicationContext applicationContext,
ServerCodecConfigurer serverCodecConfigurer
) {
super(globalErrorAttributes, new ResourceProperties(), applicationContext);
super.setMessageWriters(serverCodecConfigurer.getWriters());
}
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) {
final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, ErrorAttributeOptions.defaults());
Throwable throwable = getError(request);
return Mono
.just(throwable)
.filter(ResponseStatusException.class::isInstance)
.map(ResponseStatusException.class::cast)
.flatMap(e -> {
log.error(e.getReason(), e);
return ServerResponse
.status(e.getStatus())
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(errorPropertiesMap));
})
.onErrorResume(e -> {
log.error(e.getMessage(), e);
return ServerResponse
.status(500)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(errorPropertiesMap));
}
);
}
}
|
3e1ccd7209082b58e8a008f76e6fae3730319291 | 275 | java | Java | translator-web-meta/translator-web-orm/src/main/java/com/github/bogdanovmn/translator/web/orm/entity/UserRepository.java | bogdanovmn/translator | 0653a0215fae40682c7fbcd1d7ec85efd2f23c3e | [
"BSD-3-Clause"
] | null | null | null | translator-web-meta/translator-web-orm/src/main/java/com/github/bogdanovmn/translator/web/orm/entity/UserRepository.java | bogdanovmn/translator | 0653a0215fae40682c7fbcd1d7ec85efd2f23c3e | [
"BSD-3-Clause"
] | 96 | 2017-09-24T12:22:39.000Z | 2020-02-03T23:08:14.000Z | translator-web-meta/translator-web-orm/src/main/java/com/github/bogdanovmn/translator/web/orm/entity/UserRepository.java | bogdanovmn/translator | 0653a0215fae40682c7fbcd1d7ec85efd2f23c3e | [
"BSD-3-Clause"
] | null | null | null | 25 | 68 | 0.829091 | 12,225 | package com.github.bogdanovmn.translator.web.orm.entity;
import com.github.bogdanovmn.common.spring.jpa.BaseEntityRepository;
public interface UserRepository extends BaseEntityRepository<User> {
User findFirstByName(String name);
User findFirstByEmail(String email);
}
|
3e1ccde81dd2a4f171d8733fc6e8e0201e339e7c | 2,390 | java | Java | aliyun-java-sdk-sofa/src/main/java/com/aliyuncs/sofa/model/v20190815/InitLinkeBahamutAdmintemplateinitstcRequest.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | 1 | 2020-11-23T08:42:58.000Z | 2020-11-23T08:42:58.000Z | aliyun-java-sdk-sofa/src/main/java/com/aliyuncs/sofa/model/v20190815/InitLinkeBahamutAdmintemplateinitstcRequest.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | null | null | null | aliyun-java-sdk-sofa/src/main/java/com/aliyuncs/sofa/model/v20190815/InitLinkeBahamutAdmintemplateinitstcRequest.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | null | null | null | 25.425532 | 126 | 0.728033 | 12,226 | /*
* 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.aliyuncs.sofa.model.v20190815;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.sofa.Endpoint;
/**
* @author auto create
* @version
*/
public class InitLinkeBahamutAdmintemplateinitstcRequest extends RpcAcsRequest<InitLinkeBahamutAdmintemplateinitstcResponse> {
private String type;
private String tenantId;
private String templateId;
private String opo;
public InitLinkeBahamutAdmintemplateinitstcRequest() {
super("SOFA", "2019-08-15", "InitLinkeBahamutAdmintemplateinitstc", "sofacafedeps");
setMethod(MethodType.POST);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
if(type != null){
putBodyParameter("Type", type);
}
}
public String getTenantId() {
return this.tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
if(tenantId != null){
putBodyParameter("TenantId", tenantId);
}
}
public String getTemplateId() {
return this.templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
if(templateId != null){
putBodyParameter("TemplateId", templateId);
}
}
public String getOpo() {
return this.opo;
}
public void setOpo(String opo) {
this.opo = opo;
if(opo != null){
putBodyParameter("Opo", opo);
}
}
@Override
public Class<InitLinkeBahamutAdmintemplateinitstcResponse> getResponseClass() {
return InitLinkeBahamutAdmintemplateinitstcResponse.class;
}
}
|
3e1ccf0aba7f8d4a992ce83ec635a7bead695fa1 | 1,186 | java | Java | university/introduction_to_computer_science/otherSortingAlgorithms/QuickSort.java | dev-andreas/university-algorithms | 9d5d457acd248da7256f87787363443700da2341 | [
"Apache-2.0"
] | null | null | null | university/introduction_to_computer_science/otherSortingAlgorithms/QuickSort.java | dev-andreas/university-algorithms | 9d5d457acd248da7256f87787363443700da2341 | [
"Apache-2.0"
] | null | null | null | university/introduction_to_computer_science/otherSortingAlgorithms/QuickSort.java | dev-andreas/university-algorithms | 9d5d457acd248da7256f87787363443700da2341 | [
"Apache-2.0"
] | null | null | null | 24.708333 | 67 | 0.496627 | 12,227 | import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] array = new int[10];
System.out.println((int)(3.4d + (12 % 2)) + 3);
for (int i = 0; i < array.length; i++) {
array[i] = (int)(Math.random()*300);
}
quickSort(array, 0, array.length);
System.out.println(Arrays.toString(array));
}
public static void quickSort(int[] items) {
}
public static void quickSort(int[] items, int start, int end) {
if (start >= end)
return;
int pivot = items[end - 1];
int left = start;
int right = end - 1;
while (left < right) {
while (items[left] < pivot) {
left++;
}
while (items[right] > pivot && left < right) {
right--;
}
swap(items, left, right);
}
quickSort(items, start, left);
quickSort(items, left+1, end);
}
public static void swap(int[] items, int first, int second) {
int buffer = items[first];
items[first] = items[second];
items[second] = buffer;
}
}
|
3e1ccfac6e030fe424e60b59aa98743b94c6513f | 5,322 | java | Java | src/test/java/please/change/me/simulator/common/concurrent/ConcurrentLazyCacheTest.java | nablarch/nablarch-messaging-simulator | 06e9e69fee700b2350403dd2c4ea4a9f58790125 | [
"Apache-2.0"
] | null | null | null | src/test/java/please/change/me/simulator/common/concurrent/ConcurrentLazyCacheTest.java | nablarch/nablarch-messaging-simulator | 06e9e69fee700b2350403dd2c4ea4a9f58790125 | [
"Apache-2.0"
] | 1 | 2016-10-31T00:38:27.000Z | 2016-11-02T02:00:20.000Z | src/test/java/please/change/me/simulator/common/concurrent/ConcurrentLazyCacheTest.java | nablarch/nablarch-messaging-simulator | 06e9e69fee700b2350403dd2c4ea4a9f58790125 | [
"Apache-2.0"
] | null | null | null | 30.238636 | 102 | 0.562946 | 12,228 | package please.change.me.simulator.common.concurrent;
import org.junit.After;
import org.junit.Test;
import please.change.me.simulator.common.concurrent.ConcurrentLazyCache.CachingValueFactory;
import please.change.me.simulator.common.concurrent.ConcurrentLazyCache.ValueFactory;
import please.change.me.simulator.common.concurrent.ConcurrentLazyCache.ValueFactoryBuilder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* {@link ConcurrentLazyCache}のテストクラス。
*
* @author T.Kawasaki
* @since 1.4.2
*/
public class ConcurrentLazyCacheTest {
/** テスト対象インスタンス */
private final ConcurrentLazyCache<String, MyValue> target = new ConcurrentLazyCache<String,
MyValue>(new MyBuilder());
/** 呼び出し回数を数えるためのカウンタ */
private final AtomicInteger callCount = new AtomicInteger(0); //マルチスレッドでカウントできるようにAtomicInteger
/** テスト用の{@link ValueFactoryBuilder}実装。 */
private class MyBuilder implements ValueFactoryBuilder<String, MyValue> {
/** {@inheritDoc} */
@Override
public ConcurrentLazyCache.ValueFactory<MyValue> newInstance(String key) {
return new CachingValueFactory<String, MyValue>(key) {
@Override
public MyValue getValueOf(String key) {
// 呼び出し回数を記録
callCount.incrementAndGet();
// 毎回別のインスタンスを作る。
// 異なるスレッドから複数回呼び出されるとそれぞれ
// 別のインスタンスが返却されることになる。
return new MyValue(key);
}
};
}
}
/** キャッシュに格納されるされる値クラス。 */
private static class MyValue {
/** 文字列 */
private final String s;
/**
* コンストラクタ。
*
* @param s 文字列
*/
MyValue(String s) {
this.s = s;
}
/** {@inheritDoc} */
@Override
public String toString() {
return s;
}
}
/** シングルスレッド下で動作することを確認する。 */
@Test
public void testSingleThread() {
for (int i = 0; i < 3; i++) {
final int cnt = 10000;
List<MyValue> ret = new ArrayList<MyValue>(cnt);
for (int j = 0; j < cnt; j++) {
String key = String.valueOf(j);
MyValue o = target.get(key);
ret.add(o);
}
assertThat(ret.size(), is(10000));
// 重複がないこと
assertThat(new HashSet<MyValue>(ret).size(), is(10000));
// 呼び出し回数分カウントアップされていること。
assertThat(callCount.get(), is(10000));
}
}
private ExecutorService service;
/**
* マルチスレッド下で動作することを確認する。
*
* @throws InterruptedException
* @throws ExecutionException
*/
@Test
public void testMultiThread() throws InterruptedException, ExecutionException {
service = Executors.newFixedThreadPool(100);
final int cnt = 100000;
List<Callable<MyValue>> callables = new ArrayList<Callable<MyValue>>(cnt);
for (int i = 0; i < cnt; i++) {
final String key = new String("aaa"); // 敢えて別インスタンスを生成する。
callables.add(new Callable<MyValue>() {
@Override
public MyValue call() throws Exception {
// 全スレッドで同じキー"aaa"をgetする。
return target.get(key);
}
});
}
List<Future<MyValue>> futures = service.invokeAll(callables);
// 呼び出し回数と結果数が一致していること。
assertThat(futures.size(), is(cnt));
// 結果の種類をまとめる。
// MyObjはequalsをオーバーライドしていないので、
// インスタンスが同じでないと等価とみなされない。
Set<MyValue> results = new HashSet<MyValue>();
for (Future<MyValue> future : futures) {
results.add(future.get());
}
// 一つのキーに対して初期化が1回しか行われていない。
assertThat(results.size(), is(1));
//getValueOfが1回しか呼び出されていないこと(それ以外はキャッシュにあたっている)。
assertThat(callCount.get(), is(1));
}
@After
public void shutdown() {
if (service != null) {
service.shutdownNow();
}
}
@Test(expected = IllegalStateException.class)
public void testInvalidFactory() {
ConcurrentLazyCache<String, String> target
= new ConcurrentLazyCache<String, String>(new ValueFactoryBuilder<String, String>() {
@Override
public ValueFactory<String> newInstance(String key) {
return new CachingValueFactory<String, String>("key") {
@Override
protected String getValueOf(String key) {
return null;
}
};
}
});
target.get("will cause exception..");
}
} |
3e1cd0af2b42add35941a5528addd2ce32a89d14 | 511 | java | Java | CyrusHABLib/src/test/java/net/cyrusbuilt/cyrushab/core/telemetry/SystemStatusTest.java | cyrusbuilt/CyrusHAB | 1769c1b60101326bbcc226541f5031e61bcff217 | [
"MIT"
] | null | null | null | CyrusHABLib/src/test/java/net/cyrusbuilt/cyrushab/core/telemetry/SystemStatusTest.java | cyrusbuilt/CyrusHAB | 1769c1b60101326bbcc226541f5031e61bcff217 | [
"MIT"
] | null | null | null | CyrusHABLib/src/test/java/net/cyrusbuilt/cyrushab/core/telemetry/SystemStatusTest.java | cyrusbuilt/CyrusHAB | 1769c1b60101326bbcc226541f5031e61bcff217 | [
"MIT"
] | null | null | null | 23.227273 | 62 | 0.667319 | 12,229 | package net.cyrusbuilt.cyrushab.core.telemetry;
import org.junit.Test;
import static org.junit.Assert.*;
public class SystemStatusTest {
@Test
public void getType() {
SystemStatus expected = SystemStatus.DISABLED;
SystemStatus actual = SystemStatus.UNKNOWN.getType(1);
assertEquals(expected, actual);
}
@Test
public void getValue() {
int expected = 1;
int actual = SystemStatus.DISABLED.getValue();
assertEquals(expected, actual);
}
} |
3e1cd1764f50133ed6ddae3365f072f5e3fb0ff9 | 5,234 | java | Java | core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/VOID.java | t-rasmud/rdf4j | 8c83d0c83f55017c585e0c40349b01bfd60d6e64 | [
"BSD-3-Clause"
] | 312 | 2016-01-14T20:04:24.000Z | 2022-03-30T22:21:41.000Z | core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/VOID.java | t-rasmud/rdf4j | 8c83d0c83f55017c585e0c40349b01bfd60d6e64 | [
"BSD-3-Clause"
] | 2,611 | 2016-01-18T22:32:22.000Z | 2022-03-31T17:38:43.000Z | core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/VOID.java | t-rasmud/rdf4j | 8c83d0c83f55017c585e0c40349b01bfd60d6e64 | [
"BSD-3-Clause"
] | 186 | 2016-01-14T21:18:37.000Z | 2022-03-22T12:32:33.000Z | 31.154762 | 87 | 0.750287 | 12,230 | /**
* Copyright (c) 2015 Eclipse RDF4J contributors, and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*/
package org.eclipse.rdf4j.model.vocabulary;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Namespace;
/**
* Constants for the W3C Vocabulary of Interlinked Datasets.
*
* @see <a href="https://www.w3.org/TR/void/">Vocabulary of Interlinked Datasets</a>
*
* @author Bart Hanssens
*/
public class VOID {
/**
* The VoID namespace: http://rdfs.org/ns/void#
*/
public static final String NAMESPACE = "http://rdfs.org/ns/void#";
/**
* Recommended prefix for the VoID namespace: "void"
*/
public static final String PREFIX = "void";
/**
* An immutable {@link Namespace} constant that represents the VoID namespace.
*/
public static final Namespace NS = Vocabularies.createNamespace(PREFIX, NAMESPACE);
// Classes
/** void:Dataset */
public static final IRI DATASET;
/** void:DatasetDescription */
public static final IRI DATASET_DESCRIPTION;
/** void:Linkset */
public static final IRI LINKSET;
/** void:TechnicalFeature */
public static final IRI TECHNICAL_FEATURE;
// Properties
/** void:class */
public static final IRI CLASS;
/** void:classPartition */
public static final IRI CLASS_PARTITION;
/** void:classes */
public static final IRI CLASSES;
/** void:dataDump */
public static final IRI DATA_DUMP;
/** void:distinctObjects */
public static final IRI DISTINCT_OBJECTS;
/** void:distinctSubjects */
public static final IRI DISTINCT_SUBJECTS;
/** void:documents */
public static final IRI DOCUMENTS;
/** void:entities */
public static final IRI ENTITIES;
/** void:exampleResource */
public static final IRI EXAMPLE_RESOURCE;
/** void:feature */
public static final IRI FEATURE;
/** void:inDataset */
public static final IRI IN_DATASET;
/** void:linkPredicate */
public static final IRI LINK_PREDICATE;
/** void:objectsTarget */
public static final IRI OBJECTS_TARGET;
/** void:openSearchDescription */
public static final IRI OPEN_SEARCH_DESCRIPTION;
/** void:properties */
public static final IRI PROPERTIES;
/** void:property */
public static final IRI PROPERTY;
/** void:propertyPartition */
public static final IRI PROPERTY_PARTITION;
/** void:rootResource */
public static final IRI ROOT_RESOURCE;
/** void:sparqlEndpoint */
public static final IRI SPARQL_ENDPOINT;
/** void:subjectsTarget */
public static final IRI SUBJECTS_TARGET;
/** void:subset */
public static final IRI SUBSET;
/** void:target */
public static final IRI TARGET;
/** void:triples */
public static final IRI TRIPLES;
/** void:uriLookupEndpoint */
public static final IRI URI_LOOKUP_ENDPOINT;
/** void:uriRegexPattern */
public static final IRI URI_REGEX_PATTERN;
/** void:uriSpace */
public static final IRI URI_SPACE;
/** void:vocabulary */
public static final IRI VOCABULARY;
static {
DATASET = Vocabularies.createIRI(NAMESPACE, "Dataset");
DATASET_DESCRIPTION = Vocabularies.createIRI(NAMESPACE, "DatasetDescription");
LINKSET = Vocabularies.createIRI(NAMESPACE, "Linkset");
TECHNICAL_FEATURE = Vocabularies.createIRI(NAMESPACE, "TechnicalFeature");
CLASS = Vocabularies.createIRI(NAMESPACE, "class");
CLASS_PARTITION = Vocabularies.createIRI(NAMESPACE, "classPartition");
CLASSES = Vocabularies.createIRI(NAMESPACE, "classes");
DATA_DUMP = Vocabularies.createIRI(NAMESPACE, "dataDump");
DISTINCT_OBJECTS = Vocabularies.createIRI(NAMESPACE, "distinctObjects");
DISTINCT_SUBJECTS = Vocabularies.createIRI(NAMESPACE, "distinctSubjects");
DOCUMENTS = Vocabularies.createIRI(NAMESPACE, "documents");
ENTITIES = Vocabularies.createIRI(NAMESPACE, "entities");
EXAMPLE_RESOURCE = Vocabularies.createIRI(NAMESPACE, "exampleResource");
FEATURE = Vocabularies.createIRI(NAMESPACE, "feature");
IN_DATASET = Vocabularies.createIRI(NAMESPACE, "inDataset");
LINK_PREDICATE = Vocabularies.createIRI(NAMESPACE, "linkPredicate");
OBJECTS_TARGET = Vocabularies.createIRI(NAMESPACE, "objectsTarget");
OPEN_SEARCH_DESCRIPTION = Vocabularies.createIRI(NAMESPACE, "openSearchDescription");
PROPERTIES = Vocabularies.createIRI(NAMESPACE, "properties");
PROPERTY = Vocabularies.createIRI(NAMESPACE, "property");
PROPERTY_PARTITION = Vocabularies.createIRI(NAMESPACE, "propertyPartition");
ROOT_RESOURCE = Vocabularies.createIRI(NAMESPACE, "rootResource");
SPARQL_ENDPOINT = Vocabularies.createIRI(NAMESPACE, "sparqlEndpoint");
SUBJECTS_TARGET = Vocabularies.createIRI(NAMESPACE, "subjectsTarget");
SUBSET = Vocabularies.createIRI(NAMESPACE, "subset");
TARGET = Vocabularies.createIRI(NAMESPACE, "target");
TRIPLES = Vocabularies.createIRI(NAMESPACE, "triples");
URI_LOOKUP_ENDPOINT = Vocabularies.createIRI(NAMESPACE, "uriLookupEndpoint");
URI_REGEX_PATTERN = Vocabularies.createIRI(NAMESPACE, "uriRegexPattern");
URI_SPACE = Vocabularies.createIRI(NAMESPACE, "uriSpace");
VOCABULARY = Vocabularies.createIRI(NAMESPACE, "vocabulary");
}
}
|
3e1cd36e50c536694baaa35b0dc373ce07d17741 | 1,599 | java | Java | src/fr/eni/ecole/projet_enchere/bll/BllFactory.java | NicolasGautier/ProjetEncheres | 107ebda85e9b14cfc60fad80b621bc762bf46c3e | [
"Apache-2.0"
] | null | null | null | src/fr/eni/ecole/projet_enchere/bll/BllFactory.java | NicolasGautier/ProjetEncheres | 107ebda85e9b14cfc60fad80b621bc762bf46c3e | [
"Apache-2.0"
] | null | null | null | src/fr/eni/ecole/projet_enchere/bll/BllFactory.java | NicolasGautier/ProjetEncheres | 107ebda85e9b14cfc60fad80b621bc762bf46c3e | [
"Apache-2.0"
] | 1 | 2021-10-21T12:03:34.000Z | 2021-10-21T12:03:34.000Z | 30.169811 | 71 | 0.798624 | 12,231 | package fr.eni.ecole.projet_enchere.bll;
import fr.eni.ecole.projet_enchere.bll.client0.ArticleVenduManagerImpl;
import fr.eni.ecole.projet_enchere.bll.client0.CategorieManagerImpl;
import fr.eni.ecole.projet_enchere.bll.client0.EnchereManagerImpl;
import fr.eni.ecole.projet_enchere.bll.client0.RetraitManagerImpl;
import fr.eni.ecole.projet_enchere.bll.client0.UtilisateurManagerImpl;
public abstract class BllFactory {
private static UtilisateurManager utilisateurManager;
private static EnchereManager enchereManager;
private static CategorieManager categorieManager;
private static ArticleVenduManager articleVenduManager;
private static RetraitManager retraitManager;
public static UtilisateurManager getUniqueUtilisateurManager() {
if (utilisateurManager == null) {
utilisateurManager = new UtilisateurManagerImpl();
}
return utilisateurManager;
}
public static EnchereManager getUniqueEnchereManager() {
if (enchereManager == null) {
enchereManager = new EnchereManagerImpl();
}
return enchereManager;
}
public static CategorieManager getUniqueCategorieManager() {
if (categorieManager == null) {
categorieManager = new CategorieManagerImpl();
}
return categorieManager;
}
public static ArticleVenduManager getUniqueArticleVenduManager() {
if (articleVenduManager == null) {
articleVenduManager = new ArticleVenduManagerImpl();
}
return articleVenduManager;
}
public static RetraitManager getUniqueRetraitManager() {
if (retraitManager == null) {
retraitManager = new RetraitManagerImpl();
}
return retraitManager;
}
}
|
3e1cd4d8d10382ce230cf43214ec874e43c4493c | 356 | java | Java | src/main/java/pointGroups/geometry/Point.java | Ryugoron/point-groups | 3834bdd474847e7908d94fa1180e49d6860bbe11 | [
"BSD-2-Clause"
] | 1 | 2015-12-03T00:54:00.000Z | 2015-12-03T00:54:00.000Z | src/main/java/pointGroups/geometry/Point.java | Ryugoron/point-groups | 3834bdd474847e7908d94fa1180e49d6860bbe11 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/pointGroups/geometry/Point.java | Ryugoron/point-groups | 3834bdd474847e7908d94fa1180e49d6860bbe11 | [
"BSD-2-Clause"
] | null | null | null | 19.777778 | 80 | 0.685393 | 12,232 | package pointGroups.geometry;
/**
* Marker interface for point classes. This class only exists since we need some
* general type for points regardless whether they live in R<sup>3</sup> or
* R<sup>4</sup>.
*
* @author Alex
*/
public interface Point
{
/**
* @return Ordered coordinates of the point.
*/
public double[] getComponents();
}
|
3e1cd503a3e3cdf82b105fc0c22a1c0beda0f6a6 | 3,542 | java | Java | src/main/java/olivermakesco/de/bmc/mixin/GeyserSessionMixin.java | TheEpicBlock/bmc-rewrite | f29e39b29574f71306ac110b98a77f86fa56c567 | [
"CC0-1.0"
] | null | null | null | src/main/java/olivermakesco/de/bmc/mixin/GeyserSessionMixin.java | TheEpicBlock/bmc-rewrite | f29e39b29574f71306ac110b98a77f86fa56c567 | [
"CC0-1.0"
] | null | null | null | src/main/java/olivermakesco/de/bmc/mixin/GeyserSessionMixin.java | TheEpicBlock/bmc-rewrite | f29e39b29574f71306ac110b98a77f86fa56c567 | [
"CC0-1.0"
] | 3 | 2021-12-28T15:00:05.000Z | 2022-02-23T19:59:35.000Z | 44.275 | 134 | 0.689441 | 12,233 | package olivermakesco.de.bmc.mixin;
import com.nukkitx.nbt.NbtMap;
import com.nukkitx.nbt.NbtMapBuilder;
import com.nukkitx.protocol.bedrock.BedrockPacket;
import com.nukkitx.protocol.bedrock.data.ExperimentData;
import com.nukkitx.protocol.bedrock.data.inventory.ComponentItemData;
import com.nukkitx.protocol.bedrock.packet.ItemComponentPacket;
import com.nukkitx.protocol.bedrock.packet.StartGamePacket;
import edu.umd.cs.findbugs.annotations.NonNull;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import olivermakesco.de.bmc.impl.BedrockModCompat;
import org.geysermc.geyser.session.GeyserSession;
import org.geysermc.geyser.session.UpstreamSession;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(GeyserSession.class)
public class GeyserSessionMixin {
@Redirect(
method = "startGame()V",
at = @At(
value = "INVOKE",
target = "Lorg/geysermc/geyser/session/UpstreamSession;sendPacket(Lcom/nukkitx/protocol/bedrock/BedrockPacket;)V"
),
remap = false
)
public void editStartPacket(UpstreamSession upstreamSession, @NonNull BedrockPacket packet) {
if (!(packet instanceof StartGamePacket startGamePacket)) return;
startGamePacket.getExperiments().add(new ExperimentData("data_driven_items", true));
//TODO: Allow creation of custom blocks
upstreamSession.sendPacket(startGamePacket);
}
@Redirect(
method = "connect()V",
at = @At(
value = "INVOKE",
target = "Lorg/geysermc/geyser/session/UpstreamSession;sendPacket(Lcom/nukkitx/protocol/bedrock/BedrockPacket;)V",
ordinal = 0
),
remap = false
)
public void editItemPacket(UpstreamSession upstreamSession, @NonNull BedrockPacket packet) {
if (!(packet instanceof ItemComponentPacket itemComponentPacket)) return;
//TODO: Use bedrock IDs to generate the proper items
for (ResourceLocation id : BedrockModCompat.itemRegistry.keySet()) {
Item item = BedrockModCompat.itemRegistry.get(id);
NbtMapBuilder propertiesBuilder = NbtMap.builder();
propertiesBuilder.put("max_stack_size",item.getMaxStackSize());
propertiesBuilder.put("allow_offhand",true);
propertiesBuilder.put("hand_equipped",true);
NbtMap properties = propertiesBuilder.build();
NbtMapBuilder iconBuilder = NbtMap.builder();
iconBuilder.put("texture", id.getPath());
NbtMap icon = iconBuilder.build();
NbtMapBuilder componentsBuilder = NbtMap.builder();
componentsBuilder.put("item_properties",properties);
componentsBuilder.put("minecraft:icon",icon);
NbtMap components = componentsBuilder.build();
NbtMapBuilder itemBuilder = NbtMap.builder();
itemBuilder.put("components",components);
itemBuilder.put("id",0);
itemBuilder.put("name","zzz"+id);
itemComponentPacket.getItems().add(new ComponentItemData("zzz"+id,itemBuilder.build()));
}
BedrockModCompat.LOGGER.info("Sending item packet");
BedrockModCompat.LOGGER.info(BedrockModCompat.itemRegistry.size());
upstreamSession.sendPacket(itemComponentPacket);
}
}
|
3e1cd5e7d4d38768ce54d593fe2f7477cd99c85e | 744 | java | Java | src/main/java/functionLibrary/ReportLog.java | automationscrip/Selenium-POM-By-TestNG-Parallel | edd108265c1f0c6c3b8430ef812406853984017f | [
"MIT"
] | null | null | null | src/main/java/functionLibrary/ReportLog.java | automationscrip/Selenium-POM-By-TestNG-Parallel | edd108265c1f0c6c3b8430ef812406853984017f | [
"MIT"
] | null | null | null | src/main/java/functionLibrary/ReportLog.java | automationscrip/Selenium-POM-By-TestNG-Parallel | edd108265c1f0c6c3b8430ef812406853984017f | [
"MIT"
] | 1 | 2021-08-23T17:15:33.000Z | 2021-08-23T17:15:33.000Z | 23.25 | 90 | 0.767473 | 12,234 | package functionLibrary;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
public class ReportLog {
static ExtentReports extent;
ExtentSparkReporter spark;
ExtentTest test;
String ScreenshotPath;
public static ExtentReports extentReportGenerator() {
ExtentSparkReporter spark= new ExtentSparkReporter("target/Spark.html");
spark.config().setReportName("Page object model with parallel execution using TestNG");
spark.config().setDocumentTitle("ExtentReports in parallel test execution");
extent= new ExtentReports();
extent.attachReporter(spark);
return extent;
}
} |
3e1cd638accabfbf483518c509c8276bf7f5446a | 1,550 | java | Java | src/main/java/com/team2502/robot2021/subsystem/HopperSubsystem.java | Team-2502/RobotCode2021 | a2362ac53e72e95c0c712abbcde4170239bfda0d | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/team2502/robot2021/subsystem/HopperSubsystem.java | Team-2502/RobotCode2021 | a2362ac53e72e95c0c712abbcde4170239bfda0d | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/team2502/robot2021/subsystem/HopperSubsystem.java | Team-2502/RobotCode2021 | a2362ac53e72e95c0c712abbcde4170239bfda0d | [
"BSD-3-Clause"
] | 1 | 2021-01-22T00:35:49.000Z | 2021-01-22T00:35:49.000Z | 38.75 | 101 | 0.774839 | 12,235 | package com.team2502.robot2021.subsystem;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import com.team2502.robot2021.Constants.RobotMap.Motors;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
public class HopperSubsystem extends SubsystemBase {
private final CANSparkMax hopperSideBeltsRight;
private final CANSparkMax hopperSideBeltsLeft;
private final CANSparkMax hopperBottomBelt;
private final CANSparkMax hopperExitWheel;
public HopperSubsystem() {
hopperSideBeltsRight = new CANSparkMax(Motors.HOPPER_SIDE_BELTS_RIGHT, MotorType.kBrushless);
hopperSideBeltsRight.setSmartCurrentLimit(25);
hopperSideBeltsLeft = new CANSparkMax(Motors.HOPPER_SIDE_BELTS_LEFT, MotorType.kBrushless);
hopperSideBeltsLeft.setSmartCurrentLimit(25);
hopperBottomBelt = new CANSparkMax(Motors.HOPPER_BOTTOM_BELT, MotorType.kBrushless);
hopperBottomBelt.setSmartCurrentLimit(25);
hopperExitWheel = new CANSparkMax(Motors.HOPPER_EXIT_WHEEL, MotorType.kBrushless);
hopperExitWheel.setSmartCurrentLimit(25);
hopperSideBeltsRight.setInverted(true);
hopperExitWheel.setInverted(true);
}
public void runLeftBelt(double speed) { hopperSideBeltsLeft.set(speed); }
public void runRightBelt(double speed) { hopperSideBeltsRight.set(speed); }
public void runExitWheel(double speed){
hopperExitWheel.set(speed);
}
public void runBottomBelt(double speed) { hopperBottomBelt.set(speed); }
}
|
3e1cd72ea6c189f075746071895a6f135899dd57 | 1,898 | java | Java | src/game/world/entities/creature/OneThreeSeven.java | Matsumotorise/movingCharacter | 054506e23c5ab13b6840ecd0fe2b5adcc20416d4 | [
"Apache-2.0"
] | null | null | null | src/game/world/entities/creature/OneThreeSeven.java | Matsumotorise/movingCharacter | 054506e23c5ab13b6840ecd0fe2b5adcc20416d4 | [
"Apache-2.0"
] | null | null | null | src/game/world/entities/creature/OneThreeSeven.java | Matsumotorise/movingCharacter | 054506e23c5ab13b6840ecd0fe2b5adcc20416d4 | [
"Apache-2.0"
] | null | null | null | 26.732394 | 88 | 0.590622 | 12,236 | package game.world.entities.creature;
import game.Handler;
import game.gfx.Animator;
import game.gfx.Assets;
import game.item.Item;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Iterator;
public class OneThreeSeven extends Creature {
public OneThreeSeven(Handler handler, float x, float y, float wSpeed, float rSpeed) {
super(handler, Assets.F137, x, y,
Assets.F137.get(0).getCurrentWidth(),
Assets.F137.get(0).getCurrentWidth(),
wSpeed, rSpeed);
}
@Override
public void drop() {
handler.getWorld().getItemManager().addItem(Item.wood.createNew(
(int) (getX() + getWidth() / 2 + Math.random() * 50),
(int) (getY() + getHeight() / 2 + Math.random() * 50)));
}
@Override
public void update() {
Iterator<Animator> iterator = Assets.F137.iterator();
while (iterator.hasNext()) {
Animator a = iterator.next();
a.update();
}
double randA = Math.random();
if(randA > .5) {
setX((float) ((getX() + getSpeed().getRSpeed())*randA));
} else {
setX((float) ((getX() - getSpeed().getRSpeed())*randA));
}
double randB = Math.random();
if(randB > .5) {
setY((float) ((getY() + getSpeed().getRSpeed())*randB));
} else {
setY((float) ((getY() - getSpeed().getRSpeed())*randB));
}
}
@Override
public void render(Graphics g) {
animation.render(g);
}
@Override
protected void setHitbox() {
bounds.width = 39;
bounds.height = 49;
bounds.x = 27;
bounds.y = 42;
}
@Override
protected void showHitbox(Graphics g) {
g.setColor(Color.red);
g.fillRect((int) (getX() + bounds.x - handler.getGameCamera().getxOffset()),
(int) (getY() + bounds.y - handler.getGameCamera().getyOffset()), bounds.width,
bounds.height);
}
}
|
3e1cd73a09146379858a7bec1759b4cf6d39d89d | 4,831 | java | Java | src/main/java/org/rs2server/util/BufferUtils.java | lerages/anarchy-source | 47ad847d769f3478789df93517fde744278fd41e | [
"MIT"
] | null | null | null | src/main/java/org/rs2server/util/BufferUtils.java | lerages/anarchy-source | 47ad847d769f3478789df93517fde744278fd41e | [
"MIT"
] | null | null | null | src/main/java/org/rs2server/util/BufferUtils.java | lerages/anarchy-source | 47ad847d769f3478789df93517fde744278fd41e | [
"MIT"
] | null | null | null | 25.031088 | 138 | 0.555165 | 12,237 | package org.rs2server.util;
import org.apache.mina.core.buffer.IoBuffer;
import java.nio.ByteBuffer;
/**
* This is for streaming or whatever
*
* @author 'Mystic Flow
*/
public class BufferUtils {
private static final char[] CHARACTERS = {
'\u20ac', '\0', '\u201a', '\u0192', '\u201e', '\u2026', '\u2020',
'\u2021', '\u02c6', '\u2030', '\u0160', '\u2039', '\u0152', '\0',
'\u017d', '\0', '\0', '\u2018', '\u2019', '\u201c', '\u201d',
'\u2022', '\u2013', '\u2014', '\u02dc', '\u2122', '\u0161',
'\u203a', '\u0153', '\0', '\u017e', '\u0178'
};
public static void writeRS2String(ByteBuffer buffer, String string) {
buffer.put(string.getBytes());
buffer.put((byte) 0);
}
public static String readRS2String(ByteBuffer buffer) {
StringBuilder sb = new StringBuilder();
byte b;
while (buffer.remaining() > 0 && (b = buffer.get()) != 0) {
sb.append((char) b);
}
return sb.toString();
}
public static int readSmart(ByteBuffer buf) {
int peek = buf.get(buf.position()) & 0xFF;
if (peek < 128) {
return buf.get();
} else {
return (buf.getShort() & 0xFFFF) - 32768;
}
}
public static int readSmart(IoBuffer buf) {
int peek = buf.get(buf.position()) & 0xFF;
if (peek < 128) {
return buf.get();
} else {
return (buf.getShort() & 0xFFFF) - 32768;
}
}
public static int getMediumInt(ByteBuffer buffer) {
return ((buffer.get() & 0xFF) << 16) | ((buffer.get() & 0xFF) << 8) | (buffer.get() & 0xFF);
}
public static int readSmart2(ByteBuffer buffer) {
int i_26_ = 0;
int i_27_;
for (i_27_ = readSmart(buffer); i_27_ == 32767; i_27_ = readSmart(buffer)) {
i_26_ += 32767;
}
i_26_ += i_27_;
return i_26_;
}
public static void writeInt(int val, int index, byte[] buffer) {
buffer[index++] = (byte) (val >> 24);
buffer[index++] = (byte) (val >> 16);
buffer[index++] = (byte) (val >> 8);
buffer[index++] = (byte) val;
}
public static int readMedium(int index, byte[] buffer) {
return ((buffer[index++] & 0xff) << 16) | ((buffer[index++] & 0xff) << 8) | (buffer[index++] & 0xff);
}
public static int readInt(int index, byte[] buffer) {
return ((buffer[index++] & 0xff) << 24) | ((buffer[index++] & 0xff) << 16) | ((buffer[index++] & 0xff) << 8) | (buffer[index++] & 0xff);
}
public static char getCPCharacter(ByteBuffer buffer) {
int read = buffer.get() & 0xff;
if (read == 0) {
throw new IllegalArgumentException("Non cp1252 character 0x" + Integer.toString(read, 16) + " provided");
}
if (read >= 128 && read < 160) {
char cpChar = CHARACTERS[read - 128];
if (cpChar == '\0') {
cpChar = '?';
}
read = cpChar;
}
return (char) read;
}
/*
*
final String getString(int i) {
anInt7302++;
int i_17_ = anInt7298;
while ((aByteArray7322[anInt7298++] ^ 0xffffffff) != -1) {
}
int i_18_ = anInt7298 - i_17_ + -1;
if (i >= -122) {
return null;
}
if (i_18_ == 0) {
return "";
}
return Class358.method3742(i_17_, aByteArray7322, i_18_, (byte) 75);
}
anInt4472++;
char[] cs = new char[i_0_];
int i_1_ = 0;
for (int i_2_ = 0; i_0_ > i_2_; i_2_++) {
int i_3_ = bs[i + i_2_] & 0xff;
if (i_3_ != 0) {
if (i_3_ >= 128 && i_3_ < 160) {
int i_4_ = r.aCharArray9507[i_3_ + -128];
if (i_4_ == 0) {
i_4_ = 63;
}
i_3_ = i_4_;
}
cs[i_1_++] = (char) i_3_;
}
}
if (b != 75) {
aByteArray4479 = null;
}
*/
public static final String getString(ByteBuffer buf) {
int i_19_ = buf.position();
while (buf.get() != 0) {
/* empty */
}
int i_20_ = buf.position() - i_19_ - 1;
if (i_20_ == 0)
return "";
return method3722(i_19_, buf, i_20_);
}
static final String method3722(int i, ByteBuffer is, int i_1_) {
char[] cs = new char[i_1_];
int i_3_ = 0;
for (int i_4_ = 0; i_1_ > i_4_; i_4_++) {
int i_5_ = is.get(i + i_4_) & 0xff;
if (i_5_ != 0) {
if (i_5_ >= 128 && i_5_ < 160) {
int i_6_ = CHARACTERS[i_5_ - 128];
if (i_6_ == 0)
i_6_ = 63;
i_5_ = i_6_;
}
cs[i_3_++] = (char) i_5_;
}
}
return new String(cs, 0, i_3_);
}
/* public static String getString(ByteBuffer in) {
StringBuffer string = new StringBuffer();
int i;
while ((i = in.get()) != 0 && i != -1) {
string.append((char) i);
}
return string.toString();
}*/
public static String getJagexString(ByteBuffer buffer) {
StringBuilder sb = new StringBuilder();
int b;
buffer.get();
while (buffer.remaining() > 0 && (b = buffer.get() & 0xFF) != 0) {
if (b >= 128 && b < 160) {
int roar = CHARACTERS[b - 128];
if (roar == 0) {
roar = 63;
}
b = roar;
}
sb.append((char) b);
}
return sb.toString();
}
}
|
3e1cd78f8248fd7da4f07c79de1d018032f41984 | 602 | java | Java | src/test/java/pageObjects/initializePageObjects/PageFactoryInitializer.java | LightStein/WebAutomation_Allure | a2baf82d1957dc343ef56a084d7c63fb28bf403b | [
"Apache-2.0"
] | 4 | 2017-05-03T11:17:02.000Z | 2021-09-02T15:31:12.000Z | src/test/java/pageObjects/initializePageObjects/PageFactoryInitializer.java | arunima-rastogi/WebAutomation_Allure | 0bdf4c86bdb941a89353f8d8d3a05d50f7d2b89b | [
"Apache-2.0"
] | null | null | null | src/test/java/pageObjects/initializePageObjects/PageFactoryInitializer.java | arunima-rastogi/WebAutomation_Allure | 0bdf4c86bdb941a89353f8d8d3a05d50f7d2b89b | [
"Apache-2.0"
] | 4 | 2017-08-14T23:09:45.000Z | 2020-08-18T11:59:49.000Z | 19.419355 | 71 | 0.782392 | 12,238 | /**
*
*/
package pageObjects.initializePageObjects;
import org.openqa.selenium.support.PageFactory;
import controllers.BrowserFactory;
import pageObjects.modules.GMailPageObjects;
import pageObjects.modules.GoogleHomePageObjects;
/**
* @author ${Gladson Antony}
* @date Sep 17, 2016
*
*/
public class PageFactoryInitializer extends BrowserFactory
{
public GoogleHomePageObjects googleHomePage()
{
return PageFactory.initElements(driver, GoogleHomePageObjects.class);
}
public GMailPageObjects gmailPage()
{
return PageFactory.initElements(driver, GMailPageObjects.class);
}
}
|
3e1cd8c4f8decccbcab777c95155ad8e8fa6a184 | 4,611 | java | Java | src/test/java/com/xceptance/neodymium/tests/visual/pixel/colorfuzzy/ColorFuzzyTest.java | andre-becker/neodymium-library | 3e4e78bb9cc932b51b826c74f507a75fe7ecfb88 | [
"MIT"
] | 68 | 2018-03-23T00:03:44.000Z | 2022-01-19T05:39:58.000Z | src/test/java/com/xceptance/neodymium/tests/visual/pixel/colorfuzzy/ColorFuzzyTest.java | andre-becker/neodymium-library | 3e4e78bb9cc932b51b826c74f507a75fe7ecfb88 | [
"MIT"
] | 174 | 2018-03-02T13:59:24.000Z | 2022-01-19T05:56:11.000Z | src/test/java/com/xceptance/neodymium/tests/visual/pixel/colorfuzzy/ColorFuzzyTest.java | andre-becker/neodymium-library | 3e4e78bb9cc932b51b826c74f507a75fe7ecfb88 | [
"MIT"
] | 12 | 2019-02-26T03:14:23.000Z | 2022-02-04T11:44:45.000Z | 28.462963 | 120 | 0.655172 | 12,239 | package com.xceptance.neodymium.tests.visual.pixel.colorfuzzy;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import com.xceptance.neodymium.tests.visual.pixel.ImageTest;
import com.xceptance.neodymium.tests.visual.pixel.TestComparator;
import com.xceptance.neodymium.visual.image.algorithm.ColorFuzzy;
import com.xceptance.neodymium.visual.image.algorithm.ComparisonAlgorithm;
import com.xceptance.neodymium.visual.image.util.RectangleMask;
public class ColorFuzzyTest extends ImageTest
{
ComparisonAlgorithm a = new ColorFuzzy(0.1);
// how should a difference maSked during training
RectangleMask m = new RectangleMask(10, 10);
// how difference should maRked in difference file
int mX = 10;
int mY = 10;
TestComparator T;
@Before
public void setup()
{
T = new TestComparator(a, m, mX, mY);
}
/**
* Test default, no difference
*
* @throws IOException
*/
@Test
public void sameSimple()
{
T.match("colorfuzzy/blank.png").to("colorfuzzy/blank.png").isEqual();
}
/**
* Test default, no difference
*
* @throws IOException
*/
@Test
public void samePhoto()
{
T.match("colorfuzzy/photo.png").to("colorfuzzy/photo.png").isEqual();
}
/**
* Test default, one pixel diff
*
* @throws IOException
*/
@Test
public void onePixelDifferenceBlack()
{
T.match("colorfuzzy/white-35x35.png").to("colorfuzzy/white-35x35-1pixel-1x1.png").isNotEqual()
.hasMarking("colorfuzzy/onePixelDifferenceBlack.png");
}
/**
* Test default, difference close to being a problem s
*
* @throws IOException
*/
@Test
public void grayIncreasingDefaultEqual() throws IOException
{
final BufferedImage b = createTestImageGradient(Color.BLACK, 5, 5, 5);
final BufferedImage c = createTestImageGradient(new Color(25, 25, 25), 5, 5, 5);
T.match(b).to(c).isEqual();
}
/**
* Test color difference 1 that should not trigger anything
*
* @throws IOException
*/
@Test
public void grayIncreasingDefaultEqual_Color10() throws IOException
{
final BufferedImage b = createTestImageGradient(Color.BLACK, 5, 5, 5);
final BufferedImage c = createTestImageGradient(new Color(50, 50, 91), 5, 5, 5);
T = new TestComparator(new ColorFuzzy(1.0), m, mX, mY);
T.match(b).to(c).isEqual();
}
/**
* Test with color difference 0, hence it is always different enough
*
* @throws IOException
*/
@Test
public void grayIncreasingDefaultNotEqual_Color00() throws IOException
{
final BufferedImage b = createTestImageGradient(Color.BLACK, 5, 5, 5);
final BufferedImage c = createTestImageGradient(new Color(25, 25, 25), 5, 5, 5);
T = new TestComparator(new ColorFuzzy(0.0), m, 3, 3);
T.match(b).to(c).isNotEqual().hasMarking("colorfuzzy/grayIncreasingDefaultNotEqual_Color00.png");
}
/**
* Test default, we have a difference that is enough to trigger something
*
* @throws IOException
*/
@Test
public void grayIncreasingDefaultNotEqual() throws IOException
{
final BufferedImage b = createTestImageGradient(Color.BLACK, 5, 5, 5);
final BufferedImage c = createTestImageGradient(new Color(30, 30, 30), 5, 5, 5);
T = new TestComparator(a, m, 3, 3);
T.match(b).to(c).isNotEqual().hasMarking("colorfuzzy/grayIncreasingDefaultNotEqual.png");
}
/**
* Test default, we have a difference that is enough to trigger something
*
* @throws IOException
*/
@Test
public void gradient2DBlack_Color01() throws IOException
{
final BufferedImage b = createTestImage2DGradient(Color.BLACK, Color.BLUE);
T = new TestComparator(a, m, 1, 1);
T.match(b).to("colorfuzzy/black-256x256.png").isNotEqual().hasMarking("colorfuzzy/gradient2DBlack_Color01.png");
}
/**
* Test default, we have a difference that is enough to trigger something
*
* @throws IOException
*/
@Test
public void gradient2DBlack_Color05() throws IOException
{
final BufferedImage b = createTestImage2DGradient(Color.BLACK, Color.BLUE);
T = new TestComparator(new ColorFuzzy(0.5), m, 1, 1);
T.match(b).to("colorfuzzy/black-256x256.png").isNotEqual().hasMarking("colorfuzzy/gradient2DBlack_Color05.png");
}
}
|
3e1cd8ca4d57bbcd6163465222bab5dd1f5a2fa5 | 5,506 | java | Java | src/gradingTools/comp524f20/assignment0_1/testcases/OldGreetingRun.java | pdewan/Comp524LocalChecks | 70ac61f354f6610a4d84ac0f2496dbd9bff1135c | [
"MIT"
] | null | null | null | src/gradingTools/comp524f20/assignment0_1/testcases/OldGreetingRun.java | pdewan/Comp524LocalChecks | 70ac61f354f6610a4d84ac0f2496dbd9bff1135c | [
"MIT"
] | null | null | null | src/gradingTools/comp524f20/assignment0_1/testcases/OldGreetingRun.java | pdewan/Comp524LocalChecks | 70ac61f354f6610a4d84ac0f2496dbd9bff1135c | [
"MIT"
] | null | null | null | 45.131148 | 169 | 0.774428 | 12,240 | package gradingTools.comp524f20.assignment0_1.testcases;
import java.util.Arrays;
import java.util.regex.Pattern;
import grader.basics.config.BasicExecutionSpecificationSelector;
import grader.basics.execution.NotRunnableException;
import grader.basics.execution.RunningProject;
import grader.basics.junit.JUnitTestsEnvironment;
import grader.basics.junit.NotAutomatableException;
import grader.basics.junit.TestCaseResult;
import grader.basics.project.NotGradableException;
import grader.basics.project.Project;
import grader.basics.testcase.PassFailJUnitTestCase;
import gradingTools.shared.testcases.SubstringSequenceChecker;
import gradingTools.shared.testcases.greeting.AGreetingChecker;
import gradingTools.shared.testcases.greeting.GreetingMainProvided;
import gradingTools.shared.testcases.utils.LinesMatchKind;
import gradingTools.shared.testcases.utils.LinesMatcher;
import gradingTools.utils.RunningProjectUtils;
import util.annotations.MaxValue;
@MaxValue(6)
public class OldGreetingRun extends PassFailJUnitTestCase {
public static final int TIME_OUT_SECS = 1; // secs
protected SubstringSequenceChecker checker = new AGreetingChecker();
public OldGreetingRun() {
}
protected RunningProject createRunningProject (Project aProject) {
GreetingMainProvided aHelloWorkdClassProvided = (GreetingMainProvided) JUnitTestsEnvironment.getAndPossiblyRunGradableJUnitTest(GreetingMainProvided.class);
Class aHelloClass = aHelloWorkdClassProvided.getGreetingMain();
if (aHelloClass == null) {
System.err.println("Cannot run test, no main class");
return null;
}
BasicExecutionSpecificationSelector.getBasicExecutionSpecification().setEntryPoint(aHelloClass.getName());
RunningProject aRunningProject = RunningProjectUtils.runProject(aProject, TIME_OUT_SECS);
return aRunningProject;
}
@Override
public TestCaseResult test(Project project, boolean autoGrade) throws NotAutomatableException,
NotGradableException {
try {
// setEntryPoint(project);
// GreetingMainProvided aHelloWorkdClassProvided = (GreetingMainProvided) JUnitTestsEnvironment.getAndPossiblyRunGradableJUnitTest(GreetingMainProvided.class);
// Class aHelloClass = aHelloWorkdClassProvided.getGreetingMain();
// BasicExecutionSpecificationSelector.getBasicExecutionSpecification().setEntryPoint(aHelloClass.getName());
// RunningProject aRunningProject = RunningProjectUtils.runProject(project, TIME_OUT_SECS);
RunningProject aRunningProject = createRunningProject(project);
if (aRunningProject == null) {
return fail ("Could not create project. See console messages.");
}
String anOutput = aRunningProject.await();
LinesMatcher aLinesMatcher = aRunningProject.getLinesMatcher();
boolean aRetval = checker.check(aLinesMatcher, LinesMatchKind.ONE_TIME_LINE, Pattern.DOTALL);
String anExpectedLines = Arrays.toString(checker.getSubstrings());
if (!aRetval) {
return fail("Output did not match:" + anExpectedLines);
}
return pass();
} catch (NotRunnableException e) {
throw new NotGradableException();
}
}
// public static void processExternalMethodSNodes (RootOfProgramSNode aRootOfProgramSNode, RootOfFileSNode aRootOfFileSNode) {
// for (SNode anSNode:aRootOfFileSNode.getChildren()) {
// if (anSNode instanceof ExternalMethodSNode) {
// processExternalMethodSNode(aRootOfProgramSNode, aRootOfFileSNode, (ExternalMethodSNode) anSNode);
// }
// }
// }
// public static void processExternalMethodSNode (RootOfProgramSNode aRootOfProgramSNode, RootOfFileSNode aRootOfFileSNode, ExternalMethodSNode anExternalMethodSNode) {
// MethodSNode aMethodSNode = aRootOfProgramSNode.getExternalToInternalMethod().get(anExternalMethodSNode.toString());
// if (aMethodSNode == null) {
// aMethodSNode = findMethodSNode(aRootOfProgramSNode, aRootOfFileSNode, anExternalMethodSNode);
// if (aMethodSNode != null) {
// aRootOfProgramSNode.getExternalToInternalMethod().put(anExternalMethodSNode.toString(),aMethodSNode );
// }
// }
// if (aMethodSNode != null) {
// anExternalMethodSNode.setActualMethodSNode(aMethodSNode);
// }
// }
// public static MethodSNode findMethodSNode (RootOfProgramSNode aRootOfProgramSNode, RootOfFileSNode aRootOfFileSNode, ExternalMethodSNode anExternalMethodSNode) {
//// MethodSNode foundMethodSNode = null;
// for (String aFileName:aRootOfProgramSNode.getFileNameToSNode().keySet()) {
// if (aFileName.equals(aRootOfFileSNode.getFileName()))
// continue;
//
// RootOfFileSNode aSearchedRootOfFileSNode = aRootOfProgramSNode.getFileNameToSNode().get(aFileName);
// for (SNode anSNode:aSearchedRootOfFileSNode.getChildren()) {
// if (anSNode instanceof MethodSNode && !(anSNode instanceof ExternalMethodSNode)) {
// if (anSNode.toString().equals(anExternalMethodSNode)) {
// return (MethodSNode) anSNode;
//
// }
//// processExternalMethodSNode(aRootOfProgramSNode, aRootOfFileSNode, (ExternalMethodSNode) anSNode);
// }
// }
// }
// return null;
// }
// public static void processExternalMethodSNodes (RootOfProgramSNode aRootOfProgramSNode) {
// for (String aFileName:aRootOfProgramSNode.getFileNameToSNode().keySet()) {
// RootOfFileSNode aRootOfFileSNode = aRootOfProgramSNode.getFileNameToSNode().get(aFileName);
// processExternalMethodSNodes(aRootOfProgramSNode, aRootOfFileSNode);
//
// }
//
// }
}
|
3e1cd997fddaf32a960504eeeee00c22f38740fc | 917 | java | Java | devtestlabs/resource-manager/v2018_09_15/src/main/java/com/microsoft/azure/management/devtestlabs/v2018_09_15/implementation/RdpConnectionImpl.java | minaltolpadi/azure-sdk-for-java | a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb | [
"MIT"
] | 3 | 2021-09-15T16:25:19.000Z | 2021-12-17T05:41:00.000Z | devtestlabs/resource-manager/v2018_09_15/src/main/java/com/microsoft/azure/management/devtestlabs/v2018_09_15/implementation/RdpConnectionImpl.java | minaltolpadi/azure-sdk-for-java | a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb | [
"MIT"
] | 306 | 2019-09-27T06:41:56.000Z | 2019-10-14T08:19:57.000Z | devtestlabs/resource-manager/v2018_09_15/src/main/java/com/microsoft/azure/management/devtestlabs/v2018_09_15/implementation/RdpConnectionImpl.java | minaltolpadi/azure-sdk-for-java | a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb | [
"MIT"
] | 1 | 2019-10-05T04:59:12.000Z | 2019-10-05T04:59:12.000Z | 28.65625 | 90 | 0.742639 | 12,241 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.devtestlabs.v2018_09_15.implementation;
import com.microsoft.azure.management.devtestlabs.v2018_09_15.RdpConnection;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
class RdpConnectionImpl extends WrapperImpl<RdpConnectionInner> implements RdpConnection {
private final DevTestLabsManager manager;
RdpConnectionImpl(RdpConnectionInner inner, DevTestLabsManager manager) {
super(inner);
this.manager = manager;
}
@Override
public DevTestLabsManager manager() {
return this.manager;
}
@Override
public String contents() {
return this.inner().contents();
}
}
|
3e1cda495487138582f17de0cdaaabfa3abea909 | 10,853 | java | Java | community/detectors/spring_cloud_gateway_cve_2022_22947/src/main/java/com/google/tsunami/plugins/detectors/cves/cve202222947/Cve202222947VulnDetector.java | YuriyPobezhymov/tsunami-security-scanner-plugins | 2c18e5ef686111c189ce766eca52fd342569f0bc | [
"Apache-2.0"
] | null | null | null | community/detectors/spring_cloud_gateway_cve_2022_22947/src/main/java/com/google/tsunami/plugins/detectors/cves/cve202222947/Cve202222947VulnDetector.java | YuriyPobezhymov/tsunami-security-scanner-plugins | 2c18e5ef686111c189ce766eca52fd342569f0bc | [
"Apache-2.0"
] | null | null | null | community/detectors/spring_cloud_gateway_cve_2022_22947/src/main/java/com/google/tsunami/plugins/detectors/cves/cve202222947/Cve202222947VulnDetector.java | YuriyPobezhymov/tsunami-security-scanner-plugins | 2c18e5ef686111c189ce766eca52fd342569f0bc | [
"Apache-2.0"
] | 2 | 2021-10-02T03:30:49.000Z | 2021-10-02T03:30:51.000Z | 45.576132 | 100 | 0.705011 | 12,242 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.google.tsunami.plugins.detectors.cves.cve202222947;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.net.HttpHeaders.ACCEPT;
import static com.google.common.net.HttpHeaders.ACCEPT_ENCODING;
import static com.google.common.net.HttpHeaders.ACCEPT_LANGUAGE;
import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static com.google.common.net.HttpHeaders.USER_AGENT;
import static com.google.tsunami.common.data.NetworkEndpointUtils.toUriAuthority;
import static com.google.tsunami.common.data.NetworkServiceUtils.buildWebApplicationRootUrl;
import static com.google.tsunami.common.net.http.HttpRequest.get;
import static com.google.tsunami.common.net.http.HttpRequest.post;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.flogger.GoogleLogger;
import com.google.common.net.MediaType;
import com.google.protobuf.ByteString;
import com.google.protobuf.util.Timestamps;
import com.google.tsunami.common.data.NetworkServiceUtils;
import com.google.tsunami.common.net.http.HttpClient;
import com.google.tsunami.common.net.http.HttpHeaders;
import com.google.tsunami.common.net.http.HttpRequest;
import com.google.tsunami.common.net.http.HttpResponse;
import com.google.tsunami.common.net.http.HttpStatus;
import com.google.tsunami.common.time.UtcClock;
import com.google.tsunami.plugin.PluginType;
import com.google.tsunami.plugin.VulnDetector;
import com.google.tsunami.plugin.annotations.PluginInfo;
import com.google.tsunami.proto.DetectionReport;
import com.google.tsunami.proto.DetectionReportList;
import com.google.tsunami.proto.DetectionStatus;
import com.google.tsunami.proto.NetworkService;
import com.google.tsunami.proto.Severity;
import com.google.tsunami.proto.TargetInfo;
import com.google.tsunami.proto.Vulnerability;
import com.google.tsunami.proto.VulnerabilityId;
import java.io.IOException;
import java.time.Clock;
import java.time.Instant;
import java.util.Base64;
import java.util.UUID;
import javax.inject.Inject;
/** A {@link VulnDetector} that detects the CVE-2022-22947 vulnerability. */
@PluginInfo(
type = PluginType.VULN_DETECTION,
name = "CVE202122205VulnDetector",
version = "0.1",
description = Cve202222947VulnDetector.VULN_DESCRIPTION,
author = "hh-hunter",
bootstrapModule = Cve202222947DetectorBootstrapModule.class)
public final class Cve202222947VulnDetector implements VulnDetector {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
private static final String ROUTES = "actuator/gateway/routes/";
private static final String REFRESH = "actuator/gateway/refresh";
private static final String POST_DATA =
"kgfhvu9qnh3mr6eel97y6fq2hezzol8z"
+ "949d1u22cbffbrarjh182eig55721odj"
+ "949d1u22cbffbrarjh182eig55721odj"
+ "caf86f4uutaoxfysmf7anj01xl6sv3ps"
+ "JodHRwOi8vdGVzdC5jb20ifQ==";
@VisibleForTesting static final String CHECK_VULN_FLAG = "TSUNAMI_VULN_FLAG";
private static final String TSUNAMI_SCANNER_USER_AGENT = "TSUNAMI_SCANNER";
private static final String PLACEHOLDER = "ROUTER_TSUNAMI";
@VisibleForTesting
static final String VULN_DESCRIPTION =
"In spring cloud gateway versions prior to 3.1.1+ and 3.0.7+ , applications are vulnerable "
+ "to a code injection attack when the Gateway Actuator endpoint is enabled, exposed and "
+ "unsecured. A remote attacker could make a maliciously crafted request that could allow"
+ " arbitrary remote execution on the remote host.";
private final HttpClient httpClient;
private final Clock utcClock;
@Inject
Cve202222947VulnDetector(@UtcClock Clock utcClock, HttpClient httpClient) {
this.httpClient = checkNotNull(httpClient);
this.utcClock = checkNotNull(utcClock);
}
private static boolean isWebServiceOrUnknownService(NetworkService networkService) {
return networkService.getServiceName().isEmpty()
|| NetworkServiceUtils.isWebService(networkService)
|| NetworkServiceUtils.getServiceName(networkService).equals("unknown")
|| NetworkServiceUtils.getServiceName(networkService).equals("rtsp");
}
private static StringBuilder buildTarget(NetworkService networkService) {
StringBuilder targetUrlBuilder = new StringBuilder();
if (NetworkServiceUtils.isWebService(networkService)) {
targetUrlBuilder.append(buildWebApplicationRootUrl(networkService));
} else {
targetUrlBuilder
.append("http://")
.append(toUriAuthority(networkService.getNetworkEndpoint()))
.append("/");
}
return targetUrlBuilder;
}
@Override
public DetectionReportList detect(
TargetInfo targetInfo, ImmutableList<NetworkService> matchedServices) {
logger.atInfo().log("CVE-2921-22205 starts detecting.");
return DetectionReportList.newBuilder()
.addAllDetectionReports(
matchedServices.stream()
.filter(Cve202222947VulnDetector::isWebServiceOrUnknownService)
.filter(this::isServiceVulnerable)
.map(networkService -> buildDetectionReport(targetInfo, networkService))
.collect(toImmutableList()))
.build();
}
private String createRouter(NetworkService networkService) throws IOException {
String router = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
String url = buildTarget(networkService).append(ROUTES).append(router).toString();
String payload = new String(Base64.getDecoder().decode(POST_DATA)).replace(PLACEHOLDER, router);
HttpResponse httpResponse =
httpClient.send(
post(url)
.setHeaders(
HttpHeaders.builder()
.addHeader(CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
.addHeader(USER_AGENT, TSUNAMI_SCANNER_USER_AGENT)
.addHeader(ACCEPT_LANGUAGE, "en")
.addHeader(ACCEPT_ENCODING, "gzip, deflate")
.addHeader(ACCEPT, "*/*")
.build())
.setRequestBody(ByteString.copyFromUtf8(payload))
.build(),
networkService);
if (httpResponse.status().code() == HttpStatus.CREATED.code()) {
return router;
}
return "";
}
private void refresh(String url, NetworkService networkService) throws IOException {
httpClient.send(
post(url)
.setHeaders(
HttpHeaders.builder()
.addHeader(CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
.addHeader(USER_AGENT, TSUNAMI_SCANNER_USER_AGENT)
.build())
.build(),
networkService);
}
private boolean requestRoute(String url, NetworkService networkService) throws IOException {
HttpResponse httpResponse =
httpClient.send(
get(url)
.setHeaders(
HttpHeaders.builder()
.addHeader(CONTENT_TYPE, MediaType.FORM_DATA.toString())
.addHeader(USER_AGENT, TSUNAMI_SCANNER_USER_AGENT)
.build())
.build(),
networkService);
return httpResponse.status().code() == HttpStatus.OK.code()
&& httpResponse.bodyString().get().contains(CHECK_VULN_FLAG);
}
private void deleteRoutes(String url, NetworkService networkService) throws IOException {
httpClient.send(
HttpRequest.delete(url)
.setHeaders(
HttpHeaders.builder().addHeader(USER_AGENT, TSUNAMI_SCANNER_USER_AGENT).build())
.build(),
networkService);
}
private boolean isServiceVulnerable(NetworkService networkService) {
try {
String tmpRouter = createRouter(networkService);
if (tmpRouter.isEmpty()) {
return false;
}
refresh(buildTarget(networkService).append(REFRESH).toString(), networkService);
boolean requestRouteStatus =
requestRoute(
buildTarget(networkService).append(ROUTES).append(tmpRouter).toString(),
networkService);
deleteRoutes(
buildTarget(networkService).append(ROUTES).append(tmpRouter).toString(), networkService);
refresh(buildTarget(networkService).append(REFRESH).toString(), networkService);
return requestRouteStatus;
} catch (Exception e) {
logger.atWarning().withCause(e).log("Request to target %s failed", networkService);
return false;
}
}
private DetectionReport buildDetectionReport(
TargetInfo targetInfo, NetworkService vulnerableNetworkService) {
return DetectionReport.newBuilder()
.setTargetInfo(targetInfo)
.setNetworkService(vulnerableNetworkService)
.setDetectionTimestamp(Timestamps.fromMillis(Instant.now(utcClock).toEpochMilli()))
.setDetectionStatus(DetectionStatus.VULNERABILITY_VERIFIED)
.setVulnerability(
Vulnerability.newBuilder()
.setMainId(
VulnerabilityId.newBuilder()
.setPublisher("TSUNAMI_COMMUNITY")
.setValue("CVE_2022_22947"))
.setSeverity(Severity.CRITICAL)
.setTitle("CVE-2022-22947 Spring Cloud Gateway Actuator API SpEL Code Injection")
.setRecommendation(
"Users of affected versions should apply the following remediation. 3.1.x users"
+ " should upgrade to 3.1.1+. 3.0.x users should upgrade to 3.0.7+. If the"
+ " Gateway actuator endpoint is not needed it should be disabled via "
+ "management.endpoint.gateway.enabled: false. If the actuator is required"
+ " it should be secured using Spring Security, "
+ "see https://docs.spring.io/spring-boot/docs/current/reference/html/"
+ "actuator.html#actuator.endpoints.security.")
.setDescription(VULN_DESCRIPTION))
.build();
}
}
|
3e1cdb17f23664e61b4bf822ef2f0ca63985f7cb | 591 | java | Java | dimdwarf-core/src/main/java/net/orfjackal/dimdwarf/tasks/TaskScoped.java | luontola/dimdwarf | 5cde790c3bb98fc4a3c3aeee22d49f69ab78b285 | [
"Apache-2.0"
] | 3 | 2019-01-12T13:03:33.000Z | 2019-06-22T07:33:33.000Z | dimdwarf-core/src/main/java/net/orfjackal/dimdwarf/tasks/TaskScoped.java | luontola/dimdwarf | 5cde790c3bb98fc4a3c3aeee22d49f69ab78b285 | [
"Apache-2.0"
] | null | null | null | dimdwarf-core/src/main/java/net/orfjackal/dimdwarf/tasks/TaskScoped.java | luontola/dimdwarf | 5cde790c3bb98fc4a3c3aeee22d49f69ab78b285 | [
"Apache-2.0"
] | 4 | 2019-05-02T22:08:56.000Z | 2020-01-14T08:21:48.000Z | 28.142857 | 88 | 0.766497 | 12,243 | // Copyright © 2008-2010 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://dimdwarf.sourceforge.net/LICENSE
package net.orfjackal.dimdwarf.tasks;
import javax.inject.Scope;
import java.lang.annotation.*;
/**
* Indicates that an object needs to be task scoped. Each task will run in a transaction
* which is automatically committed when the task ends.
*
* @see net.orfjackal.dimdwarf.tasks.TaskExecutor
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Scope
public @interface TaskScoped {
}
|
3e1cdb2638101ce1d5c214b7f7f5c11068f31f68 | 354 | java | Java | SpringBootMongoDBDemo/src/test/java/com/springboot/mongodb/SpringBootMongoDbDemoApplicationTests.java | kuailexiaoyi/SpringbootLearning | 4f19c64ca2b338da4a17abcd719ecab8dd2e5500 | [
"Apache-2.0"
] | null | null | null | SpringBootMongoDBDemo/src/test/java/com/springboot/mongodb/SpringBootMongoDbDemoApplicationTests.java | kuailexiaoyi/SpringbootLearning | 4f19c64ca2b338da4a17abcd719ecab8dd2e5500 | [
"Apache-2.0"
] | null | null | null | SpringBootMongoDBDemo/src/test/java/com/springboot/mongodb/SpringBootMongoDbDemoApplicationTests.java | kuailexiaoyi/SpringbootLearning | 4f19c64ca2b338da4a17abcd719ecab8dd2e5500 | [
"Apache-2.0"
] | null | null | null | 20.823529 | 60 | 0.819209 | 12,244 | package com.springboot.mongodb;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootMongoDbDemoApplicationTests {
@Test
public void contextLoads() {
}
}
|
3e1cdb5f8e99cc0a87098a5c64d067c2f4fd10da | 12,505 | java | Java | src/net/zerobone/zerorobo/utils/Point.java | ZeroBone/ZeroRobo | 26acfdad28f68bb08142a84fa39cceae98b491a3 | [
"MIT"
] | null | null | null | src/net/zerobone/zerorobo/utils/Point.java | ZeroBone/ZeroRobo | 26acfdad28f68bb08142a84fa39cceae98b491a3 | [
"MIT"
] | null | null | null | src/net/zerobone/zerorobo/utils/Point.java | ZeroBone/ZeroRobo | 26acfdad28f68bb08142a84fa39cceae98b491a3 | [
"MIT"
] | null | null | null | 33.169761 | 120 | 0.605198 | 12,245 | package net.zerobone.zerorobo.utils;
/**
* An immutable vector in two dimensional space over doubles.
*
* The vector contains an x- and y-coordinate and provides various methods to operate on them.
* The output of the methods is chosen so that the results are easy to use in Robocode. Specifically this means that
* angles are measured from the ordinate axis in a clockwise manner and that angles returned may be negative. All angles
* are in degrees.
*
* @author Tobias Zimmermann (original)
* @author Billy Joe Franks (adaptation)
* @author Julian "Jules" Stieß (adaptation)
*/
public class Point {
/**
* The x coordinate of the vector. Guaranteed to be finite.
*/
private double x;
/**
* The y coordinate of the vector. Guaranteed to be finite.
*/
private double y;
/**
* Creates a new vector from given finite x and y coordinates.
*
* @param x The x coordinate of the newly constructed vector.
* @param y The y coordinate of the newly constructed vector.
*/
public Point(double x, double y) {
if (!Double.isFinite(x)) {
throw new IllegalArgumentException("The x-coordinate of vector must be a finite number.");
}
if (!Double.isFinite(y)) {
throw new IllegalArgumentException("The y-coordinate of vector must be a finite number.");
}
this.x = x;
this.y = y;
}
/**
* Constructs a new vector from its orientation and length.
*
* @param phi The orientation of the new vector, measured from the y-axis, in degrees.
* @param length The length of the new vector.
* @return The position vector for the given polar coordinates.
*/
public static Point fromPolarCoordinates(double phi, double length) {
phi = Math.toRadians(phi);
return new Point(Math.sin(phi) * length, Math.cos(phi) * length);
}
/**
* Returns the x coordinate of the vector. Guaranteed to be finite.
*
* @return The x coordinate of the vector.
*/
public double getX() {
return x;
}
/**
* Returns the y coordinate of the vector. Guaranteed to be finite.
*
* @return The y coordinate of the vector.
*/
public double getY() {
return y;
}
/**
* Returns a new vector with the given finite x coordinate
*
* @param newX The x coordinate of the new vector.
* @return The new vector
*/
public Point withX(double newX) {
if (!Double.isFinite(x)) {
throw new IllegalArgumentException("The x-coordinate of vector must be a finite number.");
}
return new Point(newX,y);
}
/**
* Returns a new vector with the given finite y coordinate.
*
* @param newY The y coordinate of the new vector.
* @return The new vector
*/
public Point withY(double newY) {
if (!Double.isFinite(y)) {
throw new IllegalArgumentException("The x-coordinate of vector must be a finite number.");
}
return new Point(x,newY);
}
/**
* Adds the given finite x and y values to this vector and stores the result in a new vector.
*
* @param x The finite value to add to the x-coordinate.
* @param y The finite value to add to the y-coordinate,
* @return The sum vector.
*/
public Point add(double x, double y) {
if (!Double.isFinite(x)) {
throw new IllegalArgumentException("The x-coordinate of vector must be a finite number.");
}
if (!Double.isFinite(y)) {
throw new IllegalArgumentException("The y-coordinate of vector must be a finite number.");
}
return new Point(this.x + x, this.y + y);
}
/**
* Adds the given vector to this vector by adding each coordinate and stores the result in a new vector.
*
* @param other The vector to add to this one.
* @return The sum vector.
*/
public Point add(Point other) {
return new Point(this.x + other.x, this.y + other.y);
}
/**
* Subtracts the given finite x and y values to this vector and stores the result in a new vector.
*
* @param x The finite value to subtract from the x-coordinate
* @param y The finite value to subtract from the y-coordinate
* @return The difference vector.
*/
public Point subtract(double x, double y) {
if (!Double.isFinite(x)) {
throw new IllegalArgumentException("The x-coordinate of vector must be a finite number.");
}
if (!Double.isFinite(y)) {
throw new IllegalArgumentException("The y-coordinate of vector must be a finite number.");
}
return new Point(this.x - x, this.y - y);
}
/**
* Subtracts the given vector from this one by subtracting each coordinate and stores the result in a new vector.
*
* @param other The vector to subtract from this one.
* @return The difference vector.
*/
public Point subtract(Point other) {
return new Point(this.x - other.x, this.y - other.y);
}
/**
* Multiplies the vector by a given finite scalar and stores the result in a new vector.
*
* @param scalar The finite scalar by which to multiply.
* @return The result vector.
*/
public Point multiply(double scalar) {
return new Point(x * scalar, y * scalar);
}
/**
* Returns the length of the vector.
*
* @return The length of the vector.
*/
public double length() {
return Math.sqrt(x * x + y * y);
}
/**
* Returns the square of the length of the vector.
*
* This method is provided for performance and precision reasons. The length is calculated with the Pythagorean
* theorem, which means a square root is used, which costs both CPU time and potentially precision, if the result
* cannot be represented exactly.
*
* @return The square of the length of the vector.
*/
public double lengthSquared() {
return x * x + y * y;
}
/**
* Normalizes the vector to length one and returns the result as a new vector.
*
* @return The normalized vector.
*/
public Point normalize() {
double len = length();
if (len == 0) {
throw new IllegalStateException("Cannot normalize a null vector.");
}
return multiply(1 / len);
}
/**
* Returns a new vector with the same orientation as this one and the specified length.
*
* @param desiredLength The length the vector should have.
* @return The vector with the desired length.
*/
public Point withLength(double desiredLength) {
double len = length();
if (len == 0) {
if (desiredLength == 0) {
return this;
}
throw new IllegalStateException("Cannot create a null vector of non-zero length.");
}
return multiply(desiredLength / len);
}
/**
* Returns the angle between the y-axis and this vector in degrees.
*
* The angle is measured in the range from -Pi to Pi.
*
* @return The angle between the y-axis and this vector in degrees.
*/
@SuppressWarnings("SuspiciousNameCombination")
public double angle() {
return Math.toDegrees(Math.atan2(x, y));
}
/**
* Returns the angle between this vector and the one specified by the given coordinates in degrees.
*
* The angle is measured in the range from -Pi to Pi.
*
* @param x The x-coordinate of the vector to which to measure the angle to.
* @param y The y-coordinate of the vector to which to measure the angle to.
* @return The angle between the vectors in degrees.
*/
public double angleFrom(double x, double y) {
return Math.toDegrees(Math.atan2(this.x - x, this.y - y));
}
/**
* Returns the ange between this vector and the one given as a parameter measured in degrees.
*
* The angle is measured in the range from -Pi to Pi. Returns {@code NaN} if the given vector is {@code null}.
*
* @param other The vector to which to measure the angle to.
* @return The angle between the vectors in degrees.
*/
public double angleFrom(Point other) {
if (other == null) {
return Double.NaN;
}
return Math.toDegrees(Math.atan2(x - other.x, y - other.y));
}
/**
* Returns the dot product between this vector and the one given as a parameter.
*
* @param other The other vector in the dot product.
* @return The dot product in double precision.
*/
public double dotProduct(Point other) {
return x * other.x + y * other.y;
}
/**
* Checks if this vector and the given vector point in either the same or exact opposite directions.
*
* @param other The vector to check this vector against.
* @return {@code true} if this vector and the given vector point in the same or opposite directions.
*/
public boolean isSameDirectionAs(Point other) {
if (other == null) {
return false;
}
if (other.x == 0) {
return x == 0 && (y == 0 && other.y == 0 || y != 0 && other.y != 0);
} else if (x == 0) {
return false;
} else {
double xFactor = x / other.x;
return Double.compare(y, other.y * xFactor) == 0;
}
}
/**
* Checks if this vector and the given vector point in the exact same direction and have the same heading.
*
* @param other The vector to check this vector against.
* @return {@code true} if this vector and the given vector have the same direction and heading.
*/
public boolean isSameDirectionAndHeadingAs(Point other) {
if (other == null) {
return false;
}
if (other.x == 0) {
return x == 0 && Math.signum(y) == Math.signum(other.y);
} else if (x == 0) {
return false;
} else {
double xFactor = x / other.x;
return Double.compare(y, other.y * xFactor) == 0 && Math.signum(x) == Math.signum(other.x);
}
}
/**
* Returns the distance between this vector and the given one.
*
* @param other the vector to calculate the distance to
* @return the distance between this vector and the given one
*/
public double distance(Point other) {
double xDiff = x - other.x;
double yDiff = y - other.y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
/**
* Returns the square of the distance between this vector and the given one.
*
* This method is provided for performance and precision reasons. The length is calculated with the Pythagorean
* theorem, which means a square root is used, which costs both CPU time and potentially precision, if the result
* cannot be represented exactly.
*
* @param other the vector to calculate the distance to
* @return the square of the distance between this vector and the given one
*/
public double distanceSq(Point other) {
double xDiff = x - other.x;
double yDiff = y - other.y;
return xDiff * xDiff + yDiff * yDiff;
}
/**
* Tests this vector of equality to the given vector.
*
* Vectors are equal if and only if both the x- and the y-coordinate are equal. To account for double imprecision,
* the numbers are compared with {@link Double#compare(double, double)} which allows slight differences.
* Returns {@code false} if the other vector is {@code null}.
* If the other object is not a vector, returns {@code false}.
*
* @param other The vector to compare this vector to.
* @return {@code true} if this vector and the other are equal.
*/
@Override
public boolean equals(Object other) {
if (other == null || !(other instanceof Point)) {
return false;
}
Point vec = (Point)other;
return Double.compare(x, vec.x) == 0 && Double.compare(y, vec.y) == 0;
}
/**
* Returns a string representation of this vector.
*
* @return A string representation of this vector.
*/
@Override
public String toString() {
return "<" + x + ", " + y + '>';
}
} |
3e1cdbef79029ea3e7c0a14d8205f9f5419a5293 | 3,299 | java | Java | jt-jiffle/jt-jiffle-language/src/main/java/it/geosolutions/jaiext/jiffle/parser/CompilerMessage.java | sikeoka/jai-ext | 8d2ab594dc3295c5c6eabb7da3568f734521bf2d | [
"Apache-2.0"
] | 77 | 2015-04-23T15:22:20.000Z | 2022-03-29T08:06:17.000Z | jt-jiffle/jt-jiffle-language/src/main/java/it/geosolutions/jaiext/jiffle/parser/CompilerMessage.java | sikeoka/jai-ext | 8d2ab594dc3295c5c6eabb7da3568f734521bf2d | [
"Apache-2.0"
] | 157 | 2015-03-10T08:37:01.000Z | 2022-03-28T07:51:51.000Z | jt-jiffle/jt-jiffle-language/src/main/java/it/geosolutions/jaiext/jiffle/parser/CompilerMessage.java | sikeoka/jai-ext | 8d2ab594dc3295c5c6eabb7da3568f734521bf2d | [
"Apache-2.0"
] | 39 | 2015-04-14T00:34:36.000Z | 2021-11-11T19:28:24.000Z | 36.252747 | 85 | 0.690815 | 12,246 | /* JAI-Ext - OpenSource Java Advanced Image Extensions Library
* http://www.geo-solutions.it/
* Copyright 2018 GeoSolutions
*
* 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.
*/
/*
* Copyright (c) 2013, Michael Bedward. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package it.geosolutions.jaiext.jiffle.parser;
import org.antlr.v4.runtime.Token;
import java.util.Objects;
/**
* A message relating to a position in an input script.
*
* @author michael
*/
public class CompilerMessage extends Message {
final private int line;
final private int pos;
public CompilerMessage(Level level, Token tok, String msg) {
this(level, tok.getLine(), tok.getCharPositionInLine() + 1, msg);
}
public CompilerMessage(Level level, int line, int charPos, String msg) {
super(level, msg);
this.line = line;
this.pos = charPos;
}
@Override
public String toString() {
return String.format("%d:%d %s : %s", line, pos, level, msg);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
CompilerMessage that = (CompilerMessage) o;
return line == that.line &&
pos == that.pos;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), line, pos);
}
}
|
3e1cdd5c7e14b367dca9b04f9ce3e52d24b1d1f9 | 219 | java | Java | enderio-base/src/main/java/crazypants/enderio/api/farm/package-info.java | hypherionmc/EnderIO | 70552e7deb1dedb9131495550fba3c05aa84526b | [
"Unlicense"
] | 721 | 2015-03-19T08:49:00.000Z | 2022-03-26T19:24:19.000Z | enderio-base/src/main/java/crazypants/enderio/api/farm/package-info.java | hypherionmc/EnderIO | 70552e7deb1dedb9131495550fba3c05aa84526b | [
"Unlicense"
] | 3,428 | 2015-03-17T10:13:37.000Z | 2022-03-29T17:55:38.000Z | enderio-base/src/main/java/crazypants/enderio/api/farm/package-info.java | hypherionmc/EnderIO | 70552e7deb1dedb9131495550fba3c05aa84526b | [
"Unlicense"
] | 569 | 2015-03-19T10:12:54.000Z | 2022-03-27T01:08:00.000Z | 36.5 | 91 | 0.803653 | 12,247 | @API(apiVersion = EnderIOAPIProps.VERSION, owner = "enderio", provides = "enderioapi|farm")
package crazypants.enderio.api.farm;
import crazypants.enderio.api.EnderIOAPIProps;
import net.minecraftforge.fml.common.API;
|
3e1cdde7c9b5c3e8bfb399778b93ad201e46f229 | 585 | java | Java | src/main/java/com/qf/service/Impl/CityServiceImpl.java | YaaaaaaaanG/car-rental | 74cae20785b07ef2bd38e5f1674349777a57008c | [
"MulanPSL-1.0"
] | null | null | null | src/main/java/com/qf/service/Impl/CityServiceImpl.java | YaaaaaaaanG/car-rental | 74cae20785b07ef2bd38e5f1674349777a57008c | [
"MulanPSL-1.0"
] | null | null | null | src/main/java/com/qf/service/Impl/CityServiceImpl.java | YaaaaaaaanG/car-rental | 74cae20785b07ef2bd38e5f1674349777a57008c | [
"MulanPSL-1.0"
] | null | null | null | 21.666667 | 62 | 0.74188 | 12,248 | package com.qf.service.Impl;
import com.qf.dao.CityMapper;
import com.qf.pojo.City;
import com.qf.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CityServiceImpl implements CityService {
@Autowired
CityMapper cityMapper;
@Override
public List<City> selectAllCity(Integer pid) {
return cityMapper.selectAllCity(pid);
}
@Override
public City selectById(Integer id) {
return cityMapper.selectById(id);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.