hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
18d6105adce296a1e03ca675b8341d3000ae324a
2,943
/** * Copyright (c) 2019-2030 panguBpm All rights reserved. * <p> * http://www.pangubpm.com/ * <p> * (盘古BPM工作流平台) */ package com.pangubpm.bpm.dmn.feel.impl.juel.el; import java.math.BigDecimal; import java.math.BigInteger; import javax.el.ELException; import com.pangubpm.bpm.dmn.feel.impl.juel.FeelEngineLogger; import com.pangubpm.bpm.dmn.feel.impl.juel.FeelLogger; import de.odysseus.el.misc.TypeConverterImpl; public class FeelTypeConverter extends TypeConverterImpl { public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; @Override protected Boolean coerceToBoolean(Object value) { if (value instanceof Boolean) { return (Boolean) value; } else { throw LOG.unableToConvertValue(value, Boolean.class); } } @Override protected BigDecimal coerceToBigDecimal(Object value) { if (value instanceof BigDecimal) { return (BigDecimal)value; } else if (value instanceof BigInteger) { return new BigDecimal((BigInteger)value); } else if (value instanceof Number) { return new BigDecimal(((Number)value).doubleValue()); } else { throw LOG.unableToConvertValue(value, BigDecimal.class); } } @Override protected BigInteger coerceToBigInteger(Object value) { if (value instanceof BigInteger) { return (BigInteger)value; } else if (value instanceof BigDecimal) { return ((BigDecimal)value).toBigInteger(); } else if (value instanceof Number) { return BigInteger.valueOf(((Number)value).longValue()); } else { throw LOG.unableToConvertValue(value, BigInteger.class); } } @Override protected Double coerceToDouble(Object value) { if (value instanceof Double) { return (Double)value; } else if (value instanceof Number) { return ((Number) value).doubleValue(); } else { throw LOG.unableToConvertValue(value, Double.class); } } @Override protected Long coerceToLong(Object value) { if (value instanceof Long) { return (Long)value; } else if (value instanceof Number && isLong((Number) value)) { return ((Number) value).longValue(); } else { throw LOG.unableToConvertValue(value, Long.class); } } @Override protected String coerceToString(Object value) { if (value instanceof String) { return (String)value; } else if (value instanceof Enum<?>) { return ((Enum<?>)value).name(); } else { throw LOG.unableToConvertValue(value, String.class); } } @Override public <T> T convert(Object value, Class<T> type) throws ELException { try { return super.convert(value, type); } catch (ELException e) { throw LOG.unableToConvertValue(value, type, e); } } protected boolean isLong(Number value) { double doubleValue = value.doubleValue(); return doubleValue == (long) doubleValue; } }
24.525
72
0.665987
4e483c514af9ed8759be867fe5e8fb2398a616ea
6,923
/* * Copyright 2019 The Simple File Server 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.sfs.io; import io.vertx.core.Handler; import io.vertx.core.buffer.Buffer; import io.vertx.core.file.AsyncFile; import io.vertx.core.http.HttpClientResponse; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.core.streams.ReadStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; public interface EndableReadStream<T> extends ReadStream<T> { static EndableReadStream<Buffer> from(AsyncFile asyncFile) { AtomicBoolean ended = new AtomicBoolean(false); AtomicReference<Handler<Void>> handlerRef = new AtomicReference<>(null); asyncFile.endHandler(event -> { ended.set(true); Handler<Void> h = handlerRef.get(); if (h != null) { handlerRef.set(null); h.handle(null); } }); return new EndableReadStream<Buffer>() { @Override public boolean isEnded() { return ended.get(); } @Override public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) { asyncFile.exceptionHandler(handler); return this; } @Override public ReadStream<Buffer> handler(Handler<Buffer> handler) { asyncFile.handler(handler); return this; } @Override public ReadStream<Buffer> pause() { asyncFile.pause(); return this; } @Override public ReadStream<Buffer> resume() { asyncFile.resume(); return this; } @Override public ReadStream<Buffer> fetch(long amount) { asyncFile.fetch(amount); return this; } @Override public ReadStream<Buffer> endHandler(Handler<Void> endHandler) { if (ended.get()) { if (endHandler != null) { endHandler.handle(null); } } else { handlerRef.set(endHandler); } return this; } }; } static EndableReadStream<Buffer> from(HttpClientResponse httpClientResponse) { AtomicBoolean ended = new AtomicBoolean(false); AtomicReference<Handler<Void>> handlerRef = new AtomicReference<>(null); httpClientResponse.endHandler(event -> { ended.set(true); Handler<Void> h = handlerRef.get(); if (h != null) { handlerRef.set(null); h.handle(null); } }); return new EndableReadStream<Buffer>() { @Override public boolean isEnded() { return ended.get(); } @Override public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) { httpClientResponse.exceptionHandler(handler); return this; } @Override public ReadStream<Buffer> handler(Handler<Buffer> handler) { httpClientResponse.handler(handler); return this; } @Override public ReadStream<Buffer> pause() { httpClientResponse.pause(); return this; } @Override public ReadStream<Buffer> resume() { httpClientResponse.resume(); return this; } @Override public ReadStream<Buffer> fetch(long amount) { httpClientResponse.fetch(amount); return this; } @Override public ReadStream<Buffer> endHandler(Handler<Void> endHandler) { if (ended.get()) { if (endHandler != null) { endHandler.handle(null); } } else { handlerRef.set(endHandler); } return this; } }; } static EndableReadStream<Buffer> from(HttpServerRequest httpServerRequest) { return new EndableReadStream<Buffer>() { private final Logger LOGGER = LoggerFactory.getLogger(EndableReadStream.class); @Override public boolean isEnded() { return httpServerRequest.isEnded(); } @Override public EndableReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) { httpServerRequest.exceptionHandler(handler); return this; } @Override public EndableReadStream<Buffer> handler(Handler<Buffer> handler) { httpServerRequest.handler(handler); return this; } @Override public EndableReadStream<Buffer> pause() { httpServerRequest.pause(); return this; } @Override public EndableReadStream<Buffer> resume() { httpServerRequest.resume(); return this; } @Override public EndableReadStream<Buffer> fetch(long amount) { httpServerRequest.fetch(amount); return this; } @Override public EndableReadStream<Buffer> endHandler(Handler<Void> endHandler) { httpServerRequest.endHandler(new Handler<Void>() { @Override public void handle(Void event) { LOGGER.debug("End Handler Called {}", httpServerRequest.absoluteURI()); if (endHandler != null) { LOGGER.debug("Handling end {} {}", httpServerRequest.absoluteURI(), endHandler); endHandler.handle(null); } } }); return this; } }; } boolean isEnded(); }
30.632743
108
0.530261
4f27c2251a225195cbb5d8f9dc48c7dc0bb04699
294
package cn.org.atool.fluent.processor.mybatis.base; import javax.annotation.processing.Messager; /** * 编译器相关类 * * @author darui.wu */ @SuppressWarnings({"unused"}) public interface IProcessor { /** * 返回Messager * * @return Messager */ Messager getMessager(); }
16.333333
51
0.64966
b59d9f84c83a79875f2a74349bc01d3bb0e40f19
28,483
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan.video; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * <h3>Layout</h3> * * <pre><code> * struct StdVideoH264SpsVuiFlags { * uint32_t aspect_ratio_info_present_flag : 1; * uint32_t overscan_info_present_flag : 1; * uint32_t overscan_appropriate_flag : 1; * uint32_t video_signal_type_present_flag : 1; * uint32_t video_full_range_flag : 1; * uint32_t color_description_present_flag : 1; * uint32_t chroma_loc_info_present_flag : 1; * uint32_t timing_info_present_flag : 1; * uint32_t fixed_frame_rate_flag : 1; * uint32_t bitstream_restriction_flag : 1; * uint32_t nal_hrd_parameters_present_flag : 1; * uint32_t vcl_hrd_parameters_present_flag : 1; * }</code></pre> */ public class StdVideoH264SpsVuiFlags extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; /** The struct alignment in bytes. */ public static final int ALIGNOF; /** The struct member offsets. */ public static final int BITFIELD0; static { Layout layout = __struct( __member(4) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); BITFIELD0 = layout.offsetof(0); } /** * Creates a {@code StdVideoH264SpsVuiFlags} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public StdVideoH264SpsVuiFlags(ByteBuffer container) { super(memAddress(container), __checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** @return the value of the {@code aspect_ratio_info_present_flag} field. */ @NativeType("uint32_t") public boolean aspect_ratio_info_present_flag() { return naspect_ratio_info_present_flag(address()) != 0; } /** @return the value of the {@code overscan_info_present_flag} field. */ @NativeType("uint32_t") public boolean overscan_info_present_flag() { return noverscan_info_present_flag(address()) != 0; } /** @return the value of the {@code overscan_appropriate_flag} field. */ @NativeType("uint32_t") public boolean overscan_appropriate_flag() { return noverscan_appropriate_flag(address()) != 0; } /** @return the value of the {@code video_signal_type_present_flag} field. */ @NativeType("uint32_t") public boolean video_signal_type_present_flag() { return nvideo_signal_type_present_flag(address()) != 0; } /** @return the value of the {@code video_full_range_flag} field. */ @NativeType("uint32_t") public boolean video_full_range_flag() { return nvideo_full_range_flag(address()) != 0; } /** @return the value of the {@code color_description_present_flag} field. */ @NativeType("uint32_t") public boolean color_description_present_flag() { return ncolor_description_present_flag(address()) != 0; } /** @return the value of the {@code chroma_loc_info_present_flag} field. */ @NativeType("uint32_t") public boolean chroma_loc_info_present_flag() { return nchroma_loc_info_present_flag(address()) != 0; } /** @return the value of the {@code timing_info_present_flag} field. */ @NativeType("uint32_t") public boolean timing_info_present_flag() { return ntiming_info_present_flag(address()) != 0; } /** @return the value of the {@code fixed_frame_rate_flag} field. */ @NativeType("uint32_t") public boolean fixed_frame_rate_flag() { return nfixed_frame_rate_flag(address()) != 0; } /** @return the value of the {@code bitstream_restriction_flag} field. */ @NativeType("uint32_t") public boolean bitstream_restriction_flag() { return nbitstream_restriction_flag(address()) != 0; } /** @return the value of the {@code nal_hrd_parameters_present_flag} field. */ @NativeType("uint32_t") public boolean nal_hrd_parameters_present_flag() { return nnal_hrd_parameters_present_flag(address()) != 0; } /** @return the value of the {@code vcl_hrd_parameters_present_flag} field. */ @NativeType("uint32_t") public boolean vcl_hrd_parameters_present_flag() { return nvcl_hrd_parameters_present_flag(address()) != 0; } /** Sets the specified value to the {@code aspect_ratio_info_present_flag} field. */ public StdVideoH264SpsVuiFlags aspect_ratio_info_present_flag(@NativeType("uint32_t") boolean value) { naspect_ratio_info_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code overscan_info_present_flag} field. */ public StdVideoH264SpsVuiFlags overscan_info_present_flag(@NativeType("uint32_t") boolean value) { noverscan_info_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code overscan_appropriate_flag} field. */ public StdVideoH264SpsVuiFlags overscan_appropriate_flag(@NativeType("uint32_t") boolean value) { noverscan_appropriate_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code video_signal_type_present_flag} field. */ public StdVideoH264SpsVuiFlags video_signal_type_present_flag(@NativeType("uint32_t") boolean value) { nvideo_signal_type_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code video_full_range_flag} field. */ public StdVideoH264SpsVuiFlags video_full_range_flag(@NativeType("uint32_t") boolean value) { nvideo_full_range_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code color_description_present_flag} field. */ public StdVideoH264SpsVuiFlags color_description_present_flag(@NativeType("uint32_t") boolean value) { ncolor_description_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code chroma_loc_info_present_flag} field. */ public StdVideoH264SpsVuiFlags chroma_loc_info_present_flag(@NativeType("uint32_t") boolean value) { nchroma_loc_info_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code timing_info_present_flag} field. */ public StdVideoH264SpsVuiFlags timing_info_present_flag(@NativeType("uint32_t") boolean value) { ntiming_info_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code fixed_frame_rate_flag} field. */ public StdVideoH264SpsVuiFlags fixed_frame_rate_flag(@NativeType("uint32_t") boolean value) { nfixed_frame_rate_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code bitstream_restriction_flag} field. */ public StdVideoH264SpsVuiFlags bitstream_restriction_flag(@NativeType("uint32_t") boolean value) { nbitstream_restriction_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code nal_hrd_parameters_present_flag} field. */ public StdVideoH264SpsVuiFlags nal_hrd_parameters_present_flag(@NativeType("uint32_t") boolean value) { nnal_hrd_parameters_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code vcl_hrd_parameters_present_flag} field. */ public StdVideoH264SpsVuiFlags vcl_hrd_parameters_present_flag(@NativeType("uint32_t") boolean value) { nvcl_hrd_parameters_present_flag(address(), value ? 1 : 0); return this; } /** Initializes this struct with the specified values. */ public StdVideoH264SpsVuiFlags set( boolean aspect_ratio_info_present_flag, boolean overscan_info_present_flag, boolean overscan_appropriate_flag, boolean video_signal_type_present_flag, boolean video_full_range_flag, boolean color_description_present_flag, boolean chroma_loc_info_present_flag, boolean timing_info_present_flag, boolean fixed_frame_rate_flag, boolean bitstream_restriction_flag, boolean nal_hrd_parameters_present_flag, boolean vcl_hrd_parameters_present_flag ) { aspect_ratio_info_present_flag(aspect_ratio_info_present_flag); overscan_info_present_flag(overscan_info_present_flag); overscan_appropriate_flag(overscan_appropriate_flag); video_signal_type_present_flag(video_signal_type_present_flag); video_full_range_flag(video_full_range_flag); color_description_present_flag(color_description_present_flag); chroma_loc_info_present_flag(chroma_loc_info_present_flag); timing_info_present_flag(timing_info_present_flag); fixed_frame_rate_flag(fixed_frame_rate_flag); bitstream_restriction_flag(bitstream_restriction_flag); nal_hrd_parameters_present_flag(nal_hrd_parameters_present_flag); vcl_hrd_parameters_present_flag(vcl_hrd_parameters_present_flag); return this; } /** * Copies the specified struct data to this struct. * * @param src the source struct * * @return this struct */ public StdVideoH264SpsVuiFlags set(StdVideoH264SpsVuiFlags src) { memCopy(src.address(), address(), SIZEOF); return this; } // ----------------------------------- /** Returns a new {@code StdVideoH264SpsVuiFlags} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static StdVideoH264SpsVuiFlags malloc() { return wrap(StdVideoH264SpsVuiFlags.class, nmemAllocChecked(SIZEOF)); } /** Returns a new {@code StdVideoH264SpsVuiFlags} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static StdVideoH264SpsVuiFlags calloc() { return wrap(StdVideoH264SpsVuiFlags.class, nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@code StdVideoH264SpsVuiFlags} instance allocated with {@link BufferUtils}. */ public static StdVideoH264SpsVuiFlags create() { ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF); return wrap(StdVideoH264SpsVuiFlags.class, memAddress(container), container); } /** Returns a new {@code StdVideoH264SpsVuiFlags} instance for the specified memory address. */ public static StdVideoH264SpsVuiFlags create(long address) { return wrap(StdVideoH264SpsVuiFlags.class, address); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static StdVideoH264SpsVuiFlags createSafe(long address) { return address == NULL ? null : wrap(StdVideoH264SpsVuiFlags.class, address); } /** * Returns a new {@link StdVideoH264SpsVuiFlags.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static StdVideoH264SpsVuiFlags.Buffer malloc(int capacity) { return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity); } /** * Returns a new {@link StdVideoH264SpsVuiFlags.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static StdVideoH264SpsVuiFlags.Buffer calloc(int capacity) { return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link StdVideoH264SpsVuiFlags.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static StdVideoH264SpsVuiFlags.Buffer create(int capacity) { ByteBuffer container = __create(capacity, SIZEOF); return wrap(Buffer.class, memAddress(container), capacity, container); } /** * Create a {@link StdVideoH264SpsVuiFlags.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static StdVideoH264SpsVuiFlags.Buffer create(long address, int capacity) { return wrap(Buffer.class, address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static StdVideoH264SpsVuiFlags.Buffer createSafe(long address, int capacity) { return address == NULL ? null : wrap(Buffer.class, address, capacity); } /** * Returns a new {@code StdVideoH264SpsVuiFlags} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static StdVideoH264SpsVuiFlags malloc(MemoryStack stack) { return wrap(StdVideoH264SpsVuiFlags.class, stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@code StdVideoH264SpsVuiFlags} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static StdVideoH264SpsVuiFlags calloc(MemoryStack stack) { return wrap(StdVideoH264SpsVuiFlags.class, stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link StdVideoH264SpsVuiFlags.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static StdVideoH264SpsVuiFlags.Buffer malloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link StdVideoH264SpsVuiFlags.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static StdVideoH264SpsVuiFlags.Buffer calloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- public static int nbitfield0(long struct) { return UNSAFE.getInt(null, struct + StdVideoH264SpsVuiFlags.BITFIELD0); } /** Unsafe version of {@link #aspect_ratio_info_present_flag}. */ public static int naspect_ratio_info_present_flag(long struct) { return nbitfield0(struct) & 0x00_00_00_01; } /** Unsafe version of {@link #overscan_info_present_flag}. */ public static int noverscan_info_present_flag(long struct) { return (nbitfield0(struct) & 0x00_00_00_02) >>> 1; } /** Unsafe version of {@link #overscan_appropriate_flag}. */ public static int noverscan_appropriate_flag(long struct) { return (nbitfield0(struct) & 0x00_00_00_04) >>> 2; } /** Unsafe version of {@link #video_signal_type_present_flag}. */ public static int nvideo_signal_type_present_flag(long struct) { return (nbitfield0(struct) & 0x00_00_00_08) >>> 3; } /** Unsafe version of {@link #video_full_range_flag}. */ public static int nvideo_full_range_flag(long struct) { return (nbitfield0(struct) & 0x00_00_00_10) >>> 4; } /** Unsafe version of {@link #color_description_present_flag}. */ public static int ncolor_description_present_flag(long struct) { return (nbitfield0(struct) & 0x00_00_00_20) >>> 5; } /** Unsafe version of {@link #chroma_loc_info_present_flag}. */ public static int nchroma_loc_info_present_flag(long struct) { return (nbitfield0(struct) & 0x00_00_00_40) >>> 6; } /** Unsafe version of {@link #timing_info_present_flag}. */ public static int ntiming_info_present_flag(long struct) { return (nbitfield0(struct) & 0x00_00_00_80) >>> 7; } /** Unsafe version of {@link #fixed_frame_rate_flag}. */ public static int nfixed_frame_rate_flag(long struct) { return (nbitfield0(struct) & 0x00_00_01_00) >>> 8; } /** Unsafe version of {@link #bitstream_restriction_flag}. */ public static int nbitstream_restriction_flag(long struct) { return (nbitfield0(struct) & 0x00_00_02_00) >>> 9; } /** Unsafe version of {@link #nal_hrd_parameters_present_flag}. */ public static int nnal_hrd_parameters_present_flag(long struct) { return (nbitfield0(struct) & 0x00_00_04_00) >>> 10; } /** Unsafe version of {@link #vcl_hrd_parameters_present_flag}. */ public static int nvcl_hrd_parameters_present_flag(long struct) { return (nbitfield0(struct) & 0x00_00_08_00) >>> 11; } public static void nbitfield0(long struct, int value) { UNSAFE.putInt(null, struct + StdVideoH264SpsVuiFlags.BITFIELD0, value); } /** Unsafe version of {@link #aspect_ratio_info_present_flag(boolean) aspect_ratio_info_present_flag}. */ public static void naspect_ratio_info_present_flag(long struct, int value) { nbitfield0(struct, (nbitfield0(struct) & 0xFF_FF_FF_FE) | (value & 0x00_00_00_01)); } /** Unsafe version of {@link #overscan_info_present_flag(boolean) overscan_info_present_flag}. */ public static void noverscan_info_present_flag(long struct, int value) { nbitfield0(struct, ((value << 1) & 0x00_00_00_02) | (nbitfield0(struct) & 0xFF_FF_FF_FD)); } /** Unsafe version of {@link #overscan_appropriate_flag(boolean) overscan_appropriate_flag}. */ public static void noverscan_appropriate_flag(long struct, int value) { nbitfield0(struct, ((value << 2) & 0x00_00_00_04) | (nbitfield0(struct) & 0xFF_FF_FF_FB)); } /** Unsafe version of {@link #video_signal_type_present_flag(boolean) video_signal_type_present_flag}. */ public static void nvideo_signal_type_present_flag(long struct, int value) { nbitfield0(struct, ((value << 3) & 0x00_00_00_08) | (nbitfield0(struct) & 0xFF_FF_FF_F7)); } /** Unsafe version of {@link #video_full_range_flag(boolean) video_full_range_flag}. */ public static void nvideo_full_range_flag(long struct, int value) { nbitfield0(struct, ((value << 4) & 0x00_00_00_10) | (nbitfield0(struct) & 0xFF_FF_FF_EF)); } /** Unsafe version of {@link #color_description_present_flag(boolean) color_description_present_flag}. */ public static void ncolor_description_present_flag(long struct, int value) { nbitfield0(struct, ((value << 5) & 0x00_00_00_20) | (nbitfield0(struct) & 0xFF_FF_FF_DF)); } /** Unsafe version of {@link #chroma_loc_info_present_flag(boolean) chroma_loc_info_present_flag}. */ public static void nchroma_loc_info_present_flag(long struct, int value) { nbitfield0(struct, ((value << 6) & 0x00_00_00_40) | (nbitfield0(struct) & 0xFF_FF_FF_BF)); } /** Unsafe version of {@link #timing_info_present_flag(boolean) timing_info_present_flag}. */ public static void ntiming_info_present_flag(long struct, int value) { nbitfield0(struct, ((value << 7) & 0x00_00_00_80) | (nbitfield0(struct) & 0xFF_FF_FF_7F)); } /** Unsafe version of {@link #fixed_frame_rate_flag(boolean) fixed_frame_rate_flag}. */ public static void nfixed_frame_rate_flag(long struct, int value) { nbitfield0(struct, ((value << 8) & 0x00_00_01_00) | (nbitfield0(struct) & 0xFF_FF_FE_FF)); } /** Unsafe version of {@link #bitstream_restriction_flag(boolean) bitstream_restriction_flag}. */ public static void nbitstream_restriction_flag(long struct, int value) { nbitfield0(struct, ((value << 9) & 0x00_00_02_00) | (nbitfield0(struct) & 0xFF_FF_FD_FF)); } /** Unsafe version of {@link #nal_hrd_parameters_present_flag(boolean) nal_hrd_parameters_present_flag}. */ public static void nnal_hrd_parameters_present_flag(long struct, int value) { nbitfield0(struct, ((value << 10) & 0x00_00_04_00) | (nbitfield0(struct) & 0xFF_FF_FB_FF)); } /** Unsafe version of {@link #vcl_hrd_parameters_present_flag(boolean) vcl_hrd_parameters_present_flag}. */ public static void nvcl_hrd_parameters_present_flag(long struct, int value) { nbitfield0(struct, ((value << 11) & 0x00_00_08_00) | (nbitfield0(struct) & 0xFF_FF_F7_FF)); } // ----------------------------------- /** An array of {@link StdVideoH264SpsVuiFlags} structs. */ public static class Buffer extends StructBuffer<StdVideoH264SpsVuiFlags, Buffer> implements NativeResource { private static final StdVideoH264SpsVuiFlags ELEMENT_FACTORY = StdVideoH264SpsVuiFlags.create(-1L); /** * Creates a new {@code StdVideoH264SpsVuiFlags.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link StdVideoH264SpsVuiFlags#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected StdVideoH264SpsVuiFlags getElementFactory() { return ELEMENT_FACTORY; } /** @return the value of the {@code aspect_ratio_info_present_flag} field. */ @NativeType("uint32_t") public boolean aspect_ratio_info_present_flag() { return StdVideoH264SpsVuiFlags.naspect_ratio_info_present_flag(address()) != 0; } /** @return the value of the {@code overscan_info_present_flag} field. */ @NativeType("uint32_t") public boolean overscan_info_present_flag() { return StdVideoH264SpsVuiFlags.noverscan_info_present_flag(address()) != 0; } /** @return the value of the {@code overscan_appropriate_flag} field. */ @NativeType("uint32_t") public boolean overscan_appropriate_flag() { return StdVideoH264SpsVuiFlags.noverscan_appropriate_flag(address()) != 0; } /** @return the value of the {@code video_signal_type_present_flag} field. */ @NativeType("uint32_t") public boolean video_signal_type_present_flag() { return StdVideoH264SpsVuiFlags.nvideo_signal_type_present_flag(address()) != 0; } /** @return the value of the {@code video_full_range_flag} field. */ @NativeType("uint32_t") public boolean video_full_range_flag() { return StdVideoH264SpsVuiFlags.nvideo_full_range_flag(address()) != 0; } /** @return the value of the {@code color_description_present_flag} field. */ @NativeType("uint32_t") public boolean color_description_present_flag() { return StdVideoH264SpsVuiFlags.ncolor_description_present_flag(address()) != 0; } /** @return the value of the {@code chroma_loc_info_present_flag} field. */ @NativeType("uint32_t") public boolean chroma_loc_info_present_flag() { return StdVideoH264SpsVuiFlags.nchroma_loc_info_present_flag(address()) != 0; } /** @return the value of the {@code timing_info_present_flag} field. */ @NativeType("uint32_t") public boolean timing_info_present_flag() { return StdVideoH264SpsVuiFlags.ntiming_info_present_flag(address()) != 0; } /** @return the value of the {@code fixed_frame_rate_flag} field. */ @NativeType("uint32_t") public boolean fixed_frame_rate_flag() { return StdVideoH264SpsVuiFlags.nfixed_frame_rate_flag(address()) != 0; } /** @return the value of the {@code bitstream_restriction_flag} field. */ @NativeType("uint32_t") public boolean bitstream_restriction_flag() { return StdVideoH264SpsVuiFlags.nbitstream_restriction_flag(address()) != 0; } /** @return the value of the {@code nal_hrd_parameters_present_flag} field. */ @NativeType("uint32_t") public boolean nal_hrd_parameters_present_flag() { return StdVideoH264SpsVuiFlags.nnal_hrd_parameters_present_flag(address()) != 0; } /** @return the value of the {@code vcl_hrd_parameters_present_flag} field. */ @NativeType("uint32_t") public boolean vcl_hrd_parameters_present_flag() { return StdVideoH264SpsVuiFlags.nvcl_hrd_parameters_present_flag(address()) != 0; } /** Sets the specified value to the {@code aspect_ratio_info_present_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer aspect_ratio_info_present_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.naspect_ratio_info_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code overscan_info_present_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer overscan_info_present_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.noverscan_info_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code overscan_appropriate_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer overscan_appropriate_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.noverscan_appropriate_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code video_signal_type_present_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer video_signal_type_present_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.nvideo_signal_type_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code video_full_range_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer video_full_range_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.nvideo_full_range_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code color_description_present_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer color_description_present_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.ncolor_description_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code chroma_loc_info_present_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer chroma_loc_info_present_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.nchroma_loc_info_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code timing_info_present_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer timing_info_present_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.ntiming_info_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code fixed_frame_rate_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer fixed_frame_rate_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.nfixed_frame_rate_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code bitstream_restriction_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer bitstream_restriction_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.nbitstream_restriction_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code nal_hrd_parameters_present_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer nal_hrd_parameters_present_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.nnal_hrd_parameters_present_flag(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@code vcl_hrd_parameters_present_flag} field. */ public StdVideoH264SpsVuiFlags.Buffer vcl_hrd_parameters_present_flag(@NativeType("uint32_t") boolean value) { StdVideoH264SpsVuiFlags.nvcl_hrd_parameters_present_flag(address(), value ? 1 : 0); return this; } } }
63.863229
217
0.72373
59549ccaaa6a944533a7d22c0014e9fcaee73c8c
872
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //101. Symmetric Tree //Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). //For example, this binary tree [1,2,2,3,4,4,3] is symmetric: // 1 // / \ // 2 2 // / \ / \ //3 4 4 3 //But the following [1,2,2,null,3,null,3] is not: // 1 // / \ // 2 2 // \ \ // 3 3 //Note: //Bonus points if you could solve it both recursively and iteratively. ///** // * Definition for a binary tree node. // * public class TreeNode { // * int val; // * TreeNode left; // * TreeNode right; // * TreeNode(int x) { val = x; } // * } // */ //class Solution { // public boolean isSymmetric(TreeNode root) { // } //} // Time Is Money
24.222222
96
0.606651
b67c4e1cf3f5c0182063f8d9b070344a00cefdce
13,889
package de.gsi.chart.ui; import java.security.InvalidParameterException; import de.gsi.chart.ui.geometry.Side; import javafx.animation.Animation.Status; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.beans.InvalidationListener; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.collections.MapChangeListener; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.canvas.Canvas; import javafx.scene.control.SkinBase; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Region; import javafx.scene.shape.Rectangle; import javafx.util.Duration; public class SidesPaneSkin extends SkinBase<SidesPane> { private final BorderPane borderPane = new BorderPane(); private final EventHandler<MouseEvent> exitedHandler; private boolean mousePressed; private final DoubleProperty[] visibility = new SimpleDoubleProperty[Side.values().length]; private final Timeline[] showTimeline = new Timeline[Side.values().length]; private final Timeline[] hideTimeline = new Timeline[Side.values().length]; public SidesPaneSkin(final SidesPane pane) { super(pane); exitedHandler = event -> { if (isMouseEnabled() /* && getSkinnable().getPinnedSide() == null */ && !mousePressed) { for (final Side s : Side.values()) { if (!getSkinnable().isPinned(s)) { hide(s); } } } }; getChildren().add(borderPane); updateBorderPane(); final InvalidationListener rebuildListener = observable -> updateBorderPane(); pane.contentProperty().addListener(rebuildListener); pane.topProperty().addListener(rebuildListener); pane.rightProperty().addListener(rebuildListener); pane.bottomProperty().addListener(rebuildListener); pane.leftProperty().addListener(rebuildListener); pane.addEventFilter(MouseEvent.MOUSE_MOVED, event -> { if (isMouseEnabled() /* && getSkinnable().getPinnedSide() == null */) { final Side side = getSide(event); if (side != null) { show(side); } else if (isMouseMovedOutsideSides(event)) { for (final Side s : Side.values()) { if (!getSkinnable().isPinned(s)) { hide(s); } } } } }); pane.addEventFilter(MouseEvent.MOUSE_EXITED, exitedHandler); pane.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> mousePressed = true); pane.addEventFilter(MouseEvent.MOUSE_RELEASED, event -> { mousePressed = false; if (isMouseEnabled() /* && getSkinnable().getPinnedSide() == null */) { final Side side = getSide(event); if (side != null) { show(side); } } }); for (final Side side : Side.values()) { visibility[side.ordinal()] = new SimpleDoubleProperty(0); visibility[side.ordinal()].addListener(observable -> getSkinnable().requestLayout()); } for (final Side side : Side.values()) { if (getSkinnable().isPinned(side)) { show(side); } } pane.pinnedSideProperty().addListener((MapChangeListener<Side, Boolean>) change -> { for (final Side side : Side.values()) { if (getSkinnable().isPinned(side)) { show(side); } else { hide(side); } } }); final Rectangle clip = new Rectangle(); clip.setX(0); clip.setY(0); clip.widthProperty().bind(getSkinnable().widthProperty()); clip.heightProperty().bind(getSkinnable().heightProperty()); getSkinnable().setClip(clip); } private Side getSide(final MouseEvent evt) { if (borderPane.getBoundsInLocal().contains(evt.getX(), evt.getY())) { final double trigger = getSkinnable().getTriggerDistance(); // changed to check for trigger only for side-panes with actual // content if (evt.getX() <= trigger && getSkinnable().getLeft() != null) { return Side.LEFT; } else if (evt.getX() > getSkinnable().getWidth() - trigger && getSkinnable().getRight() != null) { return Side.RIGHT; } else if (evt.getY() <= trigger && getSkinnable().getTop() != null) { return Side.TOP; } else if (evt.getY() > getSkinnable().getHeight() - trigger && getSkinnable().getBottom() != null) { return Side.BOTTOM; } } return null; } private void hide(final Side side) { if (showTimeline[side.ordinal()] != null) { showTimeline[side.ordinal()].stop(); } if (hideTimeline[side.ordinal()] != null && hideTimeline[side.ordinal()].getStatus() == Status.RUNNING) { return; } boolean sideVisible = visibility[side.ordinal()].get() > 0; // nothing to do here if (!sideVisible) { return; } final KeyValue[] keyValues = new KeyValue[Side.values().length]; keyValues[side.ordinal()] = new KeyValue(visibility[side.ordinal()], 0); final Duration delay = getSkinnable().getAnimationDelay() != null ? getSkinnable().getAnimationDelay() : Duration.millis(300); final Duration duration = getSkinnable().getAnimationDuration() != null ? getSkinnable().getAnimationDuration() : Duration.millis(200); final KeyFrame keyFrame = new KeyFrame(duration, keyValues); hideTimeline[side.ordinal()] = new Timeline(keyFrame); hideTimeline[side.ordinal()].setDelay(delay); hideTimeline[side.ordinal()].play(); } private boolean isMouseEnabled() { return getSkinnable().getTriggerDistance() > 0; } private boolean isMouseMovedOutsideSides(final MouseEvent event) { return !(getSkinnable().getLeft() != null && getSkinnable().getLeft().getBoundsInParent().contains(event.getX(), event.getY())) && (!(getSkinnable().getTop() != null && getSkinnable().getTop().getBoundsInParent().contains(event.getX(), event.getY())) && (!(getSkinnable().getRight() != null && getSkinnable().getRight().getBoundsInParent().contains(event.getX(), event.getY())) && !(getSkinnable().getBottom() != null && getSkinnable().getBottom() .getBoundsInParent().contains(event.getX(), event.getY())))); } @Override protected void layoutChildren(final double contentX, final double contentY, final double contentWidth, final double contentHeight) { /* * Layout the BorderPane in a normal way (equals "lay out the content node", the only managed node) */ super.layoutChildren(contentX, contentY, contentWidth, contentHeight); // layout the managed side nodes && update preferred initial size // estimate final Node bottom = getSkinnable().getBottom(); if (bottom != null) { final double prefHeight = getSkinnable().prefHeightBottomProperty().get(); if (bottom.prefHeight(-1) > 0) { getSkinnable().prefHeightBottomProperty().set(Math.max(bottom.prefHeight(-1), prefHeight)); } final double offset = prefHeight * visibility[Side.BOTTOM.ordinal()].get(); bottom.setVisible(visibility[Side.BOTTOM.ordinal()].get() > 0); SidesPaneSkin.setPrefHeight(bottom, offset); } final Node left = getSkinnable().getLeft(); if (left != null) { final double prefWidth = getSkinnable().prefWidthLeftProperty().get(); if (left.prefWidth(-1) > 0) { getSkinnable().prefWidthLeftProperty().set(Math.max(left.prefWidth(-1), prefWidth)); } final double offset = prefWidth * visibility[Side.LEFT.ordinal()].get(); left.setVisible(visibility[Side.LEFT.ordinal()].get() > 0); SidesPaneSkin.setPrefWidth(left, offset); } final Node right = getSkinnable().getRight(); if (right != null) { final double prefWidth = getSkinnable().prefWidthRightProperty().get(); if (right.prefWidth(-1) > 0) { getSkinnable().prefWidthRightProperty().set(Math.max(right.prefWidth(-1), prefWidth)); } final double offset = prefWidth * visibility[Side.RIGHT.ordinal()].get(); right.setVisible(visibility[Side.RIGHT.ordinal()].get() > 0); SidesPaneSkin.setPrefWidth(right, offset); } final Node top = getSkinnable().getTop(); if (top != null) { final double prefHeight = getSkinnable().prefHeightTopProperty().get(); if (top.prefHeight(-1) > 0) { getSkinnable().prefHeightTopProperty().set(Math.max(top.prefHeight(-1), prefHeight)); } final double offset = prefHeight * visibility[Side.TOP.ordinal()].get(); top.setVisible(visibility[Side.TOP.ordinal()].get() > 0); top.setClip(new Rectangle(contentWidth, offset)); SidesPaneSkin.setPrefHeight(top, offset); } } private void show(final Side side) { if (hideTimeline[side.ordinal()] != null) { hideTimeline[side.ordinal()].stop(); } if (showTimeline[side.ordinal()] != null && showTimeline[side.ordinal()].getStatus() == Status.RUNNING) { return; } final KeyValue[] keyValues = new KeyValue[Side.values().length]; keyValues[side.ordinal()] = new KeyValue(visibility[side.ordinal()], 1); final Duration delay = getSkinnable().getAnimationDelay() != null ? getSkinnable().getAnimationDelay() : Duration.millis(300); final Duration duration = getSkinnable().getAnimationDuration() != null ? getSkinnable().getAnimationDuration() : Duration.millis(200); final KeyFrame keyFrame = new KeyFrame(duration, keyValues); showTimeline[side.ordinal()] = new Timeline(keyFrame); showTimeline[side.ordinal()].setDelay(delay); showTimeline[side.ordinal()].play(); } private void updateBorderPane() { borderPane.getChildren().clear(); if (getSkinnable().getContent() != null) { borderPane.setCenter(getSkinnable().getContent()); } if (getSkinnable().getTop() != null) { borderPane.setTop(getSkinnable().getTop()); getSkinnable().getTop().setManaged(true); getSkinnable().getTop().removeEventFilter(MouseEvent.MOUSE_EXITED, exitedHandler); getSkinnable().getTop().addEventFilter(MouseEvent.MOUSE_EXITED, exitedHandler); } if (getSkinnable().getRight() != null) { borderPane.setRight(getSkinnable().getRight()); getSkinnable().getRight().setManaged(true); getSkinnable().getRight().removeEventFilter(MouseEvent.MOUSE_EXITED, exitedHandler); getSkinnable().getRight().addEventFilter(MouseEvent.MOUSE_EXITED, exitedHandler); } if (getSkinnable().getBottom() != null) { borderPane.setBottom(getSkinnable().getBottom()); getSkinnable().getBottom().setManaged(true); getSkinnable().getBottom().removeEventFilter(MouseEvent.MOUSE_EXITED, exitedHandler); getSkinnable().getBottom().addEventFilter(MouseEvent.MOUSE_EXITED, exitedHandler); } if (getSkinnable().getLeft() != null) { borderPane.setLeft(getSkinnable().getLeft()); getSkinnable().getLeft().setManaged(true); getSkinnable().getLeft().removeEventFilter(MouseEvent.MOUSE_EXITED, exitedHandler); getSkinnable().getLeft().addEventFilter(MouseEvent.MOUSE_EXITED, exitedHandler); } } /** * Sets the preferred height of the generic node object by casting it onto the known Region, ... object * * @param node the node to be adapted * @param prefHeight the desired preferred height */ private static void setPrefHeight(final Node node, final double prefHeight) { if (node instanceof Region) { ((Region) node).setPrefHeight(prefHeight); return; } else if (node instanceof Canvas) { ((Canvas) node).setHeight(prefHeight); return; } // add other derivative of 'Node' throw new InvalidParameterException("no prefHeight for class type:" + node.getClass().getCanonicalName()); } /** * Sets the preferred width of the generic node object by casting it onto the known Region, ... object * * @param node the node to be adapted * @param prefWidth the desired preferred height */ private static void setPrefWidth(final Node node, final double prefWidth) { if (node instanceof Region) { ((Region) node).setPrefWidth(prefWidth); return; } else if (node instanceof Canvas) { ((Canvas) node).setWidth(prefWidth); return; } // add other derivative of 'Node' throw new InvalidParameterException("no prefWidth for class type:" + node.getClass().getCanonicalName()); } }
42.215805
119
0.599323
39c55f4eb545061c7efc7e9f0e17674f08a55494
153
package com.ruc.anapodoton.paxos.core; public interface PaxosCallback { /** * 执行器,用于执行确定的状态 * @param msg */ public void callback(byte[] msg); }
15.3
38
0.686275
29d23e82e914ba05ec05d6fa59a8034d64118538
11,185
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ibm.drl.hbcp.predictor.crossvalid; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.ibm.drl.hbcp.api.IUnitPOJO; import com.ibm.drl.hbcp.core.attributes.Arm; import com.ibm.drl.hbcp.core.attributes.ArmifiedAttributeValuePair; import com.ibm.drl.hbcp.core.attributes.Attribute; import com.ibm.drl.hbcp.core.attributes.collection.AttributeValueCollection; import com.ibm.drl.hbcp.inforetrieval.indexer.ExtractedInfoRetriever; import com.ibm.drl.hbcp.parser.AnnotatedAttributeValuePair; import com.ibm.drl.hbcp.parser.Attributes; import com.ibm.drl.hbcp.parser.JSONRefParser; import com.ibm.drl.hbcp.parser.cleaning.Cleaner; import com.ibm.drl.hbcp.parser.cleaning.NumericValueCleaner; import com.ibm.drl.hbcp.predictor.graph.AttribNodeRelations; import com.ibm.drl.hbcp.predictor.graph.AttribNodeRelations.AttribNodeRelation; import com.ibm.drl.hbcp.util.Props; /** * Splits the graph produced from JSON annotations into a train graph and a test graph. * The train graph will be used to run node2vec and learn the vectors. * The test graph will use these vectors in combination with queries to find out how accurate the vectors for unseen edges. * @author dganguly, marting */ public class CrossValidationSplitter { private final double trainPercentage; // Easier to implement than folding... select a percentage for training and the rest for testing private final AttribNodeRelations graph; private final AttributeValueCollection<ArmifiedAttributeValuePair> attributeValueCollection; private final AttribNodeRelations train; private final AttribNodeRelations test; final List<String> trainingDocs; final List<String> testDocs; private static final int SEED = 123456; private final Random random = new Random(SEED); private static Logger logger = LoggerFactory.getLogger(CrossValidationSplitter.class); public CrossValidationSplitter(double trainPercentage, AttribNodeRelations graph) { this.trainPercentage = trainPercentage; this.graph = graph; attributeValueCollection = null; Pair<AttribNodeRelations, AttribNodeRelations> split = split(graph); train = split.getLeft(); test = split.getRight(); trainingDocs = null; testDocs = null; } /*+++REFACTOR-DG: We intend to avoid passing the 'AttribNodeRelations' object. The splitter shouldn't depend on the graph ---REFACTOR-DG */ public CrossValidationSplitter(double trainPercentage, String jsonFile, boolean isGT, boolean applyCleaning) throws Exception { attributeValueCollection = AttributeValueCollection.cast( obtainAttribVals(jsonFile, isGT, applyCleaning, Props.loadProperties())); this.trainPercentage = trainPercentage; Pair<List<String>, List<String>> split = split(trainPercentage); trainingDocs = split.getLeft(); testDocs = split.getRight(); // Used in the older flow graph = null; train = null; test = null; } /** * Refactoring: Yet another constructor... this time to ensure that we pass the AVPs to the splitter */ public CrossValidationSplitter(AttributeValueCollection<ArmifiedAttributeValuePair> attributeValueCollection, double trainPercentage) { this.attributeValueCollection = attributeValueCollection; this.trainPercentage = trainPercentage; Pair<List<String>, List<String>> splits = split(trainPercentage); trainingDocs = splits.getLeft(); testDocs = splits.getRight(); // Used in the older flow graph = null; train = null; test = null; } // Depending on the type of the source - [gt/ie] obtain these attribute value // pairs from either extracted information or from the ground truth (json) public static AttributeValueCollection<? extends ArmifiedAttributeValuePair> obtainAttribVals(Properties props) throws IOException { return obtainAttribVals( props.getProperty("ref.json"), "gt".equalsIgnoreCase(props.getProperty("prediction.source")), Boolean.parseBoolean(props.getProperty("prediction.applyCleaning", "false")), props // I need to pass it anyway so this is kind of useless ); } public static AttributeValueCollection<? extends ArmifiedAttributeValuePair> obtainAttribVals( String jsonFile, boolean isGT, boolean applyCleaning, Properties props) throws IOException { JSONRefParser parser = new JSONRefParser(new File(jsonFile)); parser.buildAll(); if (isGT) { final AttributeValueCollection<AnnotatedAttributeValuePair> attributeValuePairs = parser.getAttributeValuePairs(); // apply cleaners (if property set) if (applyCleaning) { // Cleaners cleaners = new Cleaners(props); final List<Attribute> numericAttributes = attributeValuePairs.getNumericAttributes(); final List<String> numericAttributeIds = numericAttributes.stream().map(e -> e.getId()).collect(Collectors.toList()); final NumericValueCleaner cleaners = new NumericValueCleaner(numericAttributeIds); AttributeValueCollection<AnnotatedAttributeValuePair> cleaned = cleaners.getCleaned(attributeValuePairs); logger.info("Amount cleaned: " + Cleaner.delta(cleaned, attributeValuePairs).size()); return cleaned; } else return attributeValuePairs; } else { // from ie return createFromExtractedIndex(parser, props); } } public static AttributeValueCollection<ArmifiedAttributeValuePair> createFromExtractedIndex(JSONRefParser parser, Properties props) throws IOException { Attributes attributes = parser.getAttributes(); List<ArmifiedAttributeValuePair> pairs = new ArrayList<>(); ExtractedInfoRetriever retriever = new ExtractedInfoRetriever(props); List<IUnitPOJO> iunits = retriever.getIUnitPOJOs(); for (IUnitPOJO iunit: iunits) { // iunit.getCode() contains the name which must be converted back to the id String attribName = iunit.getCode(); Attribute attribute = attributes.getFromName(attribName); if (attribute == null) { System.out.println("Unable to get id of the attribute named '" + attribName + "'"); continue; } pairs.add(new ArmifiedAttributeValuePair( attribute, iunit.getExtractedValue(), iunit.getDocName(), new Arm(iunit.getArmId(), iunit.getArmName()), iunit.getContext())); } return new AttributeValueCollection<>(pairs); } /** * Split the graph into a training graph and a testing graph * @param graph the original complete graph * @return a pair of the training graph (left) and the testing graph (right) */ private Pair<AttribNodeRelations, AttribNodeRelations> split(AttribNodeRelations graph) { // get all the docnames in the graph List<String> docNames = graph.getEdges().stream() .flatMap(rel -> Lists.newArrayList((ArmifiedAttributeValuePair)rel.source.getOriginal(), (ArmifiedAttributeValuePair)rel.target.getOriginal()) .stream()) .map(ArmifiedAttributeValuePair::getDocName) .distinct() .collect(Collectors.toList()); // shuffle them for a random split Collections.shuffle(docNames, random); // split the docnames into train/test int trainIndexEnd = (int)(trainPercentage * docNames.size()); List<String> trainDocNames = docNames.subList(0, trainIndexEnd); List<String> testDocNames = docNames.subList(trainIndexEnd, docNames.size()); // build a train and test subgraph return Pair.of( getSubgraphForDocs(graph, new HashSet<>(trainDocNames)), getSubgraphForDocs(graph, new HashSet<>(testDocNames)) ); } /*+++REFACTOR-DG: No graph object in split() Function now supposed to return a list of doc names obtained from the AVP collection. ---REFACTOR-DG */ public final Pair<List<String>, List<String>> split(double trainPercentage) { // Obtain the doc names from the AVP collection List<String> docNames = new ArrayList(attributeValueCollection.getDocNames()); // shuffle them for a random split Collections.shuffle(docNames, random); // split the docnames into train/test int trainIndexEnd = (int)(trainPercentage * docNames.size()); List<String> trainDocNames = docNames.subList(0, trainIndexEnd); List<String> testDocNames = docNames.subList(trainIndexEnd, docNames.size()); // build a train and test subgraph return Pair.of(trainDocNames, testDocNames); } private AttribNodeRelations getSubgraphForDocs(AttribNodeRelations graph, Set<String> docnames) { AttribNodeRelations res = new AttribNodeRelations(); for (AttribNodeRelation edge : graph.getEdges()) { List<ArmifiedAttributeValuePair> navps = Lists.newArrayList( (ArmifiedAttributeValuePair)edge.source.getOriginal(), (ArmifiedAttributeValuePair)edge.target.getOriginal() ); if (navps.stream().allMatch(navp -> docnames.contains(navp.getDocName()))) { res.add(edge); } } return res; } public void dumpEdgeList(AttribNodeRelations relations, String prefixForFilename) throws IOException { String fileName = "prediction/graphs/" + prefixForFilename + ".edges.txt"; FileWriter fw = new FileWriter(fileName); BufferedWriter bw = new BufferedWriter(fw); for (AttribNodeRelation ar: relations.getEdges()) { bw.write(ar.toString()); bw.newLine(); } } public AttribNodeRelations getTrainingSet() { return train; } public AttribNodeRelations getTestSet() { return test; } public List<String> getTrainingDocs() { return trainingDocs; } public List<String> getTestDocs() { return testDocs; } }
43.862745
158
0.674296
74f0bcec2f8910c26ab2ce749b4ef0471f55d20a
2,620
package com.moemoe.lalala.view.adapter; import android.view.View; import android.widget.CheckBox; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.moemoe.lalala.R; import com.moemoe.lalala.model.entity.UserTopEntity; import com.moemoe.lalala.utils.StringUtils; import com.moemoe.lalala.view.widget.adapter.ClickableViewHolder; import jp.wasabeef.glide.transformations.CropSquareTransformation; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; /** * Created by yi on 2017/7/21. */ public class PhoneGroupMemberListHolder extends ClickableViewHolder { public PhoneGroupMemberListHolder(View itemView) { super(itemView); } public void createItem(final UserTopEntity entity, boolean isCheck, String id) { ((CheckBox) $(R.id.cb_select)).setClickable(false); Glide.with(itemView.getContext()) .load(StringUtils.getUrl(itemView.getContext(), entity.getHeadPath(), (int) itemView.getContext().getResources().getDimension(R.dimen.x64), (int) itemView.getContext().getResources().getDimension(R.dimen.y64), false, true)) .error(R.drawable.shape_gray_e8e8e8_background) .placeholder(R.drawable.shape_gray_e8e8e8_background) .bitmapTransform(new CropSquareTransformation(itemView.getContext()), new RoundedCornersTransformation(itemView.getContext(), (int) context.getResources().getDimension(R.dimen.y8), 0)) .into((ImageView) $(R.id.iv_avatar)); setText(R.id.tv_name, entity.getUserName()); if ("N".equalsIgnoreCase(entity.getSex())) { setVisible(R.id.iv_sex, false); } else { setVisible(R.id.iv_sex, true); } setImageResource(R.id.iv_sex, "M".equalsIgnoreCase(entity.getSex()) ? R.drawable.ic_user_girl : R.drawable.ic_user_boy); if (isCheck) { if (id.equals(entity.getUserId())) { setVisible(R.id.cb_select, false); } else { setVisible(R.id.cb_select, true); ((CheckBox) $(R.id.cb_select)).setChecked(entity.isCheck()); } } else { setVisible(R.id.cb_select, false); } if (id.equals(entity.getUserId())) { setVisible(R.id.tv_extra, true); setText(R.id.tv_extra, "管理员"); } else { setVisible(R.id.tv_extra, true); setText(R.id.tv_extra, ""); } // itemView.setTag(this); } // public void setCheck(boolean check){ // ((CheckBox)$(R.id.cb_select)).setChecked(check); // } }
38.529412
239
0.651908
314e2fe180e58c4da21a90509b42cae6cf7bf3a4
264
package be.kuleuven.ses.factory; import be.kuleuven.ses.factory.tickets.Ticket; public class AgeBasedTicketSeller implements TicketSeller { @Override public Ticket buyTicketFor(Person person) { throw new UnsupportedOperationException(); } }
22
59
0.757576
944f5373a130a66e915c06e47f21691e9a9e4ca5
1,239
package com.github.wz2cool.elasticsearch.repository.support; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactory; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.repository.core.RepositoryMetadata; import static org.springframework.data.querydsl.QuerydslUtils.QUERY_DSL_PRESENT; /** * @author Frank **/ public class ElasticsearchExtRepositoryFactory extends ElasticsearchRepositoryFactory { public ElasticsearchExtRepositoryFactory(ElasticsearchOperations elasticsearchOperations) { super(elasticsearchOperations); } @Override protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) { if (isQueryDslRepository(metadata.getRepositoryInterface())) { throw new IllegalArgumentException("QueryDsl Support has not been implemented yet."); } return SimpleElasticsearchExtRepository.class; } private static boolean isQueryDslRepository(Class<?> repositoryInterface) { return QUERY_DSL_PRESENT && QuerydslPredicateExecutor.class.isAssignableFrom(repositoryInterface); } }
39.967742
106
0.803067
a0b8af922052ba6a24e654a234675598a9e150f1
182
package com.youlongnet.lulu.ui.event; public class GiftPageEvent { public int pageIndex; public GiftPageEvent(int pageIndex) { this.pageIndex = pageIndex; } }
16.545455
41
0.692308
9cc3bdeece8b26348ad1db475e4b46b6a7577739
2,519
package com.smaato.soma.p239c.p246f; import android.view.View; import com.smaato.soma.C12408ia; import com.smaato.soma.p238b.C12143a; import com.smaato.soma.p238b.C12146d; import com.smaato.soma.p238b.C12147e; import com.smaato.soma.p256e.C12331a; import com.smaato.soma.p256e.C12345k.C12346a; /* renamed from: com.smaato.soma.c.f.h */ /* compiled from: AdDownloader */ class C12236h implements C12346a { /* renamed from: a */ final /* synthetic */ C12239k f38324a; C12236h(C12239k this$0) { this.f38324a = this$0; } /* renamed from: a */ public void mo39596a(View receivedView) { String str = "AdDowndloader_Med_Banner"; if (receivedView != null) { try { if (this.f38324a.f38352u != null) { C12239k.f38328a.post(new C12235g(this, receivedView)); if (!(this.f38324a.f38357z == null || this.f38324a.f38357z.mo39796f() == null)) { this.f38324a.mo39605a(this.f38324a.f38357z.mo39796f()); C12146d.m39965a(new C12147e(str, "Impression Tracking triggered through on Banner displayed", 1, C12143a.DEBUG)); } this.f38324a.m40251a(C12331a.BANNER); this.f38324a.m40262e(); this.f38324a.m40253a(str, "Ad added successfully onReceiveAd"); } } catch (NoClassDefFoundError e) { this.f38324a.mo39606c(); return; } catch (Exception e2) { this.f38324a.mo39606c(); return; } } this.f38324a.mo39606c(); this.f38324a.m40253a(str, "Ad added successfully onReceiveAd"); } /* renamed from: a */ public void mo39597a(C12408ia errorCode) { if (errorCode != null) { StringBuilder sb = new StringBuilder(); sb.append("onBannerFailed with ErrorCode"); sb.append(errorCode); C12146d.m39965a(new C12147e("AdDowndloader_Med_Banner", sb.toString(), 1, C12143a.DEBUG)); } this.f38324a.mo39606c(); } public void onBannerClicked() { if (this.f38324a.f38357z != null && this.f38324a.f38357z.mo39792d() != null) { C12146d.m39965a(new C12147e("AdDowndloader_Med_Banner", "Click Tracking triggered through onBannerClicked", 1, C12143a.DEBUG)); C12239k kVar = this.f38324a; kVar.mo39605a(kVar.f38357z.mo39792d()); } } }
37.044118
139
0.590314
22a3387cdb4c19f6ca151b6493292ffbf183a08c
782
package com.example.android.quakereport; import android.content.AsyncTaskLoader; import android.content.Context; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.List; public class EarthquakeLoader extends AsyncTaskLoader<List<Earthquake>> { private String mUrl; public EarthquakeLoader(@NonNull Context context, String url) { super(context); mUrl = url; } @Override protected void onStartLoading() { forceLoad(); } @Nullable @Override public List<Earthquake> loadInBackground() { if (TextUtils.isEmpty(mUrl)) return null; return QueryUtils.extractEarthquakes(mUrl); } }
21.135135
74
0.66624
5b6c4ca589419171bd49241291eb09bb42de02e5
8,005
package org.jiucai.appframework.common.excel; import java.io.FileInputStream; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.io.FilenameUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.jiucai.appframework.base.util.DateTimeUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ExcelReader, using apache poi 3.11+ * * @author zhaidangwei */ public class ExcelReader { protected static Logger logger = LoggerFactory.getLogger(ExcelReader.class); protected static final String dateTimeFmtPattern = "yyyy-MM-dd HH:mm:ss"; protected static final String dateFmtPattern = "yyyy-MM-dd"; protected static final DataFormatter formatter = new DataFormatter(); public static void main(String[] args) throws Exception { List<Map<String, String>> list = read("e:/test1.xls"); List<Map<String, String>> list2 = read("e:/test1.xlsx"); logger.info("list:\n" + list); logger.info("lis2t:\n" + list2); } /** * 读取excel文件(同时支持2003和2007格式) * * @param fis * 文件输入流 * @param extension * 文件名扩展名: xls 或 xlsx 不区分大小写 * @return list中的map的key是列的序号 * @throws Exception * io异常等 */ public static List<Map<String, String>> read(FileInputStream fis, String extension) throws Exception { Workbook wb = null; List<Map<String, String>> list = null; try { if ("xls".equalsIgnoreCase(extension)) { wb = new HSSFWorkbook(fis); } else if ("xlsx".equalsIgnoreCase(extension)) { wb = new XSSFWorkbook(fis); } else { logger.error("file is not office excel"); throw new IllegalArgumentException("file is not office excel"); } list = readWorkbook(wb); return list; } finally { if (null != wb) { wb.close(); } } } /** * 读取excel文件(同时支持2003和2007格式) * * @param fileName * 文件名,绝对路径 * @return list中的map的key是列的序号 * @throws Exception * io异常等 */ public static List<Map<String, String>> read(String fileName) throws Exception { FileInputStream fis = null; Workbook wb = null; List<Map<String, String>> list = null; try { String extension = FilenameUtils.getExtension(fileName); fis = new FileInputStream(fileName); list = read(fis, extension); return list; } finally { if (null != wb) { wb.close(); } if (null != fis) { fis.close(); } } } @SuppressWarnings("deprecation") private static String formatDate(Date d, String sdf) { String value = null; if (d.getSeconds() == 0 && d.getMinutes() == 0 && d.getHours() == 0) { value = DateTimeUtil.getFormatedDate(d, dateFmtPattern); } else { value = DateTimeUtil.getFormatedDate(d, sdf); } return value; } @SuppressWarnings("deprecation") protected static String getCellValue(Cell cell) { String value = null; // // if (Cell.CELL_TYPE_STRING == cell.getCellType()) { // value = cell.getStringCellValue(); // } else if (Cell.CELL_TYPE_BLANK == cell.getCellType()) { // value = ""; // } else if (isCellDateFormatted(cell)) { // value = formatDate(cell); // } else { // value = formatter.formatCellValue(cell); // } switch (cell.getCellType()) { case Cell.CELL_TYPE_FORMULA: // 公式 case Cell.CELL_TYPE_NUMERIC: // 数字 // if (DateUtil.isCellDateFormatted(cell)) { // 如果是日期类型 // // value = formatDate(cell); // } else { // value = String.valueOf(cell.getNumericCellValue()); // } // 所有日期格式都可以通过getDataFormat()值来判断 // yyyy-MM-dd----- 14 // yyyy年m月d日--- 31,177,180 // 二○一五年三月二十三日 -- 179 // 二○一五年三月 -- 181 // 三月二十三日 -- 176 // yyyy年m月------- 57,182 // m月d日 ---------- 58,183 // HH:mm----------- 20 // HH:mm:ss----------- 187 // h时mm分 ------- 32 double doubleVal = cell.getNumericCellValue(); short format = cell.getCellStyle().getDataFormat(); String formatString = cell.getCellStyle().getDataFormatString(); if (format > 0) { logger.info("format: " + format + " formatString: " + formatString); } if (format == 14 || format == 31 || format == 57 || format == 58 || (format >= 176 && format <= 183)) { // 日期 Date date = DateUtil.getJavaDate(doubleVal); value = formatDate(date, dateFmtPattern); } else if (format == 20 || format == 32 || (format >= 184 && format <= 187)) { // 时间 Date date = DateUtil.getJavaDate(doubleVal); value = formatDate(date, "HH:mm"); } else { value = String.valueOf(doubleVal); } break; case Cell.CELL_TYPE_STRING: // 字符串 value = cell.getStringCellValue(); break; // case Cell.CELL_TYPE_FORMULA: // 公式 // // 用数字方式获取公式结果,根据值判断是否为日期类型 // double numericValue = cell.getNumericCellValue(); // if (DateUtil.isValidExcelDate(numericValue)) { // 如果是日期类型 // value = formatDate(cell); // } else { // value = String.valueOf(numericValue); // } // break; case Cell.CELL_TYPE_BLANK: // 空白 value = ""; break; case Cell.CELL_TYPE_BOOLEAN: // Boolean value = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: // Error,返回错误码 value = String.valueOf(cell.getErrorCellValue()); break; default: value = ""; break; } return value; } protected static List<Map<String, String>> readWorkbook(Workbook wb) throws Exception { List<Map<String, String>> list = new LinkedList<Map<String, String>>(); for (int k = 0; k < wb.getNumberOfSheets(); k++) { Sheet sheet = wb.getSheetAt(k); int rows = sheet.getPhysicalNumberOfRows(); // System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + // "\" has " + rows // + " row(s)."); for (int r = 0; r < rows; r++) { Row row = sheet.getRow(r); if (row == null) { continue; } Map<String, String> map = new HashMap<String, String>(); int cells = row.getPhysicalNumberOfCells(); // System.out.println("\nROW " + row.getRowNum() + " has " + // cells + " cell(s)."); for (int c = 0; c < cells; c++) { Cell cell = row.getCell(c); if (cell == null) { continue; } String value = getCellValue(cell); map.put(String.valueOf(cell.getColumnIndex() + 1), value); } list.add(map); } } return list; } }
31.89243
91
0.523173
8095f14bed801311600427867852ef545f3a6f00
626
package com.example.demo; import java.util.function.Consumer; import java.util.function.Function; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class StreamSolutionsLoggerApplication { public static void main(String[] args) { SpringApplication.run(StreamSolutionsLoggerApplication.class, args); } @Bean public Consumer<Solution> logSolution() { return solution -> { log.info("SOLUTION: " + solution); }; } }
23.185185
70
0.790735
043ecbf82ed2d49a7cd5a19dd1c7e7a562bffc32
3,691
package com.smartgwt.sample.showcase.client.data; import java.util.Date; import com.smartgwt.client.widgets.grid.ListGridRecord; public class ItemRecord extends ListGridRecord { public ItemRecord() { } public ItemRecord(int itemID, String item, String sku, String description, String category, String units, Double unitCost, Boolean inStock, Date nextShipment) { setItemID(itemID); setItemName(item); setSKU(sku); setDescription(description); setCategory(category); setUnits(units); setUnitCost(unitCost); setInStock(inStock); setNextShipment(nextShipment); } /** * Set the itemID. * * @param itemID the itemID */ public void setItemID(int itemID) { setAttribute("itemID", itemID); } /** * Return the itemID. * * @return the itemID */ public int getItemID() { return getAttributeAsInt("itemID"); } /** * Set the item. * * @param item the item */ public void setItemName(String item) { setAttribute("itemName", item); } /** * Return the item. * * @return the item */ public String getItemName() { return getAttribute("itemName"); } /** * Set the SKU. * * @param SKU the SKU */ public void setSKU(String SKU) { setAttribute("SKU", SKU); } /** * Return the SKU. * * @return the SKU */ public String getSKU() { return getAttribute("SKU"); } /** * Set the description. * * @param description the description */ public void setDescription(String description) { setAttribute("description", description); } /** * Return the description. * * @return the description */ public String getDescription() { return getAttribute("description"); } /** * Set the category. * * @param category the category */ public void setCategory(String category) { setAttribute("category", category); } /** * Return the category. * * @return the category */ public String getCategory() { return getAttribute("category"); } /** * Set the units. * * @param units the units */ public void setUnits(String units) { setAttribute("units", units); } /** * Return the units. * * @return the units */ public String getUnits() { return getAttribute("units"); } /** * Set the unitCost. * * @param unitCost the unitCost */ public void setUnitCost(Double unitCost) { setAttribute("unitCost", unitCost); } /** * Return the unitCost. * * @return the unitCost */ public Float getUnitCost() { return getAttributeAsFloat("unitCost"); } /** * Set the inStock. * * @param inStock the inStock */ public void setInStock(Boolean inStock) { setAttribute("inStock", inStock); } /** * Return the inStock. * * @return the inStock */ public Boolean getInStock() { return getAttributeAsBoolean("inStock"); } /** * Set the nextShipment. * * @param nextShipment the nextShipment */ public void setNextShipment(Date nextShipment) { setAttribute("nextShipment", nextShipment); } /** * Return the nextShipment. * * @return the nextShipment */ public Date getNextShipment() { return getAttributeAsDate("nextShipment"); } }
19.529101
164
0.557302
aef36e7933919e477e5a7f7449ea943648e807f6
1,211
package excx.entities; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import excx.movement.Movement; public abstract class Bullet extends Entity{ //private Image picture; public Bullet(double x, double y, Movement type){ super(x,y); setMovement(type); if(type == null){ setMovement(new Movement(null,null)); } } @Override public void render(double x2, double y2, Graphics2D g){ AffineTransform af = new AffineTransform(); af.translate(x2+getX(), y2+getY()); af.rotate(getMovement().getVelocityAngleRadians()+Math.PI/2); g.transform(af); g.drawImage(getImageNode().getImage(),-(getImageNode().getImage().getWidth(null))/2,-(getImageNode().getImage().getHeight(null))/2,null); try { g.transform(af.createInverse()); } catch (NoninvertibleTransformException e) { // TODO Auto-generated catch block e.printStackTrace(); } //g.drawImage(getImageNode().getImage(),(int)(getX()+x2-getImageNode().getImage().getWidth(null)/2),(int)(getY()+y2-getImageNode().getImage().getHeight(null)/2), null); } public String toString(){ return "bullet"; } }
28.833333
171
0.689513
c62ff42710cd55cc92b92ada2ebb6b550afc9c65
839
package com.nullfish.lib.vfs.exception; /** * 想定されてない実装があった場合に投げられる例外クラス。 * 存在しないファイルタイプが指定された、等。 * * @author shunji */ public class VFSSystemException extends VFSException { public static final String NAME = "system_error"; public VFSSystemException() { super(); } public VFSSystemException(String message) { super(message); } public VFSSystemException(String message, Throwable cause) { super(message, cause); } public VFSSystemException(Throwable cause) { super(cause); } /* (non-Javadoc) * @see com.sexyprogrammer.lib.vfs.exception.VFSException#getName() */ public String getName() { return NAME; } /* (non-Javadoc) * @see com.sexyprogrammer.lib.vfs.exception.VFSException#getErrorValues() */ public Object[] getErrorValues() { Object[] rtn = { getCause() }; return rtn; } }
18.644444
75
0.699642
df18628da9bb7c6b12b542ff90db30cfc8ef8722
1,002
package edu.sgl.samples.restaurant.domain; import java.time.LocalDateTime; import java.util.List; public class RestaurantOrdered { private String id; private String tableId; private List<RestaurantOrderedItem> items; private LocalDateTime startTime; private LocalDateTime endTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTableId() { return tableId; } public void setTableId(String tableId) { this.tableId = tableId; } public List<RestaurantOrderedItem> getItems() { return items; } public void setItems(List<RestaurantOrderedItem> items) { this.items = items; } public LocalDateTime getStartTime() { return startTime; } public void setStartTime(LocalDateTime startTime) { this.startTime = startTime; } public LocalDateTime getEndTime() { return endTime; } public void setEndTime(LocalDateTime endTime) { this.endTime = endTime; } }
16.7
59
0.701597
65a1f8f7049f6c4d0425da9b90f7faaa970162af
2,317
package clockIn; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * 820. 单词的压缩编码 * 给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。 * <p> * 例如,如果这个列表是 ["time", "me", "bell"],我们就可以将其表示为 S = "time#bell#" 和 indexes = [0, 2, 5]。 * <p> * 对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 "#" 结束,来恢复我们之前的单词列表。 * <p> * 那么成功对给定单词列表进行编码的最小字符串长度是多少呢? * <p> * <p> * <p> * 示例: * <p> * 输入: words = ["time", "me", "bell"] * 输出: 10 * 说明: S = "time#bell#" , indexes = [0, 2, 5] 。 * <p> * <p> * 提示: * <p> * 1 <= words.length <= 2000 * 1 <= words[i].length <= 7 * 每个单词都是小写字母 。 */ public class LeetCode_820_minimumLengthEncoding { /** * 暴力解法 * * @param words * @return */ public int minimumLengthEncodingForce(String[] words) { Set<String> set = new HashSet<String>(Arrays.asList(words)); for (int i = 0; i < words.length; i++) { for (int j = 1; j < words[i].length(); j++) { set.remove(words[i].substring(j)); } } int res = 0; for (String word : set) { res += word.length() + 1; } return res; } public int minimumLengthEncoding(String[] words) { int len = 0; Trie trie = new Trie(); // 先对单词列表根据单词长度由长到短排序 Arrays.sort(words, (s1, s2) -> s2.length() - s1.length()); // 单词插入trie,返回该单词增加的编码长度 for (String word : words) { len += trie.insert(word); } return len; } // 定义tire class Trie { TrieNode root; public Trie() { root = new TrieNode(); } public int insert(String word) { TrieNode cur = root; boolean isNew = false; //倒着插入单词 for (int i = word.length() - 1; i >= 0; i--) { int c = word.charAt(i) - 'a'; if (cur.children[c] == null) { isNew = true; cur.children[c] = new TrieNode(); } cur = cur.children[c]; } // 如果是新单词的话编码长度增加新单词的长度+1,否则不变。 return isNew ? word.length() + 1 : 0; } } class TrieNode { char val; TrieNode[] children = new TrieNode[26]; public TrieNode() { } } }
23.40404
87
0.480363
0a67e811d9df5891eb1add296b3c7d772b58b951
5,800
/* * MIT License * * Copyright (c) 2018 rmbar * * 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. */ /* * MIT License * * Copyright (c) 2018 rmbar * * 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 io.github.rmbar.tight_types.string; /** * An immutable string that's content is defined by an encapsulated inner immutable string that is either the empty * string or an instance of a descendant of {@code NonEmptyString}. * * This interface is useful for describing a value that is restricted to being either an instance of {@code S} or the * empty string. Namely it models the union of {@code S} and the empty string. * * @param <S> the type of the inner string that may be encapsulated by this wrapper if the wrapper is in the non-empty * state. */ public class EmptyStrOr<S extends NonEmptyString> { /** * {@code null} if the string represents the empty string, otherwise the string content of the outer string. */ private final S _innerString; /** * Creates a new string with an empty string as the inner value. */ public EmptyStrOr() { _innerString = null; } /** * Creates a new string with the given string as the inner value. * * @param innerString the string value the constructed string represents. may not be {@code null}. */ public EmptyStrOr(S innerString) { if(innerString == null) throw new NullPointerException("innerString"); _innerString = innerString; } /** * Performs one of two operations (both encapsulated in {@code cases}) depending on whether this string * is empty or not. * * If this string is empty, performs {@code cases.forEmpty()}. Otherwise performs * {@code cases.forNonEmpty(S)} passing in the inner string value. * * @param cases the two possible operations. may not be {@code null}. * @param <R> the result type of executing either of the operations. * @param <T> the type of the exception that may be raised by performing either of the operations. * @return the result of performing one of the two given operations. * @throws T if there is an exception while performing the operation. */ public final <R, T extends Throwable> R which(EmptyStrOrCases<R, S, T> cases) throws T { if(_innerString == null) return cases.forEmpty(); return cases.forNonEmpty(_innerString); } /** * @return {@code true} if this string's content is empty, otherwise {@code false} */ public final boolean isEmptyString() { return _innerString == null; } /** * @return {@code false} if this string's content is empty, otherwise {@code true} */ public final boolean isNonEmptyString() { return !isEmptyString(); } /** * Retrieves the inner non-empty string value if this string is non-empty, otherwise returns {@code defaultValue}. * * @param defaultValue the value to return if this string is empty. may be {@code null}. * @return the inner string or {@code defaultValue}. */ public final S getOrDefault(S defaultValue) // TODO rename orElse to match JDK 8 convention { if(_innerString == null) return defaultValue; return _innerString; } /** * @return if non-empty returns {@link NonEmptyString#toString()} otherwise {@code ""}. */ public String toString() { if(_innerString == null) return ""; return _innerString.toString(); } }
38.410596
119
0.672414
61b7b9041ad3a48a95682c4282fe0fb5ffd70228
63
package enumtests; public enum Colours { Red, Green, Blue; }
10.5
21
0.714286
cd377b4cb69d6bb1c91176a73f1a8621965c1e81
3,498
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.csw.foros.resources; import co.edu.uniandes.csw.foros.dtos.DiaDTO; import co.edu.uniandes.csw.foros.ejb.EmisionDiasLogic; import co.edu.uniandes.csw.foros.ejb.DiaLogic; import co.edu.uniandes.csw.foros.entities.DiaEntity; import co.edu.uniandes.csw.foros.exceptions.BusinessLogicException; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; /** * * @author ne.ortega */ @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class EmisionDiasResource { @Inject private EmisionDiasLogic emDiaLogic; @Inject private DiaLogic diaLogic; @POST @Path("{diaId: \\d+}") public DiaDTO addDia(@PathParam("emisionId") Long emisionId, @PathParam("diaId") Long diaId){ if(diaLogic.getDiaPorId(diaId)==null){ throw new WebApplicationException("El dia con el id " + diaId + " no existe.", 404); } DiaDTO dto = new DiaDTO(emDiaLogic.agregarDia(emisionId, diaId)); return dto; } @GET @Path("/dias") public List<DiaDTO> getDias(@PathParam("emisionId") Long emisionId){ List<DiaDTO> dtos = new ArrayList<>(); List<DiaEntity> entities = emDiaLogic.obtenerDias(emisionId); for(DiaEntity dia : entities){ dtos.add(new DiaDTO(dia)); } return dtos; } @GET @Path("{diaId: \\d+}") public DiaDTO getDia(@PathParam("emisionId") Long emisionId, @PathParam("diaId") Long diaId){ if(diaLogic.getDiaPorId(diaId)==null){ throw new WebApplicationException("El dia con el id " + diaId + " no existe.", 404); } DiaDTO dto = new DiaDTO(emDiaLogic.obtenerDia(emisionId, diaId)); return dto; } @PUT public List<DiaDTO> updateDias(@PathParam("emisionId") Long emisionId, List<DiaDTO> dias){ for(DiaDTO dto : dias){ if(diaLogic.getDiaPorId(dto.getId())==null){ throw new WebApplicationException("El dia con el id " + dto.getId() + " no existe.", 404); } } List<DiaEntity> entidades = new ArrayList<>(); for(DiaDTO dto : dias){ entidades.add(dto.toEntity()); } List<DiaEntity> entidadesActuales = emDiaLogic.actualizarDias(emisionId, entidades); List<DiaDTO> dtosNuevos = new ArrayList<>(); for(DiaEntity entity : entidadesActuales){ dtosNuevos.add(new DiaDTO(entity)); } return dtosNuevos; } @DELETE @Path("{produccionId: \\d+}") public void removeDia(@PathParam("emisionId") Long emisionId, @PathParam("diaId") Long diaId){ if(diaLogic.getDiaPorId(diaId)==null){ throw new WebApplicationException("El dia con el id " + diaId + " no existe.", 404); } emDiaLogic.eliminarDia(emisionId, diaId); } }
33.961165
107
0.628073
354dce980b4905ee5e936aeed159806c88de7f42
1,052
package com.lhr.jiandou.utils; import android.graphics.Bitmap; import android.support.v7.graphics.Palette; import com.lhr.jiandou.MyApplication; import com.lhr.jiandou.R; /** * Created by ChinaLHR on 2016/12/19. * Email:13435500980@163.com */ public class ImageUtils { /** * 根据bitmap提取颜色 * * @param bitmap * @return */ public static int getColor(Bitmap bitmap) { if (bitmap != null) { Palette p = Palette.from(bitmap).generate(); Palette.Swatch s_dm = p.getDarkMutedSwatch(); Palette.Swatch s_dv = p.getDarkVibrantSwatch(); if (s_dm != null) { return s_dm.getRgb(); } else { if (s_dv != null) { return s_dv.getRgb(); } else { return UIUtils.getColor(MyApplication.getContext(), R.color.colorPrimary); } } } else { return UIUtils.getColor(MyApplication.getContext(), R.color.colorPrimary); } } }
25.658537
94
0.553232
2e593d6063aaa7214f22f91cca073180075b70e5
2,272
package no.deichman.services.entity.repository; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class UniqueURIGeneratorTest { public static final String PERSON_IDENTIFIER_REGEX = "h[0-9]+"; public static final String PUBLICATION_IDENTIFIER_REGEX = "p[0-9]+"; public static final String WORK_IDENTIFIER_REGEX = "w[0-9]+"; public static final String PLACE_IDENTIFIER_REGEX = "g[0-9]+"; private UniqueURIGenerator uriGenerator; @Before public void setUp() throws Exception { uriGenerator = new UniqueURIGenerator(); } @Test public void should_return_new_work_ID() throws Exception { String uri = uriGenerator.getNewURI("Work", s -> false); assertNotNull(uri); assertTrue(uri.contains("/work")); assertTrue(getLastElementOfURI(uri).matches(WORK_IDENTIFIER_REGEX)); } @Test public void should_return_new_publication_id_even_if_first_attempt_fails() throws Exception { boolean[] existsFlag = new boolean[1]; existsFlag[0] = true; String uri = uriGenerator.getNewURI( "Publication", s -> { boolean result = existsFlag[0]; existsFlag[0] = false; return result; } ); assertNotNull(uri); assertTrue(uri.contains("/publication")); assertTrue(getLastElementOfURI(uri).matches(PUBLICATION_IDENTIFIER_REGEX)); } @Test public void should_get_new_person_id() throws Exception { String uri = uriGenerator.getNewURI("Person", s -> false); assertNotNull(uri); assertTrue(uri.contains("/person")); assertTrue(getLastElementOfURI(uri).matches(PERSON_IDENTIFIER_REGEX)); } @Test public void should_get_new_place_id() throws Exception { String uri = uriGenerator.getNewURI("Place", s -> false); assertNotNull(uri); assertTrue(uri.contains("/place")); assertTrue(getLastElementOfURI(uri).matches(PLACE_IDENTIFIER_REGEX)); } private String getLastElementOfURI(String uri) { return uri.substring(uri.lastIndexOf("/") + 1); } }
33.910448
97
0.658891
71a84e143ffe3a47fad7c348790522d7ee4c0066
6,478
package org.intermine.web.struts; /* * Copyright (C) 2002-2021 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.intermine.api.profile.Profile; import org.intermine.api.profile.SavedQuery; import org.intermine.api.util.NameUtil; import org.intermine.template.TemplateQuery; import org.intermine.web.logic.session.SessionMethods; /** * Implementation of <strong>Action</strong> that modifies a saved query or bag. * * @author Mark Woodbridge */ public class ModifyQueryChangeAction extends InterMineDispatchAction { @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(ModifyQueryChangeAction.class); /** * Load a query. * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws * an exception */ public ActionForward load(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); Profile profile = SessionMethods.getProfile(session); String queryName = request.getParameter("name"); SavedQuery sq; if ("history".equals(request.getParameter("type"))) { sq = profile.getHistory().get(queryName); } else { sq = profile.getSavedQueries().get(queryName); } if (sq == null) { recordError(new ActionMessage("errors.query.missing", queryName), request); return mapping.findForward("mymine"); } SessionMethods.loadQuery(sq.getPathQuery(), session, response); if (sq.getPathQuery() instanceof TemplateQuery) { return new ForwardParameters(mapping.findForward("template")) .addParameter("loadModifiedTemplate", "true") .addParameter("name", sq.getName()).forward(); } return mapping.findForward("query"); } /** * Excecute a query. * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws * an exception */ public ActionForward run(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); Profile profile = SessionMethods.getProfile(session); String queryName = request.getParameter("name"); String trail = request.getParameter("trail"); SavedQuery sq; if ("history".equals(request.getParameter("type"))) { sq = profile.getHistory().get(queryName); } else { sq = profile.getSavedQueries().get(queryName); } if (sq == null) { // LOG.error("No such query " + queryName + " type=" + request.getParameter("type")); // throw new NullPointerException("No such query " + queryName + " type=" // + request.getParameter("type")); recordError(new ActionMessage("errors.query.missing", queryName), request); return mapping.findForward("mymine"); } SessionMethods.loadQuery(sq.getPathQuery(), session, response); if (StringUtils.isEmpty(trail)) { trail = "%7Cquery%7Cresults"; } return new ForwardParameters(mapping.findForward("results")) .addParameter("trail", trail) .forward(); } /** * Save a query from the history. * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws * an exception */ public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); Profile profile = SessionMethods.getProfile(session); String queryName = request.getParameter("name"); SavedQuery sq = profile.getHistory().get(queryName); if (sq == null) { recordError(new ActionMessage("errors.query.missing", queryName), request); return mapping.findForward("mymine"); } sq = SessionMethods.saveQuery(session, NameUtil.findNewQueryName(profile.getSavedQueries().keySet(), queryName), sq.getPathQuery(), sq.getDateCreated()); recordMessage(new ActionMessage("savedInSavedQueries.message", sq.getName()), request); return new ForwardParameters(mapping.findForward("mymine")) .addParameter("action", "rename") .addParameter("subtab", "saved") .addParameter("name", sq.getName()).forward(); } }
40.742138
96
0.645878
1f252ea6fabce50f8c29d053d8232be8fb5d2d7c
2,649
package co.schemati.trevor.api.network.payload; import co.schemati.trevor.api.network.event.EventProcessor; import co.schemati.trevor.api.network.event.NetworkConnectEvent; import java.util.UUID; /** * Represents the payload for a {@link co.schemati.trevor.api.data.User} connecting to the network. */ public class ConnectPayload extends OwnedPayload { private String name; private String address; /** * Constructs a new ConnectPayload. * * @deprecated see {@link #ConnectPayload(String, UUID, String, String)}. * * @param source the instance source * @param uuid the user uuid * @param address the user address */ @Deprecated protected ConnectPayload(String source, UUID uuid, String address) { super(source, uuid); this.name = null; this.address = address; } /** * Constructs a new ConnectPayload. * * @param source the instance source * @param uuid the user uuid * @param name the user name * @param address the user address */ protected ConnectPayload(String source, UUID uuid, String name, String address) { super(source, uuid); this.name = name; this.address = address; } /** * The {@link co.schemati.trevor.api.data.User}'s name. * * @return the name */ public String name() { return name; } /** * The {@link co.schemati.trevor.api.data.User}'s address. * * @return the address */ public String address() { return address; } @Override public EventProcessor.EventAction<NetworkConnectEvent> process(EventProcessor processor) { return processor.onConnect(this); } /** * Wraps the {@link ConnectPayload} constructor. * * @see ConnectPayload#ConnectPayload(String, UUID, String, String) * * @deprecated see {@link ConnectPayload#of(String, UUID, String, String)} * * @param source the instance source * @param uuid the user uuid * @param address the user address * * @return the new {@link ConnectPayload} */ @Deprecated public static ConnectPayload of(String source, UUID uuid, String address) { return new ConnectPayload(source, uuid, null, address); } /** * Wraps the {@link ConnectPayload} constructor. * * @see ConnectPayload#ConnectPayload(String, UUID, String, String) * * @param source the instance source * @param uuid the user uuid * @param name the user name * @param address the user address * * @return the new {@link ConnectPayload} */ public static ConnectPayload of(String source, UUID uuid, String name, String address) { return new ConnectPayload(source, uuid, name, address); } }
25.228571
99
0.679124
73e36cf14b4120840b5608f506605a11a584ef75
1,975
package org.oxcart.streams; import java.io.IOException; import java.io.InputStream; import java.util.Stack; /** * InputStream that merges multiple other InputStreams. * * @author ox.to.a.cart /at/ gmail.com * */ public class MergedInputStream extends InputStream { private Stack<InputStream> allStreams = new Stack<InputStream>(); private Stack<InputStream> remainingStreams = new Stack<InputStream>(); private InputStream currentStream; private int bytesRead = 0; public MergedInputStream(InputStream... originalStreams) { // Add streams to stack backwards so that we pop() them in the same order as given. for (int i = originalStreams.length - 1; i >= 0; i--) { InputStream originalStream = originalStreams[i]; allStreams.push(originalStream); remainingStreams.push(originalStream); } } @Override public int read() throws IOException { int result; while (currentStream == null || (result = currentStream.read()) == -1) { if (remainingStreams.isEmpty()) { // We're done return -1; } // Move on to next stream currentStream = remainingStreams.pop(); } bytesRead += 1; return result; } /** * Close the currentStream and all remainingStreams as necessary. If the MergedInputStream was already completely * read, then all original streams will have already been closed. */ @Override public void close() throws IOException { IOException closeException = null; for (InputStream stream : allStreams) { try { stream.close(); } catch (IOException ioe) { closeException = ioe; } } if (closeException != null) { throw closeException; } } public int getBytesRead() { return bytesRead; } }
29.477612
117
0.601519
967c0283b547e2c7f6b1c811769ffbf757d17d7f
1,360
package ex1; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; // 서블릿을 상속받는다. public class Ex1_FirstServlet extends HttpServlet { public Ex1_FirstServlet() { System.out.println("Ex1_FirstServlet 생성자 호출!"); } @Override public void init() throws ServletException { System.out.println("init 호출"); } @Override protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { super.service(arg0, arg1); // 서비스는 doget , post를 항상 호출 System.out.println("service 호출"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html; charset=UTF-8"); System.out.println("do get 호출"); // 브라우져에게 응답시켜보기 PrintWriter out = resp.getWriter(); out.println("<!Doctype html>"); out.println("<html> <head> <meta charset='UTF-8'>"); out.println("<p style='color:red' >"); out.println("한글깨짐"); out.println("</p>"); out.close(); } @Override public void destroy() { System.out.println("destroy 호출"); } } // end Ex1_FirstServlet
26.153846
113
0.735294
5c992275de76b163a0ca4fb6d8d3d4c9dcf961b9
544
package nlp.floschne.thumbnailAnnotator.db.mapper; import nlp.floschne.thumbnailAnnotator.core.domain.DomainObject; import nlp.floschne.thumbnailAnnotator.db.entity.Entity; import org.mapstruct.factory.Mappers; import java.util.List; public interface IMapper<E extends Entity, D extends DomainObject> { // IMapper INSTANCE = Mappers.getMapper(IMapper.class); E mapToEntity(D domainObject); D mapFromEntity(E entity); List<E> mapToEntityList(List<D> domainObjectList); List<D> mapFromEntityList(List<E> entityList); }
25.904762
68
0.777574
2b929633233e7f617a2cdd7fdf0b488806bdf443
2,564
package net.jplugin.extension.reqrecoder.impl; import java.util.Random; import net.jplugin.common.kits.filter.FilterChain; import net.jplugin.core.kernel.api.RefAnnotationSupport; import net.jplugin.core.log.api.Logger; import net.jplugin.ext.webasic.api.HttpFilterContext; import net.jplugin.ext.webasic.api.IHttpFilter; import net.jplugin.extension.reqrecoder.api.LogRecorder; import net.jplugin.extension.reqrecoder.kit.LogRecorderHelper; public class ReqLogFilter extends RefAnnotationSupport implements IHttpFilter{ /** * 目前不需要配置log4j,因为是从specifalLog获取的 * * <pre> * #req-log log4j.logger.ReqRecorder=INFO,ReqRecorder log4j.additivity.ReqRecorder=false log4j.appender.ReqRecorder=org.apache.log4j.RollingFileAppender log4j.appender.ReqRecorder.file=${work-dir}/logs/req-recorder.log log4j.appender.ReqRecorder.maxFileSize=20MB log4j.appender.ReqRecorder.maxBackupIndex=50 log4j.appender.ReqRecorder.Threshold=info log4j.appender.ReqRecorder.layout=org.apache.log4j.PatternLayout log4j.appender.ReqRecorder.layout.ConversionPattern=%d %m %n * </pre> */ private static Logger logger; Random rand = new Random(); public static void main(String[] args) { Random r = new Random(); for (int i=0;i<100;i++) { System.out.println(r.nextDouble()); } } @Override public Object filter(FilterChain fc, HttpFilterContext ctx) throws Throwable { //如果没有开启,直接略过 if (!LogRecorderConfig.enable) return fc.next(ctx); //判断比例,比例外直接返回 if (LogRecorderConfig.simpling!=null && rand.nextDouble()>LogRecorderConfig.simpling) { return fc.next(ctx); } //规则:没有配置则通过,如果配置了则必须匹配上才记录。 //不为null,并且没有匹配上,表示略过 if (LogRecorderConfig.urlMatcher != null && !LogRecorderConfig.urlMatcher.match(ctx.getRequest().getServletPath())) return fc.next(ctx); //记录日志 long timeStart =System.currentTimeMillis(); long timeEnd; Throwable exception=null; Object result=null; //获取信息 try { result = fc.next(ctx); }catch (Throwable e) { exception = e; }finally { timeEnd = System.currentTimeMillis(); } //判断响应时间 if (LogRecorderConfig.executeTimeBottom==null || (timeEnd-timeStart>=LogRecorderConfig.executeTimeBottom)) { //默认记录日志如果发生异常,也会影响请求!!!!! LogRecorder msg = LogRecorderHelper.me.create(ctx,exception,timeStart,timeEnd); LogRecorderConfig.reqLogHandler.doLog(msg); } if (exception !=null) { throw exception; }else { return result; } } }
26.989474
111
0.710608
a4a299b5a469ae81ff93a6a376c7a76dc8e72239
6,647
package us.ihmc.mecano.multiBodySystem; import java.util.Collections; import java.util.List; import us.ihmc.euclid.referenceFrame.ReferenceFrame; import us.ihmc.euclid.transform.RigidBodyTransform; import us.ihmc.euclid.transform.interfaces.RigidBodyTransformReadOnly; import us.ihmc.mecano.frames.MovingReferenceFrame; import us.ihmc.mecano.multiBodySystem.interfaces.FixedJointBasics; import us.ihmc.mecano.multiBodySystem.interfaces.RigidBodyBasics; import us.ihmc.mecano.spatial.SpatialAcceleration; import us.ihmc.mecano.spatial.Twist; import us.ihmc.mecano.spatial.Wrench; import us.ihmc.mecano.spatial.interfaces.SpatialAccelerationReadOnly; import us.ihmc.mecano.spatial.interfaces.TwistReadOnly; import us.ihmc.mecano.spatial.interfaces.WrenchReadOnly; import us.ihmc.mecano.tools.MecanoFactories; import us.ihmc.mecano.tools.MecanoTools; /** * A {@code FixedJoint} has no degrees of freedom, it does not move. * * @author Sylvain Bertrand */ public class FixedJoint implements FixedJointBasics { /** * The name of this joint. Each joint of a robot should have a unique name, but it is not enforced * here. */ protected final String name; /** * The identification name for this joint. It is composed of this joint name and all of its * ancestors. */ private final String nameId; /** * The {@code RigidBody} directly connected to this joint and located between this joint and the * root body of the robot. The predecessor cannot be {@code null}. */ protected final RigidBodyBasics predecessor; /** * The {@code RigidBody} directly connected to this joint and located between this joint and an * end-effector of the robot. The successor should not be {@code null}, but it is not enforced here. */ protected RigidBodyBasics successor; /** * Reference frame which origin is located at this joint's origin. */ protected final MovingReferenceFrame jointFrame; /** The twist of this joint, it is always set to zero. */ private final TwistReadOnly jointTwist; /** The spatial acceleration of this joint, it is always set to zero. */ private final SpatialAccelerationReadOnly jointAcceleration; /** The wrench of this joint, it is always set to zero. */ private WrenchReadOnly jointWrench; protected MovingReferenceFrame loopClosureFrame = null; /** * Creates a new fixed joint. * <p> * This constructor is typically used for creating a root floating joint, i.e. the first joint of * the multi-body system. * </p> * * @param name the name for the new joint. * @param predecessor the rigid-body connected to and preceding this joint. */ public FixedJoint(String name, RigidBodyBasics predecessor) { this(name, predecessor, null); } /** * Creates a new fixed joint. * * @param name the name for the new joint. * @param predecessor the rigid-body connected to and preceding this joint. * @param transformToParent the transform to the frame after the parent joint. Not modified. */ public FixedJoint(String name, RigidBodyBasics predecessor, RigidBodyTransformReadOnly transformToParent) { if (name.contains(NAME_ID_SEPARATOR)) throw new IllegalArgumentException("A joint name can not contain '" + NAME_ID_SEPARATOR + "'. Tried to construct a jonit with name " + name + "."); this.name = name; this.predecessor = predecessor; jointFrame = MecanoFactories.newJointFrame(this, transformToParent, getName() + "Frame"); if (predecessor.isRootBody()) nameId = name; else nameId = predecessor.getParentJoint().getNameId() + NAME_ID_SEPARATOR + name; predecessor.addChildJoint(this); jointTwist = new Twist(jointFrame, jointFrame, jointFrame); jointAcceleration = new SpatialAcceleration(jointFrame, jointFrame, jointFrame); } /** {@inheritDoc} */ @Override public MovingReferenceFrame getFrameBeforeJoint() { return jointFrame; } /** {@inheritDoc} */ @Override public MovingReferenceFrame getFrameAfterJoint() { return jointFrame; } /** {@inheritDoc} */ @Override public RigidBodyBasics getPredecessor() { return predecessor; } /** {@inheritDoc} */ @Override public RigidBodyBasics getSuccessor() { return successor; } /** {@inheritDoc} */ @Override public String getName() { return name; } /** {@inheritDoc} */ @Override public String getNameId() { return nameId; } /** {@inheritDoc} */ @Override public void setSuccessor(RigidBodyBasics successor) { this.successor = successor; ReferenceFrame successorFrame = successor.getBodyFixedFrame(); jointWrench = new Wrench(successorFrame, jointFrame); } @Override public void setupLoopClosure(RigidBodyBasics successor, RigidBodyTransformReadOnly transformFromSuccessorParentJoint) { RigidBodyTransform transformToSuccessorParentJoint = new RigidBodyTransform(transformFromSuccessorParentJoint); transformToSuccessorParentJoint.invert(); loopClosureFrame = MovingReferenceFrame.constructFrameFixedInParent(MecanoTools.capitalize(getName()) + "LoopClosureFrame", getFrameAfterJoint(), transformToSuccessorParentJoint); setSuccessor(successor); successor.addParentLoopClosureJoint(this); } /** {@inheritDoc} */ @Override public TwistReadOnly getJointTwist() { return jointTwist; } /** {@inheritDoc} */ @Override public SpatialAccelerationReadOnly getJointAcceleration() { return jointAcceleration; } /** {@inheritDoc} */ @Override public WrenchReadOnly getJointWrench() { return jointWrench; } /** {@inheritDoc} */ @Override public List<TwistReadOnly> getUnitTwists() { return Collections.emptyList(); } @Override public MovingReferenceFrame getLoopClosureFrame() { return loopClosureFrame; } /** * Returns the implementation name of this joint and the joint name. */ @Override public String toString() { return getClass().getSimpleName() + " " + getName(); } /** * The hash code of a joint is based on its {@link #getNameId()}. * * @return the hash code of the {@link #getNameId()} of this joint. */ @Override public int hashCode() { return nameId.hashCode(); } }
30.351598
156
0.681059
0d254ad512cafa805dee7b0c7f25d6840693ae8b
9,384
package com.sciome.bmdexpress2.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import org.ciit.io.ProjectReader; import com.fasterxml.jackson.databind.ObjectMapper; import com.sciome.bmdexpress2.mvp.model.BMDProject; import com.sciome.bmdexpress2.shared.eventbus.BMDExpressEventBus; import com.sciome.bmdexpress2.shared.eventbus.project.ShowErrorEvent; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Window; /* * A singleton to return Dialog or other types of views for quickly viewing data. */ public class DialogWithThreadProcess { Dialog<String> dialog = new Dialog<>(); Window owner; public DialogWithThreadProcess(Window owner) { this.owner = owner; } public void saveJSONProject(BMDProject bmdProject, File selectedFile) { Task task = new Task<Void>() { @Override protected Void call() throws Exception { try { saveAsJSON(bmdProject, selectedFile); } catch (IOException i) { Platform.runLater(new Runnable() { @Override public void run() { BMDExpressEventBus.getInstance() .post(new ShowErrorEvent("Error saving file. " + i.toString())); } }); i.printStackTrace(); } return null; } @Override protected void succeeded() { super.succeeded(); dialog.setResult("finished"); dialog.close(); } @Override protected void cancelled() { super.cancelled(); dialog.setResult("finished"); dialog.close(); } @Override protected void failed() { super.failed(); dialog.setResult("finished"); dialog.close(); } }; new Thread(task).start(); showWaitDialog("Save Project", "Saving Project : " + bmdProject.getName() + " to " + selectedFile.getAbsolutePath()); } public void saveProject(BMDProject bmdProject, File selectedFile) { Task task = new Task<Void>() { @Override protected Void call() throws Exception { try { FileOutputStream fileOut = new FileOutputStream(selectedFile); int bufferSize = 2000 * 1024; // make it a 2mb buffer BufferedOutputStream bout = new BufferedOutputStream(fileOut, bufferSize); ObjectOutputStream out = new ObjectOutputStream(bout); bmdProject.setName(selectedFile.getName()); out.writeObject(bmdProject); out.close(); fileOut.close(); } catch (IOException i) { Platform.runLater(new Runnable() { @Override public void run() { BMDExpressEventBus.getInstance() .post(new ShowErrorEvent("Error saving file. " + i.toString())); } }); i.printStackTrace(); } return null; } @Override protected void succeeded() { super.succeeded(); dialog.setResult("finished"); dialog.close(); } @Override protected void cancelled() { super.cancelled(); dialog.setResult("finished"); dialog.close(); } @Override protected void failed() { super.failed(); dialog.setResult("finished"); dialog.close(); } }; new Thread(task).start(); showWaitDialog("Save Project", "Saving Project : " + bmdProject.getName() + " to " + selectedFile.getAbsolutePath()); } public BMDProject loadProject(File selectedFile) { final BMDProject returnProject = null; Task task = new Task<BMDProject>() { BMDProject loadedProject = null; @Override protected BMDProject call() throws Exception { try { FileInputStream fileIn = new FileInputStream(selectedFile); BufferedInputStream bIn = new BufferedInputStream(fileIn, 1024 * 2000); ObjectInputStream in = new ObjectInputStream(bIn); loadedProject = (BMDProject) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { Platform.runLater(new Runnable() { @Override public void run() { BMDExpressEventBus.getInstance() .post(new ShowErrorEvent("Project file corrupted. " + i.toString())); } }); i.printStackTrace(); } catch (ClassNotFoundException c) { Platform.runLater(new Runnable() { @Override public void run() { BMDExpressEventBus.getInstance() .post(new ShowErrorEvent("Project file incorrect. " + c.toString())); } }); c.printStackTrace(); } return loadedProject; } @Override protected void succeeded() { super.succeeded(); dialog.setResult("finished"); dialog.close(); } @Override protected void cancelled() { super.cancelled(); dialog.setResult("finished"); dialog.close(); } @Override protected void failed() { super.failed(); dialog.setResult("finished"); dialog.close(); } }; new Thread(task).start(); showWaitDialog("Load Project", "Loading Project from " + selectedFile.getAbsolutePath()); return (BMDProject) task.getValue(); } public BMDProject addProject(File selectedFile) { Task task = new Task<BMDProject>() { BMDProject loadedProject = null; @Override protected BMDProject call() throws Exception { try { FileInputStream fileIn = new FileInputStream(selectedFile); BufferedInputStream bIn = new BufferedInputStream(fileIn, 1024 * 2000); ObjectInputStream in = new ObjectInputStream(bIn); loadedProject = (BMDProject) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { Platform.runLater(new Runnable() { @Override public void run() { BMDExpressEventBus.getInstance() .post(new ShowErrorEvent("Project file corrupted. " + i.toString())); } }); i.printStackTrace(); } catch (ClassNotFoundException c) { Platform.runLater(new Runnable() { @Override public void run() { BMDExpressEventBus.getInstance() .post(new ShowErrorEvent("Project file incorrect. " + c.toString())); } }); c.printStackTrace(); } return loadedProject; } @Override protected void succeeded() { super.succeeded(); dialog.setResult("finished"); dialog.close(); } @Override protected void cancelled() { super.cancelled(); dialog.setResult("finished"); dialog.close(); } @Override protected void failed() { super.failed(); dialog.setResult("finished"); dialog.close(); } }; new Thread(task).start(); showWaitDialog("Add Project", "Adding Project from " + selectedFile.getAbsolutePath()); return (BMDProject) task.getValue(); } /* * show a dialog with indeterminate Progress bar */ private void showWaitDialog(String titleTxt, String headerText) { dialog.setTitle(titleTxt); dialog.setHeaderText(headerText); dialog.setResizable(false); dialog.initOwner(owner); dialog.initModality(Modality.WINDOW_MODAL); ProgressBar progressBar = new ProgressBar(); progressBar.setMaxHeight(20); progressBar.setMinWidth(275); VBox vBox = new VBox(); vBox.getChildren().add(new Label("Progress")); vBox.getChildren().add(progressBar); dialog.getDialogPane().setContent(vBox); dialog.getDialogPane().setPrefSize(300, 200); dialog.getDialogPane().autosize(); dialog.showAndWait(); } public BMDProject importBMDFile(File selectedFile) { final BMDProject returnProject = null; Task task = new Task<BMDProject>() { BMDProject loadedProject = null; @Override protected BMDProject call() throws Exception { try { ProjectReader bmdProjectReader = new ProjectReader(selectedFile); bmdProjectReader.read(); ConversionUtil conversion = new ConversionUtil(); loadedProject = conversion.convertOldToNew(bmdProjectReader); } catch (Exception i) { i.printStackTrace(); } return loadedProject; } @Override protected void succeeded() { super.succeeded(); dialog.setResult("finished"); dialog.close(); } @Override protected void cancelled() { super.cancelled(); dialog.setResult("finished"); dialog.close(); } @Override protected void failed() { super.failed(); dialog.setResult("finished"); dialog.close(); } }; new Thread(task).start(); showWaitDialog("Load Project", "Loading Project from " + selectedFile.getAbsolutePath()); return (BMDProject) task.getValue(); } private void saveAsJSON(BMDProject project, File theFile) throws Exception { ObjectMapper mapper = new ObjectMapper(); /** * To make the JSON String pretty use the below code */ mapper.writerWithDefaultPrettyPrinter().writeValue(theFile, project); } public BMDProject importJSONFile(File selectedFile) throws Exception { ObjectMapper mapper = new ObjectMapper(); BMDProject projecttest = mapper.readValue(selectedFile, BMDProject.class); return projecttest; } }
21.182844
91
0.661871
b1f51819b1a702342ff980f4561d7a1eec9c923a
4,290
package net.csongradyp.badger.domain.achievement.trigger; import net.csongradyp.badger.domain.AchievementType; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class ScoreTriggerTest { @Test public void testFireReturnsTrueWhenFiredWithTriggerValue() { final ScoreTrigger trigger = new ScoreTrigger(1L); final Boolean result = trigger.fire(1L); assertThat(result, is(true)); } @Test public void testFireReturnsFalseWhenTriggeredWithDifferentValueThanTheRegisteredTrigger() { final ScoreTrigger trigger = new ScoreTrigger(1L); final Boolean result = trigger.fire(2L); assertThat(result, is(false)); } @Test public void testFireReturnsTrueWhenTriggerOperationIsGreaterThanAndFiredWithGreaterValueThanTheRegisteredTrigger() { final ScoreTrigger trigger = new ScoreTrigger(1L, ScoreTrigger.Operation.GREATER_THAN); final Boolean result = trigger.fire(10L); assertThat(result, is(true)); } @Test public void testFireReturnsTrueWhenTriggerOperationIsGreaterThanAndFiredWithTriggerValue() { final ScoreTrigger trigger = new ScoreTrigger(1L, ScoreTrigger.Operation.GREATER_THAN); final Boolean result = trigger.fire(1L); assertThat(result, is(true)); } @Test public void testFireReturnsFalseWhenTriggerOperationIsGreaterThanAndFiredWithLessValueThanTheRegisteredTrigger() { final ScoreTrigger trigger = new ScoreTrigger(1L, ScoreTrigger.Operation.GREATER_THAN); final Boolean result = trigger.fire(-1L); assertThat(result, is(false)); } @Test public void testFireReturnsTrueWhenTriggerOperationIsLessThanAndFiredWithLessValueThanTheRegisteredTrigger() { final ScoreTrigger trigger = new ScoreTrigger(1L, ScoreTrigger.Operation.LESS_THAN); final Boolean result = trigger.fire(0L); assertThat(result, is(true)); } @Test public void testFireReturnsTrueWhenTriggerOperationIsLessThanAndFiredWithTriggerValue() { final ScoreTrigger trigger = new ScoreTrigger(1L, ScoreTrigger.Operation.LESS_THAN); final Boolean result = trigger.fire(1L); assertThat(result, is(true)); } @Test public void testFireReturnsFalseWhenTriggerOperationIsLessThanAndFiredWithGreaterValueThanTheRegisteredTrigger() { final ScoreTrigger trigger = new ScoreTrigger(1L, ScoreTrigger.Operation.LESS_THAN); final Boolean result = trigger.fire(2L); assertThat(result, is(false)); } @Test public void testGetTypeReturnsScoreType() { final ScoreTrigger trigger = new ScoreTrigger(0L); assertThat(trigger.getType(), is(AchievementType.SCORE)); } @Test public void testGetTriggerReturnsRegisteredTrigger() throws Exception { final ScoreTrigger trigger = new ScoreTrigger(100L); assertThat(trigger.getTrigger(), is(100L)); } @Test public void testGetOperation() { final ScoreTrigger triggerEqual = new ScoreTrigger(100L); assertThat(triggerEqual.getOperation(), is(ScoreTrigger.Operation.EQUALS)); final ScoreTrigger triggerGreater = new ScoreTrigger(100L, ScoreTrigger.Operation.GREATER_THAN); assertThat(triggerGreater.getOperation(), is(ScoreTrigger.Operation.GREATER_THAN)); final ScoreTrigger triggerLess = new ScoreTrigger(100L, ScoreTrigger.Operation.LESS_THAN); assertThat(triggerLess.getOperation(), is(ScoreTrigger.Operation.LESS_THAN)); } @Test public void testParseOperation() { final ScoreTrigger.Operation equalTo = ScoreTrigger.Operation.parse(""); final ScoreTrigger.Operation greaterThan = ScoreTrigger.Operation.parse("+"); final ScoreTrigger.Operation lessThan = ScoreTrigger.Operation.parse("-"); assertThat(equalTo, is(ScoreTrigger.Operation.EQUALS)); assertThat(greaterThan, is(ScoreTrigger.Operation.GREATER_THAN)); assertThat(lessThan, is(ScoreTrigger.Operation.LESS_THAN)); } @Test(expected = IllegalArgumentException.class) public void testParseOperationThrowsExceptionWhenInvalidOperatorStringIsGiven() { ScoreTrigger.Operation.parse("#"); } }
40.857143
120
0.7331
13b0dcaf387a5d1ccd088a971dcad03e5a5ed154
1,428
package com.stonks.android.utility; import com.github.mikephil.charting.data.Entry; import com.stonks.android.model.BarData; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class SimpleMovingAverage { final List<Entry> movingAverage; final LinkedList<BarData> chartData; int size; float sum; public SimpleMovingAverage(int size) { this.movingAverage = new ArrayList<>(); this.chartData = new LinkedList<>(); this.size = Math.max(size, 1); this.sum = 0f; } public void setData(List<BarData> barData) { this.movingAverage.clear(); this.chartData.clear(); this.sum = 0f; for (int i = 0; i < barData.size(); ++i) { this.add(barData.get(i), i); } } public void setData(List<BarData> barData, int size) { this.size = Math.max(size, 1); this.setData(barData); } void add(BarData bar, int index) { sum += bar.getOpen(); chartData.offer(bar); if (index < size) { movingAverage.add(new Entry(chartData.size(), sum / chartData.size())); return; } sum -= chartData.poll().getOpen(); movingAverage.add(new Entry(index, sum / size)); } public List<Entry> getMovingAverage() { return movingAverage; } public int getSize() { return size; } }
24.62069
83
0.596639
da0198e3ef8c5f3b624c132fd5f9f8941620f72a
2,649
package com.github.braisdom.objsql; import com.github.braisdom.objsql.transition.ColumnTransition; import java.sql.Statement; import java.util.Optional; /** * Describes the Java Bean which maps a row in the table, and behaviors * for Java Bean mapping.<br/> * * By default, a row of table will be adapted into an instance of Java Bean, if you need * different rule of mapping, you can implement it for querying and persistence. * * @see Query * @see Persistence * @see AbstractQuery#AbstractQuery(DomainModelDescriptor) * @see AbstractPersistence#AbstractPersistence(DomainModelDescriptor) * * @author braisdom */ public interface TableRowAdapter<T> { /** * Returns a table name which associates Java Bean * @return table name */ String getTableName(); /** * Returns a Java class which associates table * @return */ Class getDomainModelClass(); /** * Creates an instance of associated Java class * @return */ T newInstance(); /** * Set a primary key generated by database. Notice: not all databases support generated keys. * @param bean * @param primaryKeyValue * * @see Statement#getGeneratedKeys() */ default void setGeneratedKey(T bean, Object primaryKeyValue) { throw new UnsupportedOperationException("The setGeneratedKey is unsupported"); } /** * Returns field name by given column name * @param columnName * @return */ String getFieldName(String columnName); default Optional<String> getFieldDefaultValue(String fieldName) { throw new UnsupportedOperationException("The getFieldDefaultValue is unsupported"); } default boolean hasDefaultValue(String fieldName) { throw new UnsupportedOperationException("The hasDefaultValue is unsupported"); } default FieldValue getFieldValue(Object bean, String fieldName) { throw new UnsupportedOperationException("The getFieldValue is unsupported"); } default Class getFieldType(String fieldName) { throw new UnsupportedOperationException("The getFieldType is unsupported"); } default boolean isTransitable(String fieldName) { throw new UnsupportedOperationException("The isTransitable is unsupported"); } default ColumnTransition getColumnTransition(String fieldName) { throw new UnsupportedOperationException("The getColumnTransition is unsupported"); } default void setFieldValue(T modelObject, String fieldName, Object fieldValue) { throw new UnsupportedOperationException("The setFieldValue is unsupported"); } }
30.102273
97
0.711212
258f1da40d54d40e20884bad826b4e4c47d72dd1
2,416
/* * This file is part of ilo. It is subject to the license terms in the LICENSE file found in the top-level * directory of this distribution and at http://creativecommons.org/publicdomain/zero/1.0/. No part of ilo, * including this file, may be copied, modified, propagated, or distributed except according to the terms contained * in the LICENSE file. */ package wtf.metio.ilo.tools; import wtf.metio.ilo.compose.ComposeCLI; import wtf.metio.ilo.compose.ComposeOptions; import wtf.metio.ilo.os.OSSupport; import java.util.List; import static java.util.stream.Stream.of; import static wtf.metio.ilo.utils.Streams.*; abstract class DockerComposePodmanCompose implements ComposeCLI { @Override public final List<String> pullArguments(final ComposeOptions options) { if (options.pull) { return flatten( of(name()), fromList(OSSupport.expand(options.runtimeOptions)), withPrefix("--file", OSSupport.expand(options.file)), of("pull"), fromList(OSSupport.expand(options.runtimePullOptions))); } return List.of(); } @Override public final List<String> buildArguments(final ComposeOptions options) { if (options.build) { return flatten( of(name()), fromList(OSSupport.expand(options.runtimeOptions)), withPrefix("--file", OSSupport.expand(options.file)), of("build"), fromList(OSSupport.expand(options.runtimeBuildOptions))); } return List.of(); } @Override public final List<String> runArguments(final ComposeOptions options) { return flatten( of(name()), fromList(OSSupport.expand(options.runtimeOptions)), withPrefix("--file", OSSupport.expand(options.file)), of("run"), fromList(OSSupport.expand(options.runtimeRunOptions)), maybe(!options.interactive, "-T"), of(OSSupport.expand(options.service)), fromList(OSSupport.expand(options.arguments))); } @Override public final List<String> cleanupArguments(final ComposeOptions options) { // docker-compose needs an additional cleanup even when using 'run --rm' // see https://github.com/docker/compose/issues/2791 return flatten( of(name()), fromList(OSSupport.expand(options.runtimeOptions)), withPrefix("--file", OSSupport.expand(options.file)), of("down"), fromList(OSSupport.expand(options.runtimeCleanupOptions))); } }
33.09589
115
0.698675
4014a64ab9ef4024d15132c0ee35321b7d60c2cb
2,976
package edu.cmu.minorthird; import edu.cmu.minorthird.ui.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /** * A launch bar for Minorthird applications. */ public class Minorthird extends JFrame { static final long serialVersionUID=20071015; private String[] defaultArgs; public Minorthird(String[] args) { super(); // copy the args, adding 'gui' defaultArgs = new String[args.length+1]; defaultArgs[0] = "-gui"; for (int i=0; i<args.length; i++) { defaultArgs[i+1] = args[i]; } // build the content panel initContent(); // pop the launcher window setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); pack(); setVisible(true); } private void initContent() { JPanel panel = new JPanel(); panel.setLayout(new GridLayout(2,2)); panel.setBorder(new TitledBorder("Applications to Launch")); JPanel tcPanel = new JPanel(); tcPanel.setBorder(new TitledBorder("Classify Text")); addUIButton(tcPanel,"Expt", new TrainTestClassifier()); addUIButton(tcPanel,"Train", new TrainClassifier()); addUIButton(tcPanel,"Test", new TestClassifier()); panel.add(tcPanel); JPanel txPanel = new JPanel(); txPanel.setBorder(new TitledBorder("Extract From Text")); addUIButton(txPanel,"Expt", new TrainTestExtractor()); addUIButton(txPanel,"Train", new TrainExtractor()); addUIButton(txPanel,"Test", new TestExtractor()); panel.add(txPanel); JPanel cPanel = new JPanel(); cPanel.setBorder(new TitledBorder("Non-Text Data")); cPanel.add(new JButton(new AbstractAction("Expt/Train/Test") { static final long serialVersionUID=20071015; @Override public void actionPerformed(ActionEvent ev) { new edu.cmu.minorthird.classify.UI.DataClassificationTask().callMain(defaultArgs); } })); panel.add(cPanel); JPanel oPanel = new JPanel(); oPanel.setBorder(new TitledBorder("Execute")); addUIButton(oPanel,"Mixup",new RunMixup()); addUIButton(oPanel,"Annotator",new ApplyAnnotator()); panel.add(oPanel); //addHelpPane(panel); panel.setPreferredSize(new java.awt.Dimension(800,200)); getContentPane().removeAll(); getContentPane().add(panel, BorderLayout.CENTER); setTitle("Minorthird LaunchPad"); panel.revalidate(); } private void addUIButton(final JPanel panel,final String tag,final UIMain m) { panel.add(new JButton(new AbstractAction(tag) { static final long serialVersionUID=20071015; @Override public void actionPerformed(ActionEvent ev) { m.callMain(defaultArgs); } })); } /* private void addHelpPane(JPanel panel) { JEditorPane editorPane = new JEditorPane(); editorPane.setEditable(false); try { java.net.URL helpURL = new java.net.URL("http://wcohen.com/index.html"); editorPane.setPage(helpURL); } catch (Exception e) { e.printStackTrace(); } panel.add(new JScrollPane(editorPane)); } */ static public void main(String[] args) { new Minorthird(args); } }
25.878261
86
0.712366
e35d6c2a6e447e093bf33bbe80cd88de74a7a430
502
package org.vibioh.ioc.impl; import org.vibioh.ioc.Writer; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; public class SquareWriter implements Writer<Object> { private OutputStream out; public SquareWriter(final OutputStream out) { this.out = out; } public void write(final Object inverseValue) throws IOException { out.write(("Square: " + String.valueOf(inverseValue)).getBytes(StandardCharsets.UTF_8)); } }
25.1
96
0.733068
97e7601b67ca46b117b1e5ea57fb506b57258687
12,060
package com.github.technus.tectech.thing.metaTileEntity.single.gui; import com.github.technus.tectech.Util; import com.github.technus.tectech.thing.metaTileEntity.single.GT_MetaTileEntity_DataReader; import gregtech.api.gui.GT_GUIContainerMetaTile_Machine; import gregtech.api.gui.GT_Slot_Holo; import gregtech.api.interfaces.tileentity.IGregTechTileEntity; import gregtech.api.util.GT_Utility; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import java.util.ArrayList; import java.util.List; public class GT_GUIContainer_DataReader extends GT_GUIContainerMetaTile_Machine { public final String mName; public final String mNEI; public final byte mProgressBarDirection; public final byte mProgressBarAmount; private ItemStack stack=null; public GT_GUIContainer_DataReader(InventoryPlayer aInventoryPlayer, IGregTechTileEntity aTileEntity, String aName, String aTextureFile, String aNEI) { this(aInventoryPlayer, aTileEntity, aName, aTextureFile, aNEI, (byte) 0, (byte) 1); } public GT_GUIContainer_DataReader(InventoryPlayer aInventoryPlayer, IGregTechTileEntity aTileEntity, String aName, String aTextureFile, String aNEI, byte aProgressBarDirection, byte aProgressBarAmount) { super(new GT_Container_DataReader(aInventoryPlayer, aTileEntity), "gregtech:textures/gui/basicmachines/" + aTextureFile); this.mProgressBarDirection = aProgressBarDirection; this.mProgressBarAmount = (byte) Math.max(1, aProgressBarAmount); this.mName = aName; this.mNEI = aNEI; ySize = 256; } @Override public void drawScreen(int mouseX, int mouseY, float par3) { super.drawScreen(mouseX, mouseY, par3); if (mContainer != null) { if (mContainer.mTileEntity != null && mContainer.mTileEntity.getMetaTileEntity() instanceof GT_MetaTileEntity_DataReader) { GT_MetaTileEntity_DataReader reader = (GT_MetaTileEntity_DataReader) mContainer.mTileEntity.getMetaTileEntity(); renderDataTooltips(mouseX,mouseY,reader.mTier); } } } protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { if (mContainer != null) { if (mContainer.mTileEntity != null && mContainer.mTileEntity.getMetaTileEntity() instanceof GT_MetaTileEntity_DataReader) { GT_MetaTileEntity_DataReader reader = (GT_MetaTileEntity_DataReader) mContainer.mTileEntity.getMetaTileEntity(); if (renderDataFG(mouseX, mouseY, reader.mTier)) { return; } } } fontRendererObj.drawString(mName, 7, 8, 0xfafaff); } protected void drawGuiContainerBackgroundLayer(float par1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(par1, mouseX, mouseY); int x = (this.width - this.xSize) / 2; int y = (this.height - this.ySize) / 2; this.drawTexturedModalRect(x, y, 0, 0, this.xSize, this.ySize); if (this.mContainer != null) { if (((GT_Container_DataReader) this.mContainer).mStuttering) { this.drawTexturedModalRect(x + 127, y + 152, 176, 54, 18, 18); } if (this.mContainer.mMaxProgressTime > 0) { int tSize = this.mProgressBarDirection < 2 ? 20 : 18; int tProgress = Math.max(1, Math.min(tSize * this.mProgressBarAmount, (this.mContainer.mProgressTime > 0 ? 1 : 0) + this.mContainer.mProgressTime * tSize * this.mProgressBarAmount / this.mContainer.mMaxProgressTime)) % (tSize + 1); switch (this.mProgressBarDirection) { case 0: this.drawTexturedModalRect(x + 78, y + 152, 176, 0, tProgress, 18); break; case 1: this.drawTexturedModalRect(x + 78 + 20 - tProgress, y + 152, 196 - tProgress, 0, tProgress, 18); break; case 2: this.drawTexturedModalRect(x + 78, y + 152, 176, 0, 20, tProgress); break; case 3: this.drawTexturedModalRect(x + 78, y + 152 + 18 - tProgress, 176, 18 - tProgress, 20, tProgress); break; case 4: tProgress = 20 - tProgress; this.drawTexturedModalRect(x + 78, y + 152, 176, 0, tProgress, 18); break; case 5: tProgress = 20 - tProgress; this.drawTexturedModalRect(x + 78 + 20 - tProgress, y + 152, 196 - tProgress, 0, tProgress, 18); break; case 6: tProgress = 18 - tProgress; this.drawTexturedModalRect(x + 78, y + 152, 176, 0, 20, tProgress); break; case 7: tProgress = 18 - tProgress; this.drawTexturedModalRect(x + 78, y + 152 + 18 - tProgress, 176, 18 - tProgress, 20, tProgress); } } } if (mContainer != null) { if (mContainer.mTileEntity != null && mContainer.mTileEntity.getMetaTileEntity() instanceof GT_MetaTileEntity_DataReader) { GT_MetaTileEntity_DataReader reader = (GT_MetaTileEntity_DataReader) mContainer.mTileEntity.getMetaTileEntity(); renderDataBG(reader.getStackInSlot(reader.getOutputSlot()), mouseX, mouseY, x, y, reader.mTier); } } } private void renderDataBG(ItemStack thing, int mouseX, int mouseY, int x, int y, byte mTier) { if (thing != null) { ArrayList<GT_MetaTileEntity_DataReader.DataRender> renders = GT_MetaTileEntity_DataReader.getRenders(new Util.TT_ItemStack(thing)); for (GT_MetaTileEntity_DataReader.DataRender render : renders) { if (render.canRender(thing, mTier)) { if (!GT_Utility.areStacksEqual(stack, thing, false)) { render.initRender(thing); } render.renderBackgroundOverlay(thing, mouseX, mouseY, x, y, this); break; } } } stack=thing; } private boolean renderDataFG(int mouseX, int mouseY, byte mTier) { if(stack==null){ return false; } ArrayList<GT_MetaTileEntity_DataReader.DataRender> renders = GT_MetaTileEntity_DataReader.getRenders(new Util.TT_ItemStack(stack)); for (GT_MetaTileEntity_DataReader.DataRender render : renders) { if (render.canRender(stack, mTier)) { render.renderForeground(stack, mouseX, mouseY, this, fontRendererObj); return true; } } return false; } private boolean renderDataTooltips(int mouseX, int mouseY, byte mTier) { if(stack==null){ return false; } ArrayList<GT_MetaTileEntity_DataReader.DataRender> renders = GT_MetaTileEntity_DataReader.getRenders(new Util.TT_ItemStack(stack)); for (GT_MetaTileEntity_DataReader.DataRender render : renders) { if (render.canRender(stack, mTier)) { render.renderTooltips(stack, mouseX, mouseY, this); return true; } } return false; } public void renderItemSimple(GT_Slot_Holo slot, ItemStack itemStack) { int x = slot.xDisplayPosition; int y = slot.yDisplayPosition; this.zLevel = 100.0F; itemRender.zLevel = 100.0F; if (itemStack == null) { IIcon iicon = slot.getBackgroundIconIndex(); if (iicon != null) { GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_BLEND); // Forge: Blending needs to be enabled for this. this.mc.getTextureManager().bindTexture(TextureMap.locationItemsTexture); this.drawTexturedModelRectFromIcon(x, y, iicon, 16, 16); GL11.glDisable(GL11.GL_BLEND); // Forge: And clean that up GL11.glEnable(GL11.GL_LIGHTING); } } GL11.glEnable(GL11.GL_DEPTH_TEST); itemRender.renderItemAndEffectIntoGUI(this.fontRendererObj, this.mc.getTextureManager(), itemStack, x, y); itemRender.renderItemOverlayIntoGUI(this.fontRendererObj, this.mc.getTextureManager(), itemStack, x, y); itemRender.zLevel = 0.0F; this.zLevel = 0.0F; } public void renderTooltipSimple(int mouseX, int mouseY, GT_Slot_Holo slot, ItemStack itemStack) { int x = slot.xDisplayPosition + (width - xSize) / 2; int y = slot.yDisplayPosition + (height - ySize) / 2; if (mouseX >= x && mouseY >= y && mouseX <= x+16 && mouseY <= y+16 ) { List strings=itemStack.getTooltip(Minecraft.getMinecraft().thePlayer, false); if(strings.size()>0){ strings.set(0,itemStack.getRarity().rarityColor+(String)strings.get(0)); } hoveringText(strings, mouseX, mouseY, fontRendererObj); } } private void hoveringText(List strings, int x, int y, FontRenderer font) { if (!strings.isEmpty()) { GL11.glDisable(GL12.GL_RESCALE_NORMAL); //RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_DEPTH_TEST); int k = 0; for (Object aP_146283_1_ : strings) { String s = (String) aP_146283_1_; int l = font.getStringWidth(s); if (l > k) { k = l; } } int x2 = x + 12; int y2 = y - 12; int i1 = 8; if (strings.size() > 1) { i1 += 2 + (strings.size() - 1) * 10; } if (x2 + k > this.width) { x2 -= 28 + k; } if (y2 + i1 + 6 > this.height) { y2 = this.height - i1 - 6; } //this.zLevel = 300.0F; //itemRender.zLevel = 300.0F; int j1 = 0xf0001040;//bg this.drawGradientRect(x2 - 3, y2 - 4, x2 + k + 3, y2 - 3, j1, j1); this.drawGradientRect(x2 - 3, y2 + i1 + 3, x2 + k + 3, y2 + i1 + 4, j1, j1); this.drawGradientRect(x2 - 3, y2 - 3, x2 + k + 3, y2 + i1 + 3, j1, j1); this.drawGradientRect(x2 - 4, y2 - 3, x2 - 3, y2 + i1 + 3, j1, j1); this.drawGradientRect(x2 + k + 3, y2 - 3, x2 + k + 4, y2 + i1 + 3, j1, j1); int k1 = 0x500040ff;//border bright int l1 = (k1 & 0xfefefe) >> 1 | k1 & 0xff000000;//border dark??? this.drawGradientRect(x2 - 3, y2 - 3 + 1, x2 - 3 + 1, y2 + i1 + 3 - 1, k1, l1); this.drawGradientRect(x2 + k + 2, y2 - 3 + 1, x2 + k + 3, y2 + i1 + 3 - 1, k1, l1); this.drawGradientRect(x2 - 3, y2 - 3, x2 + k + 3, y2 - 3 + 1, k1, k1); this.drawGradientRect(x2 - 3, y2 + i1 + 2, x2 + k + 3, y2 + i1 + 3, l1, l1); for (int i2 = 0; i2 < strings.size(); ++i2) { String s1 = (String) strings.get(i2); font.drawStringWithShadow(s1, x2, y2, -1); if (i2 == 0) { y2 += 2; } y2 += 10; } //this.zLevel = 0.0F; //itemRender.zLevel = 0.0F; GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_DEPTH_TEST); //RenderHelper.enableStandardItemLighting(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); } } }
45.338346
247
0.580348
42321729e7e1d22e81af7833368f07943cb36083
300
package io.github.yexiaoxiaogo.DAOSelect; /** * Hello world! * */ public class App { public static void main( String[] args ) { WebsitesDao websitesDao = new WebsitesDaoLmpl(); Websites websites =websitesDao.getWebsites(1); System.out.println(websites.getName()); } }
18.75
53
0.666667
a2b6e67becb7abd69bd562dbc7512fd518167e9c
30,973
package eu.larkc.csparql.core.imis.tests; import eu.larkc.csparql.core.imis.models.*; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.sparql.core.Var; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.Serializer; import java.io.File; import java.util.*; public class QueryTests { public static HashMap<QueryPattern, HashSet<ArrayList<ECSTuple>>> queryAnswerListSet2 ; public static HashSet<ExtendedCharacteristicSet> visited = new HashSet<ExtendedCharacteristicSet>(); static public HashMap<Node, Integer> varMap = new HashMap<Node, Integer>(); static public HashMap<Integer, Node> reverseVarMap = new HashMap<Integer, Node>(); public static Map<String, Integer> propertiesSet ; public static int nextVar = -1; public static Map<Integer, HashMap<Integer, Integer>> propIndexMap ; public static Map<ExtendedCharacteristicSet, Integer> ecsIntegerMap ; public static HashMap<Node, Integer> varIndexMap; public static Map<Integer, long[]> ecsLongArrayMap ; public static Map<Integer, long[]> csMap ; public static Map<Integer, CharacteristicSet> rucs ; public static Map<CharacteristicSet, Integer> ucs ; public static Map<String, Integer> intMap ; public static Map<Integer, String> reverseIntMap ; public static Map<String, Integer> prefixMap ; public static void main(String[] args) { //DB db = DBMaker.newFileDB(new File("C:/temp/tempor.bin")) //args[0] = "C:/temp/temp" ; DB db = DBMaker.newFileDB(new File("/Users/yangfanyu/IdeaProjects/csparql_spark/csparql-core/src/main/java/eu/larkc/csparql/core/imis/tests/mapdb")) //DB db = DBMaker.newFileDB(new File(args[0])) .transactionDisable() .fileChannelEnable() .fileMmapEnable() .cacheSize(1000000000) .closeOnJvmShutdown() .make(); ecsLongArrayMap = db.hashMapCreate("ecsLongArrays") .keySerializer(Serializer.INTEGER) .valueSerializer(Serializer.LONG_ARRAY) .makeOrGet(); prefixMap = db.hashMapCreate("prefixMap") .keySerializer(Serializer.STRING) .valueSerializer(Serializer.INTEGER) .makeOrGet(); Map<Integer, ExtendedCharacteristicSet> ruecs = db.hashMapCreate("ruecsMap") .keySerializer(Serializer.INTEGER) //.valueSerializer(Serializer.) .makeOrGet(); intMap = db.hashMapCreate("intMap") .keySerializer(Serializer.STRING) .valueSerializer(Serializer.INTEGER) .makeOrGet(); reverseIntMap = db.hashMapCreate("reverseIntMap") .keySerializer(Serializer.INTEGER) .valueSerializer(Serializer.STRING) .makeOrGet(); csMap = db.hashMapCreate("csMap") .keySerializer(Serializer.INTEGER) .valueSerializer(Serializer.LONG_ARRAY) .makeOrGet(); /*int totalInCS = 0; long one = 0 ; for(Integer c : csMap.keySet()){ totalInCS += csMap.get(c).length; one = csMap.get(c)[csMap.get(c).length/5]; break; } for(Integer e : ecsLongArrayMap.keySet()){ long[] dff = ecsLongArrayMap.get(e); if(indexOfTriple(dff, one)>=0) System.out.println("found"); }*/ rucs = db.hashMapCreate("rucsMap") .keySerializer(Serializer.INTEGER) //.valueSerializer(Serializer.) .makeOrGet(); ucs = new HashMap<CharacteristicSet, Integer>(); for(Integer ci : rucs.keySet()){ ucs.put(rucs.get(ci), ci); } ecsIntegerMap = db.hashMapCreate("uecsMap") .valueSerializer(Serializer.INTEGER) //.valueSerializer(Serializer.) .makeOrGet(); Map<ExtendedCharacteristicSet, HashSet<ExtendedCharacteristicSet>> ecsLinks = db.hashMapCreate("ecsLinks") //.keySerializer(Serializer.INTEGER) .makeOrGet(); int tot = 0; for(Integer ecs : ruecs.keySet()){ tot += ecsLongArrayMap.get(ecs).length; } System.out.println("total mapped triples: " + tot); tot = 0; for(ExtendedCharacteristicSet e : ecsLinks.keySet()){ tot += ecsLinks.get(e).size(); } System.out.println("total ecs links: " + tot); System.out.println("ECS Links size: " + ecsLinks.size()); Map<Integer, int[]> properIndexMap = db.hashMapCreate("propIndexMap") .keySerializer(Serializer.INTEGER) .valueSerializer(Serializer.INT_ARRAY) .makeOrGet(); propIndexMap = new HashMap<Integer, HashMap<Integer, Integer>>(); for(Integer e : properIndexMap.keySet()){ HashMap<Integer, Integer> d = propIndexMap.getOrDefault(e, new HashMap<Integer, Integer>()); for(int i = 0; i < properIndexMap.get(e).length; i++){ if(properIndexMap.get(e)[i] >= 0){ d.put(i, properIndexMap.get(e)[i]); } } propIndexMap.put(e, d); } propertiesSet = db.hashMapCreate("propertiesSet") .keySerializer(Serializer.STRING) .valueSerializer(Serializer.INTEGER) .makeOrGet(); /*for(String prr : propertiesSet.keySet()){ System.out.println(prr); }*/ //APO EDW ARXIZEI TO PANHGYRI HashMap<ExtendedCharacteristicSet, HashSet<Vector<ExtendedCharacteristicSet>>> ecsVectorMap = new HashMap<ExtendedCharacteristicSet, HashSet<Vector<ExtendedCharacteristicSet>>>(); HashSet<Vector<ExtendedCharacteristicSet>> ecsVectors = new HashSet<Vector<ExtendedCharacteristicSet>>(); for(ExtendedCharacteristicSet ecs : ecsLinks.keySet()){ HashSet<ExtendedCharacteristicSet> visited = new HashSet<ExtendedCharacteristicSet>(); Stack<Vector<ExtendedCharacteristicSet>> stack = new Stack<>(); Vector<ExtendedCharacteristicSet> v = new Vector<ExtendedCharacteristicSet>(); v.add(ecs); stack.push(v); while(!stack.empty()){ v = stack.pop(); ExtendedCharacteristicSet current = v.lastElement(); visited.add(current); if(!ecsLinks.containsKey(current)){ if(ecsVectorMap.containsKey(current)) ecsVectorMap.get(current).add(v); else{ HashSet<Vector<ExtendedCharacteristicSet>> d = new HashSet<Vector<ExtendedCharacteristicSet>>(); d.add(v); ecsVectorMap.put(current, d); } ecsVectors.add(v); continue; } for(ExtendedCharacteristicSet child : ecsLinks.get(current)){ if(!visited.contains(child)){ Vector<ExtendedCharacteristicSet> _v = new Vector<ExtendedCharacteristicSet>(); _v.addAll(v); _v.add(child); stack.push(_v); } } } } System.out.println("total patterns: " + ecsVectors.size()); String queryString; Queries lubm = new Queries(); ArrayList<Long> times; for(String qs : lubm.getQueries(1)){ try{ queryString = qs; //queryString = lubm.q2; times = new ArrayList<Long>(); System.out.println(queryString); Query q=QueryFactory.create(queryString); List<Var> projectVariables = q.getProjectVars(); long tstart = System.nanoTime(); int totalresults = 0; long tend ; ECSQuery ecsq = new ECSQuery(q); ecsq.findJoins(); //ECSTree queryTree = ecsq.getEcsTree(); HashSet<LinkedHashSet<ExtendedCharacteristicSet>> queryListSet = ECSQuery.getListSet(); queryAnswerListSet2 = new HashMap<QueryPattern, HashSet<ArrayList<ECSTuple>>>(); for(LinkedHashSet<ExtendedCharacteristicSet> thisQueryList : queryListSet){ ArrayList<ExtendedCharacteristicSet> qlist = new ArrayList<>(thisQueryList); ArrayList<ECSTuple> qlistTuple = new ArrayList<ECSTuple>(); for(ExtendedCharacteristicSet qe : qlist){ String pr = qe.predicate.getURI(); /*if(pr.contains("swat")) pr = pr.replaceAll("#", "##");*/ ECSTuple nt = new ECSTuple(qe, propertiesSet.get(pr), getQueryTriplePattern(qe)); nt.subjectBinds = qe.subjectBinds; nt.objectBinds = qe.objectBinds; qlistTuple.add(nt); } boolean fl = false; for(ExtendedCharacteristicSet ecs1 : ecsLinks.keySet()){ visited = new HashSet<ExtendedCharacteristicSet>(); if(findDataPatterns(ecs1, ecsLinks, qlistTuple, qlistTuple, new ArrayList<ECSTuple>())){ fl = true; } } } System.out.println("size of query patterns " + queryAnswerListSet2.size()); varIndexMap = new HashMap<Node, Integer>(); int varIndex = 0; for(QueryPattern key : queryAnswerListSet2.keySet()){ for(ArrayList<ECSTuple> dataPattern : queryAnswerListSet2.get(key)){ for(ECSTuple ecsTuple : dataPattern){ TripleAsInt tai = ecsTuple.triplePattern; /*if(!outerBindings.containsKey(reverseVarMap.get(tai.s))) outerBindings.put(reverseVarMap.get(tai.s), new HashSet<Long>()); if(!outerBindings.containsKey(reverseVarMap.get(tai.o))) outerBindings.put(reverseVarMap.get(tai.o), new HashSet<Long>());*/ if(!varIndexMap.containsKey(reverseVarMap.get(tai.s))) varIndexMap.put(reverseVarMap.get(tai.s), varIndex++); if(!varIndexMap.containsKey(reverseVarMap.get(tai.o))) varIndexMap.put(reverseVarMap.get(tai.o), varIndex++); } } } HashMap<ArrayList<ExtendedCharacteristicSet>, HashSet<Integer>> qpVarMap = new HashMap<ArrayList<ExtendedCharacteristicSet>, HashSet<Integer>>(); HashMap<ArrayList<ECSTuple>, HashSet<Integer>> qpVarMap2 = new HashMap<ArrayList<ECSTuple>, HashSet<Integer>>(); //HashMap<ArrayList<ExtendedCharacteristicSet>, HashSet<ArrayList<ExtendedCharacteristicSet>>> skipping = new HashMap<ArrayList<ExtendedCharacteristicSet>, HashSet<ArrayList<ExtendedCharacteristicSet>>>(); HashMap<QueryPattern, HashSet<ArrayList<ExtendedCharacteristicSet>>> skipping = new HashMap<QueryPattern, HashSet<ArrayList<ExtendedCharacteristicSet>>>(); HashMap<QueryPattern, HashSet<ArrayList<ECSTuple>>> skipping2 = new HashMap<QueryPattern, HashSet<ArrayList<ECSTuple>>>(); for(QueryPattern queryPattern : queryAnswerListSet2.keySet()){ int count = 0; skipping.put(queryPattern, new HashSet<ArrayList<ExtendedCharacteristicSet>>()); skipping2.put(queryPattern, new HashSet<ArrayList<ECSTuple>>()); for(ArrayList<ECSTuple> dataPattern : queryAnswerListSet2.get(queryPattern)){ if(dataPattern.size() > 1){ //System.out.println("data pattern: " + dataPattern.toString()); boolean cont = false; ArrayList<ExtendedCharacteristicSet> dataPatECS = new ArrayList<ExtendedCharacteristicSet>(); for(ECSTuple et : dataPattern) dataPatECS.add(et.ecs); for(Vector<ExtendedCharacteristicSet> vector : ecsVectors){ if(vector.containsAll(dataPatECS)){ cont = true; break; } } if(!cont){ count++; skipping.get(queryPattern).add(dataPatECS); skipping2.get(queryPattern).add(dataPattern); } } HashSet<Integer> vars = new HashSet<Integer>(); for(ECSTuple et : dataPattern){ TripleAsInt tai = et.triplePattern; //if(reverseVarMap.get(tai.s).isVariable()){ if(tai.s < 0){ vars.add(varIndexMap.get(reverseVarMap.get(tai.s))); } if(tai.o < 0){ vars.add(varIndexMap.get(reverseVarMap.get(tai.o))); } } qpVarMap2.put(dataPattern, vars); qpVarMap2.put(queryPattern.queryPattern, vars); } System.out.println("not contains all: " + count); System.out.println("from total: " + queryAnswerListSet2.get(queryPattern).size()); } for(int i = 0; i < 10; i++){ ArrayList<QueryPattern> f = new ArrayList<>(queryAnswerListSet2.keySet()); Collections.sort(f, new BigQueryTests.ECSTupleComparator()); HashMap<QueryPattern, HashMap<ECSTuple, AnswerPattern>> qans = new HashMap<QueryPattern, HashMap<ECSTuple, AnswerPattern>>(); HashMap<QueryPattern, HashMap<ECSTuple, AnswerPattern>> qansReverse = new HashMap<QueryPattern, HashMap<ECSTuple, AnswerPattern>>(); for(QueryPattern queryPattern : f){ qans.put(queryPattern, new HashMap<ECSTuple, AnswerPattern>()); qansReverse.put(queryPattern, new HashMap<ECSTuple, AnswerPattern>()); if(queryPattern.queryPattern.size() == 1 ) { for(ArrayList<ECSTuple> dataPattern1 : queryAnswerListSet2.get(queryPattern)){ AnswerPattern ans = new AnswerPattern(dataPattern1.get(0), queryPattern); if(qans.get(queryPattern).containsKey(ans.root)){ ans = qans.get(queryPattern).get(ans.root); } qans.get(queryPattern).put(ans.root, ans); qansReverse.get(queryPattern).put(ans.root, ans); } continue; } for(ArrayList<ECSTuple> dataPattern1 : queryAnswerListSet2.get(queryPattern)){ for(int i1 = 0 ; i1 < dataPattern1.size()-1; i1++){ AnswerPattern ans = new AnswerPattern(dataPattern1.get(i1), queryPattern); if(qans.get(queryPattern).containsKey(ans.root)){ ans = qans.get(queryPattern).get(ans.root); } AnswerPattern nextAns = new AnswerPattern(dataPattern1.get(i1+1), queryPattern); if(qans.get(queryPattern).containsKey(nextAns.root)){ nextAns = qans.get(queryPattern).get(nextAns.root); } ans.addChild(nextAns); qans.get(queryPattern).put(ans.root, ans); //qans.get(queryPattern).put(nextAns.root, nextAns); } for(int i1 = dataPattern1.size()-1 ; i1 >= 1; i1--){ AnswerPattern ans = new AnswerPattern(dataPattern1.get(i1), queryPattern); if(qansReverse.get(queryPattern).containsKey(ans.root)){ ans = qansReverse.get(queryPattern).get(ans.root); } AnswerPattern nextAns = new AnswerPattern(dataPattern1.get(i1-1), queryPattern); if(qansReverse.get(queryPattern).containsKey(nextAns.root)){ nextAns = qansReverse.get(queryPattern).get(nextAns.root); } ans.addChild(nextAns); qansReverse.get(queryPattern).put(ans.root, ans); //qans.get(queryPattern).put(nextAns.root, nextAns); } } } HashMap<QueryPattern, HashSet<QueryPattern>> joinedQueryPatterns = new HashMap<QueryPattern, HashSet<QueryPattern>>(); HashMap<QueryPattern, HashSet<ArrayList<Integer>>> commonVarsMap = new HashMap<QueryPattern, HashSet<ArrayList<Integer>>>(); for(QueryPattern queryPatterns1 : f){ commonVarsMap.put(queryPatterns1, new HashSet<ArrayList<Integer>>()); joinedQueryPatterns.put(queryPatterns1, new HashSet<QueryPattern>()); } for(QueryPattern queryPatterns1 : f){ for(QueryPattern queryPatterns2 : f){ if(queryPatterns1 == queryPatterns2) continue; HashSet<Integer> vars = qpVarMap2.get(queryPatterns1.queryPattern); HashSet<Integer> previousVars = qpVarMap2.get(queryPatterns2.queryPattern); ArrayList<Integer> commonVars = new ArrayList<Integer>(); for(Integer var : vars){ if(previousVars.contains(var)){ commonVars.add(var); } } if(commonVars.isEmpty()) continue; commonVarsMap.get(queryPatterns1).add(commonVars); commonVarsMap.get(queryPatterns2).add(commonVars); joinedQueryPatterns.get(queryPatterns1).add(queryPatterns2); joinedQueryPatterns.get(queryPatterns2).add(queryPatterns1); } } HashMap<Long, Vector<Integer>> previous_res_vectors = null; tstart = System.nanoTime(); Map<QueryPattern, HashMap<Integer, Integer>> qpVarIndexMap = new HashMap<QueryPattern, HashMap<Integer, Integer>>(); for(int qi = 0; qi < f.size(); qi++){ QueryPattern qp = f.get(qi); int nextIndex = 0; HashMap<Integer, Integer> varIndexes = new HashMap<Integer, Integer>(); for(ECSTuple nextECSPattern : qp.queryPattern){ if(!varIndexes.containsKey(nextECSPattern.triplePattern.s)) varIndexes.put(nextECSPattern.triplePattern.s, nextIndex++); varIndexes.put(nextECSPattern.triplePattern.o, nextIndex++); } qpVarIndexMap.put(qp, varIndexes); //System.out.println(varIndexes.toString()); } for(int qi = 0; qi < f.size(); qi++){ QueryPattern qp = f.get(qi); tot = 0; HashMap<Long, Vector<Integer>> res_vectors = new HashMap<Long, Vector<Integer>>(); HashMap<Integer, Integer> varIndexes = qpVarIndexMap.get(qp); List<Integer> indexesOfCommonVarsToHash = new ArrayList<Integer>(); if(qi < f.size()-1){ QueryPattern nextQp = f.get(qi+1); HashMap<Integer, Integer> nextVarIndexes = qpVarIndexMap.get(nextQp); for(Integer nextVarIndex : varIndexes.keySet()){ if(nextVarIndexes.containsKey(nextVarIndex)){ indexesOfCommonVarsToHash.add(varIndexes.get(nextVarIndex)); } } } List<Integer> indexesOfCommonVarsToProbe = new ArrayList<Integer>(); if(qi > 0){ QueryPattern previousQp = f.get(qi-1); HashMap<Integer, Integer> previousVarIndexes = qpVarIndexMap.get(previousQp); for(Integer nextVarIndex : varIndexes.keySet()){ if(previousVarIndexes.containsKey(nextVarIndex)){ indexesOfCommonVarsToProbe.add(varIndexes.get(nextVarIndex)); } } } /*System.out.println("indexes of common vars to hash: " + indexesOfCommonVarsToHash.toString()); System.out.println("indexes of common vars to probe: " + indexesOfCommonVarsToProbe.toString());*/ for(ArrayList<ECSTuple> next : queryAnswerListSet2.get(qp)){ if(next.size() == 1){ if(previous_res_vectors == null) joinTwoECS(res_vectors, next.get(0), null, indexesOfCommonVarsToHash); else joinTwoECS(res_vectors, previous_res_vectors, next.get(0), null,indexesOfCommonVarsToHash, indexesOfCommonVarsToProbe); } else for(int ind = 0; ind < next.size()-1; ind++){ if(previous_res_vectors == null) joinTwoECS(res_vectors, next.get(ind),next.get(ind+1), indexesOfCommonVarsToHash); else joinTwoECS(res_vectors, previous_res_vectors, next.get(ind),next.get(ind+1),indexesOfCommonVarsToHash, indexesOfCommonVarsToProbe); } } previous_res_vectors = res_vectors; } tend = System.nanoTime(); if(previous_res_vectors != null) System.out.println("join " + previous_res_vectors.size() + "\t: " + (tend-tstart)); else System.out.println("join 0 \t: " + (tend-tstart)); times.add((tend-tstart)); } Collections.sort(times); System.out.println("best time: " + times.get(0)); } catch(Exception e){e.printStackTrace();} } db.close(); } public static TripleAsInt getQueryTriplePattern(ExtendedCharacteristicSet queryLinks){ int s = -1, p = -1, o = -1; if(!queryLinks.subject.isVariable()){ if(intMap.containsKey(queryLinks.subject)) s = intMap.get(queryLinks.subject); } else{ if(!varMap.containsKey(queryLinks.subject)){ reverseVarMap.put(nextVar, queryLinks.subject); varMap.put(queryLinks.subject, nextVar--); } s = varMap.get(queryLinks.subject); } if(!queryLinks.predicate.isVariable()){ if(intMap.containsKey(queryLinks.predicate)) p = propertiesSet.get(queryLinks.predicate.getURI()); } else{ if(!varMap.containsKey(queryLinks.predicate)){ reverseVarMap.put(nextVar, queryLinks.predicate); varMap.put(queryLinks.predicate, nextVar--); } p = varMap.get(queryLinks.predicate); } if(!queryLinks.object.isVariable()){ if(intMap.containsKey(queryLinks.object)) o = intMap.get(queryLinks.object); } else{ if(!varMap.containsKey(queryLinks.object)){ reverseVarMap.put(nextVar, queryLinks.object); varMap.put(queryLinks.object, nextVar--); } o = varMap.get(queryLinks.object); } return new TripleAsInt(s, p, o); } static public boolean findDataPatterns(ExtendedCharacteristicSet ecs, Map<ExtendedCharacteristicSet, HashSet<ExtendedCharacteristicSet>> links, ArrayList<ECSTuple> queryLinks, ArrayList<ECSTuple> originalQueryLinks, ArrayList<ECSTuple> list){ if(queryLinks.size() == 0) { if(queryAnswerListSet2.containsKey(new QueryPattern(originalQueryLinks))) queryAnswerListSet2.get(new QueryPattern(originalQueryLinks)).add(list); else{ HashSet<ArrayList<ECSTuple>> d = new HashSet<ArrayList<ECSTuple>>(); d.add(list); queryAnswerListSet2.put(new QueryPattern(originalQueryLinks),d); } return true; } if((queryLinks.get(0).ecs.subjectCS.longRep & ecs.subjectCS.longRep) != queryLinks.get(0).ecs.subjectCS.longRep){ return false; } if(queryLinks.get(0).ecs.objectCS != null && ecs.objectCS != null) if((queryLinks.get(0).ecs.objectCS.longRep & ecs.objectCS.longRep) != queryLinks.get(0).ecs.objectCS.longRep){ return false; } if(queryLinks.get(0).ecs.objectCS == null && ecs.objectCS != null) return false; if(queryLinks.get(0).ecs.objectCS != null && ecs.objectCS == null) return false; if(!propIndexMap.get(ecsIntegerMap.get(ecs)).containsKey(propertiesSet.get(queryLinks.get(0).ecs.predicate.toString()))) return false; if(visited.contains(ecs)){ if(queryAnswerListSet2.containsKey(new QueryPattern(originalQueryLinks))) queryAnswerListSet2.get(new QueryPattern(originalQueryLinks)).add(list); else{ HashSet<ArrayList<ECSTuple>> d = new HashSet<ArrayList<ECSTuple>>(); d.add(list); queryAnswerListSet2.put(new QueryPattern(originalQueryLinks),d); } } visited.add(ecs); ECSTuple ecsTuple = new ECSTuple(ecs, propertiesSet.get(queryLinks.get(0).ecs.predicate.toString()), getQueryTriplePattern(queryLinks.get(0).ecs)); ecsTuple.subjectBinds = queryLinks.get(0).ecs.subjectBinds; ecsTuple.objectBinds = queryLinks.get(0).ecs.objectBinds; list.add(ecsTuple); if(!links.containsKey(ecs)){ if(queryAnswerListSet2.containsKey(new QueryPattern(originalQueryLinks))) queryAnswerListSet2.get(new QueryPattern(originalQueryLinks)).add(list); else{ HashSet<ArrayList<ECSTuple>> d = new HashSet<ArrayList<ECSTuple>>(); d.add(list); queryAnswerListSet2.put(new QueryPattern(originalQueryLinks),d); } return true; } else{ for(ExtendedCharacteristicSet child : links.get(ecs)){ if(queryLinks.size()>1){ ArrayList<ECSTuple> dummy = new ArrayList<ECSTuple>(); dummy.addAll(list); findDataPatterns(child, links, new ArrayList<>(queryLinks.subList(1, queryLinks.size())), originalQueryLinks, dummy); } else { if(queryAnswerListSet2.containsKey(new QueryPattern(originalQueryLinks))) queryAnswerListSet2.get(new QueryPattern(originalQueryLinks)).add(list); else{ HashSet<ArrayList<ECSTuple>> d = new HashSet<ArrayList<ECSTuple>>(); d.add(list); queryAnswerListSet2.put(new QueryPattern(originalQueryLinks),d); } } } } return false; } public static HashMap<Long, Vector<Integer>> joinTwoECS(HashMap<Long, Vector<Integer>> res, HashMap<Long, Vector<Integer>> previous_res, ECSTuple e1, ECSTuple e2, List<Integer> hashIndexes, List<Integer> probeIndexes ){ if(e2 == null){ long[] checkArr = csMap.get(ucs.get(e1.ecs.subjectCS)); int p1 = propIndexMap.get(ecsIntegerMap.get(e1.ecs)).get(e1.property); long[] e1_array = ecsLongArrayMap.get(ecsIntegerMap.get(e1.ecs)); //System.out.println(Arrays.toString(e1_array)); for(int i = p1; i < e1_array.length; i++){ long t = e1_array[i]; if((int)((t >> 54) & 0x3ff) != e1.property) break; if(!checkBinds(e1, (int)(t >> 27 & 0x7FFFFFF), checkArr)) continue; Vector<Integer> v = new Vector<Integer>(); v.add((int)((t >> 27) & 0x7FFFFFF)); v.add((int)((t & 0x7FFFFFF))); //res.add(v); long hash = szudzik(v.get(probeIndexes.get(0)), v.get(probeIndexes.get(1))); if(previous_res.containsKey(hash)){ if(!hashIndexes.isEmpty()) res.put(szudzik(v.get(hashIndexes.get(0)), v.get(hashIndexes.get(1))), v); else res.put(hash, v); } } } else{ HashMap<Integer, ArrayList<Vector<Integer>>> h = new HashMap<Integer, ArrayList<Vector<Integer>>>(); //int p1 = propIndexMap.get(e1.ecs).get(e1.property); int p1 = propIndexMap.get(ecsIntegerMap.get(e1.ecs)).get(e1.property); long[] e1_array = ecsLongArrayMap.get(ecsIntegerMap.get(e1.ecs)); for(int i = p1; i < e1_array.length; i++){ Vector<Integer> v = new Vector<Integer>(); long t = e1_array[i]; if((int)((t >> 54) & 0x3ff) != e1.property) break; v.add((int)((t >> 27) & 0x7FFFFFF)); v.add((int)((t & 0x7FFFFFF))); ArrayList<Vector<Integer>> l = h.getOrDefault((int)((t & 0x7FFFFFF)), new ArrayList<Vector<Integer>>()); l.add(v); h.put((int)((t & 0x7FFFFFF)), l); } //int p2 = propIndexMap.get(e2.ecs).get(e2.property); int p2 = propIndexMap.get(ecsIntegerMap.get(e2.ecs)).get(e2.property); long[] e2_array = ecsLongArrayMap.get(ecsIntegerMap.get(e2.ecs)); for(int i = p2; i < e2_array.length; i++){ long t = e2_array[i]; if((int)((t >> 54) & 0x3ff) != e2.property) break; if(h.containsKey((int)((t >> 27) & 0x7FFFFFF))){ ArrayList<Vector<Integer>> l = h.get((int)((t >> 27) & 0x7FFFFFF)); for(Vector<Integer> v : l){ Vector<Integer> nv = new Vector<Integer>(v); nv.add((int)((t & 0x7FFFFFF))); //res.add(nv); res.put(szudzik(nv.get(hashIndexes.get(0)), nv.get(hashIndexes.get(1))), nv); } } } } return res; } public static HashMap<Long, Vector<Integer>> joinTwoECS(HashMap<Long, Vector<Integer>> res, ECSTuple e1, ECSTuple e2, List<Integer> hashIndexes ){ if(e2 == null){ int p1 = propIndexMap.get(ecsIntegerMap.get(e1.ecs)).get(e1.property); long[] e1_array = ecsLongArrayMap.get(ecsIntegerMap.get(e1.ecs)); long[] checkArr = csMap.get(ucs.get(e1.ecs.subjectCS)); for(int i = p1; i < e1_array.length; i++){ long t = e1_array[i]; if((int)((t >> 54) & 0x3ff) != e1.property) break; if(!checkBinds(e1, (int)(t >> 27 & 0x7FFFFFF), checkArr)) continue; Vector<Integer> v = new Vector<Integer>(); v.add((int)((t >> 27) & 0x7FFFFFF)); v.add((int)((t & 0x7FFFFFF))); //res.add(v); if(!hashIndexes.isEmpty()) res.put(szudzik(v.get(hashIndexes.get(0)), v.get(hashIndexes.get(1))), v); else res.put(szudzik(v.firstElement(), v.lastElement()), v); } } else{ HashMap<Integer, ArrayList<Vector<Integer>>> h = new HashMap<Integer, ArrayList<Vector<Integer>>>(); int p1 = propIndexMap.get(ecsIntegerMap.get(e1.ecs)).get(e1.property); long[] e1_array = ecsLongArrayMap.get(ecsIntegerMap.get(e1.ecs)); for(int i = p1; i < e1_array.length; i++){ Vector<Integer> v = new Vector<Integer>(); long t = e1_array[i]; if((int)((t >> 54) & 0x3ff) != e1.property) break; v.add((int)((t >> 27) & 0x7FFFFFF)); v.add((int)((t & 0x7FFFFFF))); ArrayList<Vector<Integer>> l = h.getOrDefault((int)((t & 0x7FFFFFF)), new ArrayList<Vector<Integer>>()); l.add(v); h.put((int)((t & 0x7FFFFFF)), l); } int p2 = propIndexMap.get(ecsIntegerMap.get(e2.ecs)).get(e2.property); long[] e2_array = ecsLongArrayMap.get(ecsIntegerMap.get(e2.ecs)); for(int i = p2; i < e2_array.length; i++){ long t = e2_array[i]; if((int)((t >> 54) & 0x3ff) != e2.property) break; if(h.containsKey((int)((t >> 27) & 0x7FFFFFF))){ ArrayList<Vector<Integer>> l = h.get((int)((t >> 27) & 0x7FFFFFF)); for(Vector<Integer> v : l){ Vector<Integer> nv = new Vector<Integer>(v); nv.add((int)((t & 0x7FFFFFF))); //res.add(nv); if(!hashIndexes.isEmpty()) res.put(szudzik(nv.get(hashIndexes.get(0)), nv.get(hashIndexes.get(1))), nv); else res.put(szudzik(nv.firstElement(), nv.lastElement()), nv); } } } } return res; } public static long szudzik(int a, int b){ return a >= b ? a * a + a + b : a + b * b; } public static boolean checkBinds(ECSTuple tuple, int subject, long[] array){ if(tuple.subjectBinds != null){ for(Integer prop : tuple.subjectBinds.keySet()){ int obj = tuple.subjectBinds.get(prop); long tripleSPOLong = ((long)prop << 54 | (long)(subject & 0x7FFFFFF) << 27 | (long)(obj & 0x7FFFFFF)); if(indexOfTriple(array, tripleSPOLong) < 0) { /*System.out.println(tripleSPOLong); System.out.println(Arrays.toString(array));*/ return false; } //System.out.println(reverseIntMap.get(subject) + ", " + reverseIntMap.get(obj)); } } return true; } public static int indexOfTriple(long[] a, long key) { int lo = 0; int hi = a.length - 1; while (lo <= hi) { // Key is in a[lo..hi] or not present. int mid = lo + (hi - lo) / 2; long s = a[mid]; if (key < s ) hi = mid - 1; else if (key > s) lo = mid + 1; else return mid; } return -1; } }
35.276765
210
0.618313
fb2e140a769e5ce790c5baaee7f77628dba3a985
1,854
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.packageDependencies; import com.intellij.icons.AllIcons; import com.intellij.ide.util.treeView.WeighedItem; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.psi.search.scope.packageSet.FilteredNamedScope; import com.intellij.ui.OffsetIcon; import org.jetbrains.annotations.NotNull; import javax.swing.*; public final class ChangeListScope extends FilteredNamedScope implements WeighedItem { private static final Icon ICON = new OffsetIcon(AllIcons.Scope.ChangedFiles); static final String ALL_CHANGED_FILES_SCOPE_NAME = "All Changed Files"; public ChangeListScope(@NotNull ChangeListManager manager) { super(ALL_CHANGED_FILES_SCOPE_NAME, AllIcons.Scope.ChangedFilesAll, 0, manager::isFileAffected); } public ChangeListScope(@NotNull ChangeListManager manager, @NotNull String name) { super(name, ICON, 0, file -> manager.getChangeLists(file).stream().anyMatch(list -> list.getName().equals(name))); } @Override public int hashCode() { return getName().hashCode(); } @Override public boolean equals(Object object) { if (object == this) return true; if (object instanceof ChangeListScope) { ChangeListScope scope = (ChangeListScope)object; return scope.getIcon() == getIcon() && scope.getName().equals(getName()); } return false; } @Override public String toString() { String string = super.toString(); if (AllIcons.Scope.ChangedFilesAll == getIcon()) string += "; ALL"; return string; } @Override public int getWeight() { return AllIcons.Scope.ChangedFilesAll == getIcon() ? 0 : 1; } public static String getNameText() { return "All Changed Files"; } }
33.107143
140
0.737864
09d45741cdd2f69b3805bcd62be5f99472135158
1,275
package com.svea.webpay.paymentgw.entity; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; public class Row { private String id; private String name; private String description; private Long amount; private Long vat; private Double quantity; private String SKU; private String unit; @XmlAttribute(name="id") public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } public Long getVat() { return vat; } public void setVat(Long vat) { this.vat = vat; } public Double getQuantity() { return quantity; } public void setQuantity(Double quantity) { this.quantity = quantity; } @XmlElement(name = "sku") public String getSKU() { return SKU; } public void setSKU(String sKU) { SKU = sKU; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } }
17.708333
49
0.697255
0658aaa9b8ad1ea4d045c06499f69261bd59a036
2,237
/* ################################################################################## # License: MIT # Copyright 2018 Agile Data Inc # # 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 com.adi.amf.lbcheck.probe.util; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import org.omg.CORBA_2_3.portable.InputStream; public class IoUtil { public static void copy(InputStream is, OutputStream os) throws IOException { int buf = 0; try { while((buf = is.read()) != -1) { os.write(buf); } } finally { try { is.close(); } catch (Exception e) { } try { os.close(); } catch (Exception e) { } } } public static byte[] read(FileInputStream fileInputStream) throws IOException { int buf = 0; ByteArrayOutputStream os = new ByteArrayOutputStream(); try { while((buf = fileInputStream.read()) != -1) { os.write(buf); } } finally { try { fileInputStream.close(); } catch (Exception e) { } try { os.close(); } catch (Exception e) { } } return os.toByteArray(); } }
32.42029
87
0.654448
d70557e2dc7e8e1586931a3d1f2dbab487c08771
2,690
package com.xiaojukeji.kafka.manager.common.entity.vo.normal.consumer; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @author zengqiao * @date 19/4/3 */ @ApiModel(value = "消费组的消费详情") public class ConsumerGroupDetailVO { @ApiModelProperty(value = "topic名称") private String topicName; @ApiModelProperty(value = "消费组名称") private String consumerGroup; @ApiModelProperty(value = "location") private String location; @ApiModelProperty(value = "分区Id") private Integer partitionId; @ApiModelProperty(value = "clientId") private String clientId; @ApiModelProperty(value = "消费偏移量") private Long consumeOffset; @ApiModelProperty(value = "partitionOffset") private Long partitionOffset; @ApiModelProperty(value = "lag") private Long lag; public String getTopicName() { return topicName; } public void setTopicName(String topicName) { this.topicName = topicName; } public String getConsumerGroup() { return consumerGroup; } public void setConsumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Integer getPartitionId() { return partitionId; } public void setPartitionId(Integer partitionId) { this.partitionId = partitionId; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public Long getConsumeOffset() { return consumeOffset; } public void setConsumeOffset(Long consumeOffset) { this.consumeOffset = consumeOffset; } public Long getPartitionOffset() { return partitionOffset; } public void setPartitionOffset(Long partitionOffset) { this.partitionOffset = partitionOffset; } public Long getLag() { return lag; } public void setLag(Long lag) { this.lag = lag; } @Override public String toString() { return "ConsumerGroupDetailVO{" + "topicName='" + topicName + '\'' + ", consumerGroup='" + consumerGroup + '\'' + ", location='" + location + '\'' + ", partitionId=" + partitionId + ", clientId='" + clientId + '\'' + ", consumeOffset=" + consumeOffset + ", partitionOffset=" + partitionOffset + ", lag=" + lag + '}'; } }
23.596491
70
0.613383
efd3ef1d5ce0c6767f7f5ebbb2074661187de5fd
297
package com.qa.TDL.persistence.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.qa.TDL.persistence.domain.TaskItem; @Repository public interface TaskItemRepository extends JpaRepository<TaskItem, Long> { }
24.75
76
0.835017
35cace31b1cbc5a888857e3fe89399cfc344c87f
1,561
package org.cice.jesh.filters; import java.io.IOException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.ws.rs.NameBinding; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import com.google.gson.Gson; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.cice.jesh.persistence.dao.impl.TokenDaoImpl; /** * * @author Toni */ @Provider @AuthenticationFilter.AuthenticationFilterImpl public class AuthenticationFilter implements ContainerRequestFilter { static final Logger logger = LogManager.getLogger(AuthenticationFilter.class.getName()); private final TokenDaoImpl tokenDaoImpl = new TokenDaoImpl(); @NameBinding @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface AuthenticationFilterImpl { } @Override public void filter(ContainerRequestContext request) throws IOException { String accessToken = request.getHeaderString("AccessToken"); if (accessToken == null || tokenDaoImpl.validToken("token", accessToken) == null) { logger.info("Invalid access token or null."); String responseJSON = new Gson().toJson("Unauthorized"); request.abortWith(Response.status(401).entity(responseJSON).build()); } } }
31.22
92
0.755285
3d1388ca9da2b587d928652dbe9eba3251ab6189
1,588
package com.jonki.popcorn.common.dto.movie; import com.jonki.popcorn.common.dto.movie.type.LanguageType; import com.jonki.popcorn.test.category.UnitTest; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Tests for the Language DTO. */ @Category(UnitTest.class) public class LanguageUnitTests { private static final LanguageType LANGUAGE_TYPE = LanguageType.ENGLISH; /** * Test to make sure we can build an language using the default builder constructor. */ @Test public void canBuildLanguage() { final Language language = new Language.Builder( LANGUAGE_TYPE ).build(); Assert.assertThat(language.getLanguage(), Matchers.is(LANGUAGE_TYPE)); } /** * Test equals. */ @Test public void canFindEquality() { final Language.Builder builder = new Language.Builder( LANGUAGE_TYPE ); final Language language1 = builder.build(); final Language language2 = builder.build(); Assert.assertTrue(language1.equals(language2)); Assert.assertTrue(language2.equals(language1)); } /** * Test hash code. */ @Test public void canUseHashCode() { final Language.Builder builder = new Language.Builder( LANGUAGE_TYPE ); final Language language1 = builder.build(); final Language language2 = builder.build(); Assert.assertEquals(language1.hashCode(), language2.hashCode()); } }
27.37931
88
0.656801
1a831d32b1d23f869f3a9f291fd44f4dce9d5516
1,768
/* * ChessJApplet.java * Created on October 22, 2006, 8:44 AM * Written 11/04-5/05 * @author mhenry */ package com.burcumirza.HenryChess.Logic; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class ChessJApplet extends JApplet { private ChessGame game; private Chessboard board; private Frame window; public void init(int level) { Dimension bounds = new Dimension(800, 700); board = new Chessboard(bounds); window = new Frame("Level " + level + " Chess Round"); window.add(board); window.setSize(bounds); window.setVisible(true); window.setResizable(false); window.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); window.setLocation((int) ((dim.width / 2) - (bounds.getWidth() / 2)), (int) ((dim.height / 2) - (bounds.getHeight() / 2))); Move.board = board; game = new ChessGame(board, level); game.makeMove(); } } class RoundedBorder implements Border { private int radius; RoundedBorder(int radius) { this.radius = radius; } public Insets getBorderInsets(Component c) { return new Insets(this.radius + 1, this.radius + 1, this.radius + 2, this.radius); } public boolean isBorderOpaque() { return true; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { g.drawRoundRect(x, y, width - 1, height - 1, radius, radius); } }
27.625
92
0.591063
094caa8d8d1da5b8961c4572e1c335a6d3023c7e
240
package no.fint.springfox; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackageClasses = Config.class) public class Config { }
24
60
0.841667
b0ae12ebfb680554617e73018aeb1df09ee6594f
2,306
/* * CompressorInterface.java * * Created on 22. august 2001, 17:20 */ package neqsim.processSimulation.processEquipment.compressor; import neqsim.processSimulation.processEquipment.ProcessEquipmentInterface; import neqsim.processSimulation.processEquipment.stream.StreamInterface; /** * <p> * CompressorInterface interface. * </p> * * @author esol * @version $Id: $Id */ public interface CompressorInterface extends ProcessEquipmentInterface { /** {@inheritDoc} */ @Override public void run(); /** * <p> * setOutletPressure. * </p> * * @param pressure a double */ public void setOutletPressure(double pressure); /** * <p> * setInletStream. * </p> * * @param inletStream a {@link neqsim.processSimulation.processEquipment.stream.StreamInterface} * object */ public void setInletStream(StreamInterface inletStream); /** * <p> * getEnergy. * </p> * * @return a double */ public double getEnergy(); /** {@inheritDoc} */ @Override public String getName(); /** * <p> * getOutStream. * </p> * * @return a {@link neqsim.processSimulation.processEquipment.stream.StreamInterface} object */ public StreamInterface getOutStream(); /** * <p> * getIsentropicEfficiency. * </p> * * @return a double */ public double getIsentropicEfficiency(); /** * <p> * setIsentropicEfficiency. * </p> * * @param isentropicEfficientcy a double */ public void setIsentropicEfficiency(double isentropicEfficientcy); /** * <p> * runTransient. * </p> */ public void runTransient(); /** * <p> * getPolytropicEfficiency. * </p> * * @return a double */ public double getPolytropicEfficiency(); /** * <p> * setPolytropicEfficiency. * </p> * * @param polytropicEfficiency a double */ public void setPolytropicEfficiency(double polytropicEfficiency); /** * <p> * getAntiSurge. * </p> * * @return a {@link neqsim.processSimulation.processEquipment.compressor.AntiSurge} object */ public AntiSurge getAntiSurge(); }
19.709402
100
0.589332
d114b62c9a6c4ea64cd914e12228ad1f7e1d3a92
1,657
/* * 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.olingo.client.core.edm.xml.v4; import org.apache.olingo.client.api.edm.xml.v4.NavigationPropertyBinding; import org.apache.olingo.client.core.edm.xml.AbstractEdmItem; import com.fasterxml.jackson.annotation.JsonProperty; public class NavigationPropertyBindingImpl extends AbstractEdmItem implements NavigationPropertyBinding { private static final long serialVersionUID = -7056978592235483660L; @JsonProperty(value = "Path", required = true) private String path; @JsonProperty(value = "Target", required = true) private String target; @Override public String getPath() { return path; } public void setPath(final String path) { this.path = path; } @Override public String getTarget() { return target; } public void setTarget(final String target) { this.target = target; } }
30.127273
105
0.749547
fcae65a792a912067d971fe7db55b355e1e2c627
2,133
/* * Copyright 2011-2018 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.core.codesystem.version; import static com.google.common.base.Strings.nullToEmpty; import java.util.Date; import com.b2international.snowowl.core.date.EffectiveTimes; import com.google.common.base.MoreObjects; /** * Configuration for the publication process. */ public final class VersioningConfiguration { private final String user; private final String codeSystemShortName; private final String versionId; private final String description; private final Date effectiveTime; public VersioningConfiguration( String user, String codeSystemShortName, String versionId, String description, Date effectiveTime) { this.user = user; this.codeSystemShortName = codeSystemShortName; this.versionId = versionId; this.description = description; this.effectiveTime = effectiveTime; } public String getUser() { return user; } public String getVersionId() { return versionId; } public Date getEffectiveTime() { return null == effectiveTime ? null : new Date(effectiveTime.getTime()); } public String getDescription() { return nullToEmpty(description); } public String getCodeSystemShortName() { return codeSystemShortName; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Version ID", versionId) .add("Effective time", null == effectiveTime ? "unset" : EffectiveTimes.format(effectiveTime)) .add("Description", nullToEmpty(description)) .toString(); } }
27.346154
98
0.747773
b83a2863a9973ca585776b46474584879bf38321
2,394
/* * Copyright 2017 mk * * 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 pl.mk5.gdx.fireapp.android.crash; import com.google.firebase.crashlytics.FirebaseCrashlytics; import pl.mk5.gdx.fireapp.distributions.CrashDistribution; /** * Android Firebase crash API implementation. * <p> * * @see CrashDistribution */ public class Crash implements CrashDistribution { /** * {@inheritDoc} */ @Override public void log(String message) { FirebaseCrashlytics.getInstance().log(message); } @Override public void initialize() { // do nothing } @Override public void recordException(Throwable throwable) { FirebaseCrashlytics.getInstance().recordException(throwable); } @Override public void setUserId(String userIdentifier) { FirebaseCrashlytics.getInstance().setUserId(userIdentifier); } @Override public <T> void setCustomKey(String key, T value) { if (value instanceof Boolean) { FirebaseCrashlytics.getInstance().setCustomKey(key, (Boolean) value); } else if (value instanceof String) { FirebaseCrashlytics.getInstance().setCustomKey(key, (String) value); } else if (value instanceof Double) { FirebaseCrashlytics.getInstance().setCustomKey(key, (Double) value); } else if (value instanceof Long) { FirebaseCrashlytics.getInstance().setCustomKey(key, (Long) value); } else if (value instanceof Float) { FirebaseCrashlytics.getInstance().setCustomKey(key, (Float) value); } else if (value instanceof Integer) { FirebaseCrashlytics.getInstance().setCustomKey(key, (Integer) value); } else { throw new IllegalStateException("Wrong value type. Supported types are [boolean, int, string, float, double, long]"); } } }
32.351351
129
0.680451
3420ee2ee33876beb182f9aef94a37b7dbd85a46
1,620
package dc.longshot.system; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; public final class ScreenManager { private final List<Screen> screens = new ArrayList<Screen>(); private final List<Screen> screensToAdd = new ArrayList<Screen>(); private final List<Screen> screensToRemove = new ArrayList<Screen>(); public final Screen getCurrentScreen() { if (screens.isEmpty()) { throw new UnsupportedOperationException("Could not get current screen because there are no screens"); } return screens.get(0); } public final void add(final Screen screen) { screensToAdd.add(screen); screen.show(); } public final void remove(final Screen screen) { screensToRemove.add(screen); screen.hide(); } public final void swap(final Screen currentScreen, final Screen newScreen) { remove(currentScreen); add(newScreen); } public final void update() { while (!screensToAdd.isEmpty()) { Screen screen = screensToAdd.remove(0); screens.add(screen); } while (!screensToRemove.isEmpty()) { Screen screen = screensToRemove.remove(0); screen.dispose(); screens.remove(screen); } } public final void render() { for (Screen screen : screens) { screen.render(Gdx.graphics.getDeltaTime()); } } public final void resize(final int width, final int height) { for (Screen screen : screens) { screen.resize(width, height); } } public final void dispose() { for (Screen screen : screens) { screen.dispose(); } } }
23.478261
105
0.674074
4d00d1e3786f0331be881e80e85dedd4e98e05f0
218
package com.slydm.thinking.in.spring.dependency.inject.classloader; /** * @author wangcymy@gmail.com(wangcong) 2021/2/18 15:25 */ public class A { @Override public String toString() { return "I'm A"; } }
16.769231
67
0.678899
1258f69f66f406c456d346ae177e49469f998458
288
package net.pladema.clinichistory.documents.service.generalstate; import net.pladema.clinichistory.documents.service.generalstate.EncounterGeneralState; public interface EncounterGeneralStateBuilder { EncounterGeneralState getInternmentGeneralState(Integer internmentEpisodeId); }
32
86
0.871528
d1d8b365b8f7d7a362750dd9310f628050369b25
2,294
package it.dfa.unict; import java.util.List; /** * * @author mario */ public class AppInput { // Application inputs private String inputFileName; // Filename for application input file private String jobLabel; // User' given job identifier // Each inputSandobox file must be declared below // This variable contains the content of an uploaded file private String inputSandbox; // Some user level information // must be stored as well private String username; private String timestamp; private int taskNumber; private List<String[]> arguments; private String userEmail; /** * Standard constructor just initialize empty values */ public AppInput() { this.inputFileName = ""; this.jobLabel = ""; this.inputSandbox = ""; this.username = ""; this.timestamp = ""; } public String getInputFileName() { return inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getJobLabel() { return jobLabel; } public void setJobLabel(String joblabel) { this.jobLabel = joblabel; } public String getInputSandbox() { return inputSandbox; } public void setInputSandbox(String inputFile) { this.inputSandbox += (this.inputSandbox.equals("") ? "" : ",") + inputFile; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public int getTaskNumber() { return taskNumber; } public void setTaskNumber(int taskNumber) { this.taskNumber = taskNumber; } public List<String[]> getArguments() { return arguments; } public void setArguments(List<String[]> list) { this.arguments = list; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } @Override public String toString() { return "AppInput [inputFileName=" + inputFileName + ", jobLabel=" + jobLabel + ", inputSandbox=" + inputSandbox + ", username=" + username + ", timestamp=" + timestamp + ", taskNumber=" + taskNumber + ", arguments=" + arguments + ", userEmail=" + userEmail + "]"; } }
20.300885
69
0.697472
f72384a7f67303e902667ade3002471efd8779a6
25,569
package jetbrains.mps.lang.core.plugin; /*Generated by MPS */ import jetbrains.mps.make.facet.IFacet; import java.util.List; import jetbrains.mps.make.facet.ITarget; import jetbrains.mps.internal.collections.runtime.ListSequence; import java.util.ArrayList; import jetbrains.mps.internal.collections.runtime.Sequence; import jetbrains.mps.make.resources.IPropertiesPersistence; import jetbrains.mps.make.facet.ITargetEx2; import jetbrains.mps.make.script.IJob; import jetbrains.mps.make.script.IResult; import jetbrains.mps.make.resources.IResource; import jetbrains.mps.make.script.IJobMonitor; import jetbrains.mps.make.resources.IPropertiesAccessor; import org.jetbrains.annotations.NotNull; import org.jetbrains.mps.openapi.util.ProgressMonitor; import jetbrains.mps.make.script.IConfig; import jetbrains.mps.generator.GenerationSettingsProvider; import jetbrains.mps.generator.IModifiableGenerationSettings; import jetbrains.mps.generator.GenerationOptions; import jetbrains.mps.generator.GenerationCacheContainer; import jetbrains.mps.smodel.structure.ExtensionPoint; import jetbrains.mps.generator.DefaultGenerationParametersProvider; import jetbrains.mps.project.Project; import jetbrains.mps.generator.TransientModelsProvider; import jetbrains.mps.smodel.resources.CleanupActivityResource; import jetbrains.mps.make.script.IConfigMonitor; import jetbrains.mps.baseLanguage.tuples.runtime.Tuples; import jetbrains.mps.make.script.IPropertiesPool; import jetbrains.mps.baseLanguage.tuples.runtime.MultiTuple; import jetbrains.mps.generator.ModelGenerationPlan; import jetbrains.mps.smodel.resources.MResource; import java.util.stream.IntStream; import jetbrains.mps.internal.collections.runtime.IVisitor; import org.jetbrains.mps.openapi.model.SModel; import jetbrains.mps.baseLanguage.closures.runtime.Wrappers; import java.util.Map; import org.jetbrains.mps.openapi.module.SModule; import jetbrains.mps.generator.GenPlanExtractor; import jetbrains.mps.generator.GenerationTaskRecorder; import jetbrains.mps.generator.GeneratorTask; import jetbrains.mps.messages.IMessageHandler; import org.jetbrains.mps.openapi.module.SRepository; import jetbrains.mps.smodel.ModelAccessHelper; import jetbrains.mps.util.Computable; import jetbrains.mps.generator.GeneratorTaskBase; import jetbrains.mps.generator.TransientModelsModule; import jetbrains.mps.generator.DefaultTaskBuilder; import jetbrains.mps.generator.GenerationFacade; import jetbrains.mps.generator.GenerationStatus; import jetbrains.mps.smodel.resources.GResource; import jetbrains.mps.internal.collections.runtime.MapSequence; public class Generate_Facet extends IFacet.Stub { private List<ITarget> targets = ListSequence.fromList(new ArrayList<ITarget>()); private IFacet.Name name = new IFacet.Name("jetbrains.mps.lang.core.Generate"); public Generate_Facet() { ListSequence.fromList(targets).addElement(new Target_checkParameters()); ListSequence.fromList(targets).addElement(new Target_configure()); ListSequence.fromList(targets).addElement(new Target_preloadModels()); ListSequence.fromList(targets).addElement(new Target_generate()); } public Iterable<ITarget> targets() { return targets; } public Iterable<IFacet.Name> optional() { return null; } public Iterable<IFacet.Name> required() { return Sequence.fromArray(new IFacet.Name[]{new IFacet.Name("jetbrains.mps.make.facets.Make")}); } public Iterable<IFacet.Name> extended() { return null; } public IFacet.Name getName() { return this.name; } public IPropertiesPersistence propertiesPersistence() { return new TargetProperties(); } public static class Target_checkParameters implements ITargetEx2 { private static final ITarget.Name name = new ITarget.Name("jetbrains.mps.lang.core.Generate.checkParameters"); public Target_checkParameters() { } public IJob createJob() { return new IJob.Stub() { @Override public IResult execute(final Iterable<IResource> rawInput, final IJobMonitor monitor, final IPropertiesAccessor pa, @NotNull final ProgressMonitor progressMonitor) { Iterable<IResource> _output_fi61u2_a0a = null; final Iterable<IResource> input = (Iterable) (Iterable) rawInput; switch (0) { case 0: // no-op now default: progressMonitor.done(); return new IResult.SUCCESS(_output_fi61u2_a0a); } } }; } public IConfig createConfig() { return null; } public Iterable<ITarget.Name> notAfter() { return null; } public Iterable<ITarget.Name> after() { return null; } public Iterable<ITarget.Name> notBefore() { return null; } public Iterable<ITarget.Name> before() { return null; } public ITarget.Name getName() { return name; } public boolean isOptional() { return false; } public boolean requiresInput() { return false; } public boolean producesOutput() { return false; } public Iterable<Class<? extends IResource>> expectedInput() { List<Class<? extends IResource>> rv = ListSequence.fromList(new ArrayList<Class<? extends IResource>>()); return rv; } public Iterable<Class<? extends IResource>> expectedOutput() { return null; } public <T> T createParameters(Class<T> cls) { return null; } public <T> T createParameters(Class<T> cls, T copyFrom) { T t = createParameters(cls); return t; } public int workEstimate() { return 10; } } public static class Target_configure implements ITargetEx2 { private static final ITarget.Name name = new ITarget.Name("jetbrains.mps.lang.core.Generate.configure"); public Target_configure() { } public IJob createJob() { return new IJob.Stub() { @Override public IResult execute(final Iterable<IResource> rawInput, final IJobMonitor monitor, final IPropertiesAccessor pa, @NotNull final ProgressMonitor progressMonitor) { Iterable<IResource> _output_fi61u2_a0b = null; final Iterable<IResource> input = (Iterable) (Iterable) rawInput; switch (0) { case 0: GenerationSettingsProvider gsp = monitor.getSession().getProject().getComponent(GenerationSettingsProvider.class); IModifiableGenerationSettings settings = gsp.getGenerationSettings(); if (vars(pa.global()).generationOptions() == null) { vars(pa.global()).generationOptions(GenerationOptions.fromSettings(settings)); } Iterable<GenerationCacheContainer> caches = new ExtensionPoint<GenerationCacheContainer>("jetbrains.mps.lang.core.GeneratorCache").getObjects(); GenerationCacheContainer cacheContainer = (Sequence.fromIterable(caches).isEmpty() ? null : Sequence.fromIterable(caches).first()); vars(pa.global()).generationOptions().tracing(settings.getPerformanceTracingLevel()); vars(pa.global()).generationOptions().saveTransientModels(vars(pa.global()).saveTransient()); vars(pa.global()).parametersProvider(new DefaultGenerationParametersProvider()); vars(pa.global()).generationOptions().parameters(vars(pa.global()).parametersProvider()); Project mpsProject = monitor.getSession().getProject(); TransientModelsProvider tmc = mpsProject.getComponent(TransientModelsProvider.class); boolean ownTransientsProvider = tmc == null; vars(pa.global()).transientModelsProvider((ownTransientsProvider ? new TransientModelsProvider(mpsProject.getRepository(), null) : tmc)); vars(pa.global()).transientModelsProvider().removeAllTransient(); if (ownTransientsProvider) { _output_fi61u2_a0b = Sequence.fromIterable(_output_fi61u2_a0b).concat(Sequence.fromIterable(Sequence.<IResource>singleton(new CleanupActivityResource() { public String describe() { return "Dispose provider of transient models"; } public void run() { vars(pa.global()).transientModelsProvider().removeAllTransients(true); } }))); } return new IResult.SUCCESS(_output_fi61u2_a0b); default: progressMonitor.done(); return new IResult.SUCCESS(_output_fi61u2_a0b); } } }; } public IConfig createConfig() { return new IConfig.Stub() { @Override public boolean configure(final IConfigMonitor cmonitor, final IPropertiesAccessor pa) { switch (0) { case 0: GenerationSettingsProvider gsp = cmonitor.getSession().getProject().getComponent(GenerationSettingsProvider.class); IModifiableGenerationSettings settings = gsp.getGenerationSettings(); vars(pa.global()).saveTransient(settings.isSaveTransientModels()); default: return true; } } }; } public Iterable<ITarget.Name> notAfter() { return null; } public Iterable<ITarget.Name> after() { return Sequence.fromArray(new ITarget.Name[]{new ITarget.Name("jetbrains.mps.lang.core.Generate.checkParameters")}); } public Iterable<ITarget.Name> notBefore() { return null; } public Iterable<ITarget.Name> before() { return null; } public ITarget.Name getName() { return name; } public boolean isOptional() { return false; } public boolean requiresInput() { return false; } public boolean producesOutput() { return false; } public Iterable<Class<? extends IResource>> expectedInput() { List<Class<? extends IResource>> rv = ListSequence.fromList(new ArrayList<Class<? extends IResource>>()); return rv; } public Iterable<Class<? extends IResource>> expectedOutput() { return null; } public <T> T createParameters(Class<T> cls) { return cls.cast(new Variables()); } public <T> T createParameters(Class<T> cls, T copyFrom) { T t = createParameters(cls); if (t != null) { ((Tuples._5) t).assign((Tuples._5) copyFrom); } return t; } public int workEstimate() { return 10; } public static Variables vars(IPropertiesPool ppool) { return ppool.properties(name, Variables.class); } public static class Variables extends MultiTuple._5<Boolean, GenerationOptions.OptionsBuilder, DefaultGenerationParametersProvider, TransientModelsProvider, ModelGenerationPlan> { public Variables() { super(); } public Variables(Boolean saveTransient, GenerationOptions.OptionsBuilder generationOptions, DefaultGenerationParametersProvider parametersProvider, TransientModelsProvider transientModelsProvider, ModelGenerationPlan customPlan) { super(saveTransient, generationOptions, parametersProvider, transientModelsProvider, customPlan); } public Boolean saveTransient(Boolean value) { return super._0(value); } public GenerationOptions.OptionsBuilder generationOptions(GenerationOptions.OptionsBuilder value) { return super._1(value); } public DefaultGenerationParametersProvider parametersProvider(DefaultGenerationParametersProvider value) { return super._2(value); } public TransientModelsProvider transientModelsProvider(TransientModelsProvider value) { return super._3(value); } public ModelGenerationPlan customPlan(ModelGenerationPlan value) { return super._4(value); } public Boolean saveTransient() { return super._0(); } public GenerationOptions.OptionsBuilder generationOptions() { return super._1(); } public DefaultGenerationParametersProvider parametersProvider() { return super._2(); } public TransientModelsProvider transientModelsProvider() { return super._3(); } public ModelGenerationPlan customPlan() { return super._4(); } } } public static class Target_preloadModels implements ITargetEx2 { private static final ITarget.Name name = new ITarget.Name("jetbrains.mps.lang.core.Generate.preloadModels"); public Target_preloadModels() { } public IJob createJob() { return new IJob.Stub() { @Override public IResult execute(final Iterable<IResource> rawInput, final IJobMonitor monitor, final IPropertiesAccessor pa, @NotNull final ProgressMonitor progressMonitor) { Iterable<IResource> _output_fi61u2_a0c = null; final Iterable<MResource> input = (Iterable<MResource>) (Iterable) rawInput; progressMonitor.start("", IntStream.of(1000).sum()); switch (0) { case 0: int work = Sequence.fromIterable(input).count() * 100; if (work == 0) { return new IResult.SUCCESS(_output_fi61u2_a0c); } final ProgressMonitor subProgress_c0a0c = progressMonitor.subTask(1000); subProgress_c0a0c.start("Pre-loading models", work); final Project project = monitor.getSession().getProject(); Sequence.fromIterable(input).visitAll(new IVisitor<MResource>() { public void visit(final MResource mod) { subProgress_c0a0c.advance(100); project.getModelAccess().runReadAction(() -> { Sequence.fromIterable(mod.models()).visitAll(new IVisitor<SModel>() { public void visit(SModel m) { m.load(); } }); }); } }); subProgress_c0a0c.done(); _output_fi61u2_a0c = Sequence.fromIterable(_output_fi61u2_a0c).concat(Sequence.fromIterable(input)); default: progressMonitor.done(); return new IResult.SUCCESS(_output_fi61u2_a0c); } } }; } public IConfig createConfig() { return null; } public Iterable<ITarget.Name> notAfter() { return null; } public Iterable<ITarget.Name> after() { return Sequence.fromArray(new ITarget.Name[]{new ITarget.Name("jetbrains.mps.lang.core.Generate.configure")}); } public Iterable<ITarget.Name> notBefore() { return null; } public Iterable<ITarget.Name> before() { return Sequence.fromArray(new ITarget.Name[]{new ITarget.Name("jetbrains.mps.lang.core.Generate.generate")}); } public ITarget.Name getName() { return name; } public boolean isOptional() { return false; } public boolean requiresInput() { return true; } public boolean producesOutput() { return true; } public Iterable<Class<? extends IResource>> expectedInput() { List<Class<? extends IResource>> rv = ListSequence.fromList(new ArrayList<Class<? extends IResource>>()); ListSequence.fromList(rv).addElement(MResource.class); return rv; } public Iterable<Class<? extends IResource>> expectedOutput() { return null; } public <T> T createParameters(Class<T> cls) { return null; } public <T> T createParameters(Class<T> cls, T copyFrom) { T t = createParameters(cls); return t; } public int workEstimate() { return 400; } } public static class Target_generate implements ITargetEx2 { private static final ITarget.Name name = new ITarget.Name("jetbrains.mps.lang.core.Generate.generate"); public Target_generate() { } public IJob createJob() { return new IJob.Stub() { @Override public IResult execute(final Iterable<IResource> rawInput, final IJobMonitor monitor, final IPropertiesAccessor pa, @NotNull final ProgressMonitor progressMonitor) { Iterable<IResource> _output_fi61u2_a0d = null; final Iterable<MResource> input = (Iterable<MResource>) (Iterable) rawInput; switch (0) { case 0: final Wrappers._T<Map<SModule, Iterable<SModel>>> retainedModels = new Wrappers._T<Map<SModule, Iterable<SModel>>>(); final Project mpsProject = monitor.getSession().getProject(); mpsProject.getModelAccess().runReadAction(() -> retainedModels.value = RetainedUtil.collectModelsToRetain(input)); if (Target_configure.vars(pa.global()).customPlan() == null) { mpsProject.getModelAccess().runReadAction(new Runnable() { public void run() { GenPlanExtractor planExtractor = new GenPlanExtractor(mpsProject.getRepository(), Target_configure.vars(pa.global()).generationOptions(), monitor.getSession().getMessageHandler()); for (MResource res : Sequence.fromIterable(input)) { for (SModel m : Sequence.fromIterable(res.models())) { planExtractor.configurePlanFor(m); } } } }); } final GenerationTaskRecorder<GeneratorTask> taskHandler = new GenerationTaskRecorder<GeneratorTask>(null); final IMessageHandler mh = monitor.getSession().getMessageHandler(); progressMonitor.start("Generating", 110); try { // in fact, transientsModuleRepo == mpsProject.getRepository, but I keep them separate to stress different lock scope final SRepository transientsModuleRepo = Target_configure.vars(pa.global()).transientModelsProvider().getRepository(); // XXX write is to tmm.createModule() and tmm.initCheckpointModule, although the moment transients live in a separate repository, we may // write-lock transients repository only, and read-lock the one with source models. final List<GeneratorTask> tasks = new ModelAccessHelper(transientsModuleRepo).runWriteAction(new Computable<List<GeneratorTask>>() { public List<GeneratorTask> compute() { Target_configure.vars(pa.global()).transientModelsProvider().initCheckpointModule(); GeneratorTask.Factory<GeneratorTask> factory = new GeneratorTask.Factory<GeneratorTask>() { public GeneratorTask create(SModel model) { return new GeneratorTaskBase(model); } }; ArrayList<GeneratorTask> rv = new ArrayList<GeneratorTask>(); for (MResource res : input) { final TransientModelsModule tm = Target_configure.vars(pa.global()).transientModelsProvider().createModule(res.module().getModuleName()); DefaultTaskBuilder<GeneratorTask> tb = new DefaultTaskBuilder<GeneratorTask>(factory); tb.addAll(Sequence.fromIterable(res.models()).toListSequence()); List<GeneratorTask> tasks = tb.getResult(); for (GeneratorTask t : tasks) { Target_configure.vars(pa.global()).transientModelsProvider().associate(t, tm); } rv.addAll(tasks); } return rv; } }); final SRepository projectRepo = mpsProject.getRepository(); projectRepo.getModelAccess().runReadAction(() -> { GenerationFacade genFacade = new GenerationFacade(projectRepo, Target_configure.vars(pa.global()).generationOptions().create()); genFacade.transients(Target_configure.vars(pa.global()).transientModelsProvider()).messages(mh).taskHandler(taskHandler); genFacade.process(progressMonitor.subTask(100), tasks); }); transientsModuleRepo.getModelAccess().runWriteAction(() -> Target_configure.vars(pa.global()).transientModelsProvider().publishAll()); for (GenerationStatus genStatus : taskHandler.getAllRecorded()) { if (!(genStatus.isOk())) { return new IResult.FAILURE(_output_fi61u2_a0d); } SModel inputModel = genStatus.getInputModel(); GResource data = new GResource(inputModel.getModule(), inputModel, MapSequence.fromMap(retainedModels.value).get(inputModel.getModule()), genStatus); _output_fi61u2_a0d = Sequence.fromIterable(_output_fi61u2_a0d).concat(Sequence.fromIterable(Sequence.<IResource>singleton(data))); } } finally { progressMonitor.done(); } if (!(Target_configure.vars(pa.global()).saveTransient())) { _output_fi61u2_a0d = Sequence.fromIterable(_output_fi61u2_a0d).concat(Sequence.fromIterable(Sequence.<IResource>singleton(new CleanupActivityResource() { public String describe() { return "Drop transient models"; } public void run() { Target_configure.vars(pa.global()).transientModelsProvider().removeAllTransient(); } }))); } default: progressMonitor.done(); return new IResult.SUCCESS(_output_fi61u2_a0d); } } }; } public IConfig createConfig() { return null; } public Iterable<ITarget.Name> notAfter() { return null; } public Iterable<ITarget.Name> after() { return Sequence.fromArray(new ITarget.Name[]{new ITarget.Name("jetbrains.mps.lang.core.Generate.configure")}); } public Iterable<ITarget.Name> notBefore() { return null; } public Iterable<ITarget.Name> before() { return Sequence.fromArray(new ITarget.Name[]{new ITarget.Name("jetbrains.mps.make.facets.Make.cleanup"), new ITarget.Name("jetbrains.mps.make.facets.Make.make")}); } public ITarget.Name getName() { return name; } public boolean isOptional() { return false; } public boolean requiresInput() { return true; } public boolean producesOutput() { return true; } public Iterable<Class<? extends IResource>> expectedInput() { List<Class<? extends IResource>> rv = ListSequence.fromList(new ArrayList<Class<? extends IResource>>()); ListSequence.fromList(rv).addElement(MResource.class); return rv; } public Iterable<Class<? extends IResource>> expectedOutput() { return null; } public <T> T createParameters(Class<T> cls) { return null; } public <T> T createParameters(Class<T> cls, T copyFrom) { T t = createParameters(cls); return t; } public int workEstimate() { return 5000; } } public static class TargetProperties implements IPropertiesPersistence { public TargetProperties() { } public void storeValues(Map<String, String> store, IPropertiesPool properties) { { ITarget.Name name = new ITarget.Name("jetbrains.mps.lang.core.Generate.configure"); if (properties.hasProperties(name)) { Target_configure.Variables props = properties.properties(name, Target_configure.Variables.class); MapSequence.fromMap(store).put("jetbrains.mps.lang.core.Generate.configure.saveTransient", String.valueOf(props.saveTransient())); MapSequence.fromMap(store).put("jetbrains.mps.lang.core.Generate.configure.generationOptions", null); MapSequence.fromMap(store).put("jetbrains.mps.lang.core.Generate.configure.parametersProvider", null); MapSequence.fromMap(store).put("jetbrains.mps.lang.core.Generate.configure.transientModelsProvider", null); MapSequence.fromMap(store).put("jetbrains.mps.lang.core.Generate.configure.customPlan", null); } } } public void loadValues(Map<String, String> store, IPropertiesPool properties) { try { { ITarget.Name name = new ITarget.Name("jetbrains.mps.lang.core.Generate.configure"); Target_configure.Variables props = properties.properties(name, Target_configure.Variables.class); if (MapSequence.fromMap(store).containsKey("jetbrains.mps.lang.core.Generate.configure.saveTransient")) { props.saveTransient(Boolean.valueOf(MapSequence.fromMap(store).get("jetbrains.mps.lang.core.Generate.configure.saveTransient"))); } if (MapSequence.fromMap(store).containsKey("jetbrains.mps.lang.core.Generate.configure.generationOptions")) { props.generationOptions(null); } if (MapSequence.fromMap(store).containsKey("jetbrains.mps.lang.core.Generate.configure.parametersProvider")) { props.parametersProvider(null); } if (MapSequence.fromMap(store).containsKey("jetbrains.mps.lang.core.Generate.configure.transientModelsProvider")) { props.transientModelsProvider(null); } if (MapSequence.fromMap(store).containsKey("jetbrains.mps.lang.core.Generate.configure.customPlan")) { props.customPlan(null); } } } catch (RuntimeException re) { } } } }
44.390625
236
0.660096
50b3f3eecf0f90d55d9ce7453d61528324ba223c
3,268
/** * TLS-Attacker - Anonymous submission * * Licensed under Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package anonymous.tlsattacker.tls.protocol.handshake; import anonymous.tlsattacker.modifiablevariable.ModifiableVariable; import anonymous.tlsattacker.modifiablevariable.ModifiableVariableFactory; import anonymous.tlsattacker.modifiablevariable.ModifiableVariableProperty; import anonymous.tlsattacker.modifiablevariable.bytearray.ModifiableByteArray; import anonymous.tlsattacker.modifiablevariable.integer.ModifiableInteger; import anonymous.tlsattacker.tls.constants.ConnectionEnd; import anonymous.tlsattacker.tls.constants.HandshakeMessageType; /** * @author anonymous anonymous <anonymous.anonymous@anonymous> */ public class RSAClientKeyExchangeMessage extends ClientKeyExchangeMessage { @ModifiableVariableProperty(type = ModifiableVariableProperty.Type.LENGTH) ModifiableInteger encryptedPremasterSecretLength; @ModifiableVariableProperty(type = ModifiableVariableProperty.Type.CIPHERTEXT) ModifiableByteArray encryptedPremasterSecret; @ModifiableVariableProperty(format = ModifiableVariableProperty.Format.PKCS1, type = ModifiableVariableProperty.Type.KEY_MATERIAL) ModifiableByteArray plainPaddedPremasterSecret; public RSAClientKeyExchangeMessage() { super(HandshakeMessageType.CLIENT_KEY_EXCHANGE); this.messageIssuer = ConnectionEnd.CLIENT; } public RSAClientKeyExchangeMessage(ConnectionEnd messageIssuer) { super(HandshakeMessageType.CLIENT_KEY_EXCHANGE); this.messageIssuer = messageIssuer; } public ModifiableInteger getEncryptedPremasterSecretLength() { return encryptedPremasterSecretLength; } public void setEncryptedPremasterSecretLength(ModifiableInteger encryptedPremasterSecretLength) { this.encryptedPremasterSecretLength = encryptedPremasterSecretLength; } public void setEncryptedPremasterSecretLength(int length) { this.encryptedPremasterSecretLength = ModifiableVariableFactory.safelySetValue( this.encryptedPremasterSecretLength, length); } public ModifiableByteArray getEncryptedPremasterSecret() { return encryptedPremasterSecret; } public void setEncryptedPremasterSecret(ModifiableByteArray encryptedPremasterSecret) { this.encryptedPremasterSecret = encryptedPremasterSecret; } public void setEncryptedPremasterSecret(byte[] value) { this.encryptedPremasterSecret = ModifiableVariableFactory.safelySetValue(this.encryptedPremasterSecret, value); } public ModifiableByteArray getPlainPaddedPremasterSecret() { return plainPaddedPremasterSecret; } public void setPlainPaddedPremasterSecret(ModifiableByteArray plainPaddedPremasterSecret) { this.plainPaddedPremasterSecret = plainPaddedPremasterSecret; } public void setPlainPaddedPremasterSecret(byte[] value) { this.plainPaddedPremasterSecret = ModifiableVariableFactory.safelySetValue(this.plainPaddedPremasterSecret, value); } public void setMasterSecret(ModifiableByteArray masterSecret) { this.masterSecret = masterSecret; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\nClient Key Exchange message:"); return sb.toString(); } }
36.311111
134
0.820379
46f559456dd7279276ee5a06ad59835209c4a5a5
394
package io.jentz.winter.compilertest; import javax.inject.Inject; public class OuterClass { static public class InnerClassWithInjectConstructorAndInjectedFields { @Inject NoArgumentInjectConstructor field0; @Inject OneArgumentInjectConstructor field1; @Inject public InnerClassWithInjectConstructorAndInjectedFields() { } } }
21.888889
74
0.71066
d3f1960430a8b19611daaf82d43b7ae3c43acc0a
16,968
/** * 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.oozie.command.coord; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.util.Date; import java.util.List; import java.util.Properties; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.oozie.CoordinatorActionBean; import org.apache.oozie.CoordinatorJobBean; import org.apache.oozie.ErrorCode; import org.apache.oozie.WorkflowActionBean; import org.apache.oozie.WorkflowJobBean; import org.apache.oozie.action.hadoop.MapperReducerForTest; import org.apache.oozie.client.CoordinatorAction; import org.apache.oozie.client.CoordinatorJob; import org.apache.oozie.client.OozieClient; import org.apache.oozie.client.CoordinatorAction.Status; import org.apache.oozie.command.CommandException; import org.apache.oozie.executor.jpa.CoordActionGetForStartJPAExecutor; import org.apache.oozie.executor.jpa.CoordActionGetJPAExecutor; import org.apache.oozie.executor.jpa.CoordActionInsertJPAExecutor; import org.apache.oozie.executor.jpa.JPAExecutorException; import org.apache.oozie.executor.jpa.WorkflowActionGetJPAExecutor; import org.apache.oozie.executor.jpa.WorkflowActionsGetForJobJPAExecutor; import org.apache.oozie.executor.jpa.WorkflowJobGetJPAExecutor; import org.apache.oozie.service.JPAService; import org.apache.oozie.service.Services; import org.apache.oozie.test.XDataTestCase; import org.apache.oozie.util.DateUtils; import org.apache.oozie.util.IOUtils; import org.apache.oozie.util.XConfiguration; public class TestCoordActionStartXCommand extends XDataTestCase { private Services services; @Override protected void setUp() throws Exception { super.setUp(); services = new Services(); services.init(); } @Override protected void tearDown() throws Exception { services.destroy(); super.tearDown(); } /** * Test the working of CoordActionStartXCommand with standard coord action * XML and then check the action * * @throws IOException * @throws JPAExecutorException * @throws CommandException */ public void testActionStartCommand() throws IOException, JPAExecutorException, CommandException { String actionId = new Date().getTime() + "-COORD-ActionStartCommand-C@1"; addRecordToActionTable(actionId, 1, null); new CoordActionStartXCommand(actionId, "me", "myapp", "myjob").call(); checkCoordAction(actionId); } /** * Coord action XML contains non-supported parameterized action name and * test that CoordActionStartXCommand stores error code and error message in * action's table during error handling * * @throws IOException * @throws JPAExecutorException * @throws CommandException */ public void testActionStartWithErrorReported() throws IOException, JPAExecutorException, CommandException { String actionId = new Date().getTime() + "-COORD-ActionStartCommand-C@1"; String wfApp = "<start to='${someParam}' />"; addRecordToActionTable(actionId, 1, wfApp); new CoordActionStartXCommand(actionId, "me", "myapp", "myjob").call(); final JPAService jpaService = Services.get().get(JPAService.class); CoordinatorActionBean action = jpaService.execute(new CoordActionGetForStartJPAExecutor(actionId)); if (action.getStatus() == CoordinatorAction.Status.SUBMITTED) { fail("Expected status was FAILED due to incorrect XML element"); } assertEquals(action.getErrorCode(), ErrorCode.E0701.toString()); assertTrue(action.getErrorMessage().contains( "XML schema error, cvc-pattern-valid: Value '${someParam}' " + "is not facet-valid with respect to pattern")); } /** * Test : configuration contains url string which should be escaped before put into the evaluator. * If not escape, the error 'SAXParseException' will be thrown and workflow job will not be submitted. * * @throws Exception */ public void testActionStartWithEscapeStrings() throws Exception { Date start = DateUtils.parseDateOozieTZ("2009-12-15T01:00Z"); Date end = DateUtils.parseDateOozieTZ("2009-12-16T01:00Z"); CoordinatorJobBean coordJob = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, start, end, false, false, 1); CoordinatorActionBean action = addRecordToCoordActionTable(coordJob.getId(), 1, CoordinatorAction.Status.SUBMITTED, "coord-action-start-escape-strings.xml", 0); String actionId = action.getId(); new CoordActionStartXCommand(actionId, getTestUser(), "myapp", "myjob").call(); final JPAService jpaService = Services.get().get(JPAService.class); action = jpaService.execute(new CoordActionGetJPAExecutor(actionId)); if (action.getStatus() == CoordinatorAction.Status.SUBMITTED) { fail("CoordActionStartCommand didn't work because the status for action id" + actionId + " is :" + action.getStatus() + " expected to be NOT SUBMITTED (i.e. RUNNING)"); } final String wfId = action.getExternalId(); waitFor(3000, new Predicate() { public boolean evaluate() throws Exception { List<WorkflowActionBean> wfActions = jpaService.execute(new WorkflowActionsGetForJobJPAExecutor(wfId)); return wfActions.size() > 0; } }); List<WorkflowActionBean> wfActions = jpaService.execute(new WorkflowActionsGetForJobJPAExecutor(wfId)); assertTrue(wfActions.size() > 0); final String wfActionId = wfActions.get(0).getId(); waitFor(20 * 1000, new Predicate() { public boolean evaluate() throws Exception { WorkflowActionBean wfAction = jpaService.execute(new WorkflowActionGetJPAExecutor(wfActionId)); return wfAction.getExternalId() != null; } }); WorkflowActionBean wfAction = jpaService.execute(new WorkflowActionGetJPAExecutor(wfActionId)); assertNotNull(wfAction.getExternalId()); } @Override protected Configuration getCoordConf(Path coordAppPath) throws IOException { Path wfAppPath = new Path(getFsTestCaseDir(), "app"); FileSystem fs = getFileSystem(); fs.mkdirs(new Path(wfAppPath, "lib")); File jarFile = IOUtils.createJar(new File(getTestCaseDir()), "test.jar", MapperReducerForTest.class); InputStream is = new FileInputStream(jarFile); OutputStream os = fs.create(new Path(wfAppPath, "lib/test.jar")); IOUtils.copyStream(is, os); Path input = new Path(wfAppPath, "input"); fs.mkdirs(input); Writer writer = new OutputStreamWriter(fs.create(new Path(input, "test.txt"))); writer.write("hello"); writer.close(); final String APP1 = "<workflow-app xmlns='uri:oozie:workflow:0.1' name='app'>" + "<start to='end'/>" + "<end name='end'/>" + "</workflow-app>"; String subWorkflowAppPath = new Path(wfAppPath, "subwf").toString(); fs.mkdirs(new Path(wfAppPath, "subwf")); Writer writer2 = new OutputStreamWriter(fs.create(new Path(subWorkflowAppPath, "workflow.xml"))); writer2.write(APP1); writer2.close(); Reader reader = IOUtils.getResourceAsReader("wf-url-template.xml", -1); Writer writer1 = new OutputStreamWriter(fs.create(new Path(wfAppPath, "workflow.xml"))); IOUtils.copyCharStream(reader, writer1); Properties jobConf = new Properties(); jobConf.setProperty(OozieClient.COORDINATOR_APP_PATH, coordAppPath.toString()); jobConf.setProperty(OozieClient.USER_NAME, getTestUser()); jobConf.setProperty(OozieClient.GROUP_NAME, getTestGroup()); jobConf.setProperty("myJobTracker", getJobTrackerUri()); jobConf.setProperty("myNameNode", getNameNodeUri()); jobConf.setProperty("wfAppPath", new Path(wfAppPath, "workflow.xml").toString()); jobConf.setProperty("mrclass", MapperReducerForTest.class.getName()); jobConf.setProperty("delPath", new Path(wfAppPath, "output").toString()); jobConf.setProperty("subWfApp", new Path(wfAppPath, "subwf/workflow.xml").toString()); return new XConfiguration(jobConf); } private void addRecordToActionTable(String actionId, int actionNum, String wfParam) throws IOException, JPAExecutorException { final JPAService jpaService = Services.get().get(JPAService.class); CoordinatorActionBean action = new CoordinatorActionBean(); action.setJobId(actionId); action.setId(actionId); action.setActionNumber(actionNum); action.setNominalTime(new Date()); action.setStatus(Status.SUBMITTED); File appPath = new File(getTestCaseDir(), "coord/no-op/"); String actionXml = "<coordinator-app xmlns='uri:oozie:coordinator:0.2' xmlns:sla='uri:oozie:sla:0.1' name='NAME' " + "frequency=\"1\" start='2009-02-01T01:00Z' end='2009-02-03T23:59Z' timezone='UTC' freq_timeunit='DAY' " + "end_of_duration='NONE' instance-number=\"1\" action-nominal-time=\"2009-02-01T01:00Z\">"; actionXml += "<controls>"; actionXml += "<timeout>10</timeout>"; actionXml += "<concurrency>2</concurrency>"; actionXml += "<execution>LIFO</execution>"; actionXml += "</controls>"; actionXml += "<input-events>"; actionXml += "<data-in name='A' dataset='a'>"; actionXml += "<dataset name='a' frequency='7' initial-instance='2009-02-01T01:00Z' timezone='UTC' freq_timeunit='DAY' end_of_duration='NONE'>"; actionXml += "<uri-template>" + getTestCaseFileUri("coord/workflows/${YEAR}/${DAY}") + "</uri-template>"; actionXml += "</dataset>"; actionXml += "<instance>${coord:latest(0)}</instance>"; actionXml += "</data-in>"; actionXml += "</input-events>"; actionXml += "<output-events>"; actionXml += "<data-out name='LOCAL_A' dataset='local_a'>"; actionXml += "<dataset name='local_a' frequency='7' initial-instance='2009-02-01T01:00Z' timezone='UTC' freq_timeunit='DAY' end_of_duration='NONE'>"; actionXml += "<uri-template>" + getTestCaseFileUri("coord/workflows/${YEAR}/${DAY}") + "</uri-template>"; actionXml += "</dataset>"; actionXml += "<instance>${coord:current(-1)}</instance>"; actionXml += "</data-out>"; actionXml += "</output-events>"; actionXml += "<action>"; actionXml += "<workflow>"; actionXml += "<app-path>" + appPath.toURI() + "</app-path>"; actionXml += "<configuration>"; actionXml += "<property>"; actionXml += "<name>inputA</name>"; actionXml += "<value>" + getTestCaseFileUri("coord/US//2009/02/01") + "</value>"; actionXml += "</property>"; actionXml += "<property>"; actionXml += "<name>inputB</name>"; actionXml += "<value>" + getTestCaseFileUri("coord/US//2009/02/01") + "</value>"; actionXml += "</property>"; actionXml += "</configuration>"; actionXml += "</workflow>"; String slaXml = " <sla:info xmlns:sla='uri:oozie:sla:0.1'>" + " <sla:app-name>test-app</sla:app-name>" + " <sla:nominal-time>2009-03-06T10:00Z</sla:nominal-time>" + " <sla:should-start>5</sla:should-start>" + " <sla:should-end>120</sla:should-end>" + " <sla:notification-msg>Notifying User for nominal time : 2009-03-06T10:00Z </sla:notification-msg>" + " <sla:alert-contact>abc@example.com</sla:alert-contact>" + " <sla:dev-contact>abc@example.com</sla:dev-contact>" + " <sla:qa-contact>abc@example.com</sla:qa-contact>" + " <sla:se-contact>abc@example.com</sla:se-contact>" + "</sla:info>"; actionXml += slaXml; actionXml += "</action>"; actionXml += "</coordinator-app>"; action.setActionXml(actionXml); action.setSlaXml(slaXml); String createdConf = "<configuration> "; createdConf += "<property> <name>execution_order</name> <value>LIFO</value> </property>"; createdConf += "<property> <name>user.name</name> <value>" + getTestUser() + "</value> </property>"; createdConf += "<property> <name>group.name</name> <value>other</value> </property>"; createdConf += "<property> <name>app-path</name> " + "<value>" + appPath.toURI() + "/</value> </property>"; createdConf += "<property> <name>jobTracker</name> "; createdConf += "<value>localhost:9001</value></property>"; createdConf += "<property> <name>nameNode</name> <value>hdfs://localhost:9000</value></property>"; createdConf += "<property> <name>queueName</name> <value>default</value></property>"; createdConf += "</configuration> "; action.setCreatedConf(createdConf); jpaService.execute(new CoordActionInsertJPAExecutor(action)); String content = "<workflow-app xmlns='uri:oozie:workflow:0.2' xmlns:sla='uri:oozie:sla:0.1' name='no-op-wf'>"; if (wfParam != null) { if (!wfParam.isEmpty()) { content += wfParam; } } else { content += "<start to='end' />"; } String slaXml2 = " <sla:info>" // + " <sla:client-id>axonite-blue</sla:client-id>" + " <sla:app-name>test-app</sla:app-name>" + " <sla:nominal-time>2009-03-06T10:00Z</sla:nominal-time>" + " <sla:should-start>5</sla:should-start>" + " <sla:should-end>${2 * HOURS}</sla:should-end>" + " <sla:notification-msg>Notifying User for nominal time : 2009-03-06T10:00Z </sla:notification-msg>" + " <sla:alert-contact>abc@example.com</sla:alert-contact>" + " <sla:dev-contact>abc@example.com</sla:dev-contact>" + " <sla:qa-contact>abc@example.com</sla:qa-contact>" + " <sla:se-contact>abc@example.com</sla:se-contact>" + "</sla:info>"; content += "<end name='end' />" + slaXml2 + "</workflow-app>"; writeToFile(content, appPath.getAbsolutePath()); } private void checkCoordAction(String actionId) { try { final JPAService jpaService = Services.get().get(JPAService.class); CoordinatorActionBean action = jpaService.execute(new CoordActionGetJPAExecutor(actionId)); if (action.getStatus() == CoordinatorAction.Status.SUBMITTED) { fail("CoordActionStartCommand didn't work because the status for action id" + actionId + " is :" + action.getStatus() + " expected to be NOT SUBMITTED (i.e. RUNNING)"); } if (action.getExternalId() != null) { WorkflowJobBean wfJob = jpaService.execute(new WorkflowJobGetJPAExecutor(action.getExternalId())); assertEquals(wfJob.getParentId(), action.getId()); } } catch (JPAExecutorException je) { fail("Action ID " + actionId + " was not stored properly in db"); } } private void writeToFile(String content, String appPath) throws IOException { createDir(appPath); File wf = new File(appPath, "workflow.xml"); PrintWriter out = null; try { out = new PrintWriter(new FileWriter(wf)); out.println(content); } catch (IOException iex) { iex.printStackTrace(); throw iex; } finally { if (out != null) { out.close(); } } } private void createDir(String dir) { new File(dir, "_SUCCESS").mkdirs(); } }
48.48
157
0.648161
1e4425ccfd43cc37aa026bd2ded1503b13cfde47
3,655
/* * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.uber.cadence.internal.replay; import com.uber.cadence.CancelTimerDecisionAttributes; import com.uber.cadence.Decision; import com.uber.cadence.DecisionType; import com.uber.cadence.HistoryEvent; import com.uber.cadence.StartTimerDecisionAttributes; /** * Timer doesn't have separate initiation decision as it is started immediately. But from the state * machine point of view it is modeled the same as activity with no TimerStarted event used as * initiation event. * * @author fateev */ class TimerDecisionStateMachine extends DecisionStateMachineBase { private StartTimerDecisionAttributes attributes; private boolean canceled; public TimerDecisionStateMachine(DecisionId id, StartTimerDecisionAttributes attributes) { super(id); this.attributes = attributes; } /** Used for unit testing */ TimerDecisionStateMachine( DecisionId id, StartTimerDecisionAttributes attributes, DecisionState state) { super(id, state); this.attributes = attributes; } @Override public Decision getDecision() { switch (state) { case CREATED: return createStartTimerDecision(); case CANCELED_AFTER_INITIATED: return createCancelTimerDecision(); default: return null; } } @Override public void handleDecisionTaskStartedEvent() { switch (state) { case CANCELED_AFTER_INITIATED: stateHistory.add("handleDecisionTaskStartedEvent"); state = DecisionState.CANCELLATION_DECISION_SENT; stateHistory.add(state.toString()); break; default: super.handleDecisionTaskStartedEvent(); } } @Override public void handleCancellationFailureEvent(HistoryEvent event) { switch (state) { case CANCELLATION_DECISION_SENT: stateHistory.add("handleCancellationFailureEvent"); state = DecisionState.INITIATED; stateHistory.add(state.toString()); break; default: super.handleCancellationFailureEvent(event); } } @Override public void cancel(Runnable immediateCancellationCallback) { canceled = true; immediateCancellationCallback.run(); super.cancel(null); } /** * As timer is canceled immediately there is no need for waiting after cancellation decision was * sent. */ @Override public boolean isDone() { return state == DecisionState.COMPLETED || canceled; } private Decision createCancelTimerDecision() { CancelTimerDecisionAttributes tryCancel = new CancelTimerDecisionAttributes(); tryCancel.setTimerId(attributes.getTimerId()); Decision decision = new Decision(); decision.setCancelTimerDecisionAttributes(tryCancel); decision.setDecisionType(DecisionType.CancelTimer); return decision; } private Decision createStartTimerDecision() { Decision decision = new Decision(); decision.setStartTimerDecisionAttributes(attributes); decision.setDecisionType(DecisionType.StartTimer); return decision; } }
30.206612
99
0.729959
bc4c9d0eac75afbed63cc9672113f71be15037f0
761
package sparkengine.plan.model.plan.visitor; import lombok.Value; import sparkengine.plan.model.plan.Plan; import sparkengine.plan.model.plan.mapper.PlanMapper; import sparkengine.plan.model.plan.mapper.PlanMapperException; import javax.annotation.Nonnull; import java.util.Arrays; import java.util.List; @Value public class PlanVisitors implements PlanMapper { @Nonnull List<PlanMapper> planMappers; public static PlanMapper ofMappers(PlanMapper... planMappers) { return new PlanVisitors(Arrays.asList(planMappers)); } @Override public @Nonnull Plan map(@Nonnull Plan plan) throws PlanMapperException { for (var planResolver : planMappers) plan = planResolver.map(plan); return plan; } }
24.548387
77
0.738502
359567d83a063eb734cae3f71396e338a9f80e88
2,755
package com.kaleido.kaptureclient.domain; import javax.validation.constraints.*; import java.io.Serializable; import java.time.ZonedDateTime; import java.util.Objects; /** * Chemistry Notebook */ public class Notebook implements Serializable { private static final long serialVersionUID = 1L; private Long id; @NotNull private String name; private ZonedDateTime dateCreated; @Size(max = 4000) private String description; private String location; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public Notebook name(String name) { this.name = name; return this; } public void setName(String name) { this.name = name; } public ZonedDateTime getDateCreated() { return dateCreated; } public Notebook dateCreated(ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } public void setDateCreated(ZonedDateTime dateCreated) { this.dateCreated = dateCreated; } public String getDescription() { return description; } public Notebook description(String description) { this.description = description; return this; } public void setDescription(String description) { this.description = description; } public String getLocation() { return location; } public Notebook location(String location) { this.location = location; return this; } public void setLocation(String location) { this.location = location; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Notebook notebook = (Notebook) o; if (notebook.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), notebook.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Notebook{" + "id=" + getId() + ", name='" + getName() + "'" + ", dateCreated='" + getDateCreated() + "'" + ", description='" + getDescription() + "'" + ", location='" + getLocation() + "'" + "}"; } }
22.768595
109
0.581488
d0bfe3288b19fdee91ded0103c06f5412db9ead9
1,131
package uk.co.idv.method.entities.push; import lombok.AccessLevel; import lombok.Builder; import lombok.Data; import lombok.Getter; import uk.co.idv.method.entities.eligibility.Eligibility; import uk.co.idv.method.entities.eligibility.Eligible; import uk.co.idv.method.entities.method.Method; import uk.co.idv.method.entities.method.MethodConfig; import uk.co.idv.method.entities.push.eligibility.NoMobileDevicesRegistered; import java.util.Collection; import java.util.Collections; @Builder(toBuilder = true) @Data public class PushNotification implements Method { @Getter(AccessLevel.NONE) private final PushNotificationConfig config; @Builder.Default private final Collection<String> mobileDeviceTokens = Collections.emptyList(); @Override public String getName() { return PushNotificationName.NAME; } @Override public Eligibility getEligibility() { if (mobileDeviceTokens.isEmpty()) { return new NoMobileDevicesRegistered(); } return new Eligible(); } @Override public MethodConfig getConfig() { return config; } }
25.704545
82
0.735632
f95d4bb90d874922800611ec6c564baed2197c23
760
package com.puntoslash.dipandroid; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.support.v4.content.Loader; /** * Created by antonio on 10/29/15. */ public class JobPostContentObserver extends ContentObserver { private Loader<Cursor> cursorLoader; /** * Creates a content observer. * * @param handler The handler to run {@link #onChange} on, or null if none. */ public JobPostContentObserver(Handler handler, Loader<Cursor> cursorLoader) { super(handler); this.cursorLoader = cursorLoader; } @Override public void onChange(boolean selfChange, Uri uri) { cursorLoader.onContentChanged(); } }
27.142857
81
0.707895
7080157b45c8877bd18afe2453a341545d2aede6
320
package com.tpxt.utils; import java.util.regex.Pattern; /** * 数字工具类 * @author zhoush */ public class NumberUtil { private static final Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); public static boolean isNumber(String str) { return pattern.matcher(str).matches(); } }
18.823529
79
0.6125
b80d55fc62227991d1faa649496d3d1eaad6d129
1,959
package com.github.stefvanschie.quickskript.bukkit.psi.condition; import com.github.stefvanschie.quickskript.core.context.Context; import com.github.stefvanschie.quickskript.core.psi.PsiElement; import com.github.stefvanschie.quickskript.core.psi.condition.PsiIsBurningCondition; import com.github.stefvanschie.quickskript.core.skript.SkriptRunEnvironment; import org.bukkit.entity.Entity; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Checks whether an entity is burning. This cannot be pre computed, since an entity can get burned and/or extinguished * during game play. * * @since 0.1.0 */ public class PsiIsBurningConditionImpl extends PsiIsBurningCondition { /** * Creates a new element with the given line number * * @param entity the entity to check whether they are burning * @param positive false if the execution result needs to be inverted * @param lineNumber the line number this element is associated with * @since 0.1.0 */ private PsiIsBurningConditionImpl(@NotNull PsiElement<?> entity, boolean positive, int lineNumber) { super(entity, positive, lineNumber); } @NotNull @Contract(pure = true) @Override protected Boolean executeImpl(@Nullable SkriptRunEnvironment environment, @Nullable Context context) { return positive == (entity.execute(environment, context, Entity.class).getFireTicks() > 0); } /** * A factory for creating {@link PsiIsBurningConditionImpl}s * * @since 0.1.0 */ public static class Factory extends PsiIsBurningCondition.Factory { @NotNull @Contract(pure = true) @Override public PsiIsBurningCondition create(@NotNull PsiElement<?> entity, boolean positive, int lineNumber) { return new PsiIsBurningConditionImpl(entity, positive, lineNumber); } } }
36.277778
119
0.726901
2f11310e31e4e7f2eeca779cd1eba08167a31694
1,394
package com.mobilepolice.officeMobile.utils; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; public class BitmapUtils { /** * 图片合成 之 圆角矩形 * * @param src 源图片 * @param radius 圆角半径 * @return 圆角图片 */ public static Bitmap ovalRectangleBitmap(Bitmap src, float radius) { Bitmap bitmap = src.copy(Bitmap.Config.ARGB_4444, true); Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(dest); RectF rectF = new RectF(); rectF.left = 0; rectF.right = bitmap.getWidth(); rectF.top = 0; rectF.bottom = bitmap.getHeight(); Paint paint = new Paint(); paint.setColor(Color.argb(255, 255, 255, 255)); paint.setAntiAlias(true); canvas.drawRoundRect(rectF, radius, radius, paint); canvas.save(); Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); canvas.save(); bitmap.recycle(); return dest; } }
30.977778
100
0.65495
f73fee8647c2a114209574071d52dc2ec671993b
1,924
// Targeted by JavaCPP version 1.5.5: DO NOT EDIT THIS FILE package org.bytedeco.liquidfun; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.liquidfun.global.liquidfun.*; /** The features that intersect to form the contact point * This must be 4 bytes or less. */ @Properties(inherit = org.bytedeco.liquidfun.presets.liquidfun.class) public class b2ContactFeature extends Pointer { static { Loader.load(); } /** Default native constructor. */ public b2ContactFeature() { super((Pointer)null); allocate(); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public b2ContactFeature(long size) { super((Pointer)null); allocateArray(size); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public b2ContactFeature(Pointer p) { super(p); } private native void allocate(); private native void allocateArray(long size); @Override public b2ContactFeature position(long position) { return (b2ContactFeature)super.position(position); } @Override public b2ContactFeature getPointer(long i) { return new b2ContactFeature((Pointer)this).position(position + i); } /** enum b2ContactFeature::Type */ public static final int e_vertex = 0, e_face = 1; /** Feature index on shapeA */ public native @Cast("uint8") short indexA(); public native b2ContactFeature indexA(short setter); /** Feature index on shapeB */ public native @Cast("uint8") short indexB(); public native b2ContactFeature indexB(short setter); /** The feature type on shapeA */ public native @Cast("uint8") short typeA(); public native b2ContactFeature typeA(short setter); /** The feature type on shapeB */ public native @Cast("uint8") short typeB(); public native b2ContactFeature typeB(short setter); }
40.083333
98
0.724012
96b96c0d7ac6a32e574b08932a96db5043a86f79
3,539
package com.readmill.api; import org.apache.http.client.methods.HttpGet; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; public class RequestBuilderTest { RequestBuilder instance; ReadmillWrapper mWrapper; @Before public void createInstance() { Environment testEnvironment = new Environment("api.example.com", "example.com", true); mWrapper = new ReadmillWrapper("client_id", "client_secret", testEnvironment); instance = new RequestBuilder(mWrapper, HttpGet.class, "/users/1/readings"); } @Test public void getRequest() { assertThat(instance.getRequest().toUrl(), containsString("/v2/users/1/readings")); } @Test public void chainableParamBuilder() { String queryString = instance.order("followers").highlightsCountFrom(50).getRequest().queryString(); assertThat(queryString, containsString("order=followers")); assertThat(queryString, containsString("highlights_count%5Bfrom%5D=50")); } @Test public void fetchOrThrow() throws JSONException, IOException { JSONObject user = new JSONObject("{ \"user\": { \"username\": \"christoffer\", id: 1 } }"); JSONObject json = builderWithStubbedResponseText(user.toString()).fetchOrThrow(); assertThat(json.toString(), is(user.toString())); } @Test public void fetchOrThrowString() throws JSONException, IOException { JSONObject user = new JSONObject("{ \"user\": { \"username\": \"christoffer\", id: 1 } }"); JSONObject json = builderWithStubbedResponseText(user.toString()).fetchOrThrow("user"); assertThat(json.toString(), is(user.optJSONObject("user").toString())); } @Test public void fetchItemsOrThrow() throws JSONException, IOException { JSONObject userOne = new JSONObject("{ \"user\": { \"username\": \"christoffer\", id: 1 } }"); JSONObject userTwo = new JSONObject("{ \"user\": { \"username\": \"niki\", id: 387 } }"); JSONObject usersWrapped = new JSONObject("{ \"items\": [ " + userOne.toString() + ", " + userTwo.toString() + " ]}"); JSONArray usersWithoutRoot = new JSONArray(); usersWithoutRoot.put(userOne); usersWithoutRoot.put(userTwo); JSONArray json = builderWithStubbedResponseText(usersWrapped.toString()).fetchItemsOrThrow(); assertThat(json.toString(), is(usersWithoutRoot.toString())); } @Test public void fetchItemsOrThrowString() throws JSONException, IOException { JSONObject userOne = new JSONObject("{ \"user\": { \"username\": \"christoffer\", id: 1 } }"); JSONObject userTwo = new JSONObject("{ \"user\": { \"username\": \"niki\", id: 387 } }"); JSONObject usersWrapped = new JSONObject("{ \"items\": [ " + userOne.toString() + ", " + userTwo.toString() + " ]}"); JSONArray usersUnwrapped = new JSONArray(); usersUnwrapped.put(userOne.getJSONObject("user")); usersUnwrapped.put(userTwo.getJSONObject("user")); JSONArray json = builderWithStubbedResponseText(usersWrapped.toString()).fetchItemsOrThrow("user"); assertThat(json.toString(), is(usersUnwrapped.toString())); } /* Private helpers */ private RequestBuilder builderWithStubbedResponseText(String jsonText) throws JSONException, IOException { RequestBuilder builder = Mockito.spy(instance); Mockito.doReturn(jsonText).when(builder).getResponseText(); return builder; } }
38.053763
121
0.708392
0d65bcd870bab27ea59b2a3c6acec30816c90ebb
969
package com.twu.biblioteca.service; import com.twu.biblioteca.controller.Request; import com.twu.biblioteca.dao.impl.BooksDao; import com.twu.biblioteca.service.impl.BookListService; import org.junit.Before; import org.junit.Test; import java.io.PrintStream; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class BookListServiceTest { private BookListService bookListService; private PrintStream printStream; private Request request; @Before public void setUp(){ bookListService = new BookListService(); printStream = mock(PrintStream.class); request = mock(Request.class); } @Test public void test01_shouldPrintRightBookList(){ bookListService.exec(printStream,request); verify(printStream).println("Here are the available books:"); verify(printStream).println("1 {Agile|Martin Fowler|1993}\n" +"2 {Agile2|Martin Fowler|1994}\n"); } }
27.685714
105
0.731682
d5fbc6cbefc34d9383bc0d612ecf96002967b027
1,076
package com.spacegame.game.item; import com.spacegame.game.SolGame; import java.util.List; public class TradeContainer { private static final float MAX_AWAIT = 180f; private final TradeConfig myConfig; private final ItemContainer myItems; private float myAwait; public TradeContainer(TradeConfig config) { myConfig = config; myItems = new ItemContainer(); } public void update(SolGame game) { if (0 < myAwait) { myAwait -= game.getTimeStep(); return; } myAwait = MAX_AWAIT; myItems.clear(); List<ItemConfig> items = myConfig.items; for (int i1 = 0, sz = items.size(); i1 < sz; i1++) { ItemConfig i = items.get(i1); SolItem ex = i.examples.get(0); int amt = ex.isSame(ex) ? 16 : 1; for (int j = 0; j < amt; j++) { if (myItems.canAdd(ex)) myItems.add(ex.copy()); } } } public ItemContainer getItems() { return myItems; } public ItemContainer getShips() { return myConfig.hulls; } public ItemContainer getMercs() { return myConfig.mercs; } }
21.098039
56
0.633829
d76ceb43c779ff611a47382fae0c5425ae17ffdd
473
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.reactornetty.v1_0; public final class ReactorContextKeys { public static final String CLIENT_PARENT_CONTEXT_KEY = ReactorContextKeys.class.getName() + ".client-parent-context"; public static final String CLIENT_CONTEXT_KEY = ReactorContextKeys.class.getName() + ".client-context"; private ReactorContextKeys() {} }
27.823529
69
0.767442
42fc0e24155f100b4865a10a41917e7b17d7cfd2
895
package cn.neyzoter.designpattern.factory; /** * 简单工厂模式<br/> * 简单工厂模式通常就是这样,<br/> * 一个工厂类 XxxFactory,里面有一个静态方法,<br/> * 根据我们不同的参数,返回不同的派生自同一个父类<br/> * (或实现同一接口)的实例对象。 * @author Charles Song * @date 2020-6-12 */ public class SimpleFactory { public static void main (String[] args) { Food food = FoodFactory.makeFood("Egg", 10); System.out.println("Egg's weight is " + food.weight); } } class FoodFactory { public static Food makeFood (String name, int w) { if (name.equals("Egg")) { return new Egg(w); } else if (name.equals("Chicken")) { return new Chicken(w); } else { return null; } } } class Food { int weight; } class Egg extends Food { public Egg (int w) { weight = w; } } class Chicken extends Food { public Chicken (int w) { weight = w; } }
19.888889
61
0.573184
3e05ffca1832a13f5e8727cda540a59cf2661de7
3,212
/* LCM type definition class file * This file was automatically generated by lcm-gen * DO NOT MODIFY BY HAND!!!! */ package lcmtypes; import java.io.*; import java.util.*; import lcm.lcm.*; public final class control_parameter_respones_lcmt implements lcm.lcm.LCMEncodable { public byte name[]; public long requestNumber; public byte value[]; public byte parameterKind; public byte requestKind; public control_parameter_respones_lcmt() { name = new byte[64]; value = new byte[64]; } public static final long LCM_FINGERPRINT; public static final long LCM_FINGERPRINT_BASE = 0xe827e9f6525296b9L; static { LCM_FINGERPRINT = _hashRecursive(new ArrayList<Class<?>>()); } public static long _hashRecursive(ArrayList<Class<?>> classes) { if (classes.contains(lcmtypes.control_parameter_respones_lcmt.class)) return 0L; classes.add(lcmtypes.control_parameter_respones_lcmt.class); long hash = LCM_FINGERPRINT_BASE ; classes.remove(classes.size() - 1); return (hash<<1) + ((hash>>63)&1); } public void encode(DataOutput outs) throws IOException { outs.writeLong(LCM_FINGERPRINT); _encodeRecursive(outs); } public void _encodeRecursive(DataOutput outs) throws IOException { outs.write(this.name, 0, 64); outs.writeLong(this.requestNumber); outs.write(this.value, 0, 64); outs.writeByte(this.parameterKind); outs.writeByte(this.requestKind); } public control_parameter_respones_lcmt(byte[] data) throws IOException { this(new LCMDataInputStream(data)); } public control_parameter_respones_lcmt(DataInput ins) throws IOException { if (ins.readLong() != LCM_FINGERPRINT) throw new IOException("LCM Decode error: bad fingerprint"); _decodeRecursive(ins); } public static lcmtypes.control_parameter_respones_lcmt _decodeRecursiveFactory(DataInput ins) throws IOException { lcmtypes.control_parameter_respones_lcmt o = new lcmtypes.control_parameter_respones_lcmt(); o._decodeRecursive(ins); return o; } public void _decodeRecursive(DataInput ins) throws IOException { this.name = new byte[(int) 64]; ins.readFully(this.name, 0, 64); this.requestNumber = ins.readLong(); this.value = new byte[(int) 64]; ins.readFully(this.value, 0, 64); this.parameterKind = ins.readByte(); this.requestKind = ins.readByte(); } public lcmtypes.control_parameter_respones_lcmt copy() { lcmtypes.control_parameter_respones_lcmt outobj = new lcmtypes.control_parameter_respones_lcmt(); outobj.name = new byte[(int) 64]; System.arraycopy(this.name, 0, outobj.name, 0, 64); outobj.requestNumber = this.requestNumber; outobj.value = new byte[(int) 64]; System.arraycopy(this.value, 0, outobj.value, 0, 64); outobj.parameterKind = this.parameterKind; outobj.requestKind = this.requestKind; return outobj; } }
27.452991
116
0.655978
3019bb9289f181cb6608b9ea891b1f3960b021e8
1,743
/* * Copyright (C) 2012 Google, Inc. * Copyright (C) 2021 The LineageOS Project * * 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.jpb.eleven.utils; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; /** * Provides static methods for creating {@code List} instances easily, and other * utility methods for working with lists. */ public final class Lists { /** * This class is never instantiated */ public Lists() { } /** * Creates an empty {@code ArrayList} instance. * <p> * <b>Note:</b> if you only need an <i>immutable</i> empty List, use * {@link Collections#emptyList} instead. * * @return a newly-created, initially-empty {@code ArrayList} */ public static <E> ArrayList<E> newArrayList() { return new ArrayList<>(); } /** * Creates an empty {@code LinkedList} instance. * <p> * <b>Note:</b> if you only need an <i>immutable</i> empty List, use * {@link Collections#emptyList} instead. * * @return a newly-created, initially-empty {@code LinkedList} */ public static <E> LinkedList<E> newLinkedList() { return new LinkedList<>(); } }
29.05
80
0.659208
283d366106e82ab95b2a96d1432c0624ef02e603
7,243
class QuickSort { public static void main(String[] a) { QS mtTmp2; int mtTmp3; int mtTmp1; mtTmp2 = new QS(); mtTmp3 = 10; mtTmp1 = mtTmp2.Start(mtTmp3); System.out.println(mtTmp1); } } class QS { int[] number; int size; public int Start(int sz) { int aux01; QS mtTmp5; int mtTmp4; QS mtTmp7; int mtTmp6; int mtTmp8; int mtTmp9; int mtTmp10; QS mtTmp12; int mtTmp13; int mtTmp11; QS mtTmp15; int mtTmp14; int mtTmp16; mtTmp5 = this; mtTmp4 = mtTmp5.Init(sz); aux01 = mtTmp4; mtTmp7 = this; mtTmp6 = mtTmp7.Print(); aux01 = mtTmp6; mtTmp8 = 9999; System.out.println(mtTmp8); mtTmp10 = 1; mtTmp9 = size - mtTmp10; aux01 = mtTmp9; mtTmp12 = this; mtTmp13 = 0; mtTmp11 = mtTmp12.Sort(mtTmp13,aux01); aux01 = mtTmp11; mtTmp15 = this; mtTmp14 = mtTmp15.Print(); aux01 = mtTmp14; mtTmp16 = 0; return mtTmp16; } public int Sort(int left, int right) { int v; int i; int j; int nt; int t; boolean cont01; boolean cont02; int aux03; int mtTmp17; boolean mtTmp18; int mtTmp19; int mtTmp20; int mtTmp21; boolean mtTmp22; boolean mtTmp23; int mtTmp24; int mtTmp25; int mtTmp26; boolean mtTmp27; boolean mtTmp28; boolean mtTmp29; boolean mtTmp30; boolean mtTmp31; int mtTmp32; int mtTmp33; int mtTmp34; boolean mtTmp35; boolean mtTmp36; boolean mtTmp37; boolean mtTmp38; int mtTmp39; int mtTmp40; boolean mtTmp41; int mtTmp42; int mtTmp43; boolean mtTmp44; boolean mtTmp45; int mtTmp46; int mtTmp47; QS mtTmp49; int mtTmp50; int mtTmp51; int mtTmp48; QS mtTmp53; int mtTmp54; int mtTmp55; int mtTmp52; int mtTmp56; int mtTmp57; mtTmp17 = 0; t = mtTmp17; mtTmp18 = left < right; if(mtTmp18) { { mtTmp19 = number[right]; v = mtTmp19; mtTmp21 = 1; mtTmp20 = left - mtTmp21; i = mtTmp20; j = right; mtTmp22 = true; cont01 = mtTmp22; while(cont01) { { mtTmp23 = true; cont02 = mtTmp23; while(cont02) { { mtTmp25 = 1; mtTmp24 = i + mtTmp25; i = mtTmp24; mtTmp26 = number[i]; aux03 = mtTmp26; mtTmp28 = aux03 < v; mtTmp27 = !mtTmp28; if(mtTmp27) { mtTmp29 = false; cont02 = mtTmp29; } else { mtTmp30 = true; cont02 = mtTmp30; } } } mtTmp31 = true; cont02 = mtTmp31; while(cont02) { { mtTmp33 = 1; mtTmp32 = j - mtTmp33; j = mtTmp32; mtTmp34 = number[j]; aux03 = mtTmp34; mtTmp36 = v < aux03; mtTmp35 = !mtTmp36; if(mtTmp35) { mtTmp37 = false; cont02 = mtTmp37; } else { mtTmp38 = true; cont02 = mtTmp38; } } } mtTmp39 = number[i]; t = mtTmp39; mtTmp40 = number[j]; number[i] = mtTmp40; number[j] = t; mtTmp43 = 1; mtTmp42 = i + mtTmp43; mtTmp41 = j < mtTmp42; if(mtTmp41) { mtTmp44 = false; cont01 = mtTmp44; } else { mtTmp45 = true; cont01 = mtTmp45; } } } mtTmp46 = number[i]; number[j] = mtTmp46; mtTmp47 = number[right]; number[i] = mtTmp47; number[right] = t; mtTmp49 = this; mtTmp51 = 1; mtTmp50 = i - mtTmp51; mtTmp48 = mtTmp49.Sort(left,mtTmp50); nt = mtTmp48; mtTmp53 = this; mtTmp55 = 1; mtTmp54 = i + mtTmp55; mtTmp52 = mtTmp53.Sort(mtTmp54,right); nt = mtTmp52; } } else { mtTmp56 = 0; nt = mtTmp56; } mtTmp57 = 0; return mtTmp57; } public int Print() { int j; int mtTmp58; boolean mtTmp59; int mtTmp60; int mtTmp61; int mtTmp62; int mtTmp63; int mtTmp64; mtTmp58 = 0; j = mtTmp58; mtTmp60 = size; mtTmp59 = j < mtTmp60; while(mtTmp59) { { mtTmp61 = number[j]; System.out.println(mtTmp61); mtTmp63 = 1; mtTmp62 = j + mtTmp63; j = mtTmp62; } mtTmp60 = size; mtTmp59 = j < mtTmp60; } mtTmp64 = 0; return mtTmp64; } public int Init(int sz) { int[] mtTmp65; int mtTmp66; int mtTmp67; int mtTmp68; int mtTmp69; int mtTmp70; int mtTmp71; int mtTmp72; int mtTmp73; int mtTmp74; int mtTmp75; int mtTmp76; int mtTmp77; int mtTmp78; int mtTmp79; int mtTmp80; int mtTmp81; int mtTmp82; int mtTmp83; int mtTmp84; int mtTmp85; int mtTmp86; size = sz; mtTmp65 = new int[sz]; number = mtTmp65; mtTmp66 = 0; mtTmp67 = 20; number[mtTmp66] = mtTmp67; mtTmp68 = 1; mtTmp69 = 7; number[mtTmp68] = mtTmp69; mtTmp70 = 2; mtTmp71 = 12; number[mtTmp70] = mtTmp71; mtTmp72 = 3; mtTmp73 = 18; number[mtTmp72] = mtTmp73; mtTmp74 = 4; mtTmp75 = 2; number[mtTmp74] = mtTmp75; mtTmp76 = 5; mtTmp77 = 11; number[mtTmp76] = mtTmp77; mtTmp78 = 6; mtTmp79 = 6; number[mtTmp78] = mtTmp79; mtTmp80 = 7; mtTmp81 = 9; number[mtTmp80] = mtTmp81; mtTmp82 = 8; mtTmp83 = 19; number[mtTmp82] = mtTmp83; mtTmp84 = 9; mtTmp85 = 5; number[mtTmp84] = mtTmp85; mtTmp86 = 0; return mtTmp86; } }
25.59364
50
0.408809
55bf6aabdc0d5b304113758b455872639f99bdc0
2,517
/* * Copyright 2009 Inspire-Software.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 org.yes.cart.service.async.impl; import org.junit.Test; import org.yes.cart.service.async.JobStatusListener; import org.yes.cart.service.async.model.JobStatus; import static org.junit.Assert.*; /** * User: denispavlov * Date: 24/04/2020 * Time: 21:03 */ public class JobStatusListenerImplTest { @Test public void testListener() throws Exception { final JobStatusListener listener = new JobStatusListenerImpl(); listener.notifyPing("Some message {}", "text"); listener.count("count"); listener.notifyWarning("Warn"); listener.notifyError("Error"); listener.notifyCompleted(); assertTrue(listener.isCompleted()); assertEquals(1, listener.getCount("count")); assertEquals(JobStatus.State.FINISHED, listener.getLatestStatus().getState()); assertEquals(JobStatus.Completion.ERROR, listener.getLatestStatus().getCompletion()); assertEquals( "WARNING: Warn\n" + "ERROR: Error\n" + "Completed " + listener.getJobToken() + " with status ERROR, err: 1, warn: 1\n" + "Counters [count: 1]", listener.getLatestStatus().getReport()); listener.reset(); listener.notifyPing("Some other message {}", "text"); listener.count("count"); listener.count("count", 5); listener.notifyCompleted(); assertTrue(listener.isCompleted()); assertEquals(6, listener.getCount("count")); assertEquals(JobStatus.State.FINISHED, listener.getLatestStatus().getState()); assertEquals(JobStatus.Completion.OK, listener.getLatestStatus().getCompletion()); assertEquals( "Completed " + listener.getJobToken() + " with status OK, err: 0, warn: 0\n" + "Counters [count: 6]", listener.getLatestStatus().getReport()); } }
35.450704
97
0.655542
15ce182221ee5666349707b28e4f136145875d64
2,441
/* * 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.netbeans.core; import java.net.Authenticator; import java.net.Inet4Address; import java.net.PasswordAuthentication; import java.net.URL; import java.util.concurrent.Callable; import org.netbeans.junit.NbTestCase; import org.openide.util.NetworkSettings; /** * * @author Ondrej Vrabec */ public class NbAuthenticatorTest extends NbTestCase { public NbAuthenticatorTest(String name) { super(name); } public void testUserInfoInUrl () throws Exception { NbAuthenticator.install4test(); PasswordAuthentication auth = Authenticator.requestPasswordAuthentication("wher.ev.er", Inet4Address.getByName("1.2.3.4"), 1234, "http", null, "http", new URL("http://user:password@wher.ev.er/resource"), Authenticator.RequestorType.SERVER); assertNotNull(auth); assertEquals("user", auth.getUserName()); assertEquals("password", new String(auth.getPassword())); } public void testSupressedAuthenticator () throws Exception { NbAuthenticator.install4test(); PasswordAuthentication auth = NetworkSettings.suppressAuthenticationDialog(new Callable<PasswordAuthentication>() { @Override public PasswordAuthentication call () throws Exception { return Authenticator.requestPasswordAuthentication("wher.ev.er", Inet4Address.getByName("1.2.3.4"), 1234, "http", null, "http", new URL("http://user:password@wher.ev.er/resource"), Authenticator.RequestorType.SERVER); } }); assertNull(auth); } }
39.370968
158
0.697665
869d7ff9639d7f788bf67dee8b64f3d1ee722dad
701
package com.jetbrains.python.debugger.pydev; public abstract class AbstractThreadCommand<T> extends AbstractCommand<T> { private final String myThreadId; protected AbstractThreadCommand(final RemoteDebugger debugger, final int commandCode, final String threadId) { super(debugger, commandCode); myThreadId = threadId; } @Override protected void buildPayload(Payload payload) { payload.add(myThreadId); } public static boolean isThreadCommand(int command) { return command == CREATE_THREAD || command == KILL_THREAD || command == RESUME_THREAD || command == SUSPEND_THREAD || command == SHOW_CONSOLE; } public String getThreadId() { return myThreadId; } }
20.617647
109
0.743224
22b1bb682342a9763f738b4609809f2b7bf14509
2,118
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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 internal.http.api; import org.apache.synapse.rest.cors.CORSConfiguration; import org.wso2.carbon.inbound.endpoint.internal.http.api.APIResource; import org.wso2.carbon.inbound.endpoint.internal.http.api.InternalAPI; import org.wso2.carbon.inbound.endpoint.internal.http.api.InternalAPIHandler; import java.util.List; public class SampleInternalAPI implements InternalAPI { private String name; private List<InternalAPIHandler> handlerList = null; private CORSConfiguration corsConfiguration = null; @Override public APIResource[] getResources() { APIResource[] resources = new APIResource[1]; resources[0] = new SampleResource("/bar"); return resources; } @Override public String getContext() { return "/foo"; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public void setHandlers(List<InternalAPIHandler> handlerList) { this.handlerList = handlerList; } @Override public List<InternalAPIHandler> getHandlers() { return this.handlerList; } @Override public void setCORSConfiguration(CORSConfiguration corsConfiguration) { this.corsConfiguration = corsConfiguration; } @Override public CORSConfiguration getCORSConfiguration() { return corsConfiguration; } }
27.868421
77
0.706799
2f30d7ae512d517dfbaeeffc5dc31d1eb0e1405d
16,868
/** * Copyright (c) Microsoft Corporation * * All rights reserved. * * MIT License * * 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 com.microsoft.azuretools.azureexplorer.editors; import java.text.SimpleDateFormat; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.EditorPart; import com.microsoft.tooling.msservices.components.DefaultLoader; import com.microsoft.azuretools.azurecommons.helpers.AzureCmdException; import com.microsoft.azuretools.azureexplorer.Activator; import com.microsoft.azuretools.azureexplorer.forms.QueueMessageForm; import com.microsoft.azuretools.azureexplorer.forms.ViewMessageForm; import com.microsoft.azuretools.azureexplorer.helpers.UIHelperImpl; import com.microsoft.azuretools.core.utils.PluginUtil; import com.microsoft.tooling.msservices.helpers.azure.sdk.StorageClientSDKManager; import com.microsoft.tooling.msservices.model.storage.ClientStorageAccount; import com.microsoft.tooling.msservices.model.storage.Queue; import com.microsoft.tooling.msservices.model.storage.QueueMessage; import com.microsoft.tooling.msservices.serviceexplorer.NodeActionEvent; import com.microsoft.tooling.msservices.serviceexplorer.NodeActionListener; public class QueueFileEditor extends EditorPart { private static final String OPEN = "Open"; private static final String DEQUEUE = "Dequeue"; private static final String REFRESH = "Refresh"; private static final String ADD = "Add"; private static final String CLEAR_QUEUE = "Clear queue"; private ClientStorageAccount storageAccount; private Queue queue; private Button dequeueMessageButton; private Button refreshButton; private Button addMessageButton; private Button clearQueueButton; private Table queueTable; private TableViewer tableViewer; private List<QueueMessage> queueMessages; private FileEditorVirtualNode<EditorPart> fileEditorVirtualNode; @Override public void doSave(IProgressMonitor iProgressMonitor) { } @Override public void doSaveAs() { } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { /* setSite(site); setInput(input); storageAccount = ((StorageEditorInput) input).getStorageAccount(); queue = (Queue) ((StorageEditorInput) input).getItem(); setPartName(queue.getName() + " [Queue]");*/ fileEditorVirtualNode = createVirtualNode(""); } @Override public boolean isDirty() { return false; } @Override public boolean isSaveAsAllowed() { return false; } @Override public void createPartControl(Composite composite) { composite.setLayout(new GridLayout()); createToolbar(composite); createTable(composite); createTablePopUp(composite); } private FileEditorVirtualNode<EditorPart> createVirtualNode(final String name){ final FileEditorVirtualNode<EditorPart> node = new FileEditorVirtualNode<EditorPart>(this, name); node.addAction(REFRESH, new NodeActionListener() { @Override protected void actionPerformed(NodeActionEvent e) throws AzureCmdException { fillGrid(); } }); node.addAction(DEQUEUE, new NodeActionListener() { @Override protected void actionPerformed(NodeActionEvent e) throws AzureCmdException { dequeueFirstMessage(); } }); node.addAction(ADD, new NodeActionListener() { @Override protected void actionPerformed(NodeActionEvent e) throws AzureCmdException { QueueMessageForm queueMessageForm = new QueueMessageForm(PluginUtil.getParentShell(), storageAccount, queue); queueMessageForm.setOnAddedMessage(new Runnable() { @Override public void run() { fillGrid(); } }); queueMessageForm.open(); } }); node.addAction(CLEAR_QUEUE, new NodeActionListener() { @Override protected void actionPerformed(NodeActionEvent e) throws AzureCmdException { boolean optionDialog = DefaultLoader.getUIHelper().showConfirmation( "Are you sure you want to clear the queue \"" + queue.getName() + "\"?", "Service explorer", new String[]{"Yes", "No"}, null); if (optionDialog) { DefaultLoader.getIdeHelper().runInBackground(null, "Clearing queue messages", false, true, "Clearing queue messages", new Runnable() { public void run() { /*try { StorageClientSDKManager.getManager().clearQueue(storageAccount, queue); DefaultLoader.getIdeHelper().invokeLater(new Runnable() { @Override public void run() { fillGrid(); } }); } catch (AzureCmdException e) { DefaultLoader.getUIHelper().showException("Error clearing queue messages", e, "Service Explorer", false, true); }*/ } }); } } }); node.addAction(OPEN, new NodeActionListener() { @Override protected void actionPerformed(NodeActionEvent e) throws AzureCmdException { viewMessageText(); } }); return node; } private void createToolbar(Composite parent) { GridLayout gridLayout = new GridLayout(1, false); GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; Composite container = new Composite(parent, 0); container.setLayout(gridLayout); container.setLayoutData(gridData); RowLayout rowLayout = new RowLayout(); rowLayout.type = SWT.HORIZONTAL; rowLayout.wrap = false; Composite buttonsContainer = new Composite(container, SWT.NONE); gridData = new GridData(); gridData.horizontalAlignment = SWT.RIGHT; buttonsContainer.setLayout(rowLayout); refreshButton = new Button(buttonsContainer, SWT.PUSH); refreshButton.setImage(Activator.getImageDescriptor("icons/storagerefresh.png").createImage()); refreshButton.setToolTipText("Refresh"); addMessageButton = new Button(buttonsContainer, SWT.PUSH); addMessageButton.setImage(Activator.getImageDescriptor("icons/newmessage_queue.png").createImage()); addMessageButton.setToolTipText("Add"); dequeueMessageButton = new Button(buttonsContainer, SWT.PUSH); dequeueMessageButton.setImage(Activator.getImageDescriptor("icons/dequeue.png").createImage()); dequeueMessageButton.setToolTipText("Dequeue"); clearQueueButton = new Button(buttonsContainer, SWT.PUSH); clearQueueButton.setImage(Activator.getImageDescriptor("icons/clearqueue.png").createImage()); clearQueueButton.setToolTipText("Clear queue"); refreshButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fileEditorVirtualNode.doAction(REFRESH); } }); dequeueMessageButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fileEditorVirtualNode.doAction(DEQUEUE); } }); addMessageButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fileEditorVirtualNode.doAction(ADD); } }); clearQueueButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fileEditorVirtualNode.doAction(CLEAR_QUEUE); } }); } private void createTable(Composite parent) { queueTable = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION); queueTable.setHeaderVisible(true); queueTable.setLinesVisible(true); GridData gridData = new GridData(); // gridData.heightHint = 75; gridData.horizontalAlignment = SWT.FILL; gridData.verticalAlignment = SWT.FILL; gridData.grabExcessVerticalSpace = true; gridData.grabExcessHorizontalSpace = true; GridLayout gridLayoutTable = new GridLayout(); gridLayoutTable.numColumns = 6; gridLayoutTable.marginRight = 0; queueTable.setLayout(gridLayoutTable); queueTable.setLayoutData(gridData); for (int i = 0; i < 6; i++) { TableColumn column = new TableColumn(queueTable, SWT.FILL); column.setWidth(100); } queueTable.getColumn(0).setText("Id"); queueTable.getColumn(1).setText("Message Text Preview"); queueTable.getColumn(2).setText("Size"); queueTable.getColumn(3).setText("Insertion Time (UTC)"); queueTable.getColumn(4).setText("Expiration Time (UTC)"); queueTable.getColumn(5).setText("Dequeue count"); tableViewer = new TableViewer(queueTable); tableViewer.setContentProvider(new QueueContentProvider()); tableViewer.setLabelProvider(new QueueLabelProvider()); fillGrid(); } private void createTablePopUp(Composite parent) { MenuManager menuMgr = new MenuManager("#PopupMenu"); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { if (tableViewer.getSelection().isEmpty()) { return; } if (tableViewer.getSelection() instanceof IStructuredSelection) { manager.add(fileEditorVirtualNode.createPopupAction(OPEN)); Action action = fileEditorVirtualNode.createPopupAction(DEQUEUE); if (queueTable.getSelectionIndex() != 0) { action.setEnabled(false); } manager.add(action); } } }); Menu menu = menuMgr.createContextMenu(tableViewer.getControl()); tableViewer.getControl().setMenu(menu); } public void fillGrid() { DefaultLoader.getIdeHelper().runInBackground(null, "Loading queue messages", false, true, "Loading queue messages", new Runnable() { public void run() { /*try { queueMessages = StorageClientSDKManager.getManager().getQueueMessages(storageAccount, queue); DefaultLoader.getIdeHelper().invokeLater(new Runnable() { @Override public void run() { clearQueueButton.setEnabled(queueMessages.size() != 0); dequeueMessageButton.setEnabled(queueMessages.size() != 0); tableViewer.setInput(queueMessages); } }); } catch (AzureCmdException e) { DefaultLoader.getUIHelper().showException("Error getting queue messages", e, "Service Explorer", false, true); }*/ } }); } private void dequeueFirstMessage() { if (DefaultLoader.getUIHelper().showConfirmation( "Are you sure you want to dequeue the first message in the queue?", "Service Explorer", new String[] {"Yes", "No"}, null)) { DefaultLoader.getIdeHelper().runInBackground(null, "Dequeuing message", false, true, "Dequeuing message", new Runnable() { public void run() { /*try { StorageClientSDKManager.getManager().dequeueFirstQueueMessage(storageAccount, queue); DefaultLoader.getIdeHelper().invokeLater(new Runnable() { @Override public void run() { fillGrid(); } }); } catch (AzureCmdException e) { DefaultLoader.getUIHelper().showException("Error dequeuing messages", e, "Service Explorer", false, true); }*/ } }); } } private void viewMessageText() { QueueMessage message = (QueueMessage) ((IStructuredSelection) tableViewer.getSelection()).getFirstElement(); ViewMessageForm viewMessageForm = new ViewMessageForm(PluginUtil.getParentShell(), message.getContent()); viewMessageForm.open(); } @Override public void setFocus() { } private class QueueContentProvider implements IStructuredContentProvider { public void dispose() { } public void inputChanged(Viewer viewer, Object o, Object o1) { } public Object[] getElements(Object o) { return queueMessages.toArray(); } } private class QueueLabelProvider implements ITableLabelProvider { public void addListener(ILabelProviderListener iLabelProviderListener) { } public void dispose() { } public boolean isLabelProperty(Object o, String s) { return false; } public void removeListener(ILabelProviderListener iLabelProviderListener) { } public Image getColumnImage(Object o, int i) { return null; } public String getColumnText(Object o, int i) { QueueMessage queueMessage = (QueueMessage) o; switch (i) { case 0: return queueMessage.getId(); case 1: return queueMessage.getContent(); case 2: return UIHelperImpl.readableFileSize(queueMessage.getContent().length()); case 3: return new SimpleDateFormat().format(queueMessage.getInsertionTime().getTime()); case 4: return new SimpleDateFormat().format(queueMessage.getExpirationTime().getTime()); case 5: return String.valueOf(queueMessage.getDequeueCount()); default: return ""; } } } }
40.066508
154
0.63908
2db246bd39251fb972fedee8cf07083247849371
2,080
package com.chain.utils; import java.math.BigDecimal; import java.math.BigInteger; import org.slf4j.Logger; import com.chain.logging.ChainUtilsLoggerFactory; /** * Number类的工具类 * * @author Chain * @version 1.0 */ public class NumberUtils { private static Logger logger = ChainUtilsLoggerFactory.getLogger(NumberUtils.class); /** * 是否为0 * * @param number * 要判断的数字 * @return 结果 */ public static Boolean isZero(Number number) { if (number instanceof Integer || number instanceof Short || number instanceof Byte || number instanceof Long || number instanceof BigInteger) { Long t = number.longValue(); if (t == 0) return true; } else if (number instanceof Float || number instanceof Double || number instanceof BigDecimal) { BigDecimal t = new BigDecimal(number.doubleValue()); if (new BigDecimal(0).equals(t)) return true; } return false; } /** * 是否为正数 * * @param number * 要判断的数字 * @return 结果 */ public static Boolean isPositive(Number number) { if (number instanceof Integer || number instanceof Short || number instanceof Byte || number instanceof Long || number instanceof BigInteger) { Long t = number.longValue(); if (t > 0) return true; } else if (number instanceof Float || number instanceof Double || number instanceof BigDecimal) { BigDecimal t = new BigDecimal(number.doubleValue()); if (t.compareTo(new BigDecimal(0)) > 0) return true; } return false; } /** * 是否为负数 * * @param number * 要判断的数字 * @return 结果 */ public static Boolean isNegative(Number number) { if (number instanceof Integer || number instanceof Short || number instanceof Byte || number instanceof Long || number instanceof BigInteger) { Long t = number.longValue(); if (t < 0) return true; } else if (number instanceof Float || number instanceof Double || number instanceof BigDecimal) { BigDecimal t = new BigDecimal(number.doubleValue()); if (t.compareTo(new BigDecimal(0)) < 0) return true; } return false; } }
24.761905
110
0.669231
2a235dcd4a7941ea85783bb66e5b2bd7f0966999
107
package org.nasa.posicion; /** * @author fcardozo * @version 1.0 * */ public interface IPosicion { }
9.727273
28
0.64486
1153bcf7140c9361f55600a8d11cf6196d6b8f8f
1,735
package com.jadebyte.imagewatermark; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import java.lang.ref.WeakReference; /** * Created by Wilberforce on 11/27/17 at 10:50 PM. */ public class MyPermission { public final static int WRITE_EXTERNAL_STORAGE = 1231; /** * Checks if external storage is readable * @return true is readable. Returns false otherwise */ public static boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals (state); } /** * Checks if this app has eternal storage write permission * @return true if granted. Returns false otherwise */ public static boolean isWriteExtStorPermGranted(Context context) { WeakReference<Context> weakContext = new WeakReference<>(context); return ContextCompat.checkSelfPermission(weakContext.get(), android.Manifest.permission .WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; } /** * Requests for external storage read permission * @param activity the activity to report the result to */ public static void askWriteExtStorPerm(Activity activity) { WeakReference<Activity> weakActivity = new WeakReference<>(activity); ActivityCompat.requestPermissions(weakActivity.get(), new String[] {android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE); } }
35.408163
107
0.723919
bd4c1b806c150d5e5a52ec89ff0655785935e273
351
package io.github.wanggit.antrpc.commons.config; import io.github.wanggit.antrpc.commons.codec.serialize.kryo.KryoSerializer; import lombok.Data; import java.util.HashMap; import java.util.Map; @Data public class SerializeConfig { private String type = KryoSerializer.class.getName(); private Map<String, String> map = new HashMap<>(); }
21.9375
76
0.766382
f15e00555b0fc11ea88b2fcc7fc36953f23a7ee0
5,718
package weixin.popular.api; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.StringEntity; import weixin.popular.bean.BaseResult; import weixin.popular.bean.wxaapi.*; import weixin.popular.bean.wxaapi.GetCategoryResult; import weixin.popular.client.LocalHttpClient; import weixin.popular.util.JsonUtil; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; /** * 微信小程序订阅消息接口 * @author 727288151 * @since 2.8.31 */ public class WxaapiAPI extends BaseAPI { /** * 小程序订阅消息<br> * 组合模板并添加至帐号下的个人模板库 * @since 2.8.31 * @param access_token access_token * @param tid tid 模板标题id * @param kidList 模板关键词id组合 * @param sceneDesc 模板服务场景描述 * @return result * @throws IOException * @throws ClientProtocolException */ public static AddTemplateResult addTemplate(String access_token, String tid, List<Integer> kidList, String sceneDesc) throws ClientProtocolException, IOException{ String json = String.format("{\"tid\":\"%s\",\"kidList\":%s,\"sceneDesc\":\"%s\"}", tid, JsonUtil.toJSONString(kidList), sceneDesc); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/newtmpl/addtemplate") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(json, StandardCharsets.UTF_8)) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,AddTemplateResult.class); } /** * 小程序订阅消息<br> * 删除帐号下的个人模板 * @since 2.8.31 * @param access_token access_token * @param priTmplId 个人模板id * @return result */ public static BaseResult delTemplate(String access_token, String priTmplId) throws ClientProtocolException, IOException { String json = String.format("{\"priTmplId\":\"%s\"}", priTmplId); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/newtmpl/deltemplate") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(json, StandardCharsets.UTF_8)) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,BaseResult.class); } /** * 小程序订阅消息<br> * 获取小程序账号的类目 * @since 2.8.31 * @param access_token access_token * @return result */ public static GetCategoryResult getCategory(String access_token) throws ClientProtocolException, IOException { HttpUriRequest httpUriRequest = RequestBuilder.get() .setHeader(jsonHeader) .setUri(BASE_URI + "/wxaapi/newtmpl/getcategory") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest, GetCategoryResult.class); } /** * 小程序订阅消息<br> * 获取帐号所属类目下的公共模板标题 * @since 2.8.31 * @param access_token access_token * @return result */ public static GetPubTemplateTitlesResult getPubTemplateTitles(String access_token, String ids, Integer start, Integer limit) throws ClientProtocolException, IOException { HttpUriRequest httpUriRequest = RequestBuilder.get() .setHeader(jsonHeader) .setUri(BASE_URI + "/wxaapi/newtmpl/getpubtemplatetitles") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .addParameter("ids", ids) .addParameter("start", String.valueOf(start)) .addParameter("limit", String.valueOf(limit)) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,GetPubTemplateTitlesResult.class); } /** * 小程序订阅消息<br> * 获取模板标题下的关键词列表 * @since 2.8.31 * @param access_token access_token * @return result */ public static GetPubTemplateKeywordsResult getPubTemplateKeywords(String access_token, String tid) throws ClientProtocolException, IOException { HttpUriRequest httpUriRequest = RequestBuilder.get() .setHeader(jsonHeader) .setUri(BASE_URI + "/wxaapi/newtmpl/getpubtemplatekeywords") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .addParameter("tid", tid) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,GetPubTemplateKeywordsResult.class); } /** * 小程序订阅消息<br> * 获取当前帐号下的个人模板列表 * @since 2.8.31 * @param access_token access_token * @return result */ public static GetPriTemplateListResult getPriTemplateList(String access_token) throws ClientProtocolException, IOException { HttpUriRequest httpUriRequest = RequestBuilder.get() .setHeader(jsonHeader) .setUri(BASE_URI + "/wxaapi/newtmpl/gettemplate") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,GetPriTemplateListResult.class); } }
41.737226
167
0.631515
3fae54b48acacab16aa4e6b4a8e56e8e4de250b0
4,848
package com.github.chaosfirebolt.chess.service.impl; import com.github.chaosfirebolt.chess.dto.ChangePasswordModel; import com.github.chaosfirebolt.chess.entity.Account; import com.github.chaosfirebolt.chess.entity.Confirmation; import com.github.chaosfirebolt.chess.entity.Password; import com.github.chaosfirebolt.chess.exc.InvalidRequestException; import com.github.chaosfirebolt.chess.exc.NotFoundException; import com.github.chaosfirebolt.chess.repo.AccountRepository; import com.github.chaosfirebolt.chess.repo.ConfirmationRepository; import com.github.chaosfirebolt.chess.repo.PasswordRepository; import com.github.chaosfirebolt.chess.service.contract.PasswordService; import com.github.chaosfirebolt.chess.service.contract.HashingService; import com.github.chaosfirebolt.chess.service.contract.ValidationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.http.HttpStatus; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import javax.transaction.Transactional; import java.time.LocalDateTime; /** * Created by ChaosFire on 24-Jul-19 */ @Service public class PasswordServiceImpl implements PasswordService { private static final String SAME_PASS_ERR_MSG = "You cannot use this password"; private final ConfirmationRepository confirmationRepository; private final AccountRepository accountRepository; private final PasswordRepository passwordRepository; private final HashingService hashingService; private final ValidationService validationService; private final PasswordEncoder passwordEncoder; @Autowired public PasswordServiceImpl(ConfirmationRepository confirmationRepository, AccountRepository accountRepository, PasswordRepository passwordRepository, HashingService hashingService, ValidationService validationService, PasswordEncoder passwordEncoder) { this.confirmationRepository = confirmationRepository; this.accountRepository = accountRepository; this.passwordRepository = passwordRepository; this.hashingService = hashingService; this.validationService = validationService; this.passwordEncoder = passwordEncoder; } @Override @Transactional public String setChangeConfirmation(String userHash) { Account account = this.accountRepository.findOne(Example.of(this.probe(userHash))).orElseThrow(() -> new NotFoundException("Not found")); Password password = account.getPassword(); Confirmation confirmation = password.getConfirmation(); String confirmationHash = this.hashingService.uniqueHash(s -> true); if (confirmation == null) { confirmation = new Confirmation(); password.setConfirmation(confirmation); } confirmation.setCode(confirmationHash); //TODO move minutes to props confirmation.setValidUntil(LocalDateTime.now().plusMinutes(10)); this.confirmationRepository.saveAndFlush(confirmation); return confirmationHash; } @Override @Transactional public void changePassword(String userHash, ChangePasswordModel model) { Account account = this.accountRepository.findOne(Example.of(this.probe(userHash))).orElseThrow(() -> new NotFoundException("Not found")); Password password = account.getPassword(); if (!account.getEmail().equals(model.getEmail()) || password == null || !this.passwordEncoder.matches(model.getOldPassword(), password.getEncoded())) { throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED); } Confirmation confirmation = password.getConfirmation(); if (confirmation == null || LocalDateTime.now().isAfter(confirmation.getValidUntil()) || !model.getCode().equals(confirmation.getCode())) { throw new HttpClientErrorException(HttpStatus.FORBIDDEN); } this.validationService.validate(model, InvalidRequestException::new); String newPassword = model.getPassword(); this.validationService.validate(newPassword, pass -> !this.passwordEncoder.matches(pass, password.getEncoded()), msg -> new InvalidRequestException(SAME_PASS_ERR_MSG)); password.setEncoded(this.passwordEncoder.encode(newPassword)); password.setLastModifiedBy(account); password.setLastModifiedDate(LocalDateTime.now()); password.setConfirmation(null); this.confirmationRepository.delete(confirmation); this.passwordRepository.saveAndFlush(password); } private Account probe(String hash) { Account probe = new Account(); probe.setHash(hash); return probe; } }
49.979381
176
0.760314
ce13deed11781c12eb8a95eabce6c56f30f92200
3,974
package io.github.gusandrianos.foxforreddit.ui.fragments; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.NavController; import androidx.navigation.fragment.NavHostFragment; import androidx.navigation.ui.NavigationUI; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.textfield.TextInputEditText; import io.github.gusandrianos.foxforreddit.Constants; import io.github.gusandrianos.foxforreddit.R; import io.github.gusandrianos.foxforreddit.ui.MainActivity; import io.github.gusandrianos.foxforreddit.utilities.InjectorUtils; import io.github.gusandrianos.foxforreddit.viewmodels.PostViewModel; import io.github.gusandrianos.foxforreddit.viewmodels.PostViewModelFactory; public class EditThingFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_edit_thing, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setUpNavigation(view, 0); setUpContent(view); } private void setUpContent(View view) { String selftext = EditThingFragmentArgs.fromBundle(requireArguments()).getThingText(); TextInputEditText bodyEditText = view.findViewById(R.id.edit_edit_thing_text_body); bodyEditText.setText(selftext); setUpSubmitAction(view); } private void setUpSubmitAction(View view) { Toolbar toolbar = view.findViewById(R.id.toolbar_edit_thing); toolbar.getMenu().findItem(R.id.button_submit_post).setOnMenuItemClickListener(submit -> { String selftext = EditThingFragmentArgs.fromBundle(requireArguments()).getThingText(); String thingFullname = EditThingFragmentArgs.fromBundle(requireArguments()).getThingFullname(); TextInputEditText bodyEditText = view.findViewById(R.id.edit_edit_thing_text_body); PostViewModelFactory factory = InjectorUtils.getInstance().providePostViewModelFactory(); PostViewModel viewModel = new ViewModelProvider(this, factory).get(PostViewModel.class); viewModel.editSubmission(bodyEditText.getText().toString(), thingFullname, requireActivity().getApplication()) .observe(getViewLifecycleOwner(), success -> { if (success) { Bundle result = new Bundle(); result.putString("updatedText", bodyEditText.getText().toString()); getParentFragmentManager().setFragmentResult("editThing", result); requireActivity().onBackPressed(); } }); return true; }); } private void setUpNavigation(View view, int type) { MainActivity mainActivity = (MainActivity) requireActivity(); NavController navController = NavHostFragment.findNavController(this); Toolbar toolbar = view.findViewById(R.id.toolbar_edit_thing); toolbar.inflateMenu(R.menu.button_submit_post); BottomNavigationView bottomNavigationView = mainActivity.bottomNavView; bottomNavigationView.setVisibility(View.GONE); NavigationUI.setupWithNavController(toolbar, navController); String toolbarTitle = "Edit"; if (type == Constants.EDIT_POST_TEXT) toolbarTitle += " post"; else toolbarTitle += " Comment"; toolbar.setTitle(toolbarTitle); } }
43.67033
122
0.714142
1691c3ab516ecd10d9756ed1a505979e623f42e0
872
package it.smartcommunitylab.riciclo.riapp.importer.model; public class RiappIstruzioni { private String frazione; private String comeConferire; private String prestaAttenzione; private String si; private String no; public String getFrazione() { return frazione; } public void setFrazione(String frazione) { this.frazione = frazione; } public String getComeConferire() { return comeConferire; } public void setComeConferire(String comeConferire) { this.comeConferire = comeConferire; } public String getPrestaAttenzione() { return prestaAttenzione; } public void setPrestaAttenzione(String prestaAttenzione) { this.prestaAttenzione = prestaAttenzione; } public String getSi() { return si; } public void setSi(String si) { this.si = si; } public String getNo() { return no; } public void setNo(String no) { this.no = no; } }
21.268293
59
0.744266
d45c3ad9d76af2a87216dfcf619e124b911bb766
490
package com.bugsnag.mazerunner.scenarios; import com.bugsnag.Bugsnag; import com.bugsnag.Report; import com.bugsnag.callbacks.Callback; /** * Sends a handled exception to Bugsnag, which overrides the default user via a callback */ public class ThreadsScenario extends Scenario { public ThreadsScenario(Bugsnag bugsnag) { super(bugsnag); bugsnag.setSendThreads(true); } @Override public void run() { bugsnag.notify(generateException()); } }
22.272727
88
0.712245
e367ce765f98d75ffaaeada7da97968f7726da4b
2,250
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * User: anna * Date: 09-Feb-2009 */ package com.intellij.projectImport; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.components.StorageScheme; import javax.swing.*; public class ProjectFormatPanel { private static final String STORAGE_FORMAT_PROPERTY = "default.storage.format"; public static final String DIR_BASED = ".idea (directory based)"; private static final String FILE_BASED = ".ipr (file based)"; private JComboBox myStorageFormatCombo; private JPanel myWholePanel; public ProjectFormatPanel() { myStorageFormatCombo.insertItemAt(DIR_BASED, 0); myStorageFormatCombo.insertItemAt(FILE_BASED, 1); myStorageFormatCombo.setSelectedItem(PropertiesComponent.getInstance().getOrInit(STORAGE_FORMAT_PROPERTY, DIR_BASED)); } public JPanel getPanel() { return myWholePanel; } public JComboBox getStorageFormatComboBox() { return myStorageFormatCombo; } public void updateData(WizardContext context) { StorageScheme format = FILE_BASED.equals(myStorageFormatCombo.getSelectedItem()) ? StorageScheme.DEFAULT : StorageScheme.DIRECTORY_BASED; context.setProjectStorageFormat(format); setDefaultFormat(isDefault()); } public static void setDefaultFormat(boolean aDefault) { PropertiesComponent.getInstance().setValue(STORAGE_FORMAT_PROPERTY, aDefault ? FILE_BASED : DIR_BASED); } public void setVisible(boolean visible) { myWholePanel.setVisible(visible); } public boolean isDefault() { return FILE_BASED.equals(myStorageFormatCombo.getSelectedItem()); } }
32.142857
122
0.764444
87973a1970959f3930e41c729c1e392c21f51a1b
742
package xyy.java.note.dm.observer.webObserverPattern; /** * @author xyy * @version 1.0 2017/3/10. * @since 1.0 */ public class Client { public static void main(String[] args) { // 创建一个目标 ConcreteWeatherSubject subject = new ConcreteWeatherSubject(); // 创建观察者 ConcreateObserver girl = new ConcreateObserver(); girl.setObserverName("女朋友"); girl.setRemindThing("约会, 不见不散"); ConcreateObserver mum = new ConcreateObserver(); mum.setObserverName("mum"); mum.setRemindThing("买东西"); // 注册观察者 subject.attach(girl); subject.attach(mum); // 在目标处发布天气 subject.setWeatherContent("天气晴朗"); subject.notifyObservers(); } }
23.935484
70
0.61186
01a384978ecb8b1a010ede2d81d73e14844eb0b0
4,283
package com.brins.lightmusic.ui.base.adapter; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.brins.lightmusic.utils.ShowShadowUtil; import com.brins.lightmusic.R; import com.brins.lightmusic.model.loaclmusic.LocalMusic; import java.util.List; import static com.brins.lightmusic.utils.UtilsKt.string2Bitmap; public class ListAdapter<T> extends RecyclerView.Adapter<ListAdapter.viewHolder> { private Context mContext; private List<T> mData; private OnItemClickListener mItemClickListener; private OnItemLongClickListener mItemLongClickListener; private int mLastItemClickPosition = RecyclerView.NO_POSITION; public ListAdapter(Context context, List<T> data) { mContext = context; mData = data; } @Override public ListAdapter.viewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View itemView = LayoutInflater.from(mContext).inflate(R.layout.item_local_music, parent, false); final ListAdapter.viewHolder holder = new ListAdapter.viewHolder(itemView); if (mItemClickListener != null) { itemView.setOnClickListener(v -> { int position = holder.getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { mLastItemClickPosition = position; mItemClickListener.onItemClick(itemView,position); } }); } if (mItemLongClickListener != null) { itemView.setOnLongClickListener(v -> { int position = holder.getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { mItemLongClickListener.onItemClick(position); } return false; }); } return holder; } @Override @SuppressWarnings("unchecked") public void onBindViewHolder(ListAdapter.viewHolder holder, int position) { LocalMusic music = (LocalMusic) getItem(position); holder.textViewName.setText(music.getName()); holder.textViewArtist.setText(music.getArtistBeans().get(0).getName()); if (music.getCoverBitmap() == null) { music.setCoverBitmap(string2Bitmap(music.getAlbum().getPicUrl())); } holder.imgCover.setImageBitmap(music.getCoverBitmap()); } @Override public int getItemCount() { if (mData == null) { return 0; } return mData.size(); } @Override public long getItemId(int position) { return position; } public List<T> getData() { return mData; } public void setData(List<T> data) { mData = data; } public void addData(List<T> data) { if (mData == null) { mData = data; } else { mData.addAll(data); } } public T getItem(int position) { return mData.get(position); } public void clear() { if (mData != null) { mData.clear(); } } public OnItemClickListener getItemClickListener() { return mItemClickListener; } public int getLastItemClickPosition() { return mLastItemClickPosition; } public void setOnItemClickListener(OnItemClickListener listener) { mItemClickListener = listener; } public OnItemLongClickListener getItemLongClickListener() { return mItemLongClickListener; } public void setOnItemLongClickListener(OnItemLongClickListener listener) { mItemLongClickListener = listener; } class viewHolder extends RecyclerView.ViewHolder{ TextView textViewName; TextView textViewArtist; ImageView imgCover; public viewHolder(@NonNull View view) { super(view); textViewName = view.findViewById(R.id.textViewName); textViewArtist = view.findViewById(R.id.textViewArtist); imgCover = view.findViewById(R.id.imgCover); } } }
29.335616
110
0.646509
a30f18d5972cb0f79941d407c544e658412bf756
1,445
package models; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class EndangeredAnimalsTest { // @Before // public void setUp() throws Exception { // } // // @After // public void tearDown() throws Exception { // } @Test public void endangered_instantiatesCorrectly_true(){ EndangeredAnimals testEndangered = testEndangered(); assertEquals(true, testEndangered instanceof EndangeredAnimals); } @Test public void endangered_instantiatesWithName_elephant(){ EndangeredAnimals testEndangered = testEndangered(); assertEquals("elephant", testEndangered.getEndangeredName()); } @Test public void endangered_instantiatesWithId_5(){ EndangeredAnimals testEndangered = testEndangered(); assertEquals(5, testEndangered.getEndangeredId()); } @Test public void endangered_instantiatesWithHealth_healthy(){ EndangeredAnimals testEndangered = testEndangered(); assertEquals("healthy", testEndangered.getHealth()); } @Test public void endangered_instantiatesWithAge_young(){ EndangeredAnimals testEndangered = testEndangered(); assertEquals("young", testEndangered.getAge()); } // helper methods public EndangeredAnimals testEndangered(){ return new EndangeredAnimals("elephant", 5, "healthy", "young"); } }
27.788462
72
0.697578
cc718d330f220f183d28fdd5f294a0f69c684be4
4,689
package com.sellit.controller.sale; import java.io.IOException; import org.springframework.stereotype.Component; import com.sellit.controller.Controller; import com.sellit.persistence.Payment; import com.sellit.persistence.Ticket; import com.sellit.util.AppUtil; import com.sellit.util.DoubleUtil; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.TextField; @Component public class PaymentController extends Controller { private static final String CASH = "CASH"; // TODO refactor this with login view private static final String DOT = "."; private static final String ZERO = "0"; private static final String ONE = "1"; private static final String TWO = "2"; private static final String THREE = "3"; private static final String FOUR = "4"; private static final String FIVE = "5"; private static final String SIX = "6"; private static final String SEVEN = "7"; private static final String EIGHT = "8"; private static final String NINE = "9"; private static final String EMPTY_STRING = ""; @FXML private Label ticketTotalLabel; @FXML private Label balanceDueLabel; @FXML private TextField tenderAmountField; private RetailSaleController parent; private Ticket ticket; /** * The constructor. The constructor is called before the initialize() method. */ public PaymentController() { } /** * Initializes the controller class. This method is automatically called after * the fxml file has been loaded. */ @FXML private void initialize() { } private void createPayment(String paymentMethod, Double paymentAmount) throws IOException { Double remainingBalanceDue = ticket.calcRemainingBalanceDue(); Payment payment = new Payment(); payment.setPaymentMethod(paymentMethod); if (paymentAmount > remainingBalanceDue) { payment.setPaymentAmount(remainingBalanceDue); } else { payment.setPaymentAmount(paymentAmount); } payment.setRemainingBalanceDueAmount(remainingBalanceDue); payment.setTenderAmount(paymentAmount); payment.setChangeAmount(DoubleUtil.truncate(payment.getTenderAmount() - remainingBalanceDue)); payment.setTicket(ticket); ticket.getPayments().add(payment); refresh(); if (payment.getChangeAmount() > 0 && CASH.equals(paymentMethod)) { AppUtil.showPopupWindow(String.format("Change is $%s", DoubleUtil.formatDouble(payment.getChangeAmount()))); } if (ticket.calcRemainingBalanceDue() == 0) { parent.closeTransaction(); dialogStage.close(); } } @FXML private void payWithCash() throws IOException { String tenderAmountText = tenderAmountField.getText(); Double tenderAmount = DoubleUtil.parseDouble(tenderAmountText); createPayment(CASH, tenderAmount); } @Override public void refresh() { ticketTotalLabel.setText(DoubleUtil.formatDouble(ticket.getTotalAmount())); balanceDueLabel.setText(DoubleUtil.formatDouble(ticket.calcRemainingBalanceDue())); } public void setParent(RetailSaleController parent) { this.parent = parent; } public void setTicket(Ticket ticket) { this.ticket = ticket; } @FXML private void clear() throws IOException { tenderAmountField.setText(EMPTY_STRING); } @FXML private void appendText0() throws IOException { appendText(ZERO); } @FXML private void appendText1() throws IOException { appendText(ONE); } @FXML private void appendText2() throws IOException { appendText(TWO); } @FXML private void appendText3() throws IOException { appendText(THREE); } @FXML private void appendText4() throws IOException { appendText(FOUR); } @FXML private void appendText5() throws IOException { appendText(FIVE); } @FXML private void appendText6() throws IOException { appendText(SIX); } @FXML private void appendText7() throws IOException { appendText(SEVEN); } @FXML private void appendText8() throws IOException { appendText(EIGHT); } @FXML private void appendText9() throws IOException { appendText(NINE); } @FXML private void appendTextDot() throws IOException { appendText(DOT); } @FXML private void appendText5Dollars() throws IOException { setText("5.00"); } @FXML private void appendText10Dollars() throws IOException { setText("10.00"); } @FXML private void appendText20Dollars() throws IOException { setText("20.00"); } @FXML private void appendText50Dollars() throws IOException { setText("50.00"); } private void setText(String text) throws IOException { tenderAmountField.setText(text); } private void appendText(String text) throws IOException { if (DOT.equals(text) && tenderAmountField.getText().contains(DOT)) { return; } tenderAmountField.appendText(text); } }
22.117925
111
0.744295