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
eb998840ee6107405b292906f63ce6dfe53b1274
947
package com.github.jweixin.jwx.message.mass; import java.util.List; import com.github.jweixin.jwx.message.response.Text; /** * 群发文本消息 * @author Administrator * */ public class MassTextMessage extends MassMessage { /** * 文本 */ private Text text; public MassTextMessage() { super(); this.msgtype = "text"; } public MassTextMessage(Filter filter) { super(filter); this.msgtype = "text"; } public MassTextMessage(Filter filter, String content) { super(filter); this.msgtype = "text"; this.text = new Text(content); } public MassTextMessage(List<String> touser) { super(touser); this.msgtype = "text"; } public MassTextMessage(List<String> touser, String content) { super(touser); this.msgtype = "text"; this.text = new Text(content); } public Text getText() { return text; } public void setText(Text text) { this.text = text; } }
17.537037
63
0.637804
76e2ad81d2ddb101b685426d0a1bcb44dd229905
34,342
/* * Copyright 2015, 2016 Tagir Valeev * * 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.landawn.streamex; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import com.landawn.streamex.IntStreamEx; import com.landawn.streamex.LongStreamEx; import java.nio.LongBuffer; import java.util.*; import java.util.PrimitiveIterator.OfLong; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.*; import java.util.stream.LongStream; import java.util.stream.LongStream.Builder; import static com.landawn.streamex.TestHelpers.checkSpliterator; import static org.junit.Assert.*; /** * @author Tagir Valeev */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class LongStreamExTest { LongConsumer EMPTY = l -> { // nothing }; @Test public void testCreate() { assertArrayEquals(new long[] {}, LongStreamEx.empty().toArray()); // double test is intended assertArrayEquals(new long[] {}, LongStreamEx.empty().toArray()); assertArrayEquals(new long[] { 1 }, LongStreamEx.of(1).toArray()); assertArrayEquals(new long[] { 1 }, LongStreamEx.of(OptionalLong.of(1)).toArray()); assertArrayEquals(new long[] {}, LongStreamEx.of(OptionalLong.empty()).toArray()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.of(1, 2, 3).toArray()); assertArrayEquals(new long[] { 4, 6 }, LongStreamEx.of(new long[] { 2, 4, 6, 8, 10 }, 1, 3).toArray()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.of(LongStream.of(1, 2, 3)).toArray()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.of(Arrays.asList(1L, 2L, 3L)).toArray()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.range(1L, 4L).toArray()); assertArrayEquals(new long[] { 0, 1, 2 }, LongStreamEx.range(3L).toArray()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.rangeClosed(1, 3).toArray()); assertArrayEquals(new long[] { 1, 1, 1, 1 }, LongStreamEx.generate(() -> 1).limit(4).toArray()); assertArrayEquals(new long[] { 1, 1, 1, 1 }, LongStreamEx.repeat(1L, 4).toArray()); assertEquals(10, LongStreamEx.of(new Random(), 10).count()); assertTrue(LongStreamEx.of(new Random(), 100, 1, 10).allMatch(x -> x >= 1 && x < 10)); assertArrayEquals(LongStreamEx.of(new Random(1), 100, 1, 10).toArray(), LongStreamEx.of(new Random(1), 1, 10) .limit(100).toArray()); assertArrayEquals(LongStreamEx.of(new Random(1), 100).toArray(), LongStreamEx.of(new Random(1)).limit(100) .toArray()); LongStream stream = LongStreamEx.of(1, 2, 3); assertSame(stream, LongStreamEx.of(stream)); assertArrayEquals(new long[] { 4, 2, 0, -2, -4 }, LongStreamEx.zip(new long[] { 5, 4, 3, 2, 1 }, new long[] { 1, 2, 3, 4, 5 }, (a, b) -> a - b).toArray()); assertArrayEquals(new long[] { 1, 5, 3 }, LongStreamEx.of(Spliterators.spliterator(new long[] { 1, 5, 3 }, 0)) .toArray()); assertArrayEquals(new long[] { 1, 5, 3 }, LongStreamEx.of( Spliterators.iterator(Spliterators.spliterator(new long[] { 1, 5, 3 }, 0))).toArray()); assertArrayEquals(new long[0], LongStreamEx.of(Spliterators.iterator(Spliterators.emptyLongSpliterator())) .parallel().toArray()); assertArrayEquals(new long[] { 2, 4, 6 }, LongStreamEx.of(new Long[] { 2L, 4L, 6L }).toArray()); } @Test public void testOfLongBuffer() { long[] data = LongStreamEx.range(100).toArray(); assertArrayEquals(data, LongStreamEx.of(LongBuffer.wrap(data)).toArray()); assertArrayEquals(LongStreamEx.range(50, 70).toArray(), LongStreamEx.of(LongBuffer.wrap(data, 50, 20)).toArray()); assertArrayEquals(data, LongStreamEx.of(LongBuffer.wrap(data)).parallel().toArray()); assertArrayEquals(LongStreamEx.range(50, 70).toArray(), LongStreamEx.of(LongBuffer.wrap(data, 50, 20)).parallel() .toArray()); } @Test public void testIterate() { assertArrayEquals(new long[] { 1, 2, 4, 8, 16 }, LongStreamEx.iterate(1, x -> x * 2).limit(5).toArray()); assertArrayEquals(new long[] { 1, 2, 4, 8, 16, 32, 64 }, LongStreamEx.iterate(1, x -> x < 100, x -> x * 2).toArray()); assertEquals(0, LongStreamEx.iterate(0, x -> x < 0, x -> 1 / x).count()); assertFalse(LongStreamEx.iterate(1, x -> x < 100, x -> x * 2).has(10)); checkSpliterator("iterate", () -> LongStreamEx.iterate(1, x -> x < 100, x -> x * 2).spliterator()); } @Test public void testLongs() { assertEquals(Long.MAX_VALUE, LongStreamEx.longs().spliterator().getExactSizeIfKnown()); assertArrayEquals(new long[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, LongStreamEx.longs().limit(10).toArray()); } @Test public void testRangeStep() { assertArrayEquals(new long[] { 0 }, LongStreamEx.range(0, 1000, 100000).toArray()); assertArrayEquals(new long[] { 0, Long.MAX_VALUE - 1 }, LongStreamEx.range(0, Long.MAX_VALUE, Long.MAX_VALUE - 1).toArray()); assertArrayEquals(new long[] { Long.MIN_VALUE, -1, Long.MAX_VALUE - 1 }, LongStreamEx.range(Long.MIN_VALUE, Long.MAX_VALUE, Long.MAX_VALUE).toArray()); assertArrayEquals(new long[] { Long.MIN_VALUE, -1 }, LongStreamEx.range(Long.MIN_VALUE, Long.MAX_VALUE - 1, Long.MAX_VALUE).toArray()); assertArrayEquals(new long[] { Long.MAX_VALUE, -1 }, LongStreamEx.range(Long.MAX_VALUE, Long.MIN_VALUE, Long.MIN_VALUE).toArray()); assertArrayEquals(new long[] { Long.MAX_VALUE }, LongStreamEx.range(Long.MAX_VALUE, 0, Long.MIN_VALUE) .toArray()); assertArrayEquals(new long[] { 1, Long.MIN_VALUE + 1 }, LongStreamEx.range(1, Long.MIN_VALUE, Long.MIN_VALUE) .toArray()); assertArrayEquals(new long[] { 0 }, LongStreamEx.range(0, Long.MIN_VALUE, Long.MIN_VALUE).toArray()); assertArrayEquals(new long[] { 0, 2, 4, 6, 8 }, LongStreamEx.range(0, 9, 2).toArray()); assertArrayEquals(new long[] { 0, 2, 4, 6 }, LongStreamEx.range(0, 8, 2).toArray()); assertArrayEquals(new long[] { 0, -2, -4, -6, -8 }, LongStreamEx.range(0, -9, -2).toArray()); assertArrayEquals(new long[] { 0, -2, -4, -6 }, LongStreamEx.range(0, -8, -2).toArray()); assertArrayEquals(new long[] { 5, 4, 3, 2, 1, 0 }, LongStreamEx.range(5, -1, -1).toArray()); assertEquals(Integer.MAX_VALUE + 1L, LongStreamEx.range(Integer.MIN_VALUE, Integer.MAX_VALUE, 2).spliterator() .getExactSizeIfKnown()); assertEquals(Long.MAX_VALUE, LongStreamEx.range(Long.MIN_VALUE, Long.MAX_VALUE - 1, 2).spliterator() .getExactSizeIfKnown()); java.util.Spliterator.OfLong spliterator = LongStreamEx.range(Long.MAX_VALUE, Long.MIN_VALUE, -2).spliterator(); assertEquals(-1, spliterator.getExactSizeIfKnown()); assertTrue(spliterator.tryAdvance(EMPTY)); assertEquals(Long.MAX_VALUE, spliterator.estimateSize()); assertTrue(spliterator.tryAdvance(EMPTY)); assertEquals(Long.MAX_VALUE - 1, spliterator.estimateSize()); assertEquals(Long.MAX_VALUE, LongStreamEx.range(Long.MAX_VALUE, Long.MIN_VALUE + 1, -2).spliterator() .getExactSizeIfKnown()); assertEquals(-1, LongStreamEx.range(Long.MIN_VALUE, Long.MAX_VALUE, 1).spliterator().getExactSizeIfKnown()); assertEquals(-1, LongStreamEx.range(Long.MAX_VALUE, Long.MIN_VALUE, -1).spliterator().getExactSizeIfKnown()); assertEquals(0, LongStreamEx.range(0, -1000, 1).count()); assertEquals(0, LongStreamEx.range(0, 1000, -1).count()); assertEquals(0, LongStreamEx.range(0, 0, -1).count()); assertEquals(0, LongStreamEx.range(0, 0, 1).count()); assertEquals(0, LongStreamEx.range(0, -1000, 2).count()); assertEquals(0, LongStreamEx.range(0, 1000, -2).count()); assertEquals(0, LongStreamEx.range(0, 0, -2).count()); assertEquals(0, LongStreamEx.range(0, 0, 2).count()); assertEquals(0, LongStreamEx.range(0, Long.MIN_VALUE, 2).spliterator().getExactSizeIfKnown()); assertEquals(0, LongStreamEx.range(0, Long.MAX_VALUE, -2).spliterator().getExactSizeIfKnown()); } @Test(expected = IllegalArgumentException.class) public void testRangeIllegalStep() { LongStreamEx.range(0, 1000, 0); } @Test public void testRangeClosedStep() { assertArrayEquals(new long[] { 0 }, LongStreamEx.rangeClosed(0, 1000, 100000).toArray()); assertArrayEquals(new long[] { 0, 1000 }, LongStreamEx.rangeClosed(0, 1000, 1000).toArray()); assertArrayEquals(new long[] { 0, Long.MAX_VALUE - 1 }, LongStreamEx.rangeClosed(0, Long.MAX_VALUE - 1, Long.MAX_VALUE - 1).toArray()); assertArrayEquals(new long[] { Long.MIN_VALUE, -1, Long.MAX_VALUE - 1 }, LongStreamEx.rangeClosed( Long.MIN_VALUE, Long.MAX_VALUE - 1, Long.MAX_VALUE).toArray()); assertArrayEquals(new long[] { Long.MIN_VALUE, -1 }, LongStreamEx.rangeClosed(Long.MIN_VALUE, Long.MAX_VALUE - 2, Long.MAX_VALUE).toArray()); assertArrayEquals(new long[] { Long.MAX_VALUE, -1 }, LongStreamEx.rangeClosed(Long.MAX_VALUE, Long.MIN_VALUE, Long.MIN_VALUE).toArray()); assertArrayEquals(new long[] { Long.MAX_VALUE }, LongStreamEx.rangeClosed(Long.MAX_VALUE, 0, Long.MIN_VALUE) .toArray()); assertArrayEquals(new long[] { 0, Long.MIN_VALUE }, LongStreamEx.rangeClosed(0, Long.MIN_VALUE, Long.MIN_VALUE) .toArray()); assertArrayEquals(new long[] { 0, 2, 4, 6, 8 }, LongStreamEx.rangeClosed(0, 9, 2).toArray()); assertArrayEquals(new long[] { 0, 2, 4, 6, 8 }, LongStreamEx.rangeClosed(0, 8, 2).toArray()); assertArrayEquals(new long[] { 0, 2, 4, 6 }, LongStreamEx.rangeClosed(0, 7, 2).toArray()); assertArrayEquals(new long[] { 0, -2, -4, -6, -8 }, LongStreamEx.rangeClosed(0, -9, -2).toArray()); assertArrayEquals(new long[] { 0, -2, -4, -6, -8 }, LongStreamEx.rangeClosed(0, -8, -2).toArray()); assertArrayEquals(new long[] { 0, -2, -4, -6 }, LongStreamEx.rangeClosed(0, -7, -2).toArray()); assertArrayEquals(new long[] { 5, 4, 3, 2, 1, 0 }, LongStreamEx.rangeClosed(5, 0, -1).toArray()); assertEquals(Integer.MAX_VALUE + 1L, LongStreamEx.rangeClosed(Integer.MIN_VALUE, Integer.MAX_VALUE, 2) .spliterator().getExactSizeIfKnown()); assertEquals(Long.MAX_VALUE, LongStreamEx.rangeClosed(Long.MIN_VALUE, Long.MAX_VALUE - 2, 2).spliterator() .getExactSizeIfKnown()); java.util.Spliterator.OfLong spliterator = LongStreamEx.rangeClosed(Long.MAX_VALUE, Long.MIN_VALUE, -2) .spliterator(); assertEquals(-1, spliterator.getExactSizeIfKnown()); assertTrue(spliterator.tryAdvance(EMPTY)); assertEquals(Long.MAX_VALUE, spliterator.estimateSize()); assertTrue(spliterator.tryAdvance(EMPTY)); assertEquals(Long.MAX_VALUE - 1, spliterator.estimateSize()); assertEquals(Long.MAX_VALUE, LongStreamEx.rangeClosed(Long.MAX_VALUE, Long.MIN_VALUE + 2, -2).spliterator() .getExactSizeIfKnown()); assertEquals(-1, LongStreamEx.rangeClosed(Long.MIN_VALUE, Long.MAX_VALUE, 1).spliterator() .getExactSizeIfKnown()); assertEquals(-1, LongStreamEx.rangeClosed(Long.MAX_VALUE, Long.MIN_VALUE, -1).spliterator() .getExactSizeIfKnown()); assertEquals(0, LongStreamEx.rangeClosed(0, -1000, 1).count()); assertEquals(0, LongStreamEx.rangeClosed(0, 1000, -1).count()); assertEquals(0, LongStreamEx.rangeClosed(0, 1, -1).count()); assertEquals(0, LongStreamEx.rangeClosed(0, -1, 1).count()); assertEquals(0, LongStreamEx.rangeClosed(0, -1000, 2).count()); assertEquals(0, LongStreamEx.rangeClosed(0, 1000, -2).count()); assertEquals(0, LongStreamEx.rangeClosed(0, 1, -2).count()); assertEquals(0, LongStreamEx.rangeClosed(0, -1, 2).count()); assertEquals(0, LongStreamEx.rangeClosed(0, Long.MIN_VALUE, 2).spliterator().getExactSizeIfKnown()); assertEquals(0, LongStreamEx.rangeClosed(0, Long.MAX_VALUE, -2).spliterator().getExactSizeIfKnown()); } @Test public void testBasics() { assertFalse(LongStreamEx.of(1).isParallel()); assertTrue(LongStreamEx.of(1).parallel().isParallel()); assertFalse(LongStreamEx.of(1).parallel().sequential().isParallel()); AtomicInteger i = new AtomicInteger(); try (LongStreamEx s = LongStreamEx.of(1).onClose(i::incrementAndGet)) { assertEquals(1, s.count()); } assertEquals(1, i.get()); assertEquals(6, LongStreamEx.range(0, 4).sum()); assertEquals(3, LongStreamEx.range(0, 4).max().getAsLong()); assertEquals(0, LongStreamEx.range(0, 4).min().getAsLong()); assertEquals(1.5, LongStreamEx.range(0, 4).average().getAsDouble(), 0.000001); assertEquals(4, LongStreamEx.range(0, 4).summaryStatistics().getCount()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.range(0, 5).skip(1).limit(3).toArray()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.of(3, 1, 2).sorted().toArray()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.of(1, 2, 1, 3, 2).distinct().toArray()); assertArrayEquals(new int[] { 2, 4, 6 }, LongStreamEx.range(1, 4).mapToInt(x -> (int) x * 2).toArray()); assertArrayEquals(new long[] { 2, 4, 6 }, LongStreamEx.range(1, 4).map(x -> x * 2).toArray()); assertArrayEquals(new double[] { 2, 4, 6 }, LongStreamEx.range(1, 4).mapToDouble(x -> x * 2).toArray(), 0.0); assertArrayEquals(new long[] { 1, 3 }, LongStreamEx.range(0, 5).filter(x -> x % 2 == 1).toArray()); assertEquals(6, LongStreamEx.of(1, 2, 3).reduce(Long::sum).getAsLong()); assertEquals(Long.MAX_VALUE, LongStreamEx.rangeClosed(1, Long.MAX_VALUE).spliterator().getExactSizeIfKnown()); assertTrue(LongStreamEx.of(1, 2, 3).spliterator().hasCharacteristics(Spliterator.ORDERED)); assertFalse(LongStreamEx.of(1, 2, 3).unordered().spliterator().hasCharacteristics(Spliterator.ORDERED)); OfLong iterator = LongStreamEx.of(1, 2, 3).iterator(); assertEquals(1L, iterator.nextLong()); assertEquals(2L, iterator.nextLong()); assertEquals(3L, iterator.nextLong()); assertFalse(iterator.hasNext()); AtomicInteger idx = new AtomicInteger(); long[] result = new long[500]; LongStreamEx.range(1000).atLeast(500).parallel().forEachOrdered(val -> result[idx.getAndIncrement()] = val); assertArrayEquals(LongStreamEx.range(500, 1000).toArray(), result); assertTrue(LongStreamEx.empty().noneMatch(x -> true)); assertFalse(LongStreamEx.of(1).noneMatch(x -> true)); assertTrue(LongStreamEx.of(1).noneMatch(x -> false)); } @Test public void testForEach() { List<Long> list = new ArrayList<>(); LongStreamEx.of(1).forEach(list::add); assertEquals(Arrays.asList(1L), list); } @Test public void testFlatMap() { assertArrayEquals(new long[] { 0, 0, 1, 0, 1, 2 }, LongStreamEx.of(1, 2, 3).flatMap(LongStreamEx::range) .toArray()); assertArrayEquals(new int[] { 1, 5, 1, 4, 2, 0, 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 7 }, LongStreamEx.of(15, 14, 20, Long.MAX_VALUE).flatMapToInt(n -> String.valueOf(n).chars().map(x -> x - '0')) .toArray()); String expected = LongStreamEx.range(200).boxed().flatMap( i -> LongStreamEx.range(0, i).<String> mapToObj(j -> i + ":" + j)).join("/"); String res = LongStreamEx.range(200).flatMapToObj(i -> LongStreamEx.range(i).mapToObj(j -> i + ":" + j)) .join("/"); String parallel = LongStreamEx.range(200).parallel().flatMapToObj( i -> LongStreamEx.range(i).mapToObj(j -> i + ":" + j)).join("/"); assertEquals(expected, res); assertEquals(expected, parallel); double[] fractions = LongStreamEx.range(1, 5).flatMapToDouble( i -> LongStreamEx.range(1, i).mapToDouble(j -> ((double) j) / i)).toArray(); assertArrayEquals(new double[] { 1 / 2.0, 1 / 3.0, 2 / 3.0, 1 / 4.0, 2 / 4.0, 3 / 4.0 }, fractions, 0.000001); } @Test public void testPrepend() { assertArrayEquals(new long[] { -1, 0, 1, 2, 3 }, LongStreamEx.of(1, 2, 3).prepend(-1, 0).toArray()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.of(1, 2, 3).prepend().toArray()); assertArrayEquals(new long[] { 10, 11, 0, 1, 2, 3 }, LongStreamEx.range(0, 4).prepend( LongStreamEx.range(10, 12)).toArray()); } @Test public void testAppend() { assertArrayEquals(new long[] { 1, 2, 3, 4, 5 }, LongStreamEx.of(1, 2, 3).append(4, 5).toArray()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.of(1, 2, 3).append().toArray()); assertArrayEquals(new long[] { 0, 1, 2, 3, 10, 11 }, LongStreamEx.range(0, 4) .append(LongStreamEx.range(10, 12)).toArray()); } @Test public void testHas() { assertTrue(LongStreamEx.range(1, 4).has(3)); assertFalse(LongStreamEx.range(1, 4).has(4)); } @Test public void testWithout() { assertArrayEquals(new long[] { 1, 2 }, LongStreamEx.range(1, 4).without(3).toArray()); assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.range(1, 4).without(5).toArray()); LongStreamEx lse = LongStreamEx.range(5); assertSame(lse, lse.without()); assertArrayEquals(new long[] { 0, 1, 3, 4 }, LongStreamEx.range(5).without(new long[] { 2 }).toArray()); assertArrayEquals(new long[] { 0 }, LongStreamEx.range(5).without(1, 2, 3, 4, 5, 6).toArray()); } @Test public void testRanges() { assertArrayEquals(new long[] { 5, 4, Long.MAX_VALUE }, LongStreamEx.of(1, 5, 3, 4, -1, Long.MAX_VALUE).greater( 3).toArray()); assertArrayEquals(new long[] {}, LongStreamEx.of(1, 5, 3, 4, -1, Long.MAX_VALUE).greater(Long.MAX_VALUE) .toArray()); assertArrayEquals(new long[] { 5, 3, 4, Long.MAX_VALUE }, LongStreamEx.of(1, 5, 3, 4, -1, Long.MAX_VALUE) .atLeast(3).toArray()); assertArrayEquals(new long[] { Long.MAX_VALUE }, LongStreamEx.of(1, 5, 3, 4, -1, Long.MAX_VALUE).atLeast( Long.MAX_VALUE).toArray()); assertArrayEquals(new long[] { 1, -1 }, LongStreamEx.of(1, 5, 3, 4, -1, Long.MAX_VALUE).less(3).toArray()); assertArrayEquals(new long[] { 1, 3, -1 }, LongStreamEx.of(1, 5, 3, 4, -1, Long.MAX_VALUE).atMost(3).toArray()); assertArrayEquals(new long[] { 1, 3, 4, -1 }, LongStreamEx.of(1, 5, 3, 4, -1, Long.MAX_VALUE).atMost(4).toArray()); } @Test public void testFind() { assertEquals(6, LongStreamEx.range(1, 10).findFirst(i -> i > 5).getAsLong()); assertFalse(LongStreamEx.range(1, 10).findAny(i -> i > 10).isPresent()); } @Test public void testRemove() { assertArrayEquals(new long[] { 1, 2 }, LongStreamEx.of(1, 2, 3).removeIf(x -> x > 2).toArray()); } @Test public void testSort() { assertArrayEquals(new long[] { 0, 3, 6, 1, 4, 7, 2, 5, 8 }, LongStreamEx.range(0, 9).sortedByLong( i -> i % 3 * 3 + i / 3).toArray()); assertArrayEquals(new long[] { 0, 4, 8, 1, 5, 9, 2, 6, 3, 7 }, LongStreamEx.range(0, 10).sortedByInt( i -> (int) i % 4).toArray()); assertArrayEquals(new long[] { 10, 11, 5, 6, 7, 8, 9 }, LongStreamEx.range(5, 12).sortedBy(String::valueOf) .toArray()); assertArrayEquals(new long[] { Long.MAX_VALUE, 1000, 1, 0, -10, Long.MIN_VALUE }, LongStreamEx.of(0, 1, 1000, -10, Long.MIN_VALUE, Long.MAX_VALUE).reverseSorted().toArray()); assertArrayEquals(new long[] { Long.MAX_VALUE, Long.MIN_VALUE, Long.MIN_VALUE + 1, Long.MAX_VALUE - 1 }, LongStreamEx.of(Long.MIN_VALUE, Long.MIN_VALUE + 1, Long.MAX_VALUE - 1, Long.MAX_VALUE).sortedByLong( l -> l + 1).toArray()); assertArrayEquals(new long[] { -10, Long.MIN_VALUE, Long.MAX_VALUE, 1000, 1, 0 }, LongStreamEx.of(0, 1, 1000, -10, Long.MIN_VALUE, Long.MAX_VALUE).sortedByDouble(x -> 1.0 / x).toArray()); } @SafeVarargs private final void checkEmpty(Function<LongStreamEx, OptionalLong>... fns) { int i = 0; for (Function<LongStreamEx, OptionalLong> fn : fns) { assertFalse("#" + i, fn.apply(LongStreamEx.empty()).isPresent()); assertFalse("#" + i, fn.apply(LongStreamEx.of(1, 2, 3, 4).greater(5).parallel()).isPresent()); assertEquals("#" + i, 10, fn.apply(LongStreamEx.of(1, 1, 1, 1, 10, 10, 10, 10).greater(5).parallel()) .getAsLong()); i++; } } @Test public void testMinMax() { checkEmpty(s -> s.maxBy(Long::valueOf), s -> s.maxByInt(x -> (int) x), s -> s.maxByLong(x -> x), s -> s .maxByDouble(x -> x), s -> s.minBy(Long::valueOf), s -> s.minByInt(x -> (int) x), s -> s .minByLong(x -> x), s -> s.minByDouble(x -> x)); assertEquals(9, LongStreamEx.range(5, 12).max(Comparator.comparing(String::valueOf)) .getAsLong()); assertEquals(10, LongStreamEx.range(5, 12).min(Comparator.comparing(String::valueOf)) .getAsLong()); assertEquals(9, LongStreamEx.range(5, 12).maxBy(String::valueOf).getAsLong()); assertEquals(10, LongStreamEx.range(5, 12).minBy(String::valueOf).getAsLong()); assertEquals(5, LongStreamEx.range(5, 12).maxByDouble(x -> 1.0 / x).getAsLong()); assertEquals(11, LongStreamEx.range(5, 12).minByDouble(x -> 1.0 / x).getAsLong()); assertEquals(29, LongStreamEx.of(15, 8, 31, 47, 19, 29).maxByInt(x -> (int) (x % 10 * 10 + x / 10)).getAsLong()); assertEquals(31, LongStreamEx.of(15, 8, 31, 47, 19, 29).minByInt(x -> (int) (x % 10 * 10 + x / 10)).getAsLong()); assertEquals(29, LongStreamEx.of(15, 8, 31, 47, 19, 29).maxByLong(x -> x % 10 * 10 + x / 10).getAsLong()); assertEquals(31, LongStreamEx.of(15, 8, 31, 47, 19, 29).minByLong(x -> x % 10 * 10 + x / 10).getAsLong()); Supplier<LongStreamEx> s = () -> LongStreamEx.of(1, 50, 120, 35, 130, 12, 0); LongToIntFunction intKey = x -> String.valueOf(x).length(); LongUnaryOperator longKey = x -> String.valueOf(x).length(); LongToDoubleFunction doubleKey = x -> String.valueOf(x).length(); LongFunction<Integer> objKey = x -> String.valueOf(x).length(); List<Function<LongStreamEx, OptionalLong>> minFns = Arrays.asList(is -> is.minByInt(intKey), is -> is .minByLong(longKey), is -> is.minByDouble(doubleKey), is -> is.minBy(objKey)); List<Function<LongStreamEx, OptionalLong>> maxFns = Arrays.asList(is -> is.maxByInt(intKey), is -> is .maxByLong(longKey), is -> is.maxByDouble(doubleKey), is -> is.maxBy(objKey)); minFns.forEach(fn -> assertEquals(1, fn.apply(s.get()).getAsLong())); minFns.forEach(fn -> assertEquals(1, fn.apply(s.get().parallel()).getAsLong())); maxFns.forEach(fn -> assertEquals(120, fn.apply(s.get()).getAsLong())); maxFns.forEach(fn -> assertEquals(120, fn.apply(s.get().parallel()).getAsLong())); } @Test public void testPairMap() { assertEquals(0, LongStreamEx.range(0).pairMap(Long::sum).count()); assertEquals(0, LongStreamEx.range(1).pairMap(Long::sum).count()); assertArrayEquals(new long[] { 6, 7, 8, 9, 10 }, LongStreamEx.of(1, 5, 2, 6, 3, 7).pairMap(Long::sum).toArray()); assertArrayEquals(LongStreamEx.range(999).map(x -> x * 2 + 1).toArray(), LongStreamEx.range(1000).parallel() .map(x -> x * x).pairMap((a, b) -> b - a).toArray()); assertArrayEquals(LongStreamEx.range(1, 100).toArray(), LongStreamEx.range(100).map(i -> i * (i + 1) / 2) .append(LongStream.empty()).parallel().pairMap((a, b) -> b - a).toArray()); assertArrayEquals(LongStreamEx.range(1, 100).toArray(), LongStreamEx.range(100).map(i -> i * (i + 1) / 2) .prepend(LongStream.empty()).parallel().pairMap((a, b) -> b - a).toArray()); assertEquals(1, LongStreamEx.range(1000).map(x -> x * x).pairMap((a, b) -> b - a).pairMap((a, b) -> b - a) .distinct().count()); assertFalse(LongStreamEx.range(1000).greater(2000).parallel().pairMap((a, b) -> a).findFirst().isPresent()); } @Test public void testJoining() { assertEquals("0,1,2,3,4,5,6,7,8,9", LongStreamEx.range(10).join(",")); assertEquals("0,1,2,3,4,5,6,7,8,9", LongStreamEx.range(10).parallel().join(",")); assertEquals("[0,1,2,3,4,5,6,7,8,9]", LongStreamEx.range(10).join(",", "[", "]")); assertEquals("[0,1,2,3,4,5,6,7,8,9]", LongStreamEx.range(10).parallel().join(",", "[", "]")); } @Test public void testMapToEntry() { Map<Long, List<Long>> result = LongStreamEx.range(10).mapToEntry(x -> x % 2, x -> x).groupTo(); assertEquals(Arrays.asList(0L, 2L, 4L, 6L, 8L), result.get(0L)); assertEquals(Arrays.asList(1L, 3L, 5L, 7L, 9L), result.get(1L)); } @Test public void testRecreate() { assertEquals(500, (long) LongStreamEx.iterate(0, i -> i + 1).skipOrdered(1).greater(0).boxed().parallel() .findAny(i -> i == 500).get()); assertEquals(500, (long) LongStreamEx.iterate(0, i -> i + 1).parallel().skipOrdered(1).greater(0).boxed() .findAny(i -> i == 500).get()); } @Test public void testTakeWhile() { assertArrayEquals(LongStreamEx.range(100).toArray(), LongStreamEx.iterate(0, i -> i + 1) .takeWhile(i -> i < 100).toArray()); assertEquals(0, LongStreamEx.iterate(0, i -> i + 1).takeWhile(i -> i < 0).count()); assertEquals(1, LongStreamEx.of(1, 3, 2).takeWhile(i -> i < 3).count()); assertEquals(3, LongStreamEx.of(1, 2, 3).takeWhile(i -> i < 100).count()); } @Test public void testTakeWhileInclusive() { assertArrayEquals(LongStreamEx.range(101).toArray(), LongStreamEx.iterate(0, i -> i + 1) .takeWhileInclusive(i -> i < 100).toArray()); assertEquals(1, LongStreamEx.iterate(0, i -> i + 1).takeWhileInclusive(i -> i < 0).count()); assertEquals(2, LongStreamEx.of(1, 3, 2).takeWhileInclusive(i -> i < 3).count()); assertEquals(3, LongStreamEx.of(1, 2, 3).takeWhileInclusive(i -> i < 100).count()); } @Test public void testDropWhile() { assertArrayEquals(new long[] { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, LongStreamEx.range(100).dropWhile( i -> i % 10 < 5).limit(10).toArray()); assertEquals(100, LongStreamEx.range(100).dropWhile(i -> i % 10 < 0).count()); assertEquals(0, LongStreamEx.range(100).dropWhile(i -> i % 10 < 10).count()); assertEquals(OptionalLong.of(0), LongStreamEx.range(100).dropWhile(i -> i % 10 < 0).findFirst()); assertEquals(OptionalLong.empty(), LongStreamEx.range(100).dropWhile(i -> i % 10 < 10).findFirst()); java.util.Spliterator.OfLong spltr = LongStreamEx.range(100).dropWhile(i -> i % 10 < 1).spliterator(); assertTrue(spltr.tryAdvance((long x) -> assertEquals(1, x))); Builder builder = LongStream.builder(); spltr.forEachRemaining(builder); assertArrayEquals(LongStreamEx.range(2, 100).toArray(), builder.build().toArray()); } @Test public void testIndexOf() { assertEquals(5, LongStreamEx.range(50, 100).indexOf(55).getAsLong()); assertFalse(LongStreamEx.range(50, 100).indexOf(200).isPresent()); assertEquals(5, LongStreamEx.range(50, 100).parallel().indexOf(55).getAsLong()); assertFalse(LongStreamEx.range(50, 100).parallel().indexOf(200).isPresent()); assertEquals(11, LongStreamEx.range(50, 100).indexOf(x -> x > 60).getAsLong()); assertFalse(LongStreamEx.range(50, 100).indexOf(x -> x < 0).isPresent()); assertEquals(11, LongStreamEx.range(50, 100).parallel().indexOf(x -> x > 60).getAsLong()); assertFalse(LongStreamEx.range(50, 100).parallel().indexOf(x -> x < 0).isPresent()); } @Test public void testFoldLeft() { // non-associative LongBinaryOperator accumulator = (x, y) -> (x + y) * (x + y); assertEquals(2322576, LongStreamEx.repeat(3, 4).foldLeft(accumulator).orElse(-1)); assertEquals(2322576, LongStreamEx.repeat(3, 4).parallel().foldLeft(accumulator).orElse(-1)); assertFalse(LongStreamEx.empty().foldLeft(accumulator).isPresent()); assertEquals(144, LongStreamEx.rangeClosed(1, 3).foldLeft(0L, accumulator)); assertEquals(144, LongStreamEx.rangeClosed(1, 3).parallel().foldLeft(0L, accumulator)); } @Test public void testMapFirstLast() { assertArrayEquals(new long[] { -1, 2, 3, 4, 7 }, LongStreamEx.of(1, 2, 3, 4, 5).mapFirst(x -> x - 2L).mapLast( x -> x + 2L).toArray()); } @Test public void testPeekFirst() { long[] input = {1, 10, 100, 1000}; AtomicLong firstElement = new AtomicLong(); assertArrayEquals(new long[] {10, 100, 1000}, LongStreamEx.of(input).peekFirst(firstElement::set).skip(1).toArray()); assertEquals(1, firstElement.get()); assertArrayEquals(new long[] {10, 100, 1000}, LongStreamEx.of(input).skip(1).peekFirst(firstElement::set).toArray()); assertEquals(10, firstElement.get()); firstElement.set(-1); assertArrayEquals(new long[] {}, LongStreamEx.of(input).skip(4).peekFirst(firstElement::set).toArray()); assertEquals(-1, firstElement.get()); } @Test public void testPeekLast() { long[] input = {1, 10, 100, 1000}; AtomicLong lastElement = new AtomicLong(-1); assertArrayEquals(new long[] {1, 10, 100}, LongStreamEx.of(input).peekLast(lastElement::set).limit(3).toArray()); assertEquals(-1, lastElement.get()); assertArrayEquals(new long[] { 1, 10, 100 }, LongStreamEx.of(input).less(1000).peekLast(lastElement::set) .limit(3).toArray()); assertEquals(100, lastElement.get()); assertArrayEquals(input, LongStreamEx.of(input).peekLast(lastElement::set).limit(4).toArray()); assertEquals(1000, lastElement.get()); assertArrayEquals(new long[] {1, 10, 100}, LongStreamEx.of(input).limit(3).peekLast(lastElement::set).toArray()); assertEquals(100, lastElement.get()); } @Test public void testScanLeft() { assertArrayEquals(new long[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).scanLeft(Long::sum)); assertArrayEquals(new long[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).parallel() .scanLeft(Long::sum)); assertArrayEquals(new long[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).filter(x -> true) .scanLeft(Long::sum)); assertArrayEquals(new long[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).filter(x -> true) .parallel().scanLeft(Long::sum)); assertArrayEquals(new long[] { 1, 1, 2, 6, 24, 120 }, LongStreamEx.rangeClosed(1, 5).scanLeft(1, (a, b) -> a * b)); assertArrayEquals(new long[] { 1, 1, 2, 6, 24, 120 }, LongStreamEx.rangeClosed(1, 5).parallel().scanLeft(1, (a, b) -> a * b)); } // Reads numbers from scanner stopping when non-number is encountered // leaving scanner in known state public static LongStreamEx scannerLongs(Scanner sc) { return LongStreamEx.produce(action -> { if(sc.hasNextLong()) action.accept(sc.nextLong()); return sc.hasNextLong(); }); } @Test public void testProduce() { Scanner sc = new Scanner("1 2 3 4 20000000000 test"); assertArrayEquals(new long[] {1, 2, 3, 4, 20000000000L}, scannerLongs(sc).stream().toArray()); assertEquals("test", sc.next()); } @Test public void testPrefix() { assertArrayEquals(new long[] { 1, 3, 6, 10, 20 }, LongStreamEx.of(1, 2, 3, 4, 10).scan(Long::sum).toArray()); assertEquals(OptionalLong.of(10), LongStreamEx.of(1, 2, 3, 4, 10).scan(Long::sum).findFirst(x -> x > 7)); assertEquals(OptionalLong.empty(), LongStreamEx.of(1, 2, 3, 4, 10).scan(Long::sum).findFirst(x -> x > 20)); } @Test public void testIntersperse() { assertArrayEquals(new long[] { 1, 0, 10, 0, 100, 0, 1000 }, LongStreamEx.of(1, 10, 100, 1000).intersperse(0) .toArray()); assertEquals(0L, IntStreamEx.empty().intersperse(1).count()); } }
57.620805
127
0.608206
0a6b8b3ed7074cee439049b151d08ae16d898b15
6,205
package com.rickybooks.rickybooks.Retrofit; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; import retrofit2.http.Url; public interface TextbookService { // MessagesFragment @GET("conversations/{conversation_id}/messages") Call<JsonArray> getMessages( @Header("Authorization") String tokenString, @Path("conversation_id") String conversationId ); // ConversationsFragment @GET("conversations/{user_id}") Call<JsonObject> getConversations( @Header("Authorization") String tokenString, @Path("user_id") String userId ); // ConversationsFragment @DELETE("conversations/{conversation_id}") Call<Void> deleteConversation( @Header("Authorization") String tokenString, @Path("conversation_id") String conversationId ); // DetailsFragment && MessagesFragment @FormUrlEncoded @POST("conversations/{conversation_id}/messages") Call<Void> sendMessage( @Header("Authorization") String tokenString, @Path("conversation_id") String conversationId, @Field("body") String body, @Field("user_id") String userId ); // DetailsFragment @FormUrlEncoded @POST("conversations") Call<JsonObject> createConversation( @Header("Authorization") String tokenString, @Field("sender_id") String userId, @Field("recipient_id") String sellerId, @Field("textbook_id") String textbookId ); // LoginFragment @POST("login") Call<JsonObject> login( @Body JsonObject user ); // LoginFragment && RegisterFragment @FormUrlEncoded @POST("firebase") Call<Void> storeFirebaseToken( @Header("Authorization") String tokenString, @Field("user_id") String userId, @Field("firebase_token") String firebaseToken ); // RegisterFragment @POST("users") Call<JsonObject> register( @Body JsonObject user ); // BuyFragment @GET("textbooks") Call<JsonArray> getTextbooks(); // SearchFragment @GET("search/{category}/{input}") Call<JsonArray> searchTextbooks( @Path("category") String category, @Path("input") String input ); // SellFragment @FormUrlEncoded @POST("textbooks") Call<String> postTextbook( @Header("Authorization") String tokenString, @Field("user_id") String userId, @Field("textbook_title") String textbookTitle, @Field("textbook_author") String textbookAuthor, @Field("textbook_edition") String textbookEdition, @Field("textbook_condition") String textbookCondition, @Field("textbook_type") String textbookType, @Field("textbook_coursecode") String textbookCoursecode, @Field("textbook_price") String textbookPrice ); // SellFragment @GET("aws/{textbook_id}/{extension}") Call<String> getSignedPutUrl( @Header("Authorization") String tokenString, @Path("textbook_id") String textbookId, @Path("extension") String extension ); // SellFragment @PUT Call<Void> putImageAws( @Url String url, @Body RequestBody imageFile ); // ProfileFragment @GET("users/{user_id}/textbooks") Call<JsonArray> getUserTextbooks( @Path("user_id") String userId ); // ProfileFragment @FormUrlEncoded @PUT("textbooks/{textbook_id}") Call<Void> editTextbook( @Header("Authorization") String tokenString, @Path("textbook_id") String textbookId, @Field("textbook_title") String textbookTitle, @Field("textbook_author") String textbookAuthor, @Field("textbook_edition") String textbookEdition, @Field("textbook_condition") String textbookCondition, @Field("textbook_type") String textbookType, @Field("textbook_coursecode") String textbookCoursecode, @Field("textbook_price") String textbookPrice ); // ProfileFragment @DELETE("textbooks/{textbook_id}") Call<String> deleteTextbook( @Header("Authorization") String tokenString, @Path("textbook_id") String textbookId ); // ProfileFragment @DELETE Call<Void> deleteImage( @Url String url ); // ProfileFragment @DELETE("logout") Call<Void> logout( @Header("Authorization") String tokenString ); // ProfileFragment @DELETE("users/{user_id}") Call<Void> deleteUser( @Header("Authorization") String tokenString, @Path("user_id") String userId ); // EditTextbookFragment @DELETE("delete_image/{textbook_id}") Call<Void> deleteImageEntry( @Header("Authorization") String tokenString, @Path("textbook_id") String textbookId ); // EditTextbookFragment @GET("get_delete_url/{textbook_id}") Call<String> getSignedDeleteUrl( @Header("Authorization") String tokenString, @Path("textbook_id") String textbookId ); // NotifyFragment @GET("notify_items") Call<JsonArray> getNotifyItems( @Header("Authorization") String tokenString ); // NotifyFragment @FormUrlEncoded @POST("notify_items") Call<Void> postNotifyItem( @Header("Authorization") String tokenString, @Field("user_id") String userId, @Field("category") String category, @Field("input") String input ); // NotifyFragment @GET("notify_results/{user_id}") Call<JsonArray> getNotifyResults( @Header("Authorization") String tokenString, @Path("user_id") String userId ); // NotifyFragment @DELETE("notify_items/{notify_item_id}") Call<Void> deleteNotifyItem( @Header("Authorization") String tokenString, @Path("notify_item_id") String notifyItemId ); }
28.860465
68
0.657857
ec81b4839404a4e29b95ad0cf7e57efa44978d23
861
import java.util.Scanner; /** * * Lab 11 * calculate service charges for a cheque * * @author P.M.Campbell * @version 2020-fall * */ public class Bank { public static void main(String[] args) { Scanner in = new Scanner(System.in); double amount, service=0; System.out.println("Calculating Service Charge"); System.out.print("Enter a cheque amount:"); amount = in.nextDouble(); if (amount < 10) { service = amount * .01; } else if (amount >= 10) { // do I need the if in this statement, why, why not? if (amount < 100) { service = amount * .1; } else if (amount < 1000) { service = 5+ amount * .05; } else { service = 40 +amount * .01; } } System.out.println("Check value: "+amount); System.out.println("Service charge: "+service); } }
25.323529
84
0.57259
711196cb0fc391a5167b7452a2f7784eb1509f10
480
package com.hardcore.accounting.exception; import lombok.Data; import org.springframework.http.HttpStatus; @Data public class ServiceException extends RuntimeException { private HttpStatus statusCode; private String errorCode; // biz error code private ErrorType errorType; // Service, Client, Unknown public enum ErrorType { Client, Service, Unknown; } public ServiceException(String message) { super(message); } }
21.818182
60
0.702083
cffa3d4cb1f5fbd0bf9bdf1ef5877171478e98a9
920
package org.wormsim.frontend.service; import org.geppetto.core.auth.IAuthService; import org.geppetto.core.data.model.IUser; import org.springframework.stereotype.Service; @Service public class AuthService implements IAuthService { public static final String NOBODY = "_____"; public AuthService() {} private IUser user=null; private static String cn="WSIDUS"; @Override public String authFailureRedirect() { // go back to root return "/../"; } @Override public boolean isDefault() { return false; } /** * @param user */ @Override public void setUser(IUser user) { this.user=user; } @Override public IUser getUser() { return this.user; } @Override public Boolean isAuthenticated(String sessionValue) { return !sessionValue.isEmpty() && !sessionValue.equals(NOBODY); } @Override public String getSessionId() { return cn; } }
16.428571
65
0.684783
bd5d52f3bbb7cfc607fbcc83a79f77ddd10cca62
7,966
package oolala; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.Circle; import oolala.model.Parser; import oolala.model.commands.logocommands.Back; import oolala.model.commands.logocommands.Forward; import oolala.model.commands.logocommands.HideTurtle; import oolala.model.commands.logocommands.Home; import oolala.model.commands.logocommands.Left; import oolala.model.commands.logocommands.PenDown; import oolala.model.commands.logocommands.PenUp; import oolala.model.commands.logocommands.Right; import oolala.model.commands.logocommands.ShowTurtle; import oolala.model.ReadWrite; import oolala.model.commands.logocommands.Stamp; import oolala.model.commands.logocommands.Tell; import oolala.view.Pen; import oolala.view.Turtle; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * Feel free to completely change this code or delete it entirely. */ class MainTest { // how close do real valued numbers need to be to count as the same static final double TOLERANCE = 0.0005; //test Strings (Turtle Program) to be parsed static final String[] testTurtleCodeString = new String[] {"fd 50", "lt 90"}; static final String[] testNoParamsString = new String[] {"home", "pu"}; static final String[] testDiffCasesString = new String[] {"HOME" + "lt 90"}; /** Parser parses correctly **/ @Test void testParser () { Map<String, ArrayList> testMap = new LinkedHashMap<>(); ArrayList<String> c1Params = new ArrayList<>(); c1Params.add("50"); testMap.put("fd", c1Params); ArrayList<String> c2Params = new ArrayList<>(); c2Params.add("90"); testMap.put("lt", c2Params); Parser p = new Parser(); assertEquals(testMap, p.Parse(testTurtleCodeString)); } /** tests Parser result on command with 0 params **/ @Test void testParserNoParams () { Map<String, ArrayList> testMap = new LinkedHashMap<>(); ArrayList<String> c1Params = new ArrayList<>(); testMap.put("home", c1Params); ArrayList<String> c2Params = new ArrayList<>(); testMap.put("pu", c2Params); Parser p = new Parser(); assertEquals(testMap, p.Parse(testNoParamsString)); } /** tests Parser with different case commands **/ @Test void testParserCases () { Map<String, ArrayList> testMap = new LinkedHashMap<>(); ArrayList<String> c1Params = new ArrayList<>(); testMap.put("home", c1Params); ArrayList<String> c2Params = new ArrayList<>(); c2Params.add("90"); testMap.put("lt", c2Params); Parser p = new Parser(); assertEquals(testMap, p.Parse(testDiffCasesString)); } /** Tests that showTurtle command turns fill and stroke from transparent to green **/ @Test void testShowTurtle() { ArrayList<String> Params = new ArrayList<>(); Turtle t = new Turtle(); Pen p = new Pen(); ShowTurtle show = new ShowTurtle(Params, t, p); show.commandFunc(Params, t, p); t.editTurtleColor(Color.GREEN); assertEquals(Color.GREEN, t.getColor()); } /** Tests that hideTurtle command turns fill and stroke from green to transparent**/ @Test void testHideTurtle() { ArrayList<String> Params = new ArrayList<>(); Turtle t = new Turtle(); Pen p = new Pen(); HideTurtle hide = new HideTurtle(Params, t, p); hide.commandFunc(Params, t, p); t.editTurtleColor(Color.TRANSPARENT); assertEquals(Color.TRANSPARENT, t.getColor()); } /** tests that back moves turtle to correct coordinates **/ @Test void testBack() { Turtle t = new Turtle(); Pen p = new Pen(); ArrayList<String> Params = new ArrayList<>(); Params.add("50"); Back back = new Back(Params, t, p); back.commandFunc(Params, t, p); assertEquals(t.getX(), -50); assertEquals(t.getY(), -50); } /** tests that forward moves turtle to correct coordinates **/ @Test void testForward() { Turtle t = new Turtle(); Pen p = new Pen(); ArrayList<String> Params = new ArrayList<>(); Params.add("50"); Forward forward = new Forward(Params, t, p); forward.commandFunc(Params, t, p); assertEquals(t.getX(), 50); assertEquals(t.getY(), 50); } /** tests that penUp makes penDown false **/ @Test void testPenUp() { Turtle t = new Turtle(); Pen p = new Pen(); ArrayList<String> Params = new ArrayList<>(); PenUp penUp = new PenUp(Params, t, p); penUp.commandFunc(Params, t, p); assertEquals(false, p.getPenDown()); } /** tests that penDown makes penDown true **/ @Test void testPenDown() { Turtle t = new Turtle(); Pen p = new Pen(); ArrayList<String> Params = new ArrayList<>(); PenDown penDown = new PenDown(Params, t, p); penDown.commandFunc(Params, t, p); assertEquals(true, p.getPenDown()); } /** tests that Home makes centerX and centerY 0 **/ @Test void testHome() { Turtle t = new Turtle(); Pen p = new Pen(); ArrayList<String> Params = new ArrayList<>(); Home home = new Home(Params, t, p); home.commandFunc(Params, t, p); assertEquals(0, t.getX()); assertEquals(0, t.getY()); } /** tests that Right correctly changes angle of turtle **/ @Test void testRight() { Turtle t = new Turtle(); Pen p = new Pen(); ArrayList<String> Params = new ArrayList<>(); Params.add("90"); Right r = new Right(Params, t, p); r.commandFunc(Params, t, p); assertEquals(90, (t.getAngle())); } /** tests that Left correctly changes angle of turtle **/ @Test void testLeft() { Turtle t = new Turtle(); Pen p = new Pen(); ArrayList<String> Params = new ArrayList<>(); Params.add("90"); Left l = new Left(Params, t, p); l.commandFunc(Params, t, p); assertEquals(-90, t.getAngle()); } @Test void testStamp() { Turtle t = new Turtle(); t.setX(20); t.setY(20); Pen p = new Pen(); ArrayList<String> Params = new ArrayList<>(); Stamp s = new Stamp(Params, t, p); s.commandFunc(Params, t, p); assertEquals(20, t.getX()); assertEquals(20, t.getY()); } @Test void testTell() { Turtle t = new Turtle(); Pen p = new Pen(); ArrayList<String> Params = new ArrayList<>(); Params.add("t0"); Params.add("t1"); Params.add("t2"); Tell tell = new Tell(Params, t, p); tell.getTurtles(); } /** * tests that a known file is accurately being read */ @Test void readFileTest() throws FileNotFoundException { assertEquals("F", ReadWrite.readFile("lsystem","koch_curve.txt")[5]); } @Test void readAnotherFileTest() throws FileNotFoundException { assertEquals("rt", ReadWrite.readFile("logo","triangle.txt")[2]); } /** * Test to check that a file can be written when called */ @Test void writeFileTest() { ReadWrite.writeFile("logo", "newFile.txt", "Empty File"); assertEquals("newFile.txt", ReadWrite.openFile("logo")[3]); } /** * tests to check that all program files can be opened */ @Test void OpenFileTest(){ assertEquals("grid.txt", ReadWrite.openFile("logo")[0]); assertEquals("flytrap.txt", ReadWrite.openFile("darwin")[0]); assertEquals("koch_curve.txt", ReadWrite.openFile("lsystem")[0]); } }
31.611111
89
0.607833
c8bea091a2bfec51287ee33ad75c8f63c977c155
3,575
package examples.adsabs; import org.junit.BeforeClass; import monty.solr.util.MontySolrQueryTestCase; import monty.solr.util.MontySolrSetup; public class TestPivotQuery extends MontySolrQueryTestCase { @BeforeClass public static void beforeClass() throws Exception { makeResourcesVisible(Thread.currentThread().getContextClassLoader(), new String[] { MontySolrSetup.getMontySolrHome() + "/contrib/examples/adsabs/server/solr/collection1/", MontySolrSetup.getSolrHome() + "/example/solr/collection1" }); System.setProperty("solr.allow.unsafe.resourceloading", "true"); schemaString = MontySolrSetup.getMontySolrHome() + "/contrib/examples/adsabs/server/solr/collection1/conf/schema.xml"; configString = MontySolrSetup.getMontySolrHome() + "/contrib/examples/adsabs/server/solr/collection1/conf/solrconfig.xml"; initCore(configString, schemaString, MontySolrSetup.getSolrHome() + "/example/solr"); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testSearch() throws Exception { //assertU(delQ("*:*")); //assertU(commit()); // if i remove this, the test will sometimes fail (i don't understand...) assertU(adoc("id", "0", "bibcode", "0", "year", "2011", "property", "refereed" )); assertU(adoc("id", "1", "bibcode", "1", "year", "2011", "property", "Not Refereed" )); assertU(adoc("id", "2", "bibcode", "2", "year", "2011", "property", "Not Refereed" )); assertU(adoc("id", "3", "bibcode", "3", "year", "2012", "property", "Not Refereed" )); assertU(adoc("id", "4", "bibcode", "4", "year", "2012", "property", "Refereed" )); assertU(adoc("id", "5", "bibcode", "5", "year", "2012", "property", "Not Refereed" )); assertU(commit("waitSearcher", "true")); assertQ(req("q", "*:*"), "//*[@numFound='6']" ); assertQ(req("q", "*:*", "facet", "true", "facet.pivot", "property,year", "fl", "bibcode", "indent", "true"), "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[1]//str[2]/text()='notrefereed'", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[1]/int[@name=\"count\"]='4'", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[1]/arr[@name=\"pivot\"]/lst[1]//str[1]/text()='year'", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[1]/arr[@name=\"pivot\"]/lst[1]//str[2]/text()='2011'", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[1]/arr[@name=\"pivot\"]/lst[1]/int[@name=\"count\"]=2", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[1]/arr[@name=\"pivot\"]/lst[2]//str[1]/text()='year'", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[1]/arr[@name=\"pivot\"]/lst[2]//str[2]/text()='2012'", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[1]/arr[@name=\"pivot\"]/lst[2]/int[@name=\"count\"]=2", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[2]//str[2]/text()='refereed'", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[2]/int[@name=\"count\"]='2'", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[2]/arr[@name=\"pivot\"]/lst[1]//str[2]/text()='2011'", "/response/lst[2]/lst[6]/arr[@name=\"property,year\"]/lst[2]/arr[@name=\"pivot\"]/lst[2]/int[@name=\"count\"]=1" ); } // Uniquely for Junit 3 public static junit.framework.Test suite() { return new junit.framework.JUnit4TestAdapter(TestPivotQuery.class); } }
37.631579
121
0.604755
056d63baf39bf4ea0a659e8a8ff3671ffba62ed9
612
package net.aionstudios.sorttest.algorithm; import java.util.concurrent.ThreadLocalRandom; import net.aionstudios.sorttest.SortingAlgorithm; public class BozoSort extends SortingAlgorithm { public BozoSort() { super("bozo", "Randomly switches 2 points in the array, mostly for stress testing."); enableParallel(); } @Override public int[] sortingPass(int[] ia) { int n = Math.round(ThreadLocalRandom.current().nextInt(ia.length)); int n2 = Math.round(ThreadLocalRandom.current().nextInt(ia.length)); int s1 = ia[n2]; ia[n2] = ia[n]; ia[n] = s1; return ia; } }
24.48
88
0.69281
d30922e1fe7efd61dd2ef8a6eae061ae8809e1bd
695
package org.elink.util; import static org.junit.Assert.assertEquals; import java.util.Date; import org.junit.Test; import com.elink.util.DateUtils; public class DateUtilsTest { @Test public void testParse() { assertEquals(null, DateUtils.parse(null)); Date d1 = new Date(); String s = DateUtils.format(d1); Date d2 = DateUtils.parse(s); System.out.printf("%d-%d%n", d1.getTime(), d2.getTime()); assertEquals(true, d1.getTime() >= d2.getTime()); } @Test public void testFormat() { assertEquals(null, DateUtils.format(null)); String now = DateUtils.now(); assertEquals(now, DateUtils.format(DateUtils.parse(now))); System.out.printf("now is %s%n", now); } }
21.71875
60
0.692086
d0b672c1f38239c9d6fcfd41fd35fe6a1a767043
3,329
package edu.wofford.wocoin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.web3j.crypto.Credentials; import org.web3j.crypto.WalletUtils; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.Request; import org.web3j.protocol.core.methods.response.EthGetBalance; import org.web3j.protocol.core.methods.response.TransactionReceipt; import org.web3j.protocol.http.HttpService; import org.web3j.tx.Transfer; import org.web3j.utils.Convert; import java.math.BigDecimal; import java.math.BigInteger; import java.util.concurrent.ExecutionException; public class Transaction { private static final Logger log = LoggerFactory.getLogger(Transaction.class); public static void send() throws Exception { Web3j web3j = Web3j.build(new HttpService()); log.info("Connected to Ethereum client version: " + web3j.web3ClientVersion().send().getWeb3ClientVersion()); Credentials credentials = WalletUtils.loadCredentials( "adminpwd", "C:\\Users\\cburd\\project-i-b-ok\\ethereum\\node0\\keystore\\UTC--2019-08-07T17-24-10.532680697Z--0fce4741f3f54fbffb97837b4ddaa8f769ba0f91.json"); log.info("Credentials loaded"); log.info("Sending Ether .."); TransactionReceipt transferReceipt = Transfer.sendFunds( web3j, credentials, "0xa615316333ba8622fd5bb60fe39758b3515f774d", BigDecimal.valueOf(1), Convert.Unit.ETHER).sendAsync() .get(); log.info("Transaction complete : " + transferReceipt.getTransactionHash()); } /*public static void send() throws Exception { Web3j web3j = Web3j.build(new HttpService()); log.info("Connected to Ethereum client version: " + web3j.web3ClientVersion().send().getWeb3ClientVersion()); Credentials credentials = WalletUtils.loadCredentials( "jsmith", "C:\\Users\\cburd\\project-i-b-ok\\ethereum\\node0\\keystore\\UTC--2019-08-14T05-39-33.567000000Z--a615316333ba8622fd5bb60fe39758b3515f774d.json"); log.info("Credentials loaded"); log.info("Sending Ether .."); TransactionReceipt transferReceipt = Transfer.sendFunds( web3j, credentials, "0x0fce4741f3f54fbffb97837b4ddaa8f769ba0f91", BigDecimal.valueOf(.0997), Convert.Unit.ETHER).sendAsync() .get(); log.info("Transaction complete : " + transferReceipt.getTransactionHash()); }*/ public static String getBalance(String publicKey) { try { Web3j web3 = Web3j.build(new HttpService()); EthGetBalance ethGetBalance = web3.ethGetBalance("0x" + publicKey, DefaultBlockParameterName.LATEST) .sendAsync() .get(); BigInteger bal = ethGetBalance.getBalance(); String actual = bal.toString(); actual = actual.replace(actual.substring(actual.length() - 18), ""); return actual; } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return ""; } }
43.802632
171
0.644037
1c25936c10939dfe3520cc8c1b49f8afb51071de
841
package net.minestom.server.network.packet.server.play; import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.potion.Potion; import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.utils.binary.BinaryWriter; import org.jetbrains.annotations.NotNull; public record EntityEffectPacket(int entityId, @NotNull Potion potion) implements ServerPacket { public EntityEffectPacket(BinaryReader reader) { this(reader.readVarInt(), new Potion(reader)); } @Override public void write(@NotNull BinaryWriter writer) { writer.writeVarInt(entityId); writer.write(potion); } @Override public int getId() { return ServerPacketIdentifier.ENTITY_EFFECT; } }
32.346154
96
0.760999
8b6ca386233e5675fa8afaf4b80ae84fb4511363
1,757
package com.blogfortraining.restapi.security; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; import com.blogfortraining.restapi.entity.User; import com.blogfortraining.restapi.entity.Role; import com.blogfortraining.restapi.repository.UserRepository; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class CustomUserDetailsService implements UserDetailsService { private UserRepository userRepository; public CustomUserDetailsService (UserRepository userRepository){ this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String userNameOrEmail) throws UsernameNotFoundException { User user = userRepository.findByUserNameOrEmail(userNameOrEmail, userNameOrEmail) .orElseThrow(()-> new UsernameNotFoundException("User not found: "+userNameOrEmail)); return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), mapRolesToAuthorities(user.getRoles())); } private Collection< ? extends GrantedAuthority> mapRolesToAuthorities(Set<Role> roles){ return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList()); } }
42.853659
115
0.741036
fca4a77d38c5a133a23a4bd84b765581e23cec2f
1,415
package com.weiit.web.admin.ump.service.impl; import com.weiit.core.entity.E; import com.weiit.core.entity.FormMap; import com.weiit.core.mapper.BaseMapper; import com.weiit.core.service.impl.AbstractService; import com.weiit.web.admin.ump.mapper.BargainMapper; import com.weiit.web.admin.ump.service.BargainService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * 秒杀 实现类 * Title: CouponServiceImpl.java * Description: * Company: 微云时代 * * @author hzy * @date 2017年12月26日 */ @Service("bargainService") public class BargainServiceImpl extends AbstractService implements BargainService { @Resource private BargainMapper bargainMapper; @Override public BaseMapper setMapper() { return bargainMapper; } @Override public List<E> selectBargainDetailList(FormMap formmap) { return bargainMapper.selectBargainDetailList(formmap); } @Override public List<E> selectBargainNancyList(FormMap formmap) { return bargainMapper.selectBargainNancyList(formmap); } @Override public List<E> selectProductList(FormMap formmap) { // TODO Auto-generated method stub return bargainMapper.selectProductList(formmap); } @Override public List<E> getProductByBargainIds(FormMap formmap) { return bargainMapper.getProductByBargainIds(formmap); } }
25.267857
83
0.739223
34a7f85e2e0618f722b36918f544b6a8ee62dce9
1,166
/******************************************************************************* * Copyright (c) 2013-2018 Contributors to the Eclipse Foundation * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, * Version 2.0 which accompanies this distribution and is available at * http://www.apache.org/licenses/LICENSE-2.0.txt ******************************************************************************/ package org.locationtech.geowave.adapter.vector.stats; import java.io.Serializable; import org.locationtech.geowave.core.index.persist.Persistable; import org.locationtech.geowave.core.store.adapter.statistics.InternalDataStatistics; import com.fasterxml.jackson.annotation.JsonTypeInfo; @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public interface StatsConfig<T> extends Serializable, Persistable { InternalDataStatistics<T, ?, ?> create( Short internalDataAdapterId, final String fieldName ); }
40.206897
99
0.680961
6ebb1394089d4ba5fbc01394780210bbefa80057
1,267
package hudson.tasks._ant; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlPage; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.tasks.Ant; import org.jvnet.hudson.test.HudsonTestCase; import org.jvnet.hudson.test.SingleFileSCM; import org.mozilla.javascript.tools.debugger.Dim; /** * @author Kohsuke Kawaguchi */ public class AntTargetAnnotationTest extends HudsonTestCase { public void test1() throws Exception { FreeStyleProject p = createFreeStyleProject(); Ant.AntInstallation ant = configureDefaultAnt(); p.getBuildersList().add(new Ant("foo",ant.getName(),null,null,null)); p.setScm(new SingleFileSCM("build.xml",getClass().getResource("simple-build.xml"))); FreeStyleBuild b = buildAndAssertSuccess(p); AntTargetNote.ENABLED = true; try { HudsonTestCase.WebClient wc = createWebClient(); HtmlPage c = wc.getPage(b, "console"); System.out.println(c.asText()); HtmlElement o = c.getElementById("console-outline"); assertEquals(2,o.selectNodes(".//LI").size()); } finally { AntTargetNote.ENABLED = false; } } }
35.194444
92
0.689029
cec2476d5a8acc2b53b32d17575f05ac47565d64
3,358
package com.dexesttp.hkxpack.cli.utils; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import com.dexesttp.hkxpack.cli.utils.ArgsParser.Options; /** * Tests on an {@link ArgsParser}'s analysis size. */ public class ArgsParserSizeTest { private transient ArgsParser argsParser; @Before /** * {@inheritDoc} */ public void setUp() { argsParser = new ArgsParser(); argsParser.addOption("-a"); argsParser.addOption("-b", 0); argsParser.addOption("-c", 1); } @Test /** * {@inheritDoc} */ public void itShouldOnlyCatchValuesInTheDefaultOptionIfThereIsNoOptionsInTheArguments() throws WrongSizeException { Options result = argsParser.parse(ArgsParserTest.TEST, ArgsParserTest.TEST2); assertEquals(2, result.get("").size()); } @Test /** * {@inheritDoc} */ public void itShouldCatchOneExtraOptionIfThereIsAnExtraOption() throws WrongSizeException { Options result = argsParser.parse(ArgsParserTest.TEST, "-a"); assertEquals(2, result.size()); } @Test /** * {@inheritDoc} */ public void itShouldCatchOneExtraEmptyOptionIfThereIsAnExtraOptionButNothingBehindIt() throws WrongSizeException { Options result = argsParser.parse(ArgsParserTest.TEST, "-a"); assertEquals(0, result.get("-a").size()); } @Test /** * {@inheritDoc} */ public void itShouldCatchArgumentsUntilTheNextOptionIfTheNextOptionIsGreedy() throws WrongSizeException { Options result = argsParser.parse(ArgsParserTest.TEST, "-a", ArgsParserTest.TEST2, ArgsParserTest.TEST3); assertEquals(1, result.get("").size()); } @Test /** * {@inheritDoc} */ public void itShouldCatchArgumentsAfterTheNextOptionIfTheNextOptionIsGreedy() throws WrongSizeException { Options result = argsParser.parse(ArgsParserTest.TEST, "-a", ArgsParserTest.TEST2, ArgsParserTest.TEST3); assertEquals(2, result.get("-a").size()); } @Test /** * {@inheritDoc} */ public void itShouldStopGreedyCatchingAtTheNextOption() throws WrongSizeException { Options result = argsParser.parse(ArgsParserTest.TEST, "-a", ArgsParserTest.TEST2, "-b", ArgsParserTest.TEST3); assertEquals(2, result.get("").size()); assertEquals(1, result.get("-a").size()); } @Test /** * {@inheritDoc} */ public void itShouldCatchAllArgumentsAsDefaultForAZeroSizedOption() throws WrongSizeException { Options result = argsParser.parse(ArgsParserTest.TEST, "-b", ArgsParserTest.TEST2, ArgsParserTest.TEST3); assertEquals(3, result.get("").size()); } @Test /** * {@inheritDoc} */ public void itShouldHandleZeroSizedOptionsAtTheEndOfTheArgumentArray() throws WrongSizeException { Options result = argsParser.parse(ArgsParserTest.TEST, "-b"); assertEquals(0, result.get("-b").size()); } @Test /** * {@inheritDoc} */ public void itShouldCatchTheRightNumberOfArgumentsForASizedOption() throws WrongSizeException { Options result = argsParser.parse(ArgsParserTest.TEST, "-c", ArgsParserTest.TEST2, ArgsParserTest.TEST3); assertEquals(2, result.get("").size()); assertEquals(1, result.get("-c").size()); } @Test /** * {@inheritDoc} */ public void itShouldCatchZeroArgumentsForAZeroSizedOption() throws WrongSizeException { Options result = argsParser.parse(ArgsParserTest.TEST, "-b", ArgsParserTest.TEST2, ArgsParserTest.TEST3); assertEquals(0, result.get("-b").size()); } }
27.983333
116
0.73109
2acb5e7ef3bf5aa264a97a3acd1e6cc72aa8e702
1,176
/* * 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 interfacedemo; /** * * @author Peggy Fisher */ public class MountainBike implements Bicycle{ int pedalRate = 0; int speed = 0; int gear = 1; // The compiler will now require that methods // change pedalRate, changeGear, speedUp, and applyBrakes // all be implemented. Compilation will fail if those // methods are missing from this class. @Override public void changePedalRate(int newValue) { pedalRate = newValue; } @Override public void changeGear(int newValue) { gear = newValue; } @Override public void speedUp(int increment) { speed = speed + increment; } @Override public void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println(" pedal rate: " + pedalRate + " speed: " + speed + " gear: " + gear); } }
25.565217
80
0.589286
18a740c1301a8e626fbef1e6bd134dc9ab7cf07c
12,454
package com.axeac.app.sdk.ui.datetime; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import java.util.Arrays; import java.util.Calendar; import java.util.List; import com.axeac.app.sdk.R; import com.axeac.app.sdk.utils.StaticObject; /** * 时间控件工具类 * @author axeac * @version 1.0.0 * */ public class DateTimeUtils { /**开始年份与最后年份*/ private static final int START_YEAR = 1990, END_YEAR = 2100; /** * 放置时间选择器的view * */ private View view; /** * 日期选择器年视图 * */ private DateView date_year; /** * 日期选择器月视图 * */ private DateView date_month; /** * 日期选择器日视图 * */ private DateView date_day; /** * 时间选择器时视图 * */ private DateView date_hour; /** * 时间选择器分视图 * */ private DateView date_minute; /** * 时间选择器秒视图 * */ private DateView date_second; /** * 日期时间选择器年视图 * */ private DateView date_years; /** * 日期时间选择器月视图 * */ private DateView date_months; /** * 日期时间选择器日视图 * */ private DateView date_days; /** * 日期时间选择器时视图 * */ private DateView date_hours; /** * 日期时间选择器分视图 * */ private DateView date_mins; public DateTimeUtils(Context ctx) { super(); view = LayoutInflater.from(ctx).inflate(R.layout.axeac_datetime, null); } /** * describe:Pop-up date selector * 弹出日期选择器 * @param y * 年份 * * @param m * 月份 * @param d * 日 */ public void initDatePicker(int y,int m,int d) { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); if(y>0){ year = y; } if(m>0){ month = m; } if(d>0){ day = d; } // Add the month and convert it to list, to facilitate the subsequent judgments // 添加大小月月份并将其转换为list,方便之后的判断 String[] months_big = { "1", "3", "5", "7", "8", "10", "12" }; String[] months_little = { "4", "6", "9", "11" }; final List<String> list_big = Arrays.asList(months_big); final List<String> list_little = Arrays.asList(months_little); // year // 年 date_year = (DateView) view.findViewById(R.id.labeldatetime_1); // Set the display data for "year" // 设置"年"的显示数据 date_year.setAdapter(new DateTimeAdapter(START_YEAR, END_YEAR)); // Can be Scroll // 可循环滚动 date_year.setCyclic(true); // Add text // 添加文字 date_year.setLabel(""); // The data displayed when initializing // 初始化时显示的数据 date_year.setCurrentItem(year - START_YEAR); // month // 月 date_month = (DateView) view.findViewById(R.id.labeldatetime_2); date_month.setAdapter(new DateTimeAdapter(1, 12)); date_month.setCyclic(true); date_month.setLabel(""); date_month.setCurrentItem(month); //day // 日 date_day = (DateView) view.findViewById(R.id.labeldatetime_3); date_day.setCyclic(true); // Determine the size of the month and whether the leap year, used to determine the data of the "day" // 判断大小月及是否闰年,用来确定"日"的数据 if (list_big.contains(String.valueOf(month + 1))) { date_day.setAdapter(new DateTimeAdapter(1, 31)); } else if (list_little.contains(String.valueOf(month + 1))) { date_day.setAdapter(new DateTimeAdapter(1, 30)); } else { // leap year // 闰年 if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) date_day.setAdapter(new DateTimeAdapter(1, 29)); else date_day.setAdapter(new DateTimeAdapter(1, 28)); } date_day.setLabel(""); date_day.setCurrentItem(day - 1); // Add listen to "year" // 添加"年"监听 OnDateChangedListener listener_year = new OnDateChangedListener() { public void onChanged(DateView view, int oldValue, int newValue) { int year_num = newValue + START_YEAR; // Determine the size of the month and whether the leap year, used to determine the data of the "day" // 判断大小月及是否闰年,用来确定"日"的数据 if (list_big.contains(String.valueOf(date_month.getCurrentItem() + 1))) { date_day.setAdapter(new DateTimeAdapter(1, 31)); } else if (list_little.contains(String.valueOf(date_month.getCurrentItem() + 1))) { date_day.setAdapter(new DateTimeAdapter(1, 30)); } else { if ((year_num % 4 == 0 && year_num % 100 != 0) || year_num % 400 == 0) date_day.setAdapter(new DateTimeAdapter(1, 29)); else date_day.setAdapter(new DateTimeAdapter(1, 28)); } } }; // Add listen to "month" // 添加"月"监听 OnDateChangedListener listener_month = new OnDateChangedListener() { public void onChanged(DateView view, int oldValue, int newValue) { int month_num = newValue + 1; // Determine the size of the month and whether the leap year, used to determine the data of the "day" // 判断大小月及是否闰年,用来确定"日"的数据 if (list_big.contains(String.valueOf(month_num))) { date_day.setAdapter(new DateTimeAdapter(1, 31)); } else if (list_little.contains(String.valueOf(month_num))) { date_day.setAdapter(new DateTimeAdapter(1, 30)); } else { if (((date_year.getCurrentItem() + START_YEAR) % 4 == 0 && (date_year .getCurrentItem() + START_YEAR) % 100 != 0) || (date_year.getCurrentItem() + START_YEAR) % 400 == 0) date_day.setAdapter(new DateTimeAdapter(1, 29)); else date_day.setAdapter(new DateTimeAdapter(1, 28)); } } }; date_year.addChangingListener(listener_year); date_month.addChangingListener(listener_month); int textSize = (StaticObject.deviceHeight / 100) * 3; date_day.TEXT_SIZE = textSize; date_month.TEXT_SIZE = textSize; date_year.TEXT_SIZE = textSize; } /** * describe:Pop-up date selector * 弹出时间选择器 * @param minuteStep * 分 * @param secondStep * 秒 */ public void initTimePicker(int minuteStep, int secondStep) { Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); // hour // 时 date_hour = (DateView) view.findViewById(R.id.labeldatetime_1); date_hour.setAdapter(new DateTimeAdapter(0, 23)); date_hour.setCyclic(true); date_hour.setLabel(""); date_hour.setCurrentItem(hour); //minute // 分 date_minute = (DateView) view.findViewById(R.id.labeldatetime_2); date_minute.setAdapter(new DateTimeAdapter(0, 59)); date_minute.setCyclic(true); date_minute.setLabel(""); date_minute.setCurrentItem(minute); // second // 秒 date_second = (DateView) view.findViewById(R.id.labeldatetime_3); date_second.setAdapter(new DateTimeAdapter(0, 59)); date_second.setCyclic(true); date_second.setLabel(""); date_second.setCurrentItem(second); int textSize = (StaticObject.deviceHeight / 100) * 3; date_hour.TEXT_SIZE = textSize; date_minute.TEXT_SIZE = textSize; date_second.TEXT_SIZE = textSize; } /** * describe:Pop-up date and time selector * 弹出日期时间选择器 */ public void initDateTimePicker() { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); // Add the month and convert it to list, to facilitate the subsequent judgments // 添加大小月月份并将其转换为list,方便之后的判断 String[] months_big = { "1", "3", "5", "7", "8", "10", "12" }; String[] months_little = { "4", "6", "9", "11" }; final List<String> list_big = Arrays.asList(months_big); final List<String> list_little = Arrays.asList(months_little); // year // 年 date_years = (DateView) view.findViewById(R.id.labeldatetime_1); // Set the display data for "year" // 设置"年"的显示数据 date_years.setAdapter(new DateTimeAdapter(START_YEAR, END_YEAR)); // Can be scrolled // 可循环滚动 date_years.setCyclic(true); // Add text // 添加文字 date_years.setLabel(""); // The data displayed when initializing // 初始化时显示的数据 date_years.setCurrentItem(year - START_YEAR); // month // 月 date_months = (DateView) view.findViewById(R.id.labeldatetime_2); date_months.setAdapter(new DateTimeAdapter(1, 12)); date_months.setCyclic(true); date_months.setLabel(""); date_months.setCurrentItem(month); // day // 日 date_days = (DateView) view.findViewById(R.id.labeldatetime_3); date_days.setCyclic(true); // Determine the size of the month and whether the leap year, used to determine the data of the "day" // 判断大小月及是否闰年,用来确定"日"的数据 if (list_big.contains(String.valueOf(month + 1))) { date_days.setAdapter(new DateTimeAdapter(1, 31)); } else if (list_little.contains(String.valueOf(month + 1))) { date_days.setAdapter(new DateTimeAdapter(1, 30)); } else { // leap year // 闰年 if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) date_days.setAdapter(new DateTimeAdapter(1, 29)); else date_days.setAdapter(new DateTimeAdapter(1, 28)); } date_days.setLabel(""); date_days.setCurrentItem(day - 1); // Add listen to "year" // 添加"年"监听 OnDateChangedListener listener_year = new OnDateChangedListener() { public void onChanged(DateView view, int oldValue, int newValue) { int year_num = newValue + START_YEAR; // Determine the size of the month and whether the leap year, used to determine the data of the "day" // 判断大小月及是否闰年,用来确定"日"的数据 if (list_big.contains(String.valueOf(date_months.getCurrentItem() + 1))) { date_days.setAdapter(new DateTimeAdapter(1, 31)); } else if (list_little.contains(String.valueOf(date_months.getCurrentItem() + 1))) { date_days.setAdapter(new DateTimeAdapter(1, 30)); } else { if ((year_num % 4 == 0 && year_num % 100 != 0) || year_num % 400 == 0) date_days.setAdapter(new DateTimeAdapter(1, 29)); else date_days.setAdapter(new DateTimeAdapter(1, 28)); } } }; // Add listen to "month" // 添加"月"监听 OnDateChangedListener listener_month = new OnDateChangedListener() { public void onChanged(DateView view, int oldValue, int newValue) { int month_num = newValue + 1; // Determine the size of the month and whether the leap year, used to determine the data of the "day" // 判断大小月及是否闰年,用来确定"日"的数据 if (list_big.contains(String.valueOf(month_num))) { date_days.setAdapter(new DateTimeAdapter(1, 31)); } else if (list_little.contains(String.valueOf(month_num))) { date_days.setAdapter(new DateTimeAdapter(1, 30)); } else { if (((date_years.getCurrentItem() + START_YEAR) % 4 == 0 && (date_years .getCurrentItem() + START_YEAR) % 100 != 0) || (date_years.getCurrentItem() + START_YEAR) % 400 == 0) date_days.setAdapter(new DateTimeAdapter(1, 29)); else date_days.setAdapter(new DateTimeAdapter(1, 28)); } } }; date_years.addChangingListener(listener_year); date_months.addChangingListener(listener_month); // hour // 时 date_hours = (DateView) view.findViewById(R.id.labeldatetime_4); date_hours.setVisibility(View.VISIBLE); date_hours.setAdapter(new DateTimeAdapter(0, 23)); date_hours.setCyclic(true); date_hours.setLabel(""); date_hours.setCurrentItem(hour); // minute // 分 date_mins = (DateView) view.findViewById(R.id.labeldatetime_5); date_mins.setVisibility(View.VISIBLE); date_mins.setAdapter(new DateTimeAdapter(0, 59)); date_mins.setCyclic(true); date_mins.setLabel(""); date_mins.setCurrentItem(minute); int textSize = (StaticObject.deviceHeight / 100) * 3; date_years.TEXT_SIZE = textSize; date_months.TEXT_SIZE = textSize; date_days.TEXT_SIZE = textSize; date_hours.TEXT_SIZE = textSize; date_mins.TEXT_SIZE = textSize; } /** * 返回int类型包含年月日的数组 * @return * int类型包含年月日的数组 * */ public int[] getDate() { int[] date = new int[3]; date[0] = date_year.getCurrentItem() + START_YEAR; date[1] = date_month.getCurrentItem(); date[2] = date_day.getCurrentItem() + 1; return date; } /** * 返回int类型包含时分秒的数组 * @return * int类型包含时分秒的数组 * */ public int[] getTime() { int[] time = new int[3]; time[0] = date_hour.getCurrentItem(); time[1] = date_minute.getCurrentItem(); time[2] = date_second.getCurrentItem(); return time; } /** * 返回int类型包含年月日时分的数组 * @return * int类型包含年月日时分的数组 * */ public int[] getDateTime() { int[] datetime = new int[5]; datetime[0] = date_years.getCurrentItem() + START_YEAR; datetime[1] = date_months.getCurrentItem(); datetime[2] = date_days.getCurrentItem() + 1; datetime[3] = date_hours.getCurrentItem(); datetime[4] = date_mins.getCurrentItem(); return datetime; } public View getView() { return view; } }
29.098131
105
0.681147
60058e88fc44b624cbbb619c9d004dcb1ecbf4b3
1,799
package com.nathaniel.baseui.surface; import androidx.appcompat.app.AppCompatActivity; import java.util.Stack; /** * @author nathaniel * @version V1.0.0 * @contact <a href="mailto:nathanwriting@126.com">contact me</a> * @package com.nathaniel.baseui.surface * @datetime 2021/12/19 - 15:54 */ public class ActivitiesManager { private static ActivitiesManager activitiesManager; private Stack<AppCompatActivity> activityStack; private ActivitiesManager() { if (activityStack == null) { activityStack = new Stack<>(); } } public static ActivitiesManager getInstance() { if (activitiesManager == null) { activitiesManager = new ActivitiesManager(); } return activitiesManager; } public void addActivity(AppCompatActivity activity) { activityStack.add(activity); } public void removeActivity(AppCompatActivity activity) { activityStack.remove(activity); } public AppCompatActivity currentActivity() { if (activityStack.isEmpty()) { return null; } return activityStack.lastElement(); } public void finishActivity(AppCompatActivity activity) { if (activityStack.isEmpty()) { activity.finish(); } for (AppCompatActivity activityTmp : activityStack) { if (activityTmp.getClass().getSimpleName().equalsIgnoreCase(activity.getClass().getSimpleName())) { activityStack.remove(activity); } } } public void finishActivities() { if (activityStack.isEmpty()) { return; } for (AppCompatActivity activity : activityStack) { activity.finish(); } activityStack.clear(); } }
26.850746
111
0.628683
7e2707670c14db8776752dc6387f43973d034fcf
5,571
package com.kwitterbackend.user_service.controllers; import com.google.gson.Gson; import com.kwitterbackend.user_service.dto.RegisterDTO; import com.kwitterbackend.user_service.dto.UpdateUserEvent; import com.kwitterbackend.user_service.model.DeleteUserEvent; import com.kwitterbackend.user_service.model.User; import com.kwitterbackend.user_service.repositories.UserRepository; import com.kwitterbackend.user_service.services.UserService; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller public class UserController { @Autowired private AmqpTemplate rabbitTemplate; @Value("${kwitter.rabbitmq.exchange}") private String exchange; @Value("${kwitter.rabbitmq.routingkey}") private String routingkey; @Value("${kwitter.rabbitmq.routingkeydelete}") private String routingkeyDelete; private final UserService userService; private final UserRepository userRepository; public UserController(UserService userService, UserRepository userRepository) { this.userService = userService; this.userRepository = userRepository; } @PreAuthorize("isAuthenticated()") @RequestMapping(value = RestURIConstant.deleteUser, method = RequestMethod.DELETE) public @ResponseBody String delete() { final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String username = (String) auth.getPrincipal(); System.out.println(username); DeleteUserEvent deleteUserEvent = new DeleteUserEvent(); deleteUserEvent.setUsername(username); rabbitTemplate.convertAndSend(exchange, routingkeyDelete, deleteUserEvent); System.out.println("Sent event:" + deleteUserEvent); return userService.deleteUser(username); } @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = RestURIConstant.deleteAsAdmin, method = RequestMethod.DELETE) public @ResponseBody String deleteAsAdmin(@RequestParam("username") String username) { DeleteUserEvent deleteUserEvent = new DeleteUserEvent(); deleteUserEvent.setUsername(username); rabbitTemplate.convertAndSend(exchange, routingkeyDelete, deleteUserEvent); System.out.println("Sent event:" + deleteUserEvent); return userService.deleteAsAdmin(username); } @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = RestURIConstant.allUsers, method = RequestMethod.GET) public @ResponseBody Iterable<User> allUsers() { return userService.allusers(); } @RequestMapping(value = RestURIConstant.test, method = RequestMethod.GET) public String test() { return "Test"; } @RequestMapping(value = RestURIConstant.getUser, method = RequestMethod.GET) public @ResponseBody User getUserByUsername(@RequestParam("username") String username) { return userService.getByUsername(username); } @PostMapping(value = RestURIConstant.register) public @ResponseBody String userRegister(@RequestBody String user) { try { Gson gson = new Gson(); var userObject = gson.fromJson(user, RegisterDTO.class); return gson.toJson(userService.registerUser(userObject)); } catch (Exception e) { return ("Failed to register"); } } @PreAuthorize("isAuthenticated()") @RequestMapping(value = RestURIConstant.currentUser, method = RequestMethod.GET) public @ResponseBody User current() { final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); final String username = (String) auth.getPrincipal(); return userRepository.findByUsername(username); } @PreAuthorize("isAuthenticated()") @RequestMapping(value = RestURIConstant.updateUsername, method = RequestMethod.PUT) public @ResponseBody String updateUsername(@RequestParam("username") String username){ System.out.println("currently logged in user is " + current().getUsername()); UpdateUserEvent updateUserEvent = new UpdateUserEvent(); updateUserEvent.setOldUsername(current().getUsername()); updateUserEvent.setNewUsername(username); rabbitTemplate.convertAndSend(exchange, routingkey, updateUserEvent); System.out.println("Sent event:" + updateUserEvent); return userService.changeUsername(current(), username); } @PreAuthorize("isAuthenticated()") @RequestMapping(value = RestURIConstant.changePassword, method = RequestMethod.POST) public @ResponseBody String changePassword(@RequestParam("oldPass") String oldPassword, @RequestParam("newPass") String newPassword) throws Exception { if(!userService.checkIfValidOldPassword(current(), oldPassword)){ return "Old password does not match the system"; } return userService.changePassword(current(), newPassword); } @RequestMapping(value = RestURIConstant.resetPassword, method = RequestMethod.POST) public @ResponseBody String resetPassword(@RequestParam("email") String email){ return null; } }
41.266667
134
0.736852
cc73c2894eef08227cdd13e695b86a248bb8df6f
12,979
package ui.dialog; import core.Configuration; import javafx.beans.property.*; import javafx.geometry.Insets; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.*; import ui.EmbeddedIcons; import ui.custom.fx.ColorPreview; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class PreferencesDialogFx extends Dialog<ButtonType> { private final class TitleLabel extends Label { public TitleLabel(String text) { super(text); this.setFont(Font.font(getFont().getFamily(), FontWeight.BOLD, 16.0)); this.setPadding(new Insets(4.0, 0.0, 0.0, 0.0)); } } private final SimpleStringProperty pathWireshark; private final SimpleStringProperty pathTextEditor; private final SimpleStringProperty pathPdfViewer; private final SimpleObjectProperty<Color> colorNewNode; private final SimpleObjectProperty<Color> colorModifiedNode; private final SimpleObjectProperty<Color> colorNodeText; private final SimpleObjectProperty<Color> colorNodeBackground; private final SimpleObjectProperty<Color> colorNodeHighlight; private final SimpleBooleanProperty networksCreateOnDemand; private final SimpleObjectProperty<Integer> networksSubnetSize; private final ButtonType saveButton; private final ColorPickerDialogFx colorPicker; private final FileChooser chooser; public PreferencesDialogFx() { pathWireshark = new SimpleStringProperty(); pathTextEditor = new SimpleStringProperty(); pathPdfViewer = new SimpleStringProperty(); colorNewNode = new SimpleObjectProperty<>(); colorModifiedNode = new SimpleObjectProperty<>(); colorNodeText = new SimpleObjectProperty<>(); colorNodeBackground = new SimpleObjectProperty<>(); colorNodeHighlight = new SimpleObjectProperty<>(); networksCreateOnDemand = new SimpleBooleanProperty(); networksSubnetSize = new SimpleObjectProperty<>(24); //We can't let this be null when bound to the spinner. saveButton = new ButtonType("Save", ButtonBar.ButtonData.OK_DONE); colorPicker = new ColorPickerDialogFx(); chooser = new FileChooser(); initComponents(); reloadValues(); } protected void browseForFile(StringProperty property) { browseForFile(property, null); } protected void browseForFile(StringProperty property, String prompt) { if(prompt == null) { chooser.setTitle("Open"); } else { chooser.setTitle(prompt); } File f = chooser.showOpenDialog(this.getOwner()); if (f != null && !f.getAbsolutePath().isEmpty()) { property.set(f.getAbsolutePath()); } } private void initComponents() { final Window stage = super.getDialogPane().getScene().getWindow(); if(stage instanceof Stage) { ((Stage)stage).getIcons().add(EmbeddedIcons.Vista_Personalization.getRawImage()); } this.setTitle("Preferences"); this.initModality(Modality.APPLICATION_MODAL); this.initStyle(StageStyle.UTILITY); final GridPane layout = new GridPane(); int idxRow = -1; layout.add(new TitleLabel("External Applications"), 0, ++idxRow, 3, 1); layout.add(new Label("Wireshark"), 0, ++idxRow); final TextField tbWireshark = new TextField(); tbWireshark.textProperty().bindBidirectional(pathWireshark); layout.add(tbWireshark, 1, idxRow); final Button btnWireshark = new Button("Browse..."); btnWireshark.setOnAction(event -> browseForFile(pathWireshark)); layout.add(btnWireshark, 2, idxRow); layout.add(new Label("Text Viewer"), 0, ++idxRow); final TextField tbTextViewer = new TextField(); tbTextViewer.textProperty().bindBidirectional(pathTextEditor); layout.add(tbTextViewer, 1, idxRow); final Button btnTextViewer = new Button("Browse..."); btnTextViewer.setOnAction(event -> browseForFile(pathTextEditor)); layout.add(btnTextViewer, 2, idxRow); layout.add(new Label("PDF Viewer"), 0, ++idxRow); final TextField tbPdfViewer = new TextField(); tbPdfViewer.textProperty().bindBidirectional(pathPdfViewer); layout.add(tbPdfViewer, 1, idxRow); final Button btnPdfViewer = new Button("Browse..."); btnPdfViewer.setOnAction(event -> browseForFile(pathPdfViewer)); layout.add(btnPdfViewer, 2, idxRow); layout.add(new TitleLabel("Visualization"), 0, ++idxRow, 3, 1); layout.add(new Label("New Node Highlight"), 0, ++idxRow); final ColorPreview previewNewNode = new ColorPreview(colorNewNode); previewNewNode.setOnMouseClicked(event -> { colorPicker.setColor(colorNewNode.get()); final Optional<ButtonType> result = colorPicker.showAndWait(); if (result.isPresent() && result.get().equals(ButtonType.OK)) { colorNewNode.set(colorPicker.getSelectedColor()); } }); layout.add(previewNewNode, 2, idxRow); layout.add(new Label("Modified Node Highlight"), 0, ++idxRow); final ColorPreview previewModifiedNode = new ColorPreview(colorModifiedNode); previewModifiedNode.setOnMouseClicked(event -> { colorPicker.setColor(colorModifiedNode.get()); final Optional<ButtonType> result = colorPicker.showAndWait(); if (result.isPresent() && result.get().equals(ButtonType.OK)) { colorModifiedNode.set(colorPicker.getSelectedColor()); } }); layout.add(previewModifiedNode, 2, idxRow); layout.add(new Label("Node Text"), 0, ++idxRow); final ColorPreview previewNodeText = new ColorPreview(colorNodeText); previewNodeText.setOnMouseClicked(event -> { colorPicker.setColor(colorNodeText.get()); final Optional<ButtonType> result = colorPicker.showAndWait(); if (result.isPresent() && result.get().equals(ButtonType.OK)) { colorNodeText.set(colorPicker.getSelectedColor()); } }); layout.add(previewNodeText, 2, idxRow); layout.add(new Label("Node Background"), 0, ++idxRow); final ColorPreview previewNodeBkg = new ColorPreview(colorNodeBackground); previewNodeBkg.setOnMouseClicked(event -> { colorPicker.setColor(colorNodeBackground.get()); final Optional<ButtonType> result = colorPicker.showAndWait(); if (result.isPresent() && result.get().equals(ButtonType.OK)) { colorNodeBackground.set(colorPicker.getSelectedColor()); } }); layout.add(previewNodeBkg, 2, idxRow); layout.add(new Label("Node Background (Selected)"), 0, ++idxRow); final ColorPreview previewNodeBkgSelected = new ColorPreview(colorNodeHighlight); previewNodeBkgSelected.setOnMouseClicked(event -> { colorPicker.setColor(colorNodeHighlight.get()); final Optional<ButtonType> result = colorPicker.showAndWait(); if (result.isPresent() && result.get().equals(ButtonType.OK)) { colorNodeHighlight.set(colorPicker.getSelectedColor()); } }); layout.add(previewNodeBkgSelected, 2, idxRow); layout.add(new TitleLabel("Logical Networks"), 0, ++idxRow, 3, 1); layout.add(new Label("Create CIDRs automatically"), 0, ++idxRow); final CheckBox ckCreateCidrs = new CheckBox(); ckCreateCidrs.selectedProperty().bindBidirectional(networksCreateOnDemand); layout.add(ckCreateCidrs, 2, idxRow); layout.add(new Label("Created CIDR size"), 0, ++idxRow); final Spinner<Integer> spCidrSize = new Spinner<>(); spCidrSize.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 32)); spCidrSize.getValueFactory().valueProperty().bindBidirectional(networksSubnetSize); layout.add(spCidrSize, 2, idxRow); this.getDialogPane().setContent(layout); this.getDialogPane().getButtonTypes().addAll(ButtonType.CANCEL, saveButton); } public void reloadValues() { String ws = Configuration.getPreferenceString(Configuration.Fields.WIRESHARK_EXEC); String te = Configuration.getPreferenceString(Configuration.Fields.TEXT_EDITOR_EXEC); String pdf = Configuration.getPreferenceString(Configuration.Fields.PDF_VIEWER_EXEC); pathWireshark.set(ws == null ? "" : ws); pathTextEditor.set(te == null ? "" : te); pathPdfViewer.set(pdf == null ? "" : pdf); colorNewNode.set(Color.web(Configuration.getPreferenceString(Configuration.Fields.COLOR_NODE_NEW))); colorModifiedNode.set(Color.web(Configuration.getPreferenceString(Configuration.Fields.COLOR_NODE_MODIFIED))); colorNodeText.set(Color.web(Configuration.getPreferenceString(Configuration.Fields.COLOR_NODE_TEXT))); colorNodeBackground.set(Color.web(Configuration.getPreferenceString(Configuration.Fields.COLOR_NODE_BACKGROUND))); colorNodeHighlight.set(Color.web(Configuration.getPreferenceString(Configuration.Fields.COLOR_NODE_HIGHLIGHT))); networksCreateOnDemand.set(Configuration.getPreferenceBoolean(Configuration.Fields.LOGICAL_CREATE_DYNAMIC_SUBNETS)); networksSubnetSize.set((int) Configuration.getPreferenceLong(Configuration.Fields.LOGICAL_DYNAMIC_SUBNET_BITS)); //TODO: Disable save and only enable if anything has changed. //this.getDialogPane().lookupButton(saveButton).setDisable(true); } public Map<Configuration.Fields, String> getUpdatedValues() { HashMap<Configuration.Fields, String> updatedValues = new HashMap<>(); if(Configuration.getPreferenceString(Configuration.Fields.WIRESHARK_EXEC) == null || !pathWireshark.get().equals(Configuration.getPreferenceString(Configuration.Fields.WIRESHARK_EXEC))) { updatedValues.put(Configuration.Fields.WIRESHARK_EXEC, pathWireshark.get().equals("") ? null : pathWireshark.get()); } if(Configuration.getPreferenceString(Configuration.Fields.TEXT_EDITOR_EXEC) == null|| !pathTextEditor.get().equals(Configuration.getPreferenceString(Configuration.Fields.TEXT_EDITOR_EXEC))) { updatedValues.put(Configuration.Fields.TEXT_EDITOR_EXEC, pathTextEditor.get().equals("") ? null : pathTextEditor.get()); } if(Configuration.getPreferenceString(Configuration.Fields.PDF_VIEWER_EXEC) == null || !pathPdfViewer.get().equals(Configuration.getPreferenceString(Configuration.Fields.PDF_VIEWER_EXEC))) { updatedValues.put(Configuration.Fields.PDF_VIEWER_EXEC, pathPdfViewer.get().equals("") ? null : pathWireshark.get()); } // Colors give AARRGGBB, we want only RGB if(!colorNewNode.get().equals(Color.web(Configuration.getPreferenceString(Configuration.Fields.COLOR_NODE_NEW)))) { updatedValues.put(Configuration.Fields.COLOR_NODE_NEW, colorNewNode.get().toString().substring(2, 8)); } if(!colorModifiedNode.get().equals(Color.web(Configuration.getPreferenceString(Configuration.Fields.COLOR_NODE_MODIFIED)))) { updatedValues.put(Configuration.Fields.COLOR_NODE_MODIFIED, colorModifiedNode.get().toString().substring(2, 8)); } if(!colorNodeText.get().equals(Color.web(Configuration.getPreferenceString(Configuration.Fields.COLOR_NODE_TEXT)))) { updatedValues.put(Configuration.Fields.COLOR_NODE_TEXT, colorNodeText.get().toString().substring(2, 8)); } if(!colorNodeBackground.get().equals(Color.web(Configuration.getPreferenceString(Configuration.Fields.COLOR_NODE_BACKGROUND)))) { updatedValues.put(Configuration.Fields.COLOR_NODE_BACKGROUND, colorNodeBackground.get().toString().substring(2, 8)); } if(!colorNodeHighlight.get().equals(Color.web(Configuration.getPreferenceString(Configuration.Fields.COLOR_NODE_HIGHLIGHT)))) { updatedValues.put(Configuration.Fields.COLOR_NODE_HIGHLIGHT, colorNodeHighlight.get().toString().substring(2, 8)); } if(networksCreateOnDemand.get() != Configuration.getPreferenceBoolean(Configuration.Fields.LOGICAL_CREATE_DYNAMIC_SUBNETS)) { updatedValues.put(Configuration.Fields.LOGICAL_CREATE_DYNAMIC_SUBNETS, Boolean.toString(networksCreateOnDemand.get())); } if(networksSubnetSize.get() != Configuration.getPreferenceLong(Configuration.Fields.LOGICAL_DYNAMIC_SUBNET_BITS)) { updatedValues.put(Configuration.Fields.LOGICAL_DYNAMIC_SUBNET_BITS, Long.toString(networksSubnetSize.get())); } return updatedValues; } }
49.919231
199
0.69782
fe52497ca635492d25f1af09465e4be886d7a324
742
package com.barrycommins.simplerest.controller; import com.barrycommins.simplerest.service.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController("/hello") public class HelloController { private final HelloService helloService; @Autowired public HelloController(HelloService helloService) { this.helloService = helloService; } @RequestMapping public String getGreeting(@RequestParam(name="name") String name) { return helloService.greeting() + ", " + name; } }
27.481481
71
0.768194
7888d20603cdc922d4578b01caf14c03e6e138e1
374
package aero.t2s.modes.constants; public enum TargetAltitudeType { FL, MSL, ; public static TargetAltitudeType from(int code) { switch (code) { case 0: return FL; case 1: return MSL; default: throw new IllegalArgumentException("Target Altitude Type " + code + " is not valid"); } } }
22
101
0.561497
90dd8ef235dfd125f87c48bcdf72a9b40a15fa1c
4,746
/* * Copyright 2012-2021 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements WHICH ARE COMPATIBLE WITH THE APACHE LICENSE, VERSION 2.0. * * 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.aerospike.examples; import java.util.concurrent.atomic.AtomicInteger; import com.aerospike.client.AerospikeClient; import com.aerospike.client.AerospikeException; import com.aerospike.client.Bin; import com.aerospike.client.Key; import com.aerospike.client.Record; import com.aerospike.client.ResultCode; import com.aerospike.client.async.EventLoop; import com.aerospike.client.command.Buffer; import com.aerospike.client.listener.RecordSequenceListener; import com.aerospike.client.listener.WriteListener; import com.aerospike.client.policy.Policy; import com.aerospike.client.query.Filter; import com.aerospike.client.query.IndexType; import com.aerospike.client.query.Statement; import com.aerospike.client.task.IndexTask; import com.aerospike.client.util.Util; public class AsyncQuery extends AsyncExample { /** * Asynchronous query example. */ @Override public void runExample(AerospikeClient client, EventLoop eventLoop) { String indexName = "asqindex"; String keyPrefix = "asqkey"; String binName = params.getBinName("asqbin"); int size = 50; createIndex(client, indexName, binName); runQueryExample(client, eventLoop, keyPrefix, binName, size); // Wait until query finishes before dropping index. waitTillComplete(); client.dropIndex(policy, params.namespace, params.set, indexName); } private void createIndex( AerospikeClient client, String indexName, String binName ) { console.info("Create index: ns=%s set=%s index=%s bin=%s", params.namespace, params.set, indexName, binName); Policy policy = new Policy(); policy.socketTimeout = 0; // Do not timeout on index create. try { IndexTask task = client.createIndex(policy, params.namespace, params.set, indexName, binName, IndexType.NUMERIC); task.waitTillComplete(); } catch (AerospikeException ae) { if (ae.getResultCode() != ResultCode.INDEX_ALREADY_EXISTS) { throw ae; } } } private void runQueryExample( final AerospikeClient client, final EventLoop eventLoop, final String keyPrefix, final String binName, final int size ) { console.info("Write " + size + " records."); WriteListener listener = new WriteListener() { private int count = 0; public void onSuccess(final Key key) { // Use non-atomic increment because all writes are performed // in the same event loop thread. if (++count == size) { runQuery(client, eventLoop, binName); } } public void onFailure(AerospikeException e) { console.error("Failed to put: " + e.getMessage()); notifyComplete(); } }; for (int i = 1; i <= size; i++) { Key key = new Key(params.namespace, params.set, keyPrefix + i); Bin bin = new Bin(binName, i); client.put(eventLoop, listener, writePolicy, key, bin); } } private void runQuery(AerospikeClient client, EventLoop eventLoop, final String binName) { int begin = 26; int end = 34; console.info("Query for: ns=%s set=%s bin=%s >= %s <= %s", params.namespace, params.set, binName, begin, end); Statement stmt = new Statement(); stmt.setNamespace(params.namespace); stmt.setSetName(params.set); stmt.setBinNames(binName); stmt.setFilter(Filter.range(binName, begin, end)); final AtomicInteger count = new AtomicInteger(); client.query(eventLoop, new RecordSequenceListener() { public void onRecord(Key key, Record record) throws AerospikeException { int result = record.getInt(binName); console.info("Record found: ns=%s set=%s bin=%s digest=%s value=%s", key.namespace, key.setName, binName, Buffer.bytesToHexString(key.digest), result); count.incrementAndGet(); } public void onSuccess() { int size = count.get(); if (size != 9) { console.error("Query count mismatch. Expected 9. Received " + size); } notifyComplete(); } public void onFailure(AerospikeException e) { console.error("Query failed: " + Util.getErrorMessage(e)); notifyComplete(); } }, null, stmt); } }
30.619355
116
0.722082
720c88d60233ad398f8533454449498ceeec70a2
1,942
/* * Copyright 2000-2012 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. */ package com.intellij.openapi.module.impl; import com.intellij.psi.search.GlobalSearchScope; /** * Author: dmitrylomov */ public interface ModuleScopeProvider { /** * Returns module scope including sources and tests, excluding libraries and dependencies. * * @return scope including sources and tests, excluding libraries and dependencies. */ GlobalSearchScope getModuleScope(); GlobalSearchScope getModuleScope(boolean includeTests); /** * Returns module scope including sources, tests, and libraries, excluding dependencies. * * @return scope including sources, tests, and libraries, excluding dependencies. */ GlobalSearchScope getModuleWithLibrariesScope(); /** * Returns module scope including sources, tests, and dependencies, excluding libraries. * * @return scope including sources, tests, and dependencies, excluding libraries. */ GlobalSearchScope getModuleWithDependenciesScope(); GlobalSearchScope getModuleContentScope(); GlobalSearchScope getModuleContentWithDependenciesScope(); GlobalSearchScope getModuleWithDependenciesAndLibrariesScope(boolean includeTests); GlobalSearchScope getModuleWithDependentsScope(); GlobalSearchScope getModuleTestsWithDependentsScope(); GlobalSearchScope getModuleRuntimeScope(boolean includeTests); void clearCache(); }
33.482759
92
0.771885
d6503e9cccbcf486b100199c483df484debeaaae
7,070
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|master package|; end_package begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertFalse import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertNull import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseClassTestRule import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseTestingUtility import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|regionserver operator|. name|ChunkCreator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|MasterTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|MediumTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|FSUtils import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|AfterClass import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|BeforeClass import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|ClassRule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|experimental operator|. name|categories operator|. name|Category import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_class annotation|@ name|Category argument_list|( block|{ name|MasterTests operator|. name|class block|, name|MediumTests operator|. name|class block|} argument_list|) specifier|public class|class name|TestMasterNotCarryTable block|{ annotation|@ name|ClassRule specifier|public specifier|static specifier|final name|HBaseClassTestRule name|CLASS_RULE init|= name|HBaseClassTestRule operator|. name|forClass argument_list|( name|TestMasterNotCarryTable operator|. name|class argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|TestMasterNotCarryTable operator|. name|class argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|HBaseTestingUtility name|UTIL init|= operator|new name|HBaseTestingUtility argument_list|() decl_stmt|; specifier|private specifier|static name|HMaster name|master decl_stmt|; annotation|@ name|BeforeClass specifier|public specifier|static name|void name|setUp parameter_list|() throws|throws name|Exception block|{ name|Configuration name|c init|= name|UTIL operator|. name|getConfiguration argument_list|() decl_stmt|; comment|// We use local filesystem. Set it so it writes into the testdir. name|FSUtils operator|. name|setRootDir argument_list|( name|c argument_list|, name|UTIL operator|. name|getDataTestDir argument_list|() argument_list|) expr_stmt|; name|UTIL operator|. name|startMiniZKCluster argument_list|() expr_stmt|; name|master operator|= operator|new name|HMaster argument_list|( name|UTIL operator|. name|getConfiguration argument_list|() argument_list|) expr_stmt|; name|master operator|. name|start argument_list|() expr_stmt|; comment|// As no regionservers, only wait master to create AssignmentManager. while|while condition|( name|master operator|. name|getAssignmentManager argument_list|() operator|!= literal|null condition|) block|{ name|LOG operator|. name|debug argument_list|( literal|"Wait master to create AssignmentManager" argument_list|) expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; block|} block|} annotation|@ name|AfterClass specifier|public specifier|static name|void name|tearDown parameter_list|() throws|throws name|Exception block|{ name|master operator|. name|stop argument_list|( literal|"Shutdown" argument_list|) expr_stmt|; name|UTIL operator|. name|shutdownMiniZKCluster argument_list|() expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testMasterNotCarryTable parameter_list|() block|{ comment|// The default config is false name|assertFalse argument_list|( name|LoadBalancer operator|. name|isTablesOnMaster argument_list|( name|UTIL operator|. name|getConfiguration argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertFalse argument_list|( name|LoadBalancer operator|. name|isSystemTablesOnlyOnMaster argument_list|( name|UTIL operator|. name|getConfiguration argument_list|() argument_list|) argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testMasterBlockCache parameter_list|() block|{ comment|// no need to instantiate block cache. name|assertFalse argument_list|( name|master operator|. name|getBlockCache argument_list|() operator|. name|isPresent argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testMasterMOBFileCache parameter_list|() block|{ comment|// no need to instantiate mob file cache. name|assertFalse argument_list|( name|master operator|. name|getMobFileCache argument_list|() operator|. name|isPresent argument_list|() argument_list|) expr_stmt|; block|} block|} end_class end_unit
15.010616
814
0.805799
d056c38912b7252ab30c50ab6e07440ccf6a0073
1,710
package act.fsa.binding; import act.data.Data; import org.osgl.$; import org.osgl.util.S; @Data public class Person { public static final String TABLE_VIEW = "id,fullName,address.asString as address"; private String id; private String firstName; private String lastName; private Address address; protected Person() {} public Person(String id, String firstName, String lastName, Address address) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.address = address; } public String getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getFullName() { return S.builder(firstName).append(" ").append(lastName).toString(); } public Address getAddress() { return address; } public void setId(String id) { this.id = id; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setAddress(Address address) { this.address = address; } @Override public String toString() { return S.fmt("%s %s", firstName, lastName); } public static Person random(String id) { String firstName = $.random("Tom", "Peter", "Joe", "Kate", "Leonard", "Alex", "Owen"); String lastName = $.random("Cincotta", "Luo", "Wall", "Berry", "Chris", "Lagan"); Address address = Address.random(); return new Person(id, firstName, lastName, address); } }
22.8
94
0.612281
cd46090cb92237dc5f900a23145558c6e4b560cb
2,896
package dynamicprogramming; import java.util.Arrays; public class MinimumCandies { // Complete the candies function below. private static long candies(int n, int[] arr) { // Sort according to their rating. int numberOfCandies = 1; // for the first one. int result = 1; for (int i=1; i < arr.length; i++) { if(arr[i] > arr[i -1]) { numberOfCandies ++; } else { numberOfCandies --; } if (arr[i] == arr[i - 1]) { if (numberOfCandies > 1) { numberOfCandies -- ; } else { numberOfCandies ++; } } result = result + numberOfCandies; } return result; } /** * We can divide the children in below categories. * if rating[i-1] >= rating[i] <= rating[i+1] , we say Child is a valley. * If rating[i-1] < rating[i] <= rating[i+1], we say Child is a rise. * If rating[i-1] >= rating[i] >= rating[i+1], we say Child is a fall. * If rating[i-1] < rating[i] > </>rating[i+1], we say Child is a peak. * Based on the above categorization we can distribute the candies as below: * * For each valley child, give him/her 1 candy. * For each rise child, give him/her C[i-1] +1 candies. * For each fall child, give him/her C[i+1] +1 candies. * For each peak child, give him/her Max(C[i-1], C[i+1]) candies. * * 1. Distribute the candies to the valleys. * 2. Distribute the candies to the rises from left to right. * 3. Distribute the candies to the falls from right to left. * 4. Distribute the candies to the peaks. * Note that the order in which we distribute candies to rises and falls is pretty important! * * @param n * @param rating * @return */ public static long candies1(int n, int[] rating) { int[] dp = new int[rating.length]; // Distribute the 1 candies to the valley children. Arrays.fill(dp, 1); for (int i=1; i< rating.length; i++) { if (rating[i] > rating[i-1]) { // Distribute the candies to the rising children dp[i] = dp[i-1] +1; } } for (int i = rating.length-2; i >= 0; i-- ) { if (rating[i] > rating[i +1]) { // Distribute the candies to the rising falling children dp[i] = Math.max(dp[i] +1, dp[i+1]); } } // find the sum of the array. long sum = 0; for (int i : dp) { sum = sum + i; } return sum; } public static void main(String[] args) { int[] inputArray = new int[]{2, 4, 2, 6, 1, 7, 8, 9, 2, 1}; System.out.println(candies1(10, inputArray)); } }
34.47619
97
0.515884
3990f464b2108e0a976f46cd2730db9e6de2d169
1,234
package ol.style; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import ol.Options; /** * Options for the circle style. * * @author Tino Desjardins * */ @JsType(isNative = true) public interface CircleOptions extends Options { /** * Fill style. * * @param fill {@link Fill} */ @JsProperty void setFill(Fill fill); /** * Circle radius. Required. * * @param radius radius */ @JsProperty void setRadius(double radius); /** * If true integral numbers of pixels are used as the X and Y pixel * coordinate when drawing the circle in the output canvas. If false * fractional numbers may be used. Using true allows for "sharp" rendering * (no blur), while using false allows for "accurate" rendering. Note that * accuracy is important if the circle's position is animated. Without it, * the circle may jitter noticeably. Default value is true. * * @param snapToPixel snap to pixels? */ @JsProperty void setSnapToPixel(boolean snapToPixel); /** * Stroke style. * * @param stroke {@link Stroke} */ @JsProperty void setStroke(Stroke stroke); }
22.436364
78
0.641005
ad0e28254bf1b98fa3d2448644bfbaa2f26a2f1b
10,059
package crypto; import java.util.Random; import static crypto.Helper.*; public class Encrypt { public static final int CAESAR = 0; public static final int VIGENERE = 1; public static final int XOR = 2; public static final int ONETIME = 3; public static final int CBC = 4; public static final byte SPACE = 32; final static Random rand = new Random(); //-----------------------General------------------------- /** * General method to encode a message using a key, you can choose the method you want to use to encode. * @param message the message to encode already cleaned * @param key the key used to encode * @param type the method used to encode : 0 = Caesar, 1 = Vigenere, 2 = XOR, 3 = One time pad, 4 = CBC * * @return an encoded String * if the method is called with an unknown type of algorithm, it returns the original message */ public static String encrypt(String message, String key, int type) { byte[] inputKeyTable = stringToBytes(key); // /!\ Tableau des clés (input utilisateur) byte[] plainText = stringToBytes(cleanString(message)); String encodedStrings; switch(type){ case CAESAR: byte ceasarKey = inputKeyTable[0]; //La clé du chiffrement césar ne contient qu'un seul caractère encodedStrings = bytesToString(caesar(plainText, ceasarKey, false)); return encodedStrings; case VIGENERE: encodedStrings = bytesToString(vigenere(plainText, stringToBytes(key))); return encodedStrings; case XOR: byte xorKey = inputKeyTable[0]; //La clé du chiffrement xor ne contient qu'un seul caractère encodedStrings = bytesToString(xor(plainText, xorKey)); return encodedStrings; case ONETIME: try { encodedStrings = bytesToString(oneTimePad(plainText, stringToBytes(key))); return encodedStrings; } catch (NullPointerException e) { return ""; } //TODO : Complete the function case CBC: byte[] bytePAD = stringToBytes(key); byte[] encodedBytes = cbc(plainText , bytePAD); return bytesToString(encodedBytes); default: return null; } } //-----------------------Caesar------------------------- /** * Method to encode a byte array message using a single character key * the key is simply added to each byte of the original message * @param plainText The byte array representing the string to encode * @param key the byte corresponding to the char we use to shift * @param spaceEncoding if false, then spaces are not encoded * @return an encoded byte array */ public static byte[] caesar(byte[] plainText, byte key, boolean spaceEncoding) { assert(plainText != null); byte[] encodedText = new byte[plainText.length]; for(int byteIndex = 0; byteIndex < plainText.length; ++byteIndex) { if(!spaceEncoding) // Si on choisit de ne pas encoder les espaces { if(plainText[byteIndex] == SPACE) // Si charactère associé au byte est un espace { encodedText[byteIndex] = plainText[byteIndex]; // Aucun décalage } else { encodedText[byteIndex] = (byte) (plainText[byteIndex] + key); } } else { encodedText[byteIndex] = (byte) (plainText[byteIndex] + key); } } return encodedText; } /** * Method to encode a byte array message using a single character key * the key is simply added to each byte of the original message * spaces are not encoded * @param plainText The byte array representing the string to encode * @param key the byte corresponding to the char we use to shift * @return an encoded byte array */ public static byte[] caesar(byte[] plainText, byte key) { byte[] encodedText = new byte[plainText.length]; for (int byteIndex = 0; byteIndex < plainText.length; ++byteIndex) { if (plainText[byteIndex] == 20) // Si charactère associé au byte est un espace { encodedText[byteIndex] = plainText[byteIndex]; // Aucun décalage } else { encodedText[byteIndex] = (byte) (plainText[byteIndex] + key); } } return encodedText; } //-----------------------XOR------------------------- /** * Method to encode a byte array using a XOR with a single byte long key * @param plainText the byte array representing the string to encode * @param key the byte we will use to XOR * @param spaceEncoding if false, then spaces are not encoded * @return an encoded byte array */ public static byte[] xor(byte[] plainText, byte key, boolean spaceEncoding) { byte[] encodedBytes = new byte[plainText.length]; if(spaceEncoding){ for (int i = 0; i< encodedBytes.length; i++) { encodedBytes[i] = (byte)(plainText[i] ^ key); } } else { for (int i = 0; i< encodedBytes.length; i++) { if(plainText[i] != SPACE){ encodedBytes[i] = (byte)(plainText[i] ^ key); } else { encodedBytes[i] = plainText[i]; } } } return encodedBytes; } /** * Method to encode a byte array using a XOR with a single byte long key * spaces are not encoded * @param key the byte we will use to XOR * @return an encoded byte array */ public static byte[] xor(byte[] plainText, byte key) { return xor(plainText, key, false); } //-----------------------Vigenere------------------------- /** * Method to encode a byte array using a byte array keyword * The keyword is repeated along the message to encode * The bytes of the keyword are added to those of the message to encode * @param plainText the byte array representing the message to encode * @param keyword the byte array representing the key used to perform the shift * @param spaceEncoding if false, then spaces are not encoded * @return an encoded byte array */ public static byte[] vigenere(byte[] plainText, byte[] keyword, boolean spaceEncoding) { byte[] encodedBytes = new byte[plainText.length]; int spaceShift = 0; for(int i = 0; i< plainText.length; i++){ if(spaceEncoding){ encodedBytes[i] = (byte) (plainText[i] + keyword[i % keyword.length]); } else { if(plainText[i] != SPACE){ encodedBytes[i] = (byte) ((plainText[i] + keyword[(i - spaceShift)% keyword.length]));//+ (spaceShift * (keyword.length-1))) % keyword.length])); } else { encodedBytes[i] = plainText[i]; ++spaceShift; } } } return encodedBytes; } /** * Method to encode a byte array using a byte array keyword * The keyword is repeated along the message to encode * spaces are not encoded * The bytes of the keyword are added to those of the message to encode * @param plainText the byte array representing the message to encode * @param keyword the byte array representing the key used to perform the shift * @return an encoded byte array */ public static byte[] vigenere(byte[] plainText, byte[] keyword) { return vigenere(plainText, keyword, false); } //-----------------------One Time Pad------------------------- /** * Method to encode a byte array using a one time pad of the same length. * The method XOR them together. * @param plainText the byte array representing the string to encode * @param pad the one time pad * @return an encoded byte array */ public static byte[] oneTimePad(byte[] plainText, byte[] pad) { try{ byte[] encodedBytes = new byte[plainText.length]; for(int i = 0; i< plainText.length; i++){ encodedBytes[i] = (byte)(plainText[i]^pad[i]); } return encodedBytes; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("The length of the Pad does not correspond."); return null; } } //-----------------------Basic CBC------------------------- /** * Method applying a basic chain block counter of XOR without encryption method. Encodes spaces. * @param plainText the byte array representing the string to encode * @param iv the pad of size BLOCKSIZE we use to start the chain encoding * @return an encoded byte array */ public static byte[] cbc(byte[] plainText, byte[] iv) { byte[] encodedBytes = new byte[plainText.length]; int alreadyEncodedBytes = 0; boolean encodedBytesListFullyCompleted = false; int blockDone = 0; byte [][] allBlocks = new byte[plainText.length][plainText.length]; //Taille maximale byte[] ivUtilisation = new byte[iv.length]; for(int z = 0; z < iv.length; ++z ) { ivUtilisation[z] = iv[z]; } while(!encodedBytesListFullyCompleted) { // Encodage jusqu'au T ème byte. T étant la taille du pad for (int padIndex = 0, encodedBytesNumber1 = alreadyEncodedBytes; padIndex < iv.length; ++padIndex, ++encodedBytesNumber1) { if (encodedBytesNumber1 < plainText.length) //Eviter le Out Of Bound { allBlocks[blockDone][padIndex] = (byte) (plainText[encodedBytesNumber1] ^ ivUtilisation[padIndex]); // On génère la T ème partie encodée } } // On transforme maintenant les bytes encodés précédemment en nouveau PAD qui sera utilisé par la suite for (int m = 0; m < iv.length; ++m) { ivUtilisation[m] = allBlocks[blockDone][m]; } //On transfert les caractères de AllBlocks dans le tableu unidimensionel des caractères encodés (encodedBytes) for (int j = 0, encodedBytesNumber2 = alreadyEncodedBytes; j < iv.length; j++, ++encodedBytesNumber2) { if (encodedBytesNumber2 < encodedBytes.length) //Eviter le Out Of Bound { encodedBytes[encodedBytesNumber2] = allBlocks[blockDone][j]; } } alreadyEncodedBytes += iv.length; //Vérifie si le texte est toalement chiffré, auquel cas, on s'arrête if (alreadyEncodedBytes > plainText.length) { encodedBytesListFullyCompleted = true; // L'intégralité du message a été chiffré, on s'arrête comme promis. } blockDone += 1; } return encodedBytes; } /** * Generate a random pad/IV of bytes to be used for encoding * @param size the size of the pad * @return random bytes in an array */ public static byte[] generatePad(int size) { byte[] pad = new byte[size]; for (int i = 0; i< pad.length; i++) { pad[i] = (byte)(rand.nextInt(Decrypt.ALPHABETSIZE)); } return pad; } }
29.9375
150
0.663485
381d9470dc94ed8b7ea7fcd4a5921a0ed92be606
560
package top.xcphoenix.groupblog.service.blog; import top.xcphoenix.groupblog.model.dao.BlogType; import top.xcphoenix.groupblog.model.dao.User; import java.text.ParseException; /** * @author xuanc * @version 1.0 * @date 2020/1/15 下午3:25 */ public interface BlogService { /** * 全量更新 * * @param user 用户信息 * @param blogType 博客类型 */ void execFull(User user, BlogType blogType); /** * 增量更新 * * @param user 用户信息 * @param blogType 博客类型 */ void execIncrement(User user, BlogType blogType); }
17.5
53
0.635714
6ca2808bac0da172190c9981a56b286ef0ab4f34
3,102
/* * Hibernate Search, full-text search for your domain model * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.demos.hswithes.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.IndexedEmbedded; @Entity @Indexed(index = "videogame") public class VideoGame { @Id @GeneratedValue public long id; @Field() public String title; @Field public String description; @Field public int rating; @Field(name="release") public Date publishingDate; @IndexedEmbedded public Publisher publisher; @ElementCollection @Field @IndexedEmbedded public List<String> tags = new ArrayList<>(); @ManyToMany @IndexedEmbedded public List<Character> characters = new ArrayList<>(); VideoGame() { } private VideoGame(String title, String description, int rating, Date publishingDate, Publisher publisher, List<Character> characters, List<String> tags) { this.title = title; this.description = description; this.rating = rating; this.publishingDate = publishingDate; this.publisher = publisher; this.characters.addAll( characters ); this.tags.addAll( tags ); } public String getTitle() { return title; } @Override public String toString() { return "VideoGame [id=" + id + ", title=" + title + ", description=" + description + "]"; } public static class Builder { private String title; private String description; private int rating; private Date publishingDate; private Publisher publisher; private final List<String> tags = new ArrayList<>(); private final List<Character> characters = new ArrayList<>(); public Builder withTitle(String title) { this.title = title; return this; } public Builder withDescription(String description) { this.description = description; return this; } public Builder withRating(int rating) { this.rating = rating; return this; } public Builder withPublishingDate(Date publishingDate) { this.publishingDate = publishingDate; return this; } public Builder withPublisher(Publisher publisher) { this.publisher = publisher; return this; } public Builder withTags(String... tags) { this.tags.addAll( Arrays.asList( tags ) ); return this; } public Builder withCharacters(Character... characters) { this.characters.addAll( Arrays.asList( characters ) ); return this; } public VideoGame build() { VideoGame game = new VideoGame( title, description, rating, publishingDate, publisher, characters, tags ); for ( Character character : game.characters ) { character.appearsIn.add( game ); } return game; } } }
23.149254
155
0.729529
a64be4bc257c5fd46132898abbcf795b5d024899
369
package doko.database.user; import org.springframework.data.repository.CrudRepository; import javax.transaction.Transactional; import java.util.List; @Transactional public interface UserRepository extends CrudRepository<User, Long> { List<User> findAll(); List<User> findByIdIn(List<Long> ids); User findOne(Long id); User findByUsername(String username); }
19.421053
68
0.791328
1af2aef8761c887c3d46f825106d84c20b15b71c
37,578
package com.marathon.domain; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; public class MrtonClothesDemandExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; protected int limitStart = -1; protected int limitEnd = -1; public MrtonClothesDemandExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } public void setLimitStart(int limitStart) { this.limitStart=limitStart; } public int getLimitStart() { return limitStart; } public void setLimitEnd(int limitEnd) { this.limitEnd=limitEnd; } public int getLimitEnd() { return limitEnd; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andProcIdIsNull() { addCriterion("proc_id is null"); return (Criteria) this; } public Criteria andProcIdIsNotNull() { addCriterion("proc_id is not null"); return (Criteria) this; } public Criteria andProcIdEqualTo(String value) { addCriterion("proc_id =", value, "procId"); return (Criteria) this; } public Criteria andProcIdNotEqualTo(String value) { addCriterion("proc_id <>", value, "procId"); return (Criteria) this; } public Criteria andProcIdGreaterThan(String value) { addCriterion("proc_id >", value, "procId"); return (Criteria) this; } public Criteria andProcIdGreaterThanOrEqualTo(String value) { addCriterion("proc_id >=", value, "procId"); return (Criteria) this; } public Criteria andProcIdLessThan(String value) { addCriterion("proc_id <", value, "procId"); return (Criteria) this; } public Criteria andProcIdLessThanOrEqualTo(String value) { addCriterion("proc_id <=", value, "procId"); return (Criteria) this; } public Criteria andProcIdLike(String value) { addCriterion("proc_id like", value, "procId"); return (Criteria) this; } public Criteria andProcIdNotLike(String value) { addCriterion("proc_id not like", value, "procId"); return (Criteria) this; } public Criteria andProcIdIn(List<String> values) { addCriterion("proc_id in", values, "procId"); return (Criteria) this; } public Criteria andProcIdNotIn(List<String> values) { addCriterion("proc_id not in", values, "procId"); return (Criteria) this; } public Criteria andProcIdBetween(String value1, String value2) { addCriterion("proc_id between", value1, value2, "procId"); return (Criteria) this; } public Criteria andProcIdNotBetween(String value1, String value2) { addCriterion("proc_id not between", value1, value2, "procId"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("`name` is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("`name` is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("`name` =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("`name` <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("`name` >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("`name` >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("`name` <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("`name` <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("`name` like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("`name` not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("`name` in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("`name` not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("`name` between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("`name` not between", value1, value2, "name"); return (Criteria) this; } public Criteria andGenderIsNull() { addCriterion("gender is null"); return (Criteria) this; } public Criteria andGenderIsNotNull() { addCriterion("gender is not null"); return (Criteria) this; } public Criteria andGenderEqualTo(Integer value) { addCriterion("gender =", value, "gender"); return (Criteria) this; } public Criteria andGenderNotEqualTo(Integer value) { addCriterion("gender <>", value, "gender"); return (Criteria) this; } public Criteria andGenderGreaterThan(Integer value) { addCriterion("gender >", value, "gender"); return (Criteria) this; } public Criteria andGenderGreaterThanOrEqualTo(Integer value) { addCriterion("gender >=", value, "gender"); return (Criteria) this; } public Criteria andGenderLessThan(Integer value) { addCriterion("gender <", value, "gender"); return (Criteria) this; } public Criteria andGenderLessThanOrEqualTo(Integer value) { addCriterion("gender <=", value, "gender"); return (Criteria) this; } public Criteria andGenderIn(List<Integer> values) { addCriterion("gender in", values, "gender"); return (Criteria) this; } public Criteria andGenderNotIn(List<Integer> values) { addCriterion("gender not in", values, "gender"); return (Criteria) this; } public Criteria andGenderBetween(Integer value1, Integer value2) { addCriterion("gender between", value1, value2, "gender"); return (Criteria) this; } public Criteria andGenderNotBetween(Integer value1, Integer value2) { addCriterion("gender not between", value1, value2, "gender"); return (Criteria) this; } public Criteria andShirtSizeIsNull() { addCriterion("shirt_size is null"); return (Criteria) this; } public Criteria andShirtSizeIsNotNull() { addCriterion("shirt_size is not null"); return (Criteria) this; } public Criteria andShirtSizeEqualTo(String value) { addCriterion("shirt_size =", value, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeNotEqualTo(String value) { addCriterion("shirt_size <>", value, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeGreaterThan(String value) { addCriterion("shirt_size >", value, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeGreaterThanOrEqualTo(String value) { addCriterion("shirt_size >=", value, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeLessThan(String value) { addCriterion("shirt_size <", value, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeLessThanOrEqualTo(String value) { addCriterion("shirt_size <=", value, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeLike(String value) { addCriterion("shirt_size like", value, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeNotLike(String value) { addCriterion("shirt_size not like", value, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeIn(List<String> values) { addCriterion("shirt_size in", values, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeNotIn(List<String> values) { addCriterion("shirt_size not in", values, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeBetween(String value1, String value2) { addCriterion("shirt_size between", value1, value2, "shirtSize"); return (Criteria) this; } public Criteria andShirtSizeNotBetween(String value1, String value2) { addCriterion("shirt_size not between", value1, value2, "shirtSize"); return (Criteria) this; } public Criteria andTrousersSizeIsNull() { addCriterion("trousers_size is null"); return (Criteria) this; } public Criteria andTrousersSizeIsNotNull() { addCriterion("trousers_size is not null"); return (Criteria) this; } public Criteria andTrousersSizeEqualTo(String value) { addCriterion("trousers_size =", value, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeNotEqualTo(String value) { addCriterion("trousers_size <>", value, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeGreaterThan(String value) { addCriterion("trousers_size >", value, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeGreaterThanOrEqualTo(String value) { addCriterion("trousers_size >=", value, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeLessThan(String value) { addCriterion("trousers_size <", value, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeLessThanOrEqualTo(String value) { addCriterion("trousers_size <=", value, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeLike(String value) { addCriterion("trousers_size like", value, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeNotLike(String value) { addCriterion("trousers_size not like", value, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeIn(List<String> values) { addCriterion("trousers_size in", values, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeNotIn(List<String> values) { addCriterion("trousers_size not in", values, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeBetween(String value1, String value2) { addCriterion("trousers_size between", value1, value2, "trousersSize"); return (Criteria) this; } public Criteria andTrousersSizeNotBetween(String value1, String value2) { addCriterion("trousers_size not between", value1, value2, "trousersSize"); return (Criteria) this; } public Criteria andShoesSizeIsNull() { addCriterion("shoes_size is null"); return (Criteria) this; } public Criteria andShoesSizeIsNotNull() { addCriterion("shoes_size is not null"); return (Criteria) this; } public Criteria andShoesSizeEqualTo(String value) { addCriterion("shoes_size =", value, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeNotEqualTo(String value) { addCriterion("shoes_size <>", value, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeGreaterThan(String value) { addCriterion("shoes_size >", value, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeGreaterThanOrEqualTo(String value) { addCriterion("shoes_size >=", value, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeLessThan(String value) { addCriterion("shoes_size <", value, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeLessThanOrEqualTo(String value) { addCriterion("shoes_size <=", value, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeLike(String value) { addCriterion("shoes_size like", value, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeNotLike(String value) { addCriterion("shoes_size not like", value, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeIn(List<String> values) { addCriterion("shoes_size in", values, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeNotIn(List<String> values) { addCriterion("shoes_size not in", values, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeBetween(String value1, String value2) { addCriterion("shoes_size between", value1, value2, "shoesSize"); return (Criteria) this; } public Criteria andShoesSizeNotBetween(String value1, String value2) { addCriterion("shoes_size not between", value1, value2, "shoesSize"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andCategoryIsNull() { addCriterion("category is null"); return (Criteria) this; } public Criteria andCategoryIsNotNull() { addCriterion("category is not null"); return (Criteria) this; } public Criteria andCategoryEqualTo(Integer value) { addCriterion("category =", value, "category"); return (Criteria) this; } public Criteria andCategoryNotEqualTo(Integer value) { addCriterion("category <>", value, "category"); return (Criteria) this; } public Criteria andCategoryGreaterThan(Integer value) { addCriterion("category >", value, "category"); return (Criteria) this; } public Criteria andCategoryGreaterThanOrEqualTo(Integer value) { addCriterion("category >=", value, "category"); return (Criteria) this; } public Criteria andCategoryLessThan(Integer value) { addCriterion("category <", value, "category"); return (Criteria) this; } public Criteria andCategoryLessThanOrEqualTo(Integer value) { addCriterion("category <=", value, "category"); return (Criteria) this; } public Criteria andCategoryIn(List<Integer> values) { addCriterion("category in", values, "category"); return (Criteria) this; } public Criteria andCategoryNotIn(List<Integer> values) { addCriterion("category not in", values, "category"); return (Criteria) this; } public Criteria andCategoryBetween(Integer value1, Integer value2) { addCriterion("category between", value1, value2, "category"); return (Criteria) this; } public Criteria andCategoryNotBetween(Integer value1, Integer value2) { addCriterion("category not between", value1, value2, "category"); return (Criteria) this; } public Criteria andDelFlagIsNull() { addCriterion("del_flag is null"); return (Criteria) this; } public Criteria andDelFlagIsNotNull() { addCriterion("del_flag is not null"); return (Criteria) this; } public Criteria andDelFlagEqualTo(Integer value) { addCriterion("del_flag =", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotEqualTo(Integer value) { addCriterion("del_flag <>", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagGreaterThan(Integer value) { addCriterion("del_flag >", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagGreaterThanOrEqualTo(Integer value) { addCriterion("del_flag >=", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagLessThan(Integer value) { addCriterion("del_flag <", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagLessThanOrEqualTo(Integer value) { addCriterion("del_flag <=", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagIn(List<Integer> values) { addCriterion("del_flag in", values, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotIn(List<Integer> values) { addCriterion("del_flag not in", values, "delFlag"); return (Criteria) this; } public Criteria andDelFlagBetween(Integer value1, Integer value2) { addCriterion("del_flag between", value1, value2, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotBetween(Integer value1, Integer value2) { addCriterion("del_flag not between", value1, value2, "delFlag"); return (Criteria) this; } public Criteria andCreateUserNameIsNull() { addCriterion("create_user_name is null"); return (Criteria) this; } public Criteria andCreateUserNameIsNotNull() { addCriterion("create_user_name is not null"); return (Criteria) this; } public Criteria andCreateUserNameEqualTo(String value) { addCriterion("create_user_name =", value, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameNotEqualTo(String value) { addCriterion("create_user_name <>", value, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameGreaterThan(String value) { addCriterion("create_user_name >", value, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameGreaterThanOrEqualTo(String value) { addCriterion("create_user_name >=", value, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameLessThan(String value) { addCriterion("create_user_name <", value, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameLessThanOrEqualTo(String value) { addCriterion("create_user_name <=", value, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameLike(String value) { addCriterion("create_user_name like", value, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameNotLike(String value) { addCriterion("create_user_name not like", value, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameIn(List<String> values) { addCriterion("create_user_name in", values, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameNotIn(List<String> values) { addCriterion("create_user_name not in", values, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameBetween(String value1, String value2) { addCriterion("create_user_name between", value1, value2, "createUserName"); return (Criteria) this; } public Criteria andCreateUserNameNotBetween(String value1, String value2) { addCriterion("create_user_name not between", value1, value2, "createUserName"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(LocalDateTime value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(LocalDateTime value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(LocalDateTime value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(LocalDateTime value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(LocalDateTime value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(LocalDateTime value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<LocalDateTime> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<LocalDateTime> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andUpdateUserNameIsNull() { addCriterion("update_user_name is null"); return (Criteria) this; } public Criteria andUpdateUserNameIsNotNull() { addCriterion("update_user_name is not null"); return (Criteria) this; } public Criteria andUpdateUserNameEqualTo(String value) { addCriterion("update_user_name =", value, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameNotEqualTo(String value) { addCriterion("update_user_name <>", value, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameGreaterThan(String value) { addCriterion("update_user_name >", value, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameGreaterThanOrEqualTo(String value) { addCriterion("update_user_name >=", value, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameLessThan(String value) { addCriterion("update_user_name <", value, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameLessThanOrEqualTo(String value) { addCriterion("update_user_name <=", value, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameLike(String value) { addCriterion("update_user_name like", value, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameNotLike(String value) { addCriterion("update_user_name not like", value, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameIn(List<String> values) { addCriterion("update_user_name in", values, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameNotIn(List<String> values) { addCriterion("update_user_name not in", values, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameBetween(String value1, String value2) { addCriterion("update_user_name between", value1, value2, "updateUserName"); return (Criteria) this; } public Criteria andUpdateUserNameNotBetween(String value1, String value2) { addCriterion("update_user_name not between", value1, value2, "updateUserName"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(LocalDateTime value) { addCriterion("update_time =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(LocalDateTime value) { addCriterion("update_time <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(LocalDateTime value) { addCriterion("update_time >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(LocalDateTime value) { addCriterion("update_time >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(LocalDateTime value) { addCriterion("update_time <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(LocalDateTime value) { addCriterion("update_time <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<LocalDateTime> values) { addCriterion("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<LocalDateTime> values) { addCriterion("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
32.934268
102
0.588908
e4edf5dee82c88921df651cf9ab2aebcd342ff1f
4,957
/* * 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.geode.internal.cache.tier.sockets; import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_ID; import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS; import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; import static org.junit.Assert.fail; import java.io.IOException; import java.util.Properties; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.cache.AttributesFactory; import org.apache.geode.cache.Cache; import org.apache.geode.cache.NoSubscriptionServersAvailableException; import org.apache.geode.cache.Region; import org.apache.geode.cache.Scope; import org.apache.geode.cache.client.PoolManager; import org.apache.geode.cache.client.internal.PoolImpl; import org.apache.geode.cache.server.CacheServer; import org.apache.geode.internal.AvailablePortHelper; import org.apache.geode.test.awaitility.GeodeAwaitility; import org.apache.geode.test.dunit.Assert; import org.apache.geode.test.dunit.Host; import org.apache.geode.test.dunit.NetworkUtils; import org.apache.geode.test.dunit.SerializableRunnable; import org.apache.geode.test.dunit.VM; import org.apache.geode.test.dunit.WaitCriterion; import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase; import org.apache.geode.test.junit.categories.ClientSubscriptionTest; @Category({ClientSubscriptionTest.class}) public class DurableClientBug39997DUnitTest extends JUnit4CacheTestCase { public final void postTearDownCacheTestCase() { Host.getHost(0).getVM(0).invoke(() -> disconnectFromDS()); } @Test public void testNoServerAvailableOnStartup() { Host host = Host.getHost(0); VM vm0 = host.getVM(0); VM vm1 = host.getVM(1); final String hostName = NetworkUtils.getServerHostName(host); final int port = AvailablePortHelper.getRandomAvailableTCPPort(); vm0.invoke(new SerializableRunnable("create cache") { public void run() { getSystem(getClientProperties()); PoolImpl p = (PoolImpl) PoolManager.createFactory().addServer(hostName, port) .setSubscriptionEnabled(true).setSubscriptionRedundancy(0) .create("DurableClientReconnectDUnitTestPool"); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); factory.setPoolName(p.getName()); Cache cache = getCache(); Region region1 = cache.createRegion("region", factory.create()); cache.readyForEvents(); try { region1.registerInterest("ALL_KEYS"); fail("Should have received an exception trying to register interest"); } catch (NoSubscriptionServersAvailableException expected) { // this is expected } } }); vm1.invoke(new SerializableRunnable() { public void run() { Cache cache = getCache(); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.DISTRIBUTED_ACK); cache.createRegion("region", factory.create()); CacheServer server = cache.addCacheServer(); server.setPort(port); try { server.start(); } catch (IOException e) { Assert.fail("couldn't start server", e); } } }); vm0.invoke(new SerializableRunnable() { public void run() { Cache cache = getCache(); final Region region = cache.getRegion("region"); GeodeAwaitility.await().untilAsserted(new WaitCriterion() { public String description() { return "Wait for register interest to succeed"; } public boolean done() { try { region.registerInterest("ALL_KEYS"); } catch (NoSubscriptionServersAvailableException e) { return false; } return true; } }); } }); } public Properties getClientProperties() { Properties props = new Properties(); props.setProperty(MCAST_PORT, "0"); props.setProperty(LOCATORS, ""); props.setProperty(DURABLE_CLIENT_ID, "my_id"); return props; } }
37.55303
100
0.710914
25810912406a96d796a1044b2a5063b95eb8a12e
1,358
package cards.dumbgame; import cards.common.*; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Sergey Sokolov <xlamserg@gmail.com> */ public class MemoryStrategyTest { @Test public void testMemoryStrategyPossibleDeckCards() { MemoryStrategy strategy = new MemoryStrategy(); DumbHand hand = new DumbHand(); hand.add(new Card(Suit.CLUBS, Rank.NINE)); hand.add(new Card(Suit.CLUBS, Rank.TEN)); // 1 pass strategy.knownEnemyCards.add(new Card(Suit.CLUBS, Rank.SIX)); strategy.knownEnemyCards.add(new Card(Suit.CLUBS, Rank.SEVEN)); strategy.knownOutCards.add(new Card(Suit.DIAMONDS, Rank.SIX)); strategy.knownOutCards.add(new Card(Suit.DIAMONDS, Rank.SEVEN)); strategy.calculatePossibleDeckCards(hand); //System.out.println(strategy.possibleDeckCards.toString()); assertEquals(30, strategy.possibleDeckCards.size()); // 2 pass strategy.knownEnemyCards.add(new Card(Suit.CLUBS, Rank.EIGHT)); strategy.knownOutCards.add(new Card(Suit.DIAMONDS, Rank.EIGHT)); hand.add(new Card(Suit.CLUBS, Rank.JACK)); strategy.calculatePossibleDeckCards(hand); //System.out.println(strategy.possibleDeckCards.toString()); assertEquals(27, strategy.possibleDeckCards.size()); } }
37.722222
72
0.679676
58fe6015698440e01fe3424cebf5016953c3cf48
2,425
/* * 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.ignite.ml.util.plugin; import org.apache.ignite.plugin.PluginConfiguration; /** * Configuration of ML plugin that defines which ML inference services should be start up on Ignite startup. */ public class MLPluginConfiguration implements PluginConfiguration { /** Model storage should be created on startup. */ private boolean withMdlStorage; /** Model descriptor storage should be created on startup. */ private boolean withMdlDescStorage; /** Number of backups in model storage cache. */ private Integer mdlStorageBackups; /** Number of backups in model descriptor storage cache. */ private Integer mdlDescStorageBackups; /** */ public boolean isWithMdlStorage() { return withMdlStorage; } /** */ public void setWithMdlStorage(boolean withMdlStorage) { this.withMdlStorage = withMdlStorage; } /** */ public boolean isWithMdlDescStorage() { return withMdlDescStorage; } /** */ public void setWithMdlDescStorage(boolean withMdlDescStorage) { this.withMdlDescStorage = withMdlDescStorage; } /** */ public Integer getMdlStorageBackups() { return mdlStorageBackups; } /** */ public void setMdlStorageBackups(Integer mdlStorageBackups) { this.mdlStorageBackups = mdlStorageBackups; } /** */ public Integer getMdlDescStorageBackups() { return mdlDescStorageBackups; } /** */ public void setMdlDescStorageBackups(Integer mdlDescStorageBackups) { this.mdlDescStorageBackups = mdlDescStorageBackups; } }
31.089744
108
0.710928
9f6bc8db99020778b65f975b34cf04f030494f03
681
package com.zs.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.zs.entity.BlogListRel; public interface BlogListRelMapper { int deleteByPrimaryKey(Integer id); int insert(BlogListRel record); int insertSelective(BlogListRel record); BlogListRel selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(BlogListRel record); int updateByPrimaryKey(BlogListRel record); int getCountFromBlid(@Param("blId") Integer blId); List<BlogListRel> selectByBlidOrBid(@Param("blId")Integer blId,@Param("bId")Integer bId); int deleteByBlidOrBid(@Param("blId")Integer blId,@Param("bId")Integer bId); }
26.192308
93
0.750367
638bc5cd81d185401cf50ef0e13eb9f16a9a6502
5,050
/** * Copyright (c) 2011, The University of Southampton and the individual contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the University of Southampton nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openimaj.demos; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.openimaj.feature.local.list.MemoryLocalFeatureList; import org.openimaj.image.feature.local.aggregate.FisherVector; import org.openimaj.image.feature.local.keypoints.FloatKeypoint; import org.openimaj.image.feature.local.keypoints.Keypoint; import org.openimaj.math.matrix.algorithm.pca.ThinSvdPrincipalComponentAnalysis; import org.openimaj.math.statistics.distribution.MixtureOfGaussians; import org.openimaj.ml.gmm.GaussianMixtureModelEM; import org.openimaj.ml.gmm.GaussianMixtureModelEM.CovarianceType; import org.openimaj.util.array.ArrayUtils; import Jama.Matrix; public class FisherTesting { public static void main(String[] args) throws IOException { final List<MemoryLocalFeatureList<FloatKeypoint>> data = new ArrayList<MemoryLocalFeatureList<FloatKeypoint>>(); final List<FloatKeypoint> allKeys = new ArrayList<FloatKeypoint>(); for (int i = 0; i < 100; i++) { final MemoryLocalFeatureList<FloatKeypoint> tmp = FloatKeypoint.convert(MemoryLocalFeatureList.read( new File(String.format("/Users/jsh2/Data/ukbench/sift/ukbench%05d.jpg", i)), Keypoint.class)); data.add(tmp); allKeys.addAll(tmp); } Collections.shuffle(allKeys); final double[][] sample128 = new double[1000][]; for (int i = 0; i < sample128.length; i++) { sample128[i] = ArrayUtils.convertToDouble(allKeys.get(i).vector); } System.out.println("Performing PCA " + sample128.length); final ThinSvdPrincipalComponentAnalysis pca = new ThinSvdPrincipalComponentAnalysis(64); pca.learnBasis(sample128); final double[][] sample64 = pca.project(new Matrix(sample128)).getArray(); System.out.println("Projecting features"); for (final MemoryLocalFeatureList<FloatKeypoint> kpl : data) { for (final FloatKeypoint kp : kpl) { kp.vector = ArrayUtils.convertToFloat(pca.project(ArrayUtils.convertToDouble(kp.vector))); } } System.out.println("Learning GMM " + sample64.length); final GaussianMixtureModelEM gmmem = new GaussianMixtureModelEM(512, CovarianceType.Diagonal); final MixtureOfGaussians gmm = gmmem.estimate(sample64); final double[][] v1 = gmm.logProbability(new double[][] { sample64[0] }); final double[][] v2 = MixtureOfGaussians.logProbability(new double[][] { sample64[0] }, gmm.gaussians); System.out.println("Done"); // for (int i = 0; i < 512; i++) { // System.out.println(gmm.gaussians[i].getMean().get(0, 0) + "," + // gmm.gaussians[i].getMean().get(0, 1)); // } final FisherVector<float[]> fisher = new FisherVector<float[]>(gmm, true, true); final List<FloatKeypoint> kpl = allKeys.subList(0, 26000); final long t1 = System.currentTimeMillis(); fisher.aggregate(kpl).asDoubleVector(); final long t2 = System.currentTimeMillis(); System.out.println(t2 - t1); // int i = 0; // final double[][] fvs = new double[5][]; // for (final MemoryLocalFeatureList<FloatKeypoint> kpl : data) { // final long t1 = System.currentTimeMillis(); // fvs[i++] = fisher.aggregate(kpl).asDoubleVector(); // final long t2 = System.currentTimeMillis(); // System.out.println(t2 - t1); // // if (i == 5) // break; // } // // final ThinSvdPrincipalComponentAnalysis pca2 = new // ThinSvdPrincipalComponentAnalysis(128); // pca2.learnBasis(fvs); } }
42.083333
114
0.743564
d878e26abe298170d3e95adff3f02571492a5f55
1,098
package io.github.phantamanta44.resyn.parser.directive; import io.github.phantamanta44.resyn.parser.ParserState; import io.github.phantamanta44.resyn.parser.construct.Context; import java.util.function.Function; import java.util.function.Supplier; public class DirectiveContextSwitch implements IDirective { private final Function<Context, Context> contextBinder; private final String name; private final boolean visiting; public DirectiveContextSwitch(Function<Context, Context> contextBinder, String name, boolean visiting) { this.contextBinder = contextBinder; this.name = name; this.visiting = visiting; } public DirectiveContextSwitch(Function<Context, Context> contextBinder) { this(contextBinder, null, false); } @Override public void execute(ParserState state, String match, Supplier<String> tokens) { Context ctx = contextBinder.apply(state.getContext()); if (visiting) ctx.setVisiting(); state.setContext(ctx, name != null ? name : ctx.getName()); } }
33.272727
109
0.708561
d2195a0e013f5d54dbc9a79e865a9fd58c4d8dc9
1,582
/* * Encog(tm) Core v3.4 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2017 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.util.logging; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * A simple formatter for logging. * * @author jheaton * */ public class EncogFormatter extends Formatter { /** * Format the log record. * * @param record * What to log. * @return The formatted log record. */ @Override public String format(final LogRecord record) { final StringBuilder result = new StringBuilder(); result.append("["); result.append(record.getLevel()); result.append("] ["); result.append(record.getSourceClassName()); result.append("] "); result.append(record.getMessage()); result.append("\n"); return result.toString(); } }
26.813559
75
0.704804
4c204d1028db5f5deaa5b601ba6410366dae1479
2,764
package com.google.gson.internal.bind; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.C$Gson$Types; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.ObjectConstructor; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collection; public final class CollectionTypeAdapterFactory implements TypeAdapterFactory { private final ConstructorConstructor constructorConstructor; private static final class Adapter<E> extends TypeAdapter<Collection<E>> { private final ObjectConstructor<? extends Collection<E>> constructor; private final TypeAdapter<E> elementTypeAdapter; public Adapter(Gson context, Type elementType, TypeAdapter<E> elementTypeAdapter, ObjectConstructor<? extends Collection<E>> constructor) { this.elementTypeAdapter = new TypeAdapterRuntimeTypeWrapper(context, elementTypeAdapter, elementType); this.constructor = constructor; } public Collection<E> read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Collection<E> collection = (Collection) this.constructor.construct(); in.beginArray(); while (in.hasNext()) { collection.add(this.elementTypeAdapter.read(in)); } in.endArray(); return collection; } public void write(JsonWriter out, Collection<E> collection) throws IOException { if (collection == null) { out.nullValue(); return; } out.beginArray(); for (E element : collection) { this.elementTypeAdapter.write(out, element); } out.endArray(); } } public CollectionTypeAdapterFactory(ConstructorConstructor constructorConstructor) { this.constructorConstructor = constructorConstructor; } public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Type type = typeToken.getType(); Class<? super T> rawType = typeToken.getRawType(); if (!Collection.class.isAssignableFrom(rawType)) { return null; } Type elementType = C$Gson$Types.getCollectionElementType(type, rawType); return new Adapter(gson, elementType, gson.getAdapter(TypeToken.get(elementType)), this.constructorConstructor.get(typeToken)); } }
39.485714
147
0.672214
cfb992975478482eba3ee8bbc7268c107bb35132
2,575
package com.bdth.rure.demo.dao.modle; import java.io.Serializable; /** * Created by Administrator on 2017/9/8. */ public class DemoUser implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String username; private String password; private Integer sex; private String crtime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public String getCrtime() { return crtime; } public void setCrtime(String crtime) { this.crtime = crtime; } @Override public String toString() { return "DemoUser{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", sex=" + sex + ", crtime='" + crtime + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DemoUser demoUser = (DemoUser) o; if (id != null ? !id.equals(demoUser.id) : demoUser.id != null) return false; if (username != null ? !username.equals(demoUser.username) : demoUser.username != null) return false; if (password != null ? !password.equals(demoUser.password) : demoUser.password != null) return false; if (sex != null ? !sex.equals(demoUser.sex) : demoUser.sex != null) return false; return crtime != null ? crtime.equals(demoUser.crtime) : demoUser.crtime == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (username != null ? username.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + (sex != null ? sex.hashCode() : 0); result = 31 * result + (crtime != null ? crtime.hashCode() : 0); return result; } }
26.822917
110
0.539417
59cae08eff2601b39f6efe4f1e159eef4cbe3f6a
4,806
// -------------------------------------------------------------------------------- // Copyright 2002-2022 Echo Three, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // -------------------------------------------------------------------------------- package com.echothree.model.control.core.server.transfer; import com.echothree.model.control.core.common.CoreOptions; import com.echothree.model.control.core.common.transfer.EntityAttributeTransfer; import com.echothree.model.control.core.common.transfer.EntityBlobAttributeTransfer; import com.echothree.model.control.core.common.transfer.EntityInstanceTransfer; import com.echothree.model.control.core.common.transfer.EntityTimeTransfer; import com.echothree.model.control.core.common.transfer.MimeTypeTransfer; import com.echothree.model.control.core.server.control.CoreControl; import com.echothree.model.control.party.common.transfer.LanguageTransfer; import com.echothree.model.control.party.server.control.PartyControl; import com.echothree.model.data.core.server.entity.EntityBlobAttribute; import com.echothree.model.data.core.server.entity.EntityInstance; import com.echothree.model.data.user.server.entity.UserVisit; import com.echothree.util.common.persistence.type.ByteArray; import com.echothree.util.server.persistence.Session; import java.util.Set; public class EntityBlobAttributeTransferCache extends BaseCoreTransferCache<EntityBlobAttribute, EntityBlobAttributeTransfer> { PartyControl partyControl = Session.getModelController(PartyControl.class); boolean includeBlob; boolean includeETag; /** Creates a new instance of EntityBlobAttributeTransferCache */ public EntityBlobAttributeTransferCache(UserVisit userVisit, CoreControl coreControl) { super(userVisit, coreControl); var options = session.getOptions(); if(options != null) { includeBlob = options.contains(CoreOptions.EntityBlobAttributeIncludeBlob); includeETag = options.contains(CoreOptions.EntityBlobAttributeIncludeETag); } } public EntityBlobAttributeTransfer getEntityBlobAttributeTransfer(EntityBlobAttribute entityBlobAttribute, EntityInstance entityInstance) { EntityBlobAttributeTransfer entityBlobAttributeTransfer = get(entityBlobAttribute); if(entityBlobAttributeTransfer == null) { EntityAttributeTransfer entityAttribute = entityInstance == null ? coreControl.getEntityAttributeTransfer(userVisit, entityBlobAttribute.getEntityAttribute(), entityInstance) : null; EntityInstanceTransfer entityInstanceTransfer = coreControl.getEntityInstanceTransfer(userVisit, entityBlobAttribute.getEntityInstance(), false, false, false, false, false); LanguageTransfer language = partyControl.getLanguageTransfer(userVisit, entityBlobAttribute.getLanguage()); ByteArray blobAttribute = includeBlob ? entityBlobAttribute.getBlobAttribute() : null; MimeTypeTransfer mimeType = coreControl.getMimeTypeTransfer(userVisit, entityBlobAttribute.getMimeType()); String eTag = null; if(includeETag) { // Item Descriptions do not have their own EntityTime, fall back on the Item's EntityTime. EntityTimeTransfer entityTimeTransfer = entityInstanceTransfer.getEntityTime(); Long modifiedTime = entityTimeTransfer.getUnformattedModifiedTime(); long maxTime = modifiedTime == null ? entityTimeTransfer.getUnformattedCreatedTime() : modifiedTime; long eTagEntityId = entityBlobAttribute.getPrimaryKey().getEntityId(); int eTagSize = entityBlobAttribute.getBlobAttribute().length(); // EntityId-Size-ModifiedTime eTag = new StringBuilder(Long.toHexString(eTagEntityId)).append('-').append(Integer.toHexString(eTagSize)).append('-').append(Long.toHexString(maxTime)).toString(); } entityBlobAttributeTransfer = new EntityBlobAttributeTransfer(entityAttribute, entityInstanceTransfer, language, blobAttribute, mimeType, eTag); put(entityBlobAttribute, entityBlobAttributeTransfer); } return entityBlobAttributeTransfer; } }
57.214286
194
0.727216
cbd8b1eedf7308f0d97b30b6e10c7ec631d33a26
4,775
package com.semmle.js.ast; import java.util.Arrays; import java.util.List; /** * Defines bitmasks where each bit corresponds to a flag on {@linkplain MemberDefinition} or * {@linkplain VariableDeclarator}. */ public class DeclarationFlags { public static final int computed = 1 << 0; public static final int abstract_ = 1 << 1; public static final int static_ = 1 << 2; public static final int readonly = 1 << 3; public static final int public_ = 1 << 4; public static final int private_ = 1 << 5; public static final int protected_ = 1 << 6; public static final int optional = 1 << 7; public static final int definiteAssignmentAssertion = 1 << 8; public static final int declareKeyword = 1 << 9; public static final int none = 0; public static final int numberOfFlags = 10; public static final List<String> names = Arrays.asList( "computed", "abstract", "static", "readonly", "public", "private", "protected", "optional", "definiteAssignmentAssertion", "declare"); public static final List<String> relationNames = Arrays.asList( "is_computed", "is_abstract_member", "is_static", "has_readonly_keyword", "has_public_keyword", "has_private_keyword", "has_protected_keyword", "is_optional_member", "has_definite_assignment_assertion", "has_declare_keyword"); public static boolean isComputed(int flags) { return (flags & computed) != 0; } public static boolean isAbstract(int flags) { return (flags & abstract_) != 0; } public static boolean isStatic(int flags) { return (flags & static_) != 0; } public static boolean isReadonly(int flags) { return (flags & readonly) != 0; } public static boolean isPublic(int flags) { return (flags & public_) != 0; } public static boolean isPrivate(int flags) { return (flags & private_) != 0; } public static boolean isProtected(int flags) { return (flags & protected_) != 0; } public static boolean isOptional(int flags) { return (flags & optional) != 0; } public static boolean hasDefiniteAssignmentAssertion(int flags) { return (flags & definiteAssignmentAssertion) != 0; } public static boolean hasDeclareKeyword(int flags) { return (flags & declareKeyword) != 0; } /** Returns a mask with the computed bit set to the value of <code>enable</code>. */ public static int getComputed(boolean enable) { return enable ? computed : 0; } /** Returns a mask with the abstract bit set to the value of <code>enable</code>. */ public static int getAbstract(boolean enable) { return enable ? abstract_ : 0; } /** Returns a mask with the static bit set to the value of <code>enable</code>. */ public static int getStatic(boolean enable) { return enable ? static_ : 0; } /** Returns a mask with the public bit set to the value of <code>enable</code>. */ public static int getPublic(boolean enable) { return enable ? public_ : 0; } /** Returns a mask with the readonly bit set to the value of <code>enable</code>. */ public static int getReadonly(boolean enable) { return enable ? readonly : 0; } /** Returns a mask with the private bit set to the value of <code>enable</code>. */ public static int getPrivate(boolean enable) { return enable ? private_ : 0; } /** Returns a mask with the protected bit set to the value of <code>enable</code>. */ public static int getProtected(boolean enable) { return enable ? protected_ : 0; } /** Returns a mask with the optional bit set to the value of <code>enable</code>. */ public static int getOptional(boolean enable) { return enable ? optional : 0; } /** * Returns a mask with the definite assignment assertion bit set to the value of <code>enable</code>. */ public static int getDefiniteAssignmentAssertion(boolean enable) { return enable ? definiteAssignmentAssertion : 0; } /** Returns a mask with the declare keyword bit set to the value of <code>enable</code>. */ public static int getDeclareKeyword(boolean enable) { return enable ? declareKeyword : 0; } /** Returns true if the <code>n</code>th bit is set in <code>flags</code>. */ public static boolean hasNthFlag(int flags, int n) { return (flags & (1 << n)) != 0; } public static String getFlagNames(int flags) { StringBuilder b = new StringBuilder(); for (int i = 0; i < numberOfFlags; ++i) { if (hasNthFlag(flags, i)) { if (b.length() > 0) { b.append(", "); } b.append(names.get(i)); } } return b.toString(); } }
29.658385
103
0.646702
fcc114422a0a9fccdc0d6651362207b1add95f50
4,599
package com.objectcomputing.checkins.services.permissions; import com.objectcomputing.checkins.security.permissions.Permissions; import com.objectcomputing.checkins.services.TestContainersSuite; import com.objectcomputing.checkins.services.fixture.MemberProfileFixture; import com.objectcomputing.checkins.services.fixture.PermissionFixture; import com.objectcomputing.checkins.services.fixture.RoleFixture; import com.objectcomputing.checkins.services.memberprofile.MemberProfile; import com.objectcomputing.checkins.services.role.Role; import com.objectcomputing.checkins.services.role.RoleType; import io.micronaut.core.type.Argument; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.HttpStatus; import io.micronaut.http.client.HttpClient; import io.micronaut.http.client.annotation.Client; import io.micronaut.http.client.exceptions.HttpClientResponseException; import org.junit.jupiter.api.Test; import javax.inject.Inject; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class PermissionsControllerTest extends TestContainersSuite implements PermissionFixture, MemberProfileFixture, RoleFixture { @Inject @Client("/services/permissions") HttpClient client; @Test void testGetAllPermissionsEnsureAlphabeticalOrder() { // create role and permissions Role memberRole = createRole(new Role(RoleType.MEMBER.name(), "Member Role")); Permission someTestPermission = createACustomPermission(Permissions.CAN_VIEW_ROLE_PERMISSIONS); Permission someOtherPermission = createACustomPermission(Permissions.CAN_VIEW_PERMISSIONS); setPermissionsForMember(memberRole.getId()); // assign role to user MemberProfile user = createADefaultMemberProfile(); assignMemberRole(user); List<Permission> expected = new ArrayList<>(Arrays.asList(someOtherPermission, someTestPermission)); final HttpRequest<Object> request = HttpRequest. GET("/OrderByPermission").basicAuth(user.getWorkEmail(), RoleType.Constants.MEMBER_ROLE); final HttpResponse<List<Permission>> response = client.toBlocking().exchange(request, Argument.listOf(Permission.class)); assertEquals(HttpStatus.OK, response.getStatus()); assertTrue(response.getBody().isPresent()); assertEquals(expected, response.getBody().get()); } @Test void getOrderByPermissionIsNotAuthenticatedThrowsError() { final HttpRequest<Object> request = HttpRequest.GET("/OrderByPermission"); HttpClientResponseException responseException = assertThrows(HttpClientResponseException.class, () -> client.toBlocking().exchange(request, Map.class)); assertEquals(HttpStatus.UNAUTHORIZED, responseException.getStatus()); } @Test void testGetAllPermissions() { // create role and permissions Role memberRole = createRole(new Role(RoleType.MEMBER.name(), "Member Role")); Permission someTestPermission = createACustomPermission(Permissions.CAN_VIEW_ROLE_PERMISSIONS); Permission someOtherPermission = createACustomPermission(Permissions.CAN_VIEW_PERMISSIONS); setPermissionsForMember(memberRole.getId()); // assign role to user MemberProfile user = createADefaultMemberProfile(); assignMemberRole(user); List<Permission> expected = new ArrayList<>(Arrays.asList(someTestPermission, someOtherPermission)); final HttpRequest<Object> request = HttpRequest. GET("/").basicAuth(user.getWorkEmail(), RoleType.Constants.MEMBER_ROLE); final HttpResponse<List<Permission>> response = client.toBlocking().exchange(request, Argument.listOf(Permission.class)); assertEquals(HttpStatus.OK, response.getStatus()); assertTrue(response.getBody().isPresent()); assertEquals(expected, response.getBody().get()); } @Test void getAllPermissionsnIsNotAuthenticatedThrowsError() { final HttpRequest<Object> request = HttpRequest.GET("/"); HttpClientResponseException responseException = assertThrows(HttpClientResponseException.class, () -> client.toBlocking().exchange(request, Map.class)); assertEquals(HttpStatus.UNAUTHORIZED, responseException.getStatus()); } }
43.8
132
0.752772
7401cf024e54610d7102bfd5f2ba28ce5b897572
9,497
package tedking.lovewords; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.avos.avoscloud.AVAnalytics; import com.avos.avoscloud.AVException; import com.avos.avoscloud.AVUser; import com.avos.avoscloud.LogInCallback; import com.avos.avoscloud.RequestPasswordResetCallback; /** * A login screen that offers login via email/password. */ public class LoginActivity extends AppCompatActivity { // UI references. private AutoCompleteTextView mUsernameView; private EditText mPasswordView; private View mProgressView; private View mLoginFormView; private Dialog dialog; private EditText email_dialog; private Button forgetButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); if (AVUser.getCurrentUser() != null) { startActivity(new Intent(LoginActivity.this, MainActivity.class)); LoginActivity.this.finish(); } forgetButton = findViewById(R.id.forgetPassword); buildDialog(); //getSupportActionBar().setDisplayHomeAsUpEnabled(true); //getSupportActionBar().setTitle(getString(R.string.login)); // Set up the login form. mUsernameView = findViewById(R.id.username); mPasswordView = findViewById(R.id.password); mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } }); Button mUsernameLoginButton = findViewById(R.id.username_login_button); mUsernameLoginButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } }); Button mUsernameRegisterButton = findViewById(R.id.username_register_button); mUsernameRegisterButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(LoginActivity.this, RegisterActivity.class)); LoginActivity.this.finish(); } }); forgetButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { dialog.show(); } }); mLoginFormView = findViewById(R.id.login_form); mProgressView = findViewById(R.id.login_progress); } private void buildDialog(){ View view = LayoutInflater.from(this).inflate(R.layout.layout_email_dialog,null); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(view); dialog = builder.create(); Button cancel = view.findViewById(R.id.cancel_dialog); Button confirm = view.findViewById(R.id.confirm_dialog); email_dialog = view.findViewById(R.id.emailAddress_dialog); confirm.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$"; if (email_dialog.getText().toString().matches(strPattern)) { AVUser.requestPasswordResetInBackground(email_dialog.getText().toString(), new RequestPasswordResetCallback() { @Override public void done(AVException e) { if (e == null){ Toast.makeText(LoginActivity.this,"We have sent an email to your email box.Please reset your password!",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(LoginActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show(); } } }); dialog.dismiss(); }else { Toast.makeText(LoginActivity.this,"Please input correct email address!",Toast.LENGTH_SHORT).show(); } } }); cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); } private void attemptLogin() { // Reset errors. mUsernameView.setError(null); mPasswordView.setError(null); // Store values at the time of the login attempt. final String username = mUsernameView.getText().toString(); final String password = mPasswordView.getText().toString(); boolean cancel = false; View focusView = null; // Check for a valid password, if the user entered one. if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) { mPasswordView.setError(getString(R.string.error_invalid_password)); focusView = mPasswordView; cancel = true; } // Check for a valid username. if (TextUtils.isEmpty(username)) { mUsernameView.setError(getString(R.string.error_field_required)); focusView = mUsernameView; cancel = true; } if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { // Show a progress spinner, and kick off a background task to // perform the user login attempt. showProgress(true); AVUser.logInInBackground(username, password, new LogInCallback<AVUser>() { @Override public void done(AVUser avUser, AVException e) { if (e == null) { LoginActivity.this.finish(); startActivity(new Intent(LoginActivity.this, MainActivity.class)); } else { showProgress(false); Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } }); } } private boolean isPasswordValid(String password) { //TODO: Replace this with your own logic return password.length() > 4; } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); mLoginFormView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return super.onOptionsItemSelected(item); } @Override protected void onPause() { super.onPause(); AVAnalytics.onPause(this); } @Override protected void onResume() { super.onResume(); AVAnalytics.onResume(this); } }
37.537549
163
0.606402
ec7ce4b8b7db3a171996d177d10f5cffdb22d3b1
1,374
import java.util.ArrayList; public class SingleNumber { public static void main (String... args) { String[] list = new String[] { "2", "3", "4", "2", "3", "5", "4", "6", "4", "6", "9", "10", "9", "8", "7", "8", "10", "7" }; String[] list2 = new String[] { "2", "a", "l", "3", "l", "4", "k", "2", "3", "4", "a", "6", "c", "4", "m", "6", "m", "k", "9", "10", "9", "8", "7", "8", "10", "7" }; System.out.println(findUniqueChar(list)); // 5 System.out.println(findUniqueChar(list2)); // c } public static String findUniqueChar (String[] list) { ArrayList<String> chars = new ArrayList<String>(); ArrayList<String> charsToRemove = new ArrayList<String>(); for (int i = 0; i < list.length; i++) { if (chars.contains(list[i])) { chars.add(list[i]); charsToRemove.add(list[i]); } else { chars.add(list[i]); } } return uniqueChar(chars, charsToRemove); } // Remove non-unique chars. public static String uniqueChar (ArrayList<String> uniqueChars, ArrayList<String> charsToRemove) { uniqueChars.removeAll(charsToRemove); return uniqueChars.get(0); } }
31.227273
69
0.466521
337d6437889cb313ccedda481ec13fa4979801e4
1,006
package com.xiaobai.polestar.scheduleconsole.models; import java.util.Date; /** * Title. * <p/> * Description. * * @author Bill Lv {@literal <billcc.lv@hotmail.com>} * @version 1.0 * @since 2015-10-17 */ public class Schedules { Long id; String name; String cron; String command; Boolean enabled; Date createTime; public Schedules(Long id, String name, String cron, String command, Boolean enabled, Date createTime) { this.id = id; this.name = name; this.cron = cron; this.command = command; this.enabled = enabled; this.createTime = createTime; } public Long getId() { return id; } public String getName() { return name; } public String getCron() { return cron; } public String getCommand() { return command; } public Boolean getEnabled() { return enabled; } public Date getCreateTime() { return createTime; } }
18.290909
107
0.588469
6b40f38524b6874ca3023d21ae6437232a7a6ebe
2,312
/* * Copyright 2017 Apereo * * 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.tle.web.wizard.standard.controls; import com.tle.core.guice.Bind; import com.tle.core.wizard.controls.HTMLControl; import com.tle.web.freemarker.annotations.ViewFactory; import com.tle.web.sections.SectionInfo; import com.tle.web.sections.SectionResult; import com.tle.web.sections.SectionUtils; import com.tle.web.sections.equella.component.MultiEditBox; import com.tle.web.sections.events.RenderEventContext; import com.tle.web.sections.js.ElementId; import com.tle.web.sections.standard.annotations.Component; import com.tle.web.wizard.controls.AbstractSimpleWebControl; import com.tle.web.wizard.controls.CMultiEditBox; import com.tle.web.wizard.render.WizardFreemarkerFactory; import javax.inject.Inject; @Bind public class MultiEditBoxWebControl extends AbstractSimpleWebControl { @ViewFactory(name = "wizardFreemarkerFactory") private WizardFreemarkerFactory viewFactory; @Inject @Component(stateful = false) private MultiEditBox multiEdit; private CMultiEditBox editBox; @Override public void setWrappedControl(HTMLControl control) { super.setWrappedControl(control); editBox = (CMultiEditBox) control; } @Override public SectionResult renderHtml(RenderEventContext context) throws Exception { multiEdit.setSize(editBox.getSize2()); multiEdit.setLangMap(context, editBox.getLangValues()); addDisabler(context, multiEdit); setGroupLabellNeeded(true); return viewFactory.createWizardResult(SectionUtils.renderSection(context, multiEdit), context); } @Override public void doEdits(SectionInfo info) { editBox.setLangValues(multiEdit.getLangMap(info)); } @Override protected ElementId getIdForLabel() { return multiEdit; } }
33.028571
99
0.781142
8b43e4f53fef52e43c19e37b7877bcc9b81482cf
213
package org.firstinspires.ftc.ppProject.RobotUtilities; public class MovementVars { public static double movement_x = 0; public static double movement_y = 0; public static double movement_turn = 0; }
26.625
55
0.760563
ac757aea06433dd8be19ac7b3b013c29264306ec
949
package kdu_jni; public class Jpx_fragment_list { static { System.loadLibrary("kdu_jni"); Native_init_class(); } private static native void Native_init_class(); protected long _native_ptr = 0; protected Jpx_fragment_list(long ptr) { _native_ptr = ptr; } public Jpx_fragment_list() { this(0); } public native boolean Exists() throws KduException; public native boolean Read_only() throws KduException; public native boolean Add_fragment(int _url_idx, long _offset, long _length) throws KduException; public native long Get_total_length() throws KduException; public native int Get_num_fragments() throws KduException; public native boolean Get_fragment(int _frag_idx, int[] _url_idx, long[] _offset, long[] _length) throws KduException; public native int Locate_fragment(long _pos, long[] _bytes_into_fragment) throws KduException; public native boolean Any_local_fragments() throws KduException; }
37.96
120
0.769231
f6d159d3977b2d2010ed8d4bf910d3b175de12d4
10,689
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.exoplayer.smoothstreaming; import android.net.Uri; import com.google.android.exoplayer.chunk.Format; import com.google.android.exoplayer.util.*; import java.util.List; // Referenced classes of package com.google.android.exoplayer.smoothstreaming: // SmoothStreamingManifest public static class SmoothStreamingManifest$StreamElement { public Uri buildRequestUri(int i, int j) { SmoothStreamingManifest.TrackElement atrackelement[] = tracks; // 0 0:aload_0 // 1 1:getfield #82 <Field SmoothStreamingManifest$TrackElement[] tracks> // 2 4:astore 5 boolean flag1 = true; // 3 6:iconst_1 // 4 7:istore 4 boolean flag; if(atrackelement != null) //* 5 9:aload 5 //* 6 11:ifnull 19 flag = true; // 7 14:iconst_1 // 8 15:istore_3 else //* 9 16:goto 21 flag = false; // 10 19:iconst_0 // 11 20:istore_3 Assertions.checkState(flag); // 12 21:iload_3 // 13 22:invokestatic #119 <Method void Assertions.checkState(boolean)> if(chunkStartTimes != null) //* 14 25:aload_0 //* 15 26:getfield #92 <Field List chunkStartTimes> //* 16 29:ifnull 37 flag = true; // 17 32:iconst_1 // 18 33:istore_3 else //* 19 34:goto 39 flag = false; // 20 37:iconst_0 // 21 38:istore_3 Assertions.checkState(flag); // 22 39:iload_3 // 23 40:invokestatic #119 <Method void Assertions.checkState(boolean)> if(j < chunkStartTimes.size()) //* 24 43:iload_2 //* 25 44:aload_0 //* 26 45:getfield #92 <Field List chunkStartTimes> //* 27 48:invokeinterface #88 <Method int List.size()> //* 28 53:icmpge 62 flag = flag1; // 29 56:iload 4 // 30 58:istore_3 else //* 31 59:goto 64 flag = false; // 32 62:iconst_0 // 33 63:istore_3 Assertions.checkState(flag); // 34 64:iload_3 // 35 65:invokestatic #119 <Method void Assertions.checkState(boolean)> String s = Integer.toString(tracks[i].format.bitrate); // 36 68:aload_0 // 37 69:getfield #82 <Field SmoothStreamingManifest$TrackElement[] tracks> // 38 72:iload_1 // 39 73:aaload // 40 74:getfield #125 <Field Format SmoothStreamingManifest$TrackElement.format> // 41 77:getfield #130 <Field int Format.bitrate> // 42 80:invokestatic #136 <Method String Integer.toString(int)> // 43 83:astore 5 String s1 = ((Long)chunkStartTimes.get(j)).toString(); // 44 85:aload_0 // 45 86:getfield #92 <Field List chunkStartTimes> // 46 89:iload_2 // 47 90:invokeinterface #140 <Method Object List.get(int)> // 48 95:checkcast #142 <Class Long> // 49 98:invokevirtual #145 <Method String Long.toString()> // 50 101:astore 6 s = chunkTemplate.replace("{bitrate}", ((CharSequence) (s))).replace("{Bitrate}", ((CharSequence) (s))).replace("{start time}", ((CharSequence) (s1))).replace("{start_time}", ((CharSequence) (s1))); // 51 103:aload_0 // 52 104:getfield #60 <Field String chunkTemplate> // 53 107:ldc1 #20 <String "{bitrate}"> // 54 109:aload 5 // 55 111:invokevirtual #151 <Method String String.replace(CharSequence, CharSequence)> // 56 114:ldc1 #23 <String "{Bitrate}"> // 57 116:aload 5 // 58 118:invokevirtual #151 <Method String String.replace(CharSequence, CharSequence)> // 59 121:ldc1 #26 <String "{start time}"> // 60 123:aload 6 // 61 125:invokevirtual #151 <Method String String.replace(CharSequence, CharSequence)> // 62 128:ldc1 #29 <String "{start_time}"> // 63 130:aload 6 // 64 132:invokevirtual #151 <Method String String.replace(CharSequence, CharSequence)> // 65 135:astore 5 return UriUtil.resolveToUri(baseUri, s); // 66 137:aload_0 // 67 138:getfield #58 <Field String baseUri> // 68 141:aload 5 // 69 143:invokestatic #157 <Method Uri UriUtil.resolveToUri(String, String)> // 70 146:areturn } public long getChunkDurationUs(int i) { if(i == chunkCount - 1) //* 0 0:iload_1 //* 1 1:aload_0 //* 2 2:getfield #90 <Field int chunkCount> //* 3 5:iconst_1 //* 4 6:isub //* 5 7:icmpne 15 { return lastChunkDurationUs; // 6 10:aload_0 // 7 11:getfield #102 <Field long lastChunkDurationUs> // 8 14:lreturn } else { long al[] = chunkStartTimesUs; // 9 15:aload_0 // 10 16:getfield #108 <Field long[] chunkStartTimesUs> // 11 19:astore_2 return al[i + 1] - al[i]; // 12 20:aload_2 // 13 21:iload_1 // 14 22:iconst_1 // 15 23:iadd // 16 24:laload // 17 25:aload_2 // 18 26:iload_1 // 19 27:laload // 20 28:lsub // 21 29:lreturn } } public int getChunkIndex(long l) { return Util.binarySearchFloor(chunkStartTimesUs, l, true, true); // 0 0:aload_0 // 1 1:getfield #108 <Field long[] chunkStartTimesUs> // 2 4:lload_1 // 3 5:iconst_1 // 4 6:iconst_1 // 5 7:invokestatic #165 <Method int Util.binarySearchFloor(long[], long, boolean, boolean)> // 6 10:ireturn } public long getStartTimeUs(int i) { return chunkStartTimesUs[i]; // 0 0:aload_0 // 1 1:getfield #108 <Field long[] chunkStartTimesUs> // 2 4:iload_1 // 3 5:laload // 4 6:lreturn } public static final int TYPE_AUDIO = 0; public static final int TYPE_TEXT = 2; public static final int TYPE_UNKNOWN = -1; public static final int TYPE_VIDEO = 1; private static final String URL_PLACEHOLDER_BITRATE_1 = "{bitrate}"; private static final String URL_PLACEHOLDER_BITRATE_2 = "{Bitrate}"; private static final String URL_PLACEHOLDER_START_TIME_1 = "{start time}"; private static final String URL_PLACEHOLDER_START_TIME_2 = "{start_time}"; private final String baseUri; public final int chunkCount; private final List chunkStartTimes; private final long chunkStartTimesUs[]; private final String chunkTemplate; public final int displayHeight; public final int displayWidth; public final String language; private final long lastChunkDurationUs; public final int maxHeight; public final int maxWidth; public final String name; public final int qualityLevels; public final String subType; public final long timescale; public final SmoothStreamingManifest.TrackElement tracks[]; public final int type; public SmoothStreamingManifest$StreamElement(String s, String s1, int i, String s2, long l, String s3, int j, int k, int i1, int j1, int k1, String s4, SmoothStreamingManifest.TrackElement atrackelement[], List list, long l1) { // 0 0:aload_0 // 1 1:invokespecial #56 <Method void Object()> baseUri = s; // 2 4:aload_0 // 3 5:aload_1 // 4 6:putfield #58 <Field String baseUri> chunkTemplate = s1; // 5 9:aload_0 // 6 10:aload_2 // 7 11:putfield #60 <Field String chunkTemplate> type = i; // 8 14:aload_0 // 9 15:iload_3 // 10 16:putfield #62 <Field int type> subType = s2; // 11 19:aload_0 // 12 20:aload 4 // 13 22:putfield #64 <Field String subType> timescale = l; // 14 25:aload_0 // 15 26:lload 5 // 16 28:putfield #66 <Field long timescale> name = s3; // 17 31:aload_0 // 18 32:aload 7 // 19 34:putfield #68 <Field String name> qualityLevels = j; // 20 37:aload_0 // 21 38:iload 8 // 22 40:putfield #70 <Field int qualityLevels> maxWidth = k; // 23 43:aload_0 // 24 44:iload 9 // 25 46:putfield #72 <Field int maxWidth> maxHeight = i1; // 26 49:aload_0 // 27 50:iload 10 // 28 52:putfield #74 <Field int maxHeight> displayWidth = j1; // 29 55:aload_0 // 30 56:iload 11 // 31 58:putfield #76 <Field int displayWidth> displayHeight = k1; // 32 61:aload_0 // 33 62:iload 12 // 34 64:putfield #78 <Field int displayHeight> language = s4; // 35 67:aload_0 // 36 68:aload 13 // 37 70:putfield #80 <Field String language> tracks = atrackelement; // 38 73:aload_0 // 39 74:aload 14 // 40 76:putfield #82 <Field SmoothStreamingManifest$TrackElement[] tracks> chunkCount = list.size(); // 41 79:aload_0 // 42 80:aload 15 // 43 82:invokeinterface #88 <Method int List.size()> // 44 87:putfield #90 <Field int chunkCount> chunkStartTimes = list; // 45 90:aload_0 // 46 91:aload 15 // 47 93:putfield #92 <Field List chunkStartTimes> lastChunkDurationUs = Util.scaleLargeTimestamp(l1, 0xf4240L, l); // 48 96:aload_0 // 49 97:lload 16 // 50 99:ldc2w #93 <Long 0xf4240L> // 51 102:lload 5 // 52 104:invokestatic #100 <Method long Util.scaleLargeTimestamp(long, long, long)> // 53 107:putfield #102 <Field long lastChunkDurationUs> chunkStartTimesUs = Util.scaleLargeTimestamps(list, 0xf4240L, l); // 54 110:aload_0 // 55 111:aload 15 // 56 113:ldc2w #93 <Long 0xf4240L> // 57 116:lload 5 // 58 118:invokestatic #106 <Method long[] Util.scaleLargeTimestamps(List, long, long)> // 59 121:putfield #108 <Field long[] chunkStartTimesUs> // 60 124:return } }
38.039146
200
0.56226
b2d4302f53fccd18d424b4dcb02a2d54f1cb362c
2,462
/******************************************************************************* * Copyright (c) 2012, 2013 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * ailitche - testing for embedded with FK OneToMany ******************************************************************************/ package org.eclipse.persistence.testing.models.jpa.ddlgeneration; import javax.persistence.AssociationOverride; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; @Entity public class PatentInvestigator { @Id private int id; @Embedded @AttributeOverride(name="description", column=@Column(name = "LAST_DESRIPTION")) @AssociationOverride(name="patent", joinColumns=@JoinColumn(name = "LAST_PATENT")) private PatentInvestigation last; @Embedded @AttributeOverride(name="description", column=@Column(name = "CURRENT_DESRIPTION")) @AssociationOverride(name="patent", joinColumns=@JoinColumn(name = "CURRENT_PATENT")) private PatentInvestigation current; @Embedded @AttributeOverride(name="description", column=@Column(name = "NEXT_DESRIPTION")) @AssociationOverride(name="patent", joinColumns=@JoinColumn(name = "NEXT_PATENT")) private PatentInvestigation next; public int getId() { return id; } public void setId(int id) { this.id = id; } public PatentInvestigation getLast() { return last; } public void setLastCompleted(PatentInvestigation last) { this.last = last; } public PatentInvestigation getCurrent() { return current; } public void setCurrent(PatentInvestigation current) { this.current = current; } public PatentInvestigation getNext() { return next; } public void setNextPlanned(PatentInvestigation next) { this.next = next; } }
35.681159
89
0.675467
79415400c590d1719b7fddeedcaa2ff94f0497e1
2,298
/** * Copyright 2017 FuBaBaz Team. * * 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.fubabaz.rpm.service; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.InvalidPropertiesFormatException; import java.util.Locale; import java.util.Map; import java.util.Properties; import org.fubabaz.rpm.exception.SystemException; /** * @author ejpark * */ public class QueryManager { private Map<String, String> queryMap = new HashMap<String, String>(); private final String path = "query"; public QueryManager() { load(path); } private void load(String path) { File dir = new File(Thread.currentThread().getContextClassLoader().getResource(path).getFile()); if (dir == null || !dir.exists()) { throw new IllegalArgumentException(path + " not found."); } if (dir.isDirectory()) { File[] files = dir.listFiles(); for (File file : files) { loadFile(file); } } else { loadFile(dir); } } private void loadFile(File file) { InputStream in = null; Properties props = new Properties(); try { String fileName = file.getName(); int dotIndex = fileName.lastIndexOf('.'); String extension = fileName.substring(dotIndex + 1).toLowerCase(Locale.ENGLISH); if("xml".equals(extension)) { in = new FileInputStream(file); props.loadFromXML(in); } } catch (InvalidPropertiesFormatException e) { throw new SystemException(e); } catch (IOException e) { throw new SystemException(e); } finally { try { in.close(); } catch (IOException e) { // Ignore. } } queryMap.putAll(new HashMap(props)); } public String getQuery(String key) { return this.queryMap.get(key); } }
25.533333
98
0.692776
75817cff7c27789ad8f4656a94d5298bf60455ba
747
package com.xhyan.zero.cloud.wallet; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.scheduling.annotation.EnableScheduling; /** * spring cloud eureka server 启动程序 * * @author yanliwei */ //@EnableFeignClients //@EnableHystrix //@EnableHystrixDashboard @EnableScheduling @EnableDiscoveryClient @SpringBootApplication //@MapperScan(basePackages = "com.xhyan.zero.cloud.wallet.mapper") public class WalletApplication { public static void main(String[] args) { new SpringApplicationBuilder(WalletApplication.class).web(true).run(args); } }
27.666667
82
0.803213
449e5c281194c6c1af2a1ee89689627c4780009a
16,509
package uk.ac.ebi.quickgo.client.service.search.ontology; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import uk.ac.ebi.quickgo.client.QuickGOREST; import uk.ac.ebi.quickgo.ontology.common.OntologyDocument; import uk.ac.ebi.quickgo.ontology.common.OntologyRepository; import uk.ac.ebi.quickgo.ontology.common.OntologyType; import uk.ac.ebi.quickgo.rest.search.SearchControllerSetup; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static uk.ac.ebi.quickgo.ontology.common.OntologyFields.Facetable; import static uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl.MAX_PAGE_NUMBER; @SpringBootTest(classes = {QuickGOREST.class}) public class OntologySearchIT extends SearchControllerSetup { private static final String ONTOLOGY_RESOURCE_URL = "/internal/search/ontology"; private static final String ASPECT_PARAM = "aspect"; private static final String TYPE_PARAM = "ontologyType"; private static final String BIOLOGICAL_PROCESS = "Process"; private static final String MOLECULAR_FUNCTION = "Function"; private static final String COMPONENT = "Component"; @Autowired private OntologyRepository repository; @Before public void setUp() throws Exception { repository.deleteAll(); resourceUrl = ONTOLOGY_RESOURCE_URL; } // response format --------------------------------------------------------- @Test public void requestWhichFindsNothingReturnsValidResponse() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); saveToRepository(doc1); checkValidEmptyResultsResponse("doesn't exist"); } @Test public void requestWhichAsksForPage0WithLimit0Returns400Response() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); saveToRepository(doc1); checkInvalidPageInfoInResponse("aaaa", 0, 0, HttpStatus.SC_BAD_REQUEST); } @Test public void pageRequestHigherThanPaginationLimitReturns400() throws Exception { int totalEntries = MAX_PAGE_NUMBER + 1; int pageSize = 1; int pageNumWhichIsTooHigh = totalEntries; saveNDocs(totalEntries); checkInvalidPageInfoInResponse("bbbb", pageNumWhichIsTooHigh, pageSize, HttpStatus.SC_BAD_REQUEST); } @Test public void requestWithNegativePageNumberReturns400Response() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go3"); saveToRepository(doc1, doc2, doc3); int pageNum = -1; int entriesPerPage = 10; checkInvalidPageInfoInResponse("go", pageNum, entriesPerPage, HttpStatus.SC_BAD_REQUEST); } @Test public void requestWithNegativeLimitNumberReturns400Response() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go3"); saveToRepository(doc1, doc2, doc3); int pageNum = 1; int entriesPerPage = -1; checkInvalidPageInfoInResponse("go", pageNum, entriesPerPage, HttpStatus.SC_BAD_REQUEST); } @Test public void requestForOntologyFindsAllFieldsInModelPopulated() throws Exception { String id = "GO:0000001"; String name = "go1"; boolean isObsolete = true; OntologyDocument doc1 = createGODocWithObsolete(id, name, isObsolete); saveToRepository(doc1); checkResultsBodyResponse("go") .andExpect(jsonPath("$.results[0].id", is(id))) .andExpect(jsonPath("$.results[0].name", is(name))) .andExpect(jsonPath("$.results[0].isObsolete", is(isObsolete))); } @Test public void requestForFirstPageWithLimitOf10ReturnsAllResults() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go3"); saveToRepository(doc1, doc2, doc3); int pageNum = 1; int entriesPerPage = 3; checkValidPageInfoInResponse("go", pageNum, entriesPerPage); } @Test public void requestForSecondPageWithLimitOf2ReturnsLastEntry() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go3"); saveToRepository(doc1, doc2, doc3); int pageNum = 2; int entriesPerPage = 2; checkValidPageInfoInResponse("go", pageNum, entriesPerPage); } @Test public void requestForPageThatIsLargerThanTotalNumberOfPagesInResponseReturns400Response() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go3"); saveToRepository(doc1, doc2, doc3); int pageNum = 3; int entriesPerPage = 2; checkInvalidPageInfoInResponse("go", pageNum, entriesPerPage, HttpStatus.SC_BAD_REQUEST); } // facets --------------------------------------------------------- @Test public void requestWithInValidFacetFieldReturns400Response() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go3"); saveToRepository(doc1, doc2, doc3); checkInvalidFacetResponse("go", "incorrect_field"); } @Test public void requestWithValidFacetFieldReturnsResponseWithFacetInResult() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go3"); saveToRepository(doc1, doc2, doc3); checkValidFacetResponse("go", ASPECT_PARAM); } @Test public void requestWithMultipleValidFacetFieldsReturnsResponseWithMultipleFacetsInResult() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go3"); saveToRepository(doc1, doc2, doc3); checkValidFacetResponse("go", Facetable.ASPECT, Facetable.ONTOLOGY_TYPE, Facetable.IS_OBSOLETE); } // filter queries --------------------------------------------------------- @Test public void requestWithInvalidFilterQueryIgnoresFilter() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go3"); saveToRepository(doc1, doc2, doc3); Param filterParam = new Param("thisFieldDoesNotExist", BIOLOGICAL_PROCESS); checkValidFilterQueryResponse("go", 3, filterParam); } @Test public void requestWithAFilterQueryReturnsFilteredResponse() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); doc1.aspect = BIOLOGICAL_PROCESS; OntologyDocument doc2 = createGODoc("GO:0000002", "go function 2"); doc2.aspect = MOLECULAR_FUNCTION; OntologyDocument doc3 = createGODoc("GO:0000003", "go function 3"); doc3.aspect = BIOLOGICAL_PROCESS; repository.save(doc1); repository.save(doc2); repository.save(doc3); Param filterParam = new Param(ASPECT_PARAM, BIOLOGICAL_PROCESS); checkValidFilterQueryResponse("go function", 2, filterParam); } @Test public void requestWith2FilterQueriesThatFilterOutAllResults() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); doc1.aspect = BIOLOGICAL_PROCESS; doc1.ontologyType = "GO"; OntologyDocument doc2 = createGODoc("GO:0000002", "go function 2"); doc2.aspect = MOLECULAR_FUNCTION; doc2.ontologyType = "GO"; OntologyDocument doc3 = createGODoc("GO:0000003", "go function 3"); doc3.aspect = BIOLOGICAL_PROCESS; doc3.ontologyType = "GO"; repository.save(doc1); repository.save(doc2); repository.save(doc3); Param fq1 = new Param(ASPECT_PARAM, BIOLOGICAL_PROCESS); Param fq2 = new Param(TYPE_PARAM, "eco"); checkValidFilterQueryResponse("go function", 0, fq1, fq2); } @Test public void requestWithFilterQueryThatDoesNotFilterOutAnyEntryReturnsAllResults() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); doc1.aspect = BIOLOGICAL_PROCESS; OntologyDocument doc2 = createGODoc("GO:0000002", "go function 2"); doc2.aspect = BIOLOGICAL_PROCESS; OntologyDocument doc3 = createGODoc("GO:0000003", "go function 3"); doc3.aspect = BIOLOGICAL_PROCESS; repository.save(doc1); repository.save(doc2); repository.save(doc3); Param fq = new Param(ASPECT_PARAM, BIOLOGICAL_PROCESS); checkValidFilterQueryResponse("go function", 3, fq); } @Test public void requestWith1ValidFilterQueryReturnsFilteredResponse() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); doc1.aspect = BIOLOGICAL_PROCESS; OntologyDocument doc2 = createGODoc("GO:0000002", "go function 2"); doc2.aspect = MOLECULAR_FUNCTION; OntologyDocument doc3 = createGODoc("GO:0000003", "go function 3"); doc3.aspect = BIOLOGICAL_PROCESS; repository.save(doc1); repository.save(doc2); repository.save(doc3); Param fq = new Param(ASPECT_PARAM, BIOLOGICAL_PROCESS); checkValidFilterQueryResponse("go function", 2, fq) .andExpect(jsonPath("$.results[0].id").value("GO:0000001")) .andExpect(jsonPath("$.results[1].id").value("GO:0000003")); } @Test public void requestWithValidAspectComponentFilterQueryReturnsFilteredResponse() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); doc1.aspect = COMPONENT; OntologyDocument doc2 = createGODoc("GO:0000002", "go function 1"); doc2.aspect = MOLECULAR_FUNCTION; OntologyDocument doc3 = createGODoc("GO:0000003", "go function 2"); doc3.aspect = COMPONENT; repository.save(doc1); repository.save(doc2); repository.save(doc3); Param fq = new Param(ASPECT_PARAM, COMPONENT); checkValidFilterQueryResponse("go function", 2, fq) .andExpect(jsonPath("$.results[0].id").value("GO:0000001")) .andExpect(jsonPath("$.results[1].id").value("GO:0000003")); } @Test public void requestWithInvalidAspectFilterQueryReturns500() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); doc1.aspect = COMPONENT; OntologyDocument doc2 = createGODoc("GO:0000002", "go function 1"); doc2.aspect = MOLECULAR_FUNCTION; repository.save(doc1); repository.save(doc2); String invalidAspect = "biological_process"; Param fq = new Param(ASPECT_PARAM, invalidAspect); checkInvalidFilterQueryResponse("go function", fq) .andExpect(status().is(HttpStatus.SC_BAD_REQUEST)); } // highlighting ------------------------------------------------ @Test public void requestWithHighlightingOnAndOneHitReturnsValidResponse() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go function 2"); repository.save(doc1); repository.save(doc2); checkValidHighlightOnQueryResponse("function 2", "GO:0000002", "GO:0000001"); } @Test public void requestWithHighlightingOnAndTwoHitsReturnsValidResponse() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go anotherFunction 2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go anotherFunction 3"); repository.save(doc1); repository.save(doc2); repository.save(doc3); checkValidHighlightOnQueryResponse("anotherFunction", "GO:0000002", "GO:0000003"); } @Test public void requestWithHighlightingOnAndZeroHitsReturnsValidResponse() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go function 2"); repository.save(doc1); repository.save(doc2); checkValidHighlightOnQueryResponse("Southampton"); } @Test public void requestWithHighlightingOffAndOneHitReturnsValidResponse() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go function 2"); repository.save(doc1); repository.save(doc2); checkValidHighlightOffQueryResponse("go function 2", 2); } @Test public void requestWithHighlightingOffAndOnZeroHitsReturnsValidResponse() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go function 2"); repository.save(doc1); repository.save(doc2); checkValidHighlightOffQueryResponse("Southampton", 0); } @Test public void requestWithHighlightingOnReturnsTwoHighlightedValuesInResponse() throws Exception { OntologyDocument doc1 = createGODoc("GO:0000001", "go function 1"); OntologyDocument doc2 = createGODoc("GO:0000002", "go anotherFunction 2"); OntologyDocument doc3 = createGODoc("GO:0000003", "go anotherFunction 3"); repository.save(doc1); repository.save(doc2); repository.save(doc3); checkValidHighlightOnQueryResponse("anotherFunction", "GO:0000002", "GO:0000003") .andExpect(jsonPath("$.results.*.id", containsInAnyOrder("GO:0000002", "GO:0000003"))) .andExpect(jsonPath("$.highlighting.*.id", containsInAnyOrder("GO:0000002", "GO:0000003"))) .andExpect(jsonPath("$.highlighting.*.matches.*.field", containsInAnyOrder("name", "name"))) .andExpect(jsonPath("$.highlighting[0].matches[0].values[0]", containsString("anotherFunction"))) .andExpect(jsonPath("$.highlighting[1].matches[0].values[0]", containsString("anotherFunction"))); } private void saveToRepository(OntologyDocument... documents) { repository.saveAll(asList(documents)); } private void saveNDocs(int n) { List<OntologyDocument> documents = IntStream.range(1, n + 1) .mapToObj(i -> createGODoc(String.valueOf(i), "name " + n)) .collect(Collectors.toList()); repository.saveAll(documents); } private OntologyDocument createGODoc(String id, String name) { OntologyDocument od = new OntologyDocument(); od.id = id; od.name = name; od.ontologyType = OntologyType.GO.name(); return od; } private OntologyDocument createGODocWithObsolete(String id, String name, boolean isObsolete) { OntologyDocument doc = createGODoc(id, name); doc.isObsolete = isObsolete; return doc; } }
38.753521
114
0.676237
104f8567a6d6e3b1a9582a0673e0adf7a12d618a
3,793
package org.nocket.component.form.beans; import gengui.util.SevereGUIException; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Resolves properties of the specified entity class. * * Usage: * * <pre> * ... * final Map<String, BeanInfoPropertyDescriptor> entityProperties = * new BeanInfoResolver(my.example.package.MyPojo.class).resolveProperties() * ... * </pre> * * It works recursively, with respect to cycle references. * * @author blaz02 */ public class BeanInfoResolver { final private static Logger log = LoggerFactory.getLogger(BeanInfoResolver.class); final private static List<String> IGNORE = Arrays.asList("java.lang", "java.util.Date", "java.math"); private Class<?> entityClass; private Set<Class<?>> alredyResolved; /** * Constructor. * * @param entityClass * Class which has to be resolved. */ public BeanInfoResolver(Class<?> entityClass) { this(entityClass, new HashSet<Class<?>>()); } /** * Friendly constructor for recursive resolving. * * @param entityClass * @param alreadyResolved */ BeanInfoResolver(Class<?> entityClass, Set<Class<?>> alreadyResolved) { this.entityClass = entityClass; this.alredyResolved = alreadyResolved; } /** * Performs property resolving of the entity class. * * @return Map with the all information about class properties. Key is a * string with a full class name and a property name i.e.: * "my.example.package.MyPojo.propertyName". */ public HashMap<String, BeanInfoPropertyDescriptor> resolveProperties() { if (log.isDebugEnabled()) { log.debug("Analyzing: " + entityClass.getCanonicalName()); } alredyResolved.add(entityClass); HashMap<String, BeanInfoPropertyDescriptor> entityProperties = new HashMap<String, BeanInfoPropertyDescriptor>(); BeanInfo entityBeanInfo; try { entityBeanInfo = Introspector.getBeanInfo(entityClass); } catch (IntrospectionException ex) { throw new SevereGUIException(ex); } for (PropertyDescriptor p : entityBeanInfo.getPropertyDescriptors()) { entityProperties.put(getPropertyPath(p), new BeanInfoPropertyDescriptor(entityClass, p)); // Decide if a property should be resolved recursive if (doRecursive(p.getPropertyType()) && !isClassAlreadyResolved(p.getPropertyType())) entityProperties.putAll(new BeanInfoResolver(p.getPropertyType(), this.alredyResolved) .resolveProperties()); } return entityProperties; } private String getPropertyPath(PropertyDescriptor p) { return entityClass.getName() + "." + p.getName(); } private boolean doRecursive(Class<?> entityClass) { if (entityClass == null || entityClass.isEnum()) return false; String canonicalName = entityClass.getCanonicalName(); for (String s : IGNORE) { if (canonicalName.startsWith(s)) return false; } return true; } /** * @param entityClass * Class name * * @return True if class has been resolved already. This is important to * avoid cycle references. */ private boolean isClassAlreadyResolved(Class<?> entityClass) { return alredyResolved.contains(entityClass); } }
30.344
121
0.651727
aecee4dc236f01ccc3909e318306c24770309964
2,544
package exercise23; class NumberToWords { public static void numberToWords(int num) { if (num < 0) { System.out.println("Invalid Value"); } //reverse(num) will truncate any of the trailing zero hence we need to //remember the digit count before that int digitCount = getDigitCount(num); //we need to reverse the num otherwise it will print in reverse order num = reverse(num); while (digitCount > 0) { //get last digit int lastDigit = num % 10; num /= 10; digitCount--; switch (lastDigit) { case 0: System.out.println("Zero"); break; case 1: System.out.println("One"); break; case 2: System.out.println("Two"); break; case 3: System.out.println("Three"); break; case 4: System.out.println("Four"); break; case 5: System.out.println("Five"); break; case 6: System.out.println("Six"); break; case 7: System.out.println("Seven"); break; case 8: System.out.println("Eight"); break; case 9: System.out.println("Nine"); break; default: System.out.println("Something went wrong"); break; } } } //courtesy : https://www.geeksforgeeks.org/reverse-digits-integer-overflow-handled/ public static int reverse(int num) { int reverseNum = 0; while (num != 0) { int lastDigit = num % 10; reverseNum = reverseNum * 10 + lastDigit; num /= 10; } return reverseNum; //Below is bit level operations and is not what we need here // return Integer.reverse(num); } public static int getDigitCount(int num) { if (num < 0) { return -1; } if (num == 0) { return 1; } int count = 0; while (num > 0) { count++; num /= 10; } return count; } // write your code here }
28.58427
87
0.424921
d92158ea39d44596bc75b29ab3b8a286ea49d90c
1,914
/* * 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 at.rodrigo.api.gateway.cache; import at.rodrigo.api.gateway.entity.Api; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.map.IMap; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component @Slf4j public class NewApiManager { @Autowired private HazelcastInstance hazelcastInstance; @Autowired private NewApiListener newApiListener; @PostConstruct public void addListener() { getCachedApi().addEntryListener( newApiListener, true ); } private IMap<String, Api> getCachedApi() { return hazelcastInstance.getMap(CacheConstants.API_IMAP_NAME); } public Api getApiByContext(String context) { IMap<String, Api> iMap = getCachedApi(); for(String id : iMap.keySet()) { Api api = iMap.get(id); if(api.getContext().equals(context)) { return api; } } return null; } }
33
79
0.702717
a3e9e10fecd22940dca01c6043f1ff61bbf73772
1,936
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.util.json; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * A LinkedHashMap of String to Object, which is the variety most often useful * for JSON Serialization purposes For added usefulness, in addition to the * standard Map methods, also has an add method that will create a List with the * given key (or use one that already exists), and then add the value to that * List. Any entries with null values will be omitted upon json serialization. */ public class JsonFriendlyMap extends LinkedHashMap<Object, Object> { public JsonFriendlyMap() { } public JsonFriendlyMap(Map<? extends Object, ? extends Object> m) { super(m); } private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") public <T> void add(String key, T value) { Object oldValue = get(key); List<T> valueList = null; if (oldValue == null) { valueList = new ArrayList<T>(); } else if (oldValue.getClass().equals(value.getClass())) { valueList = new ArrayList<T>(); valueList.add((T) oldValue); } else { valueList = (List<T>) oldValue; } valueList.add(value); put(key, valueList); } }
32.813559
80
0.677686
1507054328239eb623ceae9f6dd51482494eb9fb
699
package org.opencb.bionetdb.server.rest; import io.swagger.annotations.Api; import org.opencb.bionetdb.server.exception.VersionException; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; @Path("/{apiVersion}/analysis") @Produces("application/json") @Api(value = "Analysis", position = 1, description = "Methods for working with 'nodes'") public class AnalysisWSServer extends GenericRestWSServer { public AnalysisWSServer(@Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws VersionException { super(uriInfo, hsr); } }
29.125
88
0.742489
372702f89abd5e6d136c15065ac2fdc6e6f24f51
1,554
package com.patnox.covidtritest.countries; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(path = "api/v1/country") public class CountryController { private final CountryService countryService; @Autowired public CountryController(CountryService countryService) { this.countryService = countryService; } @GetMapping public List<Country> getAll() { return countryService.getAllCountries(); } @GetMapping(path = "{countryId}") public Country getCountry(@PathVariable("countryId") Long countryId) { return countryService.getCountry(countryId); } @PostMapping public void createNewCountry(@RequestBody Country newCountry) { countryService.addNewCountry(newCountry); } @DeleteMapping(path = "{countryId}") public void deleteCountry(@PathVariable("countryId") Long countryId) { countryService.deleteCountry(countryId); } @PutMapping(path = "{countryId}") public void updateCountry(@PathVariable("countryId") Long countryId, @RequestParam(required = false) Long product_id, @RequestParam(required = false) Long quantity, @RequestParam(required = false) Boolean is_fullfilled, @RequestParam(required = false) String date_ordered, @RequestParam(required = false) String date_fullfilled, @RequestParam(required = false) Boolean is_deleted ) { countryService.updateCountry(countryId, product_id, quantity, is_fullfilled, date_ordered, date_fullfilled, is_deleted); } }
27.75
122
0.771557
ea3fa86d5fc3589cbca6a9e312d682ce859e1741
541
package com.google.android.gms.internal.ads; public final class zzbnq implements zzdti<zzbpb> { /* renamed from: a */ private final zzbnk f25623a; public zzbnq(zzbnk zzbnk) { this.f25623a = zzbnk; } /* renamed from: a */ public static zzbpb m27303a(zzbnk zzbnk) { zzbpb c = zzbnk.mo30752c(); zzdto.m30114a(c, "Cannot return null from a non-@Nullable @Provides method"); return c; } public final /* synthetic */ Object get() { return m27303a(this.f25623a); } }
23.521739
85
0.619224
07a401f6f8c7f34c6067e3e5719ee3d11db1e9f8
2,357
/* * Copyright 2018 Shinya Mochida * * Licensed under the Apache License,Version2.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.mikeneck.youtrack; import static org.asynchttpclient.Dsl.asyncHttpClient; import org.asynchttpclient.AsyncHttpClient; import org.jetbrains.annotations.NotNull; import org.mikeneck.youtrack.api.issue.create.CreateNewIssue; import org.mikeneck.youtrack.api.project.GetAccessibleProjects; import org.mikeneck.youtrack.api.project.YouTrackProject; import org.mikeneck.youtrack.request.RequestContext; import org.mikeneck.youtrack.request.http.AsyncHttpClientBackedHttpClient; import org.mikeneck.youtrack.request.http.HttpClient; public final class YouTrack implements AutoCloseable { private final RequestContext context; private YouTrack( @NotNull final HttpClient client, @NotNull final YouTrackConfiguration configuration) { this.context = new RequestContext(client, configuration.getAccessToken(), configuration.getBaseUrl()); } private YouTrack( @NotNull final AsyncHttpClient client, @NotNull final YouTrackConfiguration configuration) { this(AsyncHttpClientBackedHttpClient.with(client), configuration); } private YouTrack() { this(asyncHttpClient(), YouTrackConfiguration.load()); } @NotNull public static YouTrack getInstance() { return new YouTrack(); } @NotNull public GetAccessibleProjects getAccessibleProjects() { return GetAccessibleProjects.noVerbose(context); } @NotNull public CreateNewIssue.Builder createNewIssueInProject(final YouTrackProject project) { return CreateNewIssue.newIssueBuilder(context, project); } @NotNull public CreateNewIssue.Builder createNewIssueInProject(final String projectId) { return CreateNewIssue.newIssueBuilder(context, projectId); } @Override public void close() throws Exception { context.close(); } }
32.287671
98
0.779381
22b226d8d11fa884afdc43903c10bd7bf545c8e1
8,031
/* * Copyright 2018 ELIXIR EGA * * 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 eu.elixir.ega.ebi.reencryptionmvc.service.internal; import com.google.common.base.Strings; import eu.elixir.ega.ebi.reencryptionmvc.domain.Format; import eu.elixir.ega.ebi.reencryptionmvc.service.KeyService; import eu.elixir.ega.ebi.reencryptionmvc.service.ResService; import htsjdk.samtools.seekablestream.SeekableBasicAuthHTTPStream; import htsjdk.samtools.seekablestream.SeekableFileStream; import htsjdk.samtools.seekablestream.SeekableHTTPStream; import io.minio.MinioClient; import io.minio.errors.*; import io.minio.http.Method; import lombok.extern.slf4j.Slf4j; import no.uio.ifi.crypt4gh.stream.Crypt4GHOutputStream; import no.uio.ifi.crypt4gh.stream.SeekableStreamInput; import org.apache.commons.crypto.stream.CtrCryptoOutputStream; import org.apache.commons.crypto.stream.PositionedCryptoInputStream; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.BoundedInputStream; import org.apache.commons.lang.StringUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.crypto.codec.Hex; import org.springframework.stereotype.Service; import org.xmlpull.v1.XmlPullParserException; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Security; import java.util.Properties; /** * @author asenf */ @Service @Slf4j @Profile("LocalEGA") @EnableDiscoveryClient public class LocalEGAServiceImpl implements ResService { private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; private static final int MAX_EXPIRATION_TIME = 7 * 24 * 3600; @Value("${ega.ebi.aws.endpoint.url:#{null}}") private String s3URL; @Value("${ega.ebi.aws.bucket:lega}") private String s3Bucket; @Value("${ega.ebi.aws.access.key:#{null}}") private String s3Key; @Value("${ega.ebi.aws.access.secret:#{null}}") private String s3Secret; @Autowired private KeyService keyService; private MinioClient s3Client; @PostConstruct private void init() throws InvalidPortException, InvalidEndpointException { Security.addProvider(new BouncyCastleProvider()); if (s3URL != null && s3Key != null && s3Secret != null) { s3Client = new MinioClient(s3URL, s3Key, s3Secret); } } @Override public long transfer(String sourceFormat, String sourceKey, String sourceIV, String destinationFormat, String destinationKey, String destinationIV, String fileLocation, long startCoordinate, long endCoordinate, long fileSize, String httpAuth, String id, HttpServletRequest request, HttpServletResponse response) { long transferSize = 0; InputStream inputStream; OutputStream outputStream; String sessionId= Strings.isNullOrEmpty(request.getHeader("Session-Id"))? "" : request.getHeader("Session-Id") + " "; try { inputStream = getInputStream(Hex.decode(sourceKey), Hex.decode(sourceIV), fileLocation, httpAuth, startCoordinate, endCoordinate); outputStream = getOutputStream(response.getOutputStream(), Format.valueOf(destinationFormat.toUpperCase()), destinationKey, destinationIV); } catch (Exception e) { log.error(sessionId + e.getMessage(), e); throw new RuntimeException(e); } response.setStatus(200); response.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE); try { transferSize = IOUtils.copyLarge(inputStream, outputStream); inputStream.close(); outputStream.flush(); return transferSize; } catch (IOException e) { log.error(sessionId + e.getMessage(), e); throw new RuntimeException(e); } } protected InputStream getInputStream(byte[] key, byte[] iv, String fileLocation, String httpAuth, long startCoordinate, long endCoordinate) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidExpiresRangeException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException, InvalidArgumentException { InputStream inputStream; if (fileLocation.startsWith("http")) { // some external URL if (StringUtils.isNotEmpty(httpAuth)) { inputStream = new SeekableBasicAuthHTTPStream(new URL(fileLocation), httpAuth); } else { inputStream = new SeekableHTTPStream(new URL(fileLocation)); } } else if (fileLocation.startsWith("/")) { // absolute file path inputStream = new SeekableFileStream(new File(fileLocation)); } else { // S3 object String presignedObjectUrl = s3Client.getPresignedObjectUrl(Method.GET, s3Bucket, fileLocation, MAX_EXPIRATION_TIME, null); inputStream = new SeekableHTTPStream(new URL(presignedObjectUrl)); } // 32 bytes for SHA256 checksum - it's prepended to the file by lega-cryptor (LocalEGA python encryption tool) SeekableStreamInput seekableStreamInput = new SeekableStreamInput(inputStream, DEFAULT_BUFFER_SIZE, 32); PositionedCryptoInputStream positionedStream = new PositionedCryptoInputStream(new Properties(), seekableStreamInput, key, iv, 32); positionedStream.seek(startCoordinate); return endCoordinate != 0 && endCoordinate > startCoordinate ? new BoundedInputStream(positionedStream, endCoordinate - startCoordinate) : positionedStream; } protected OutputStream getOutputStream(OutputStream outputStream, Format targetFormat, String targetKey, String targetIV) throws IOException, PGPException { switch (targetFormat) { case CRYPT4GH: return new Crypt4GHOutputStream(outputStream, keyService.getPublicKey(targetKey)); case AES: return new CtrCryptoOutputStream(new Properties(), outputStream, targetKey.getBytes(), targetIV.getBytes()); default: return outputStream; } } }
42.946524
327
0.673764
9b6fb3420132b60e261c50678904824112693308
1,675
package com.goldze.mvvmhabit.ui.set; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.widget.CompoundButton; import com.goldze.mvvmhabit.BR; import com.goldze.mvvmhabit.R; import com.goldze.mvvmhabit.app.AppViewModelFactory; import com.goldze.mvvmhabit.databinding.ActivitySetBinding; import me.goldze.mvvmhabit.base.BaseActivity; public class SetActivity extends BaseActivity<ActivitySetBinding, SetViewModel> { //ActivityLoginBinding类是databinding框架自定生成的,对应activity_login.xml @Override public int initContentView(Bundle savedInstanceState) { return R.layout.activity_set; } @Override public int initVariableId() { return BR.viewModel; } @Override public SetViewModel initViewModel() { //使用自定义的ViewModelFactory来创建ViewModel,如果不重写该方法,则默认会调用LoginViewModel(@NonNull Application application)构造方法 AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication()); return ViewModelProviders.of(this, factory).get(SetViewModel.class); } @Override public void initViewObservable() { if (viewModel.entity.get().getRateDay() == 0.03) binding.rb0.setChecked(true); else binding.rb1.setChecked(true); if (viewModel.entity.get().isShowChange()) binding.cb.setChecked(true); binding.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { viewModel.entity.get().setShowChange(isChecked); } }); } }
33.5
112
0.717612
104439d30e935af372f156fea883d269fc0eb690
110
package net.viperfish.latinQuiz.core; public interface Answer { @Override boolean equals(Object arg0); }
12.222222
37
0.763636
3d184d69a744a451083c032ddf6e085672557162
1,726
/******************************************************************************* * Copyright Duke Comprehensive Cancer Center and SemanticBits * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/c3pr/LICENSE.txt for details. ******************************************************************************/ package edu.duke.cabig.c3pr.esb; /** * Callback methods for tracking message through * the ESB * <p/> * <p/> * <p/> * Created by IntelliJ IDEA. * User: kherm * Date: Nov 15, 2007 * Time: 11:28:07 AM * To change this template use File | Settings | File Templates. */ public interface MessageWorkflowCallback { /** * Handle message sent to ESB successfully * * @param objectId id of the domain object (external Identifier) */ public void messageSendSuccessful(String objectId); /** * Message failed * * @param objectId id of the domain object (external Identifier) */ public void messageSendFailed(String objectId); /** * Message acknowledgment failed * * @param objectId id of the domain object (external Identifier) */ public void messageAcknowledgmentFailed(String objectId); /** * Confirm that message was sent to CCTS Hub and confirmation * was received * * @param objectId id of the domain object (external Identifier) */ public void messageSendConfirmed(String objectId); /** * Records any error if received * * @param objectId id of the domain object (external Identifier) */ public void recordError(String objectId, ResponseErrors errors); }
29.254237
81
0.582271
35cf4e34eb0796462615310fa736658425dae351
1,271
package string_handle; import java.io.BufferedReader; import java.io.InputStreamReader; /** * * @author minchoba * 백준 10205번: 헤라클레스와 히드라 * * @see https://www.acmicpc.net/problem/10205/ * */ public class Boj10205 { private static final char[] CUT = {'b', 'c'}; private static final String ANS = "Data Set "; private static final String COLON = ":"; private static final String NEW_LINE = "\n"; public static void main(String[] args) throws Exception{ // 버퍼를 통한 값 입력 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int K = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); int loop = 1; while(K-- > 0){ int h = Integer.parseInt(br.readLine()); // 머리의 갯수 String head = br.readLine(); // 머리 갯수 방식 int leng = head.length(); for(int i = 0; i < leng; i++){ if(h == 0){ // 제거 할 머리가 없다면 종료 break; } if(head.charAt(i) == CUT[0]){ // 머리자르고 불로지짐 h--; } if(head.charAt(i) == CUT[1]){ // 머리 자르기만함 h++; } } sb.append(ANS).append(loop).append(COLON).append(NEW_LINE); // 결과를 버퍼에 담음 sb.append(h).append(NEW_LINE).append(NEW_LINE); loop++; } System.out.println(sb.toString()); // 결과값 한번에 출력 } }
22.696429
77
0.599528
1160df9ccab895d13a3db20e85dce449d7ac4877
1,384
package com.manos.prototype.search; import java.time.LocalDateTime; import com.pastelstudios.db.GeneratedSearchConstraint; import com.pastelstudios.db.SearchConstraint; public class ProductSearch { private Integer statusId = null; private LocalDateTime fromDate = null; private LocalDateTime toDate = null; private String projectName = null; @SearchConstraint(value = "project.projectName") public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } @SearchConstraint(value = "productStatus.id") public Integer getStatusId() { return statusId; } public void setStatusId(Integer statusId) { this.statusId = statusId; } public LocalDateTime getFromDate() { return fromDate; } public void setFromDate(LocalDateTime fromDate) { this.fromDate = fromDate; } public LocalDateTime getToDate() { return toDate; } public void setToDate(LocalDateTime toDate) { this.toDate = toDate; } @GeneratedSearchConstraint public String getDateRangeSearchConstraint() { if (fromDate != null && toDate != null) { return "product.createdAt BETWEEN :fromDate AND :toDate";// emit the first AND } else if (fromDate != null) { return "product.createdAt >= :fromDate"; } else if (toDate != null) { return "product.createdAt <= :toDate"; } return null; } }
21.968254
81
0.734827
3a5bb540d53ed1dcc697e129f28454b090ed85f9
2,447
/* * @项目名称: 出口扫码付 * @文件名称: DownLoadCompleteReceiver.java * @Copyright: 2016 悦畅科技有限公司. All rights reserved. * 注意:本内容仅限于悦畅科技有限公司内部传阅,禁止外泄以及用于其他的商业目的 */ package com.ddu.icore.util.sys; import android.app.DownloadManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import com.ddu.icore.aidl.GodIntent; import com.ddu.icore.common.ObserverManager; import com.ddu.icore.logic.Actions; /** * Created by yzbzz on 16/7/12. */ public class DownLoadCompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) { long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); long downLoadId = DownloadManagerUtils.DOWNLOAD_ID; if (id == downLoadId) { DownloadManagerUtils.DOWNLOAD_ID = -1; Cursor cursor = DownloadManagerUtils.query(context, id); if (cursor.moveToFirst()) { int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)); switch (status) { //下载暂停 case DownloadManager.STATUS_PAUSED: break; //下载延迟 case DownloadManager.STATUS_PENDING: break; //正在下载 case DownloadManager.STATUS_RUNNING: break; //下载完成 case DownloadManager.STATUS_SUCCESSFUL: GodIntent godIntent = new GodIntent(); godIntent.setAction(Actions.DOWNLOAD_COMPLETE); godIntent.putLong("downloadId", id); ObserverManager.notify(godIntent); // DownloadManagerUtils.startInstall(context.getApplicationContext(), id); break; //下载失败 case DownloadManager.STATUS_FAILED: // ToastUtils.showToast("下载失败"); break; } } cursor.close(); } } } }
36.522388
101
0.542705
1033c2f0071efea6b37e5d37308a0dcbaa5b7d8f
1,008
package fi.solita.utils.meta; import java.lang.reflect.Method; import fi.solita.utils.functional.Predicate; public abstract class MetaMethodPredicate<T> extends Predicate<T> implements MetaMethod<T, Boolean> { private transient Method $r; private final Class<?> clazz; private final String name; private final Class<?>[] argClasses; public MetaMethodPredicate(Class<?> clazz, String name, Class<?>... argClasses) { this.clazz = clazz; this.name = name; this.argClasses = argClasses; } @Override public boolean accept(T candidate) { return apply(candidate); } @Override public final Method getMember() { if ($r == null) { $r = MetaMethods.doGetMember(clazz, name, argClasses); } return $r; } public final String getName() { return name; } @Override public final String toString() { return MetaMethods.doToString(clazz, name); } }
25.2
101
0.622024
6baf5bc03f597b5984f31ec82605dd2e9c688397
17,124
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ // <RAVE> Copy from projects/projectui/src/org/netbeans/modules/project/ui package org.netbeans.modules.portalpack.visualweb.ui; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; import javax.swing.Action; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectUtils; import org.netbeans.api.project.ProjectInformation; import org.netbeans.api.project.SourceGroup; import org.netbeans.api.project.Sources; import org.netbeans.api.queries.VisibilityQuery; import org.netbeans.spi.project.ui.support.CommonProjectActions; import org.openide.ErrorManager; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.ChangeableDataFilter; import org.openide.loaders.DataFilter; import org.openide.loaders.DataFolder; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; import org.openide.nodes.FilterNode; import org.openide.nodes.Node; import org.openide.nodes.NodeNotFoundException; import org.openide.nodes.NodeOp; import org.openide.util.NbBundle; import org.openide.util.Lookup; import org.openide.util.WeakListeners; import org.openide.util.lookup.Lookups; import org.openide.util.lookup.ProxyLookup; /** * Support for creating logical views. * @author Po-Ting Wu, Jesse Glick, Petr Hrebejk */ public class PhysicalView { public static boolean isProjectDirNode( Node n ) { return n instanceof GroupNode && ((GroupNode)n).isProjectDir; } public static Node[] createNodesForProject( Project p ) { Sources s = ProjectUtils.getSources(p); SourceGroup[] groups = s.getSourceGroups(Sources.TYPE_GENERIC); FileObject projectDirectory = p.getProjectDirectory(); SourceGroup projectDirGroup = null; // First find the source group which will represent the project for( int i = 0; i < groups.length; i++ ) { FileObject groupRoot = groups[i].getRootFolder(); if ( projectDirectory.equals( groupRoot ) || FileUtil.isParentOf( groupRoot, projectDirectory ) ) { if ( projectDirGroup != null ) { // more than once => Illegal projectDirGroup = null; break; } else { projectDirGroup = groups[i]; } } } if ( projectDirGroup == null ) { // Illegal project ErrorManager.getDefault().log(ErrorManager.WARNING, "Project " + p + // NOI18N "either does not contain it's project directory under the " + // NOI18N "Generic source groups or the project directory is under " + // NOI18N "more than one source group"); // NOI18N return new Node[0]; } // Create the nodes ArrayList nodesList = new ArrayList( groups.length ); nodesList.add(/*new GroupContainmentFilterNode(*/new GroupNode(p, projectDirGroup, true, DataFolder.findFolder(projectDirGroup.getRootFolder()))/*, projectDirGroup)*/); for( int i = 0; i < groups.length; i++ ) { if ( groups[i] == projectDirGroup ) { continue; } nodesList.add(/*new GroupContainmentFilterNode(*/new GroupNode(p, groups[i], false, DataFolder.findFolder(groups[i].getRootFolder()))/*, groups[i])*/); } Node nodes[] = new Node[ nodesList.size() ]; nodesList.toArray( nodes ); return nodes; } static final class VisibilityQueryDataFilter implements ChangeListener, ChangeableDataFilter { EventListenerList ell = new EventListenerList(); public VisibilityQueryDataFilter() { VisibilityQuery.getDefault().addChangeListener( this ); } public boolean acceptDataObject(DataObject obj) { FileObject fo = obj.getPrimaryFile(); return VisibilityQuery.getDefault().isVisible( fo ); } public void stateChanged( ChangeEvent e) { Object[] listeners = ell.getListenerList(); ChangeEvent event = null; for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i] == ChangeListener.class) { if ( event == null) { event = new ChangeEvent( this ); } ((ChangeListener)listeners[i+1]).stateChanged( event ); } } } public void addChangeListener( ChangeListener listener ) { ell.add( ChangeListener.class, listener ); } public void removeChangeListener( ChangeListener listener ) { ell.remove( ChangeListener.class, listener ); } } static final class GroupNode extends FilterNode implements PropertyChangeListener { private static final DataFilter VISIBILITY_QUERY_FILTER = new VisibilityQueryDataFilter(); static final String GROUP_NAME_PATTERN = NbBundle.getMessage( PhysicalView.class, "FMT_PhysicalView_GroupName" ); // NOI18N private Project project; private ProjectInformation pi; private SourceGroup group; private boolean isProjectDir; public GroupNode(Project project, SourceGroup group, boolean isProjectDir, DataFolder dataFolder ) { super( dataFolder.getNodeDelegate(), dataFolder.createNodeChildren( VISIBILITY_QUERY_FILTER ), createLookup( project, group, dataFolder ) ); this.project = project; this.pi = ProjectUtils.getInformation( project ); this.group = group; this.isProjectDir = isProjectDir; pi.addPropertyChangeListener(WeakListeners.propertyChange(this, pi)); group.addPropertyChangeListener( WeakListeners.propertyChange( this, group ) ); } // XXX May need to change icons as well public String getName() { if ( isProjectDir ) { return pi.getName(); } else { String n = group.getName(); if (n == null) { n = "???"; // NOI18N ErrorManager.getDefault().log(ErrorManager.WARNING, "SourceGroup impl of type " + group.getClass().getName() + " specified a null getName(); this is illegal"); } return n; } } public String getDisplayName() { if ( isProjectDir ) { return pi.getDisplayName(); } else { return MessageFormat.format( GROUP_NAME_PATTERN, new Object[] { group.getDisplayName(), pi.getDisplayName(), getOriginal().getDisplayName() } ); } } public String getShortDescription() { FileObject gdir = group.getRootFolder(); String dir = FileUtil.getFileDisplayName(gdir); return NbBundle.getMessage(PhysicalView.class, isProjectDir ? "HINT_project" : "HINT_group", // NOI18N dir); } public boolean canRename() { return false; } public boolean canCut() { return false; } public boolean canCopy() { // At least for now. return false; } public boolean canDestroy() { return false; } public Action[] getActions( boolean context ) { if ( context ) { return super.getActions( true ); } else { Action[] folderActions = super.getActions( false ); Action[] projectActions; if ( isProjectDir ) { // If this is project dir then the properties action // has to be replaced to invoke project customizer projectActions = new Action[ folderActions.length ]; for ( int i = 0; i < folderActions.length; i++ ) { if ( folderActions[i] instanceof org.openide.actions.PropertiesAction ) { projectActions[i] = CommonProjectActions.customizeProjectAction(); } else { projectActions[i] = folderActions[i]; } } } else { projectActions = folderActions; } return projectActions; } } // Private methods ------------------------------------------------- public void propertyChange(PropertyChangeEvent evt) { String prop = evt.getPropertyName(); if (ProjectInformation.PROP_DISPLAY_NAME.equals(prop)) { fireDisplayNameChange(null, null); } else if (ProjectInformation.PROP_NAME.equals(prop)) { fireNameChange(null, null); } else if (ProjectInformation.PROP_ICON.equals(prop)) { // OK, ignore } else if ( "name".equals(prop) ) { // NOI18N fireNameChange(null, null); } else if ( "displayName".equals(prop) ) { // NOI18N fireDisplayNameChange(null, null); } else if ( "icon".equals(prop) ) { // NOI18N // OK, ignore } else if ( "rootFolder".equals(prop) ) { // NOI18N // XXX Do something to children and lookup fireNameChange(null, null); fireDisplayNameChange(null, null); fireShortDescriptionChange(null, null); } else { assert false : "Attempt to fire an unsupported property change event from " + pi.getClass().getName() + ": " + prop; } } private static Lookup createLookup( Project p, SourceGroup group, DataFolder dataFolder ) { return new ProxyLookup(new Lookup[] { dataFolder.getNodeDelegate().getLookup(), Lookups.fixed( new Object[] { p, new PathFinder( group ) } ), p.getLookup(), }); } } /* XXX disabled for now pending resolution of interaction with planned VCS annotations (color only): /** * Specially displays nodes corresponding to files which are not contained in this source group. * / private static final class GroupContainmentFilterNode extends FilterNode { private final SourceGroup g; public GroupContainmentFilterNode(Node orig, SourceGroup g) { super(orig, orig.isLeaf() ? Children.LEAF : new GroupContainmentFilterChildren(orig, g)); this.g = g; } public String getHtmlDisplayName() { Node orig = getOriginal(); DataObject d = (DataObject) orig.getCookie(DataObject.class); assert d != null : orig; FileObject f = d.getPrimaryFile(); String barename = orig.getHtmlDisplayName(); if (!FileUtil.isParentOf(g.getRootFolder(), f) || g.contains(f)) { // Leave it alone. return barename; } // Try to grey it out. if (barename == null) { try { barename = XMLUtil.toElementContent(orig.getDisplayName()); } catch (CharConversionException e) { // Never mind. return null; } } return "<font color='!Label.disabledForeground'>" + barename + "</font>"; // NOI18N } private static final class GroupContainmentFilterChildren extends FilterNode.Children { private final SourceGroup g; public GroupContainmentFilterChildren(Node orig, SourceGroup g) { super(orig); this.g = g; } protected Node copyNode(Node node) { if (original.getCookie(DataFolder.class) != null && node.getCookie(DataObject.class) != null) { return new GroupContainmentFilterNode(node, g); } else { return super.copyNode(node); } } } } */ public static class PathFinder { private SourceGroup group; public PathFinder( SourceGroup group ) { this.group = group; } public Node findPath( Node root, Object object ) { if ( !( object instanceof FileObject ) ) { return null; } FileObject fo = (FileObject)object; FileObject groupRoot = group.getRootFolder(); if ( FileUtil.isParentOf( groupRoot, fo ) /* && group.contains( fo ) */ ) { // The group contains the object String relPath = FileUtil.getRelativePath( groupRoot, fo ); ArrayList path = new ArrayList(); StringTokenizer strtok = new StringTokenizer( relPath, "/" ); while( strtok.hasMoreTokens() ) { path.add( strtok.nextToken() ); } String name = fo.getName(); try { DataObject dobj = DataObject.find( fo ); name = dobj.getNodeDelegate().getName(); } catch( DataObjectNotFoundException e ) { } path.set( path.size() - 1, name ); try { return NodeOp.findPath( root, Collections.enumeration( path ) ); } catch ( NodeNotFoundException e ) { return null; } } else if ( groupRoot.equals( fo ) ) { return root; } return null; } } }
39.638889
179
0.562719
8695538f8639a04b09eae32b3c1ed4681c9aa9dd
1,272
package familiar.service.assist; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class DiceServiceTest { @InjectMocks private DiceService underTest; @BeforeEach private void setUp() { MockitoAnnotations.initMocks(this); } @ParameterizedTest @ValueSource(strings = {"153", "", "d8", "<>~", "153+", "1d8+", "2d8+4-1d5+"}) @DisplayName("Invalid expressions should result in error.") public void test1(String input) { assertThrows(IllegalArgumentException.class, () -> underTest.evaluateDiceExpression(input)); } @Test @DisplayName("DiceService calculates 15d1-3+5d1+2 expression properly") public void test2() { // GIVEN String diceExpression = "15d1-3+5d1+2"; // WHEN int result = underTest.evaluateDiceExpression(diceExpression); // THEN assertEquals(19, result); } }
28.266667
100
0.706761
d5a251c5b645e5278dd8dafdf73e1aa62d734e23
626
package net.dubboclub.circuitbreaker.exception; /** * Created by bieber on 2015/6/3. */ public class CircuitBreakerException extends RuntimeException { private String message; public CircuitBreakerException(String interfaceName, String methodName) { StringBuilder message = new StringBuilder(); message.append(interfaceName).append(".").append(methodName).append("进入默认服务降级方案."); this.message = message.toString(); } public CircuitBreakerException(String message) { super(message); } @Override public String getMessage() { return message; } }
23.185185
91
0.685304
29e53133edb7e4313f02ef42c3d195a9c35ccc0c
40,408
package javassist.compiler; import javassist.compiler.ast.MethodDecl; import javassist.bytecode.ConstPool; import javassist.bytecode.FieldInfo; import javassist.CtField; import javassist.NotFoundException; import javassist.Modifier; import javassist.bytecode.Descriptor; import javassist.bytecode.AccessFlag; import javassist.compiler.ast.Symbol; import javassist.compiler.ast.Expr; import javassist.compiler.ast.Keyword; import javassist.compiler.ast.Member; import javassist.compiler.ast.CallExpr; import javassist.compiler.ast.ASTree; import javassist.compiler.ast.ArrayInit; import javassist.compiler.ast.NewExpr; import javassist.compiler.ast.Declarator; import javassist.compiler.ast.Pair; import javassist.compiler.ast.Visitor; import java.util.ArrayList; import javassist.compiler.ast.ASTList; import javassist.compiler.ast.Stmnt; import javassist.CtMethod; import javassist.bytecode.ClassFile; import javassist.ClassPool; import javassist.bytecode.Bytecode; import javassist.bytecode.MethodInfo; import javassist.CtClass; public class MemberCodeGen extends CodeGen { protected MemberResolver resolver; protected CtClass thisClass; protected MethodInfo thisMethod; protected boolean resultStatic; public MemberCodeGen(final Bytecode a1, final CtClass a2, final ClassPool a3) { super(a1); this.resolver = new MemberResolver(a3); this.thisClass = a2; this.thisMethod = null; } public int getMajorVersion() { final ClassFile v1 = /*EL:46*/this.thisClass.getClassFile2(); /*SL:47*/if (v1 == null) { /*SL:48*/return ClassFile.MAJOR_VERSION; } /*SL:50*/return v1.getMajorVersion(); } public void setThisMethod(final CtMethod a1) { /*SL:57*/this.thisMethod = a1.getMethodInfo2(); /*SL:58*/if (this.typeChecker != null) { /*SL:59*/this.typeChecker.setThisMethod(this.thisMethod); } } public CtClass getThisClass() { /*SL:62*/return this.thisClass; } @Override protected String getThisName() { /*SL:68*/return MemberResolver.javaToJvmName(this.thisClass.getName()); } @Override protected String getSuperName() throws CompileError { /*SL:75*/return MemberResolver.javaToJvmName(/*EL:76*/MemberResolver.getSuperclass(this.thisClass).getName()); } @Override protected void insertDefaultSuperCall() throws CompileError { /*SL:80*/this.bytecode.addAload(0); /*SL:81*/this.bytecode.addInvokespecial(MemberResolver.getSuperclass(this.thisClass), "<init>", "()V"); } @Override protected void atTryStmnt(final Stmnt v-11) throws CompileError { final Bytecode bytecode = /*EL:190*/this.bytecode; final Stmnt stmnt = /*EL:191*/(Stmnt)v-11.getLeft(); /*SL:192*/if (stmnt == null) { /*SL:193*/return; } ASTList tail = /*EL:195*/(ASTList)v-11.getRight().getLeft(); final Stmnt v-12 = /*EL:196*/(Stmnt)v-11.getRight().getRight().getLeft(); final ArrayList v5 = /*EL:197*/new ArrayList(); JsrHook jsrHook = /*EL:199*/null; /*SL:200*/if (v-12 != null) { /*SL:201*/jsrHook = new JsrHook(this); } final int currentPc = /*EL:203*/bytecode.currentPc(); /*SL:204*/stmnt.accept(this); final int currentPc2 = /*EL:205*/bytecode.currentPc(); /*SL:206*/if (currentPc == currentPc2) { /*SL:207*/throw new CompileError("empty try block"); } boolean b = /*EL:209*/!this.hasReturned; /*SL:210*/if (b) { /*SL:211*/bytecode.addOpcode(167); /*SL:212*/v5.add(new Integer(bytecode.currentPc())); /*SL:213*/bytecode.addIndex(0); } final int maxLocals = /*EL:216*/this.getMaxLocals(); /*SL:217*/this.incMaxLocals(1); /*SL:218*/while (tail != null) { final Pair a1 = /*EL:220*/(Pair)tail.head(); /*SL:221*/tail = tail.tail(); final Declarator v1 = /*EL:222*/(Declarator)a1.getLeft(); final Stmnt v2 = /*EL:223*/(Stmnt)a1.getRight(); /*SL:225*/v1.setLocalVar(maxLocals); final CtClass v3 = /*EL:227*/this.resolver.lookupClassByJvmName(v1.getClassName()); /*SL:228*/v1.setClassName(MemberResolver.javaToJvmName(v3.getName())); /*SL:229*/bytecode.addExceptionHandler(currentPc, currentPc2, bytecode.currentPc(), v3); /*SL:230*/bytecode.growStack(1); /*SL:231*/bytecode.addAstore(maxLocals); /*SL:232*/this.hasReturned = false; /*SL:233*/if (v2 != null) { /*SL:234*/v2.accept(this); } /*SL:236*/if (!this.hasReturned) { /*SL:237*/bytecode.addOpcode(167); /*SL:238*/v5.add(new Integer(bytecode.currentPc())); /*SL:239*/bytecode.addIndex(0); /*SL:240*/b = true; } } /*SL:244*/if (v-12 != null) { /*SL:245*/jsrHook.remove(this); final int v4 = /*EL:247*/bytecode.currentPc(); /*SL:248*/bytecode.addExceptionHandler(currentPc, v4, v4, 0); /*SL:249*/bytecode.growStack(1); /*SL:250*/bytecode.addAstore(maxLocals); /*SL:251*/this.hasReturned = false; /*SL:252*/v-12.accept(this); /*SL:253*/if (!this.hasReturned) { /*SL:254*/bytecode.addAload(maxLocals); /*SL:255*/bytecode.addOpcode(191); } /*SL:258*/this.addFinally(jsrHook.jsrList, v-12); } final int v4 = /*EL:261*/bytecode.currentPc(); /*SL:262*/this.patchGoto(v5, v4); /*SL:263*/this.hasReturned = !b; /*SL:264*/if (v-12 != null && /*EL:265*/b) { /*SL:266*/v-12.accept(this); } } private void addFinally(final ArrayList v-6, final Stmnt v-5) throws CompileError { final Bytecode bytecode = /*EL:276*/this.bytecode; /*SL:278*/for (int size = v-6.size(), i = 0; i < size; ++i) { final int[] a1 = /*EL:279*/v-6.get(i); final int a2 = /*EL:280*/a1[0]; /*SL:281*/bytecode.write16bit(a2, bytecode.currentPc() - a2 + 1); final ReturnHook v1 = /*EL:282*/new JsrHook2(this, a1); /*SL:283*/v-5.accept(this); /*SL:284*/v1.remove(this); /*SL:285*/if (!this.hasReturned) { /*SL:286*/bytecode.addOpcode(167); /*SL:287*/bytecode.addIndex(a2 + 3 - bytecode.currentPc()); } } } @Override public void atNewExpr(final NewExpr v-1) throws CompileError { /*SL:293*/if (v-1.isArray()) { /*SL:294*/this.atNewArrayExpr(v-1); } else { final CtClass a1 = /*EL:296*/this.resolver.lookupClassByName(v-1.getClassName()); final String v1 = /*EL:297*/a1.getName(); final ASTList v2 = /*EL:298*/v-1.getArguments(); /*SL:299*/this.bytecode.addNew(v1); /*SL:300*/this.bytecode.addOpcode(89); /*SL:302*/this.atMethodCallCore(a1, "<init>", v2, false, true, -1, null); /*SL:305*/this.exprType = 307; /*SL:306*/this.arrayDim = 0; /*SL:307*/this.className = MemberResolver.javaToJvmName(v1); } } public void atNewArrayExpr(final NewExpr a1) throws CompileError { final int v1 = /*EL:312*/a1.getArrayType(); final ASTList v2 = /*EL:313*/a1.getArraySize(); final ASTList v3 = /*EL:314*/a1.getClassName(); final ArrayInit v4 = /*EL:315*/a1.getInitializer(); /*SL:316*/if (v2.length() <= 1) { final ASTree v5 = /*EL:326*/v2.head(); /*SL:327*/this.atNewArrayExpr2(v1, v5, Declarator.astToClassName(v3, '/'), v4); /*SL:328*/return; } if (v4 != null) { throw new CompileError("sorry, multi-dimensional array initializer for new is not supported"); } this.atMultiNewArray(v1, v3, v2); } private void atNewArrayExpr2(final int v-4, final ASTree v-3, final String v-2, final ArrayInit v-1) throws CompileError { /*SL:332*/if (v-1 == null) { /*SL:333*/if (v-3 == null) { /*SL:334*/throw new CompileError("no array size"); } /*SL:336*/v-3.accept(this); } else { /*SL:338*/if (v-3 != null) { /*SL:343*/throw new CompileError("unnecessary array size specified for new"); } final int a1 = v-1.length(); this.bytecode.addIconst(a1); } final String v0; /*SL:346*/if (v-4 == 307) { final String a2 = /*EL:347*/this.resolveClassName(v-2); /*SL:348*/this.bytecode.addAnewarray(MemberResolver.jvmToJavaName(a2)); } else { /*SL:351*/v0 = null; int a3 = /*EL:352*/0; /*SL:353*/switch (v-4) { case 301: { /*SL:355*/a3 = 4; /*SL:356*/break; } case 306: { /*SL:358*/a3 = 5; /*SL:359*/break; } case 317: { /*SL:361*/a3 = 6; /*SL:362*/break; } case 312: { /*SL:364*/a3 = 7; /*SL:365*/break; } case 303: { /*SL:367*/a3 = 8; /*SL:368*/break; } case 334: { /*SL:370*/a3 = 9; /*SL:371*/break; } case 324: { /*SL:373*/a3 = 10; /*SL:374*/break; } case 326: { /*SL:376*/a3 = 11; /*SL:377*/break; } default: { badNewExpr(); break; } } /*SL:383*/this.bytecode.addOpcode(188); /*SL:384*/this.bytecode.add(a3); } /*SL:387*/if (v-1 != null) { final int v = /*EL:388*/v-1.length(); ASTList v2 = /*EL:389*/v-1; /*SL:390*/for (int a4 = 0; a4 < v; ++a4) { /*SL:391*/this.bytecode.addOpcode(89); /*SL:392*/this.bytecode.addIconst(a4); /*SL:393*/v2.head().accept(this); /*SL:394*/if (!CodeGen.isRefType(v-4)) { /*SL:395*/this.atNumCastExpr(this.exprType, v-4); } /*SL:397*/this.bytecode.addOpcode(CodeGen.getArrayWriteOp(v-4, 0)); /*SL:398*/v2 = v2.tail(); } } /*SL:402*/this.exprType = v-4; /*SL:403*/this.arrayDim = 1; /*SL:404*/this.className = v0; } private static void badNewExpr() throws CompileError { /*SL:408*/throw new CompileError("bad new expression"); } @Override protected void atArrayVariableAssign(final ArrayInit a1, final int a2, final int a3, final String a4) throws CompileError { /*SL:413*/this.atNewArrayExpr2(a2, null, a4, a1); } @Override public void atArrayInit(final ArrayInit a1) throws CompileError { /*SL:417*/throw new CompileError("array initializer is not supported"); } protected void atMultiNewArray(final int v1, final ASTList v2, ASTList v3) throws CompileError { final int v4 = /*EL:424*/v3.length(); int v5 = /*EL:425*/0; while (v3 != null) { final ASTree a1 = /*EL:426*/v3.head(); /*SL:427*/if (a1 == null) { /*SL:428*/break; } /*SL:430*/++v5; /*SL:431*/a1.accept(this); /*SL:432*/if (this.exprType != 324) { /*SL:433*/throw new CompileError("bad type for array size"); } v3 = v3.tail(); } /*SL:437*/this.exprType = v1; /*SL:438*/this.arrayDim = v4; final String v6; /*SL:439*/if (v1 == 307) { /*SL:440*/this.className = this.resolveClassName(v2); final String a2 = /*EL:441*/CodeGen.toJvmArrayName(this.className, v4); } else { /*SL:444*/v6 = CodeGen.toJvmTypeName(v1, v4); } /*SL:446*/this.bytecode.addMultiNewarray(v6, v5); } @Override public void atCallExpr(final CallExpr v-10) throws CompileError { String a2 = /*EL:450*/null; CtClass ctClass = /*EL:451*/null; final ASTree oprand1 = /*EL:452*/v-10.oprand1(); final ASTList a3 = /*EL:453*/(ASTList)v-10.oprand2(); boolean a4 = /*EL:454*/false; boolean v3 = /*EL:455*/false; int v4 = /*EL:456*/-1; final MemberResolver.Method method = /*EL:458*/v-10.getMethod(); /*SL:459*/if (oprand1 instanceof Member) { /*SL:460*/a2 = ((Member)oprand1).get(); /*SL:461*/ctClass = this.thisClass; /*SL:462*/if (this.inStaticMethod || (method != null && method.isStatic())) { /*SL:463*/a4 = true; } else { /*SL:465*/v4 = this.bytecode.currentPc(); /*SL:466*/this.bytecode.addAload(0); } } else/*SL:469*/ if (oprand1 instanceof Keyword) { /*SL:470*/v3 = true; /*SL:471*/a2 = "<init>"; /*SL:472*/ctClass = this.thisClass; /*SL:473*/if (this.inStaticMethod) { /*SL:474*/throw new CompileError("a constructor cannot be static"); } /*SL:476*/this.bytecode.addAload(0); /*SL:478*/if (((Keyword)oprand1).get() == 336) { /*SL:479*/ctClass = MemberResolver.getSuperclass(ctClass); } } else/*SL:481*/ if (oprand1 instanceof Expr) { final Expr expr = /*EL:482*/(Expr)oprand1; /*SL:483*/a2 = ((Symbol)expr.oprand2()).get(); final int v0 = /*EL:484*/expr.getOperator(); /*SL:485*/if (v0 == 35) { /*SL:487*/ctClass = this.resolver.lookupClass(((Symbol)expr.oprand1()).get(), false); /*SL:488*/a4 = true; } else/*SL:490*/ if (v0 == 46) { final ASTree v = /*EL:491*/expr.oprand1(); final String v2 = /*EL:492*/TypeChecker.isDotSuper(v); /*SL:493*/if (v2 != null) { /*SL:494*/v3 = true; /*SL:495*/ctClass = MemberResolver.getSuperInterface(this.thisClass, v2); /*SL:497*/if (this.inStaticMethod || (method != null && method.isStatic())) { /*SL:498*/a4 = true; } else { /*SL:500*/v4 = this.bytecode.currentPc(); /*SL:501*/this.bytecode.addAload(0); } } else { /*SL:505*/if (v instanceof Keyword && /*EL:506*/((Keyword)v).get() == 336) { /*SL:507*/v3 = true; } try { /*SL:510*/v.accept(this); } catch (NoFieldException a1) { /*SL:513*/if (a1.getExpr() != v) { /*SL:514*/throw a1; } /*SL:517*/this.exprType = 307; /*SL:518*/this.arrayDim = 0; /*SL:519*/this.className = a1.getField(); /*SL:520*/a4 = true; } /*SL:523*/if (this.arrayDim > 0) { /*SL:524*/ctClass = this.resolver.lookupClass("java.lang.Object", true); } else/*SL:525*/ if (this.exprType == 307) { /*SL:526*/ctClass = this.resolver.lookupClassByJvmName(this.className); } else { badMethod(); } } } else { badMethod(); } } else { fatal(); } /*SL:537*/this.atMethodCallCore(ctClass, a2, a3, a4, v3, v4, method); } private static void badMethod() throws CompileError { /*SL:542*/throw new CompileError("bad method"); } public void atMethodCallCore(final CtClass a4, final String a5, final ASTList a6, boolean a7, final boolean v1, final int v2, MemberResolver.Method v3) throws CompileError { final int v4 = /*EL:556*/this.getMethodArgsLength(a6); final int[] v5 = /*EL:557*/new int[v4]; final int[] v6 = /*EL:558*/new int[v4]; final String[] v7 = /*EL:559*/new String[v4]; /*SL:561*/if (!a7 && v3 != null && v3.isStatic()) { /*SL:562*/this.bytecode.addOpcode(87); /*SL:563*/a7 = true; } final int v8 = /*EL:566*/this.bytecode.getStackDepth(); /*SL:569*/this.atMethodArgs(a6, v5, v6, v7); /*SL:571*/if (v3 == null) { /*SL:572*/v3 = this.resolver.lookupMethod(a4, this.thisClass, this.thisMethod, a5, v5, v6, v7); } /*SL:575*/if (v3 == null) { final String a9; /*SL:577*/if (a5.equals("<init>")) { final String a8 = /*EL:578*/"constructor not found"; } else { /*SL:581*/a9 = "Method " + a5 + " not found in " + a4.getName(); } /*SL:583*/throw new CompileError(a9); } /*SL:586*/this.atMethodCallCore2(a4, a5, a7, v1, v2, v3); } private void atMethodCallCore2(final CtClass a4, String a5, boolean a6, boolean v1, final int v2, final MemberResolver.Method v3) throws CompileError { CtClass v4 = /*EL:596*/v3.declaring; final MethodInfo v5 = /*EL:597*/v3.info; String v6 = /*EL:598*/v5.getDescriptor(); int v7 = /*EL:599*/v5.getAccessFlags(); /*SL:601*/if (a5.equals("<init>")) { /*SL:602*/v1 = true; /*SL:603*/if (v4 != a4) { /*SL:604*/throw new CompileError("no such constructor: " + a4.getName()); } /*SL:606*/if (v4 != this.thisClass && AccessFlag.isPrivate(v7)) { /*SL:607*/v6 = this.getAccessibleConstructor(v6, v4, v5); /*SL:608*/this.bytecode.addOpcode(1); } } else/*SL:611*/ if (AccessFlag.isPrivate(v7)) { /*SL:612*/if (v4 == this.thisClass) { /*SL:613*/v1 = true; } else { /*SL:615*/v1 = false; /*SL:616*/a6 = true; final String a7 = /*EL:617*/v6; /*SL:618*/if ((v7 & 0x8) == 0x0) { /*SL:619*/v6 = Descriptor.insertParameter(v4.getName(), a7); } /*SL:622*/v7 = (AccessFlag.setPackage(v7) | 0x8); /*SL:623*/a5 = this.getAccessiblePrivate(a5, a7, v6, v5, v4); } } boolean v8 = /*EL:627*/false; /*SL:628*/if ((v7 & 0x8) != 0x0) { /*SL:629*/if (!a6) { /*SL:635*/a6 = true; /*SL:636*/if (v2 >= 0) { /*SL:637*/this.bytecode.write(v2, 0); } else { /*SL:639*/v8 = true; } } /*SL:642*/this.bytecode.addInvokestatic(v4, a5, v6); } else/*SL:644*/ if (v1) { /*SL:645*/this.bytecode.addInvokespecial(a4, a5, v6); } else { /*SL:647*/if (!Modifier.isPublic(v4.getModifiers()) || v4.isInterface() != /*EL:648*/a4.isInterface()) { /*SL:649*/v4 = a4; } /*SL:651*/if (v4.isInterface()) { final int a8 = /*EL:652*/Descriptor.paramSize(v6) + 1; /*SL:653*/this.bytecode.addInvokeinterface(v4, a5, v6, a8); } else { /*SL:656*/if (a6) { /*SL:657*/throw new CompileError(a5 + " is not static"); } /*SL:659*/this.bytecode.addInvokevirtual(v4, a5, v6); } } /*SL:662*/this.setReturnType(v6, a6, v8); } protected String getAccessiblePrivate(final String a3, final String a4, final String a5, final MethodInfo v1, final CtClass v2) throws CompileError { /*SL:677*/if (this.isEnclosing(v2, this.thisClass)) { final AccessorMaker a6 = /*EL:678*/v2.getAccessorMaker(); /*SL:679*/if (a6 != null) { /*SL:680*/return a6.getMethodAccessor(a3, a4, a5, v1); } } /*SL:684*/throw new CompileError("Method " + a3 + " is private"); } protected String getAccessibleConstructor(final String a3, final CtClass v1, final MethodInfo v2) throws CompileError { /*SL:701*/if (this.isEnclosing(v1, this.thisClass)) { final AccessorMaker a4 = /*EL:702*/v1.getAccessorMaker(); /*SL:703*/if (a4 != null) { /*SL:704*/return a4.getConstructor(v1, a3, v2); } } /*SL:707*/throw new CompileError("the called constructor is private in " + v1.getName()); } private boolean isEnclosing(final CtClass a1, CtClass a2) { try { /*SL:713*/while (a2 != null) { /*SL:714*/a2 = a2.getDeclaringClass(); /*SL:715*/if (a2 == a1) { /*SL:716*/return true; } } } catch (NotFoundException ex) {} /*SL:720*/return false; } public int getMethodArgsLength(final ASTList a1) { /*SL:724*/return ASTList.length(a1); } public void atMethodArgs(ASTList a3, final int[] a4, final int[] v1, final String[] v2) throws CompileError { int v3 = /*EL:729*/0; /*SL:730*/while (a3 != null) { final ASTree a5 = /*EL:731*/a3.head(); /*SL:732*/a5.accept(this); /*SL:733*/a4[v3] = this.exprType; /*SL:734*/v1[v3] = this.arrayDim; /*SL:735*/v2[v3] = this.className; /*SL:736*/++v3; /*SL:737*/a3 = a3.tail(); } } void setReturnType(final String a3, final boolean v1, final boolean v2) throws CompileError { int v3 = /*EL:744*/a3.indexOf(41); /*SL:745*/if (v3 < 0) { badMethod(); } char v4 = /*EL:748*/a3.charAt(++v3); int v5 = /*EL:749*/0; /*SL:750*/while (v4 == '[') { /*SL:751*/++v5; /*SL:752*/v4 = a3.charAt(++v3); } /*SL:755*/this.arrayDim = v5; /*SL:756*/if (v4 == 'L') { final int a4 = /*EL:757*/a3.indexOf(59, v3 + 1); /*SL:758*/if (a4 < 0) { badMethod(); } /*SL:761*/this.exprType = 307; /*SL:762*/this.className = a3.substring(v3 + 1, a4); } else { /*SL:765*/this.exprType = MemberResolver.descToType(v4); /*SL:766*/this.className = null; } final int v6 = /*EL:769*/this.exprType; /*SL:770*/if (v1 && /*EL:771*/v2) { /*SL:772*/if (CodeGen.is2word(v6, v5)) { /*SL:773*/this.bytecode.addOpcode(93); /*SL:774*/this.bytecode.addOpcode(88); /*SL:775*/this.bytecode.addOpcode(87); } else/*SL:777*/ if (v6 == 344) { /*SL:778*/this.bytecode.addOpcode(87); } else { /*SL:780*/this.bytecode.addOpcode(95); /*SL:781*/this.bytecode.addOpcode(87); } } } @Override protected void atFieldAssign(final Expr v-11, final int v-10, final ASTree v-9, final ASTree v-8, final boolean v-7) throws CompileError { final CtField fieldAccess = /*EL:790*/this.fieldAccess(v-9, false); final boolean resultStatic = /*EL:791*/this.resultStatic; /*SL:792*/if (v-10 != 61 && !resultStatic) { /*SL:793*/this.bytecode.addOpcode(89); } final int atFieldRead; /*SL:796*/if (v-10 == 61) { FieldInfo a2 = /*EL:797*/fieldAccess.getFieldInfo2(); /*SL:798*/this.setFieldType(a2); /*SL:799*/a2 = this.isAccessibleField(fieldAccess, a2); /*SL:800*/if (a2 == null) { final int a3 = /*EL:801*/this.addFieldrefInfo(fieldAccess, a2); } else { final int a4 = /*EL:803*/0; } } else { /*SL:806*/atFieldRead = this.atFieldRead(fieldAccess, resultStatic); } final int exprType = /*EL:808*/this.exprType; final int arrayDim = /*EL:809*/this.arrayDim; final String className = /*EL:810*/this.className; /*SL:812*/this.atAssignCore(v-11, v-10, v-8, exprType, arrayDim, className); final boolean v0 = /*EL:814*/CodeGen.is2word(exprType, arrayDim); /*SL:815*/if (v-7) { final int v; /*SL:817*/if (resultStatic) { final int a5 = /*EL:818*/v0 ? 92 : 89; } else { /*SL:820*/v = (v0 ? 93 : 90); } /*SL:822*/this.bytecode.addOpcode(v); } /*SL:825*/this.atFieldAssignCore(fieldAccess, resultStatic, atFieldRead, v0); /*SL:827*/this.exprType = exprType; /*SL:828*/this.arrayDim = arrayDim; /*SL:829*/this.className = className; } private void atFieldAssignCore(final CtField v2, final boolean v3, final int v4, final boolean v5) throws CompileError { /*SL:836*/if (v4 != 0) { /*SL:837*/if (v3) { /*SL:838*/this.bytecode.add(179); /*SL:839*/this.bytecode.growStack(v5 ? -2 : -1); } else { /*SL:842*/this.bytecode.add(181); /*SL:843*/this.bytecode.growStack(v5 ? -3 : -2); } /*SL:846*/this.bytecode.addIndex(v4); } else { final CtClass a1 = /*EL:849*/v2.getDeclaringClass(); final AccessorMaker a2 = /*EL:850*/a1.getAccessorMaker(); final FieldInfo a3 = /*EL:852*/v2.getFieldInfo2(); final MethodInfo a4 = /*EL:853*/a2.getFieldSetter(a3, v3); /*SL:854*/this.bytecode.addInvokestatic(a1, a4.getName(), a4.getDescriptor()); } } @Override public void atMember(final Member a1) throws CompileError { /*SL:862*/this.atFieldRead(a1); } @Override protected void atFieldRead(final ASTree a1) throws CompileError { final CtField v1 = /*EL:867*/this.fieldAccess(a1, true); /*SL:868*/if (v1 == null) { /*SL:869*/this.atArrayLength(a1); /*SL:870*/return; } final boolean v2 = /*EL:873*/this.resultStatic; final ASTree v3 = /*EL:874*/TypeChecker.getConstantFieldValue(v1); /*SL:875*/if (v3 == null) { /*SL:876*/this.atFieldRead(v1, v2); } else { /*SL:878*/v3.accept(this); /*SL:879*/this.setFieldType(v1.getFieldInfo2()); } } private void atArrayLength(final ASTree a1) throws CompileError { /*SL:884*/if (this.arrayDim == 0) { /*SL:885*/throw new CompileError(".length applied to a non array"); } /*SL:887*/this.bytecode.addOpcode(190); /*SL:888*/this.exprType = 324; /*SL:889*/this.arrayDim = 0; } private int atFieldRead(final CtField v2, final boolean v3) throws CompileError { final FieldInfo v4 = /*EL:898*/v2.getFieldInfo2(); final boolean v5 = /*EL:899*/this.setFieldType(v4); final AccessorMaker v6 = /*EL:900*/this.isAccessibleField(v2, v4); /*SL:901*/if (v6 != null) { final MethodInfo a1 = /*EL:902*/v6.getFieldGetter(v4, v3); /*SL:903*/this.bytecode.addInvokestatic(v2.getDeclaringClass(), a1.getName(), a1.getDescriptor()); /*SL:905*/return 0; } final int a2 = /*EL:908*/this.addFieldrefInfo(v2, v4); /*SL:909*/if (v3) { /*SL:910*/this.bytecode.add(178); /*SL:911*/this.bytecode.growStack(v5 ? 2 : 1); } else { /*SL:914*/this.bytecode.add(180); /*SL:915*/this.bytecode.growStack(v5 ? 1 : 0); } /*SL:918*/this.bytecode.addIndex(a2); /*SL:919*/return a2; } private AccessorMaker isAccessibleField(final CtField v2, final FieldInfo v3) throws CompileError { /*SL:931*/if (!AccessFlag.isPrivate(v3.getAccessFlags()) || v2.getDeclaringClass() == /*EL:932*/this.thisClass) { /*SL:946*/return null; } CtClass a2 = v2.getDeclaringClass(); if (!this.isEnclosing(a2, this.thisClass)) { throw new CompileError("Field " + v2.getName() + " in " + a2.getName() + " is private."); } a2 = a2.getAccessorMaker(); if (a2 != null) { return a2; } throw new CompileError("fatal error. bug?"); } private boolean setFieldType(final FieldInfo a1) throws CompileError { final String v1 = /*EL:955*/a1.getDescriptor(); int v2 = /*EL:957*/0; int v3 = /*EL:958*/0; char v4; /*SL:960*/for (v4 = v1.charAt(v2); v4 == '['; /*SL:962*/v4 = v1.charAt(++v2)) { ++v3; } /*SL:965*/this.arrayDim = v3; /*SL:966*/this.exprType = MemberResolver.descToType(v4); /*SL:968*/if (v4 == 'L') { /*SL:969*/this.className = v1.substring(v2 + 1, v1.indexOf(59, v2 + 1)); } else { /*SL:971*/this.className = null; } final boolean v5 = /*EL:973*/v3 == 0 && (v4 == 'J' || v4 == 'D'); /*SL:974*/return v5; } private int addFieldrefInfo(final CtField a1, final FieldInfo a2) { final ConstPool v1 = /*EL:978*/this.bytecode.getConstPool(); final String v2 = /*EL:979*/a1.getDeclaringClass().getName(); final int v3 = /*EL:980*/v1.addClassInfo(v2); final String v4 = /*EL:981*/a2.getName(); final String v5 = /*EL:982*/a2.getDescriptor(); /*SL:983*/return v1.addFieldrefInfo(v3, v4, v5); } @Override protected void atClassObject2(final String a1) throws CompileError { /*SL:987*/if (this.getMajorVersion() < 49) { /*SL:988*/super.atClassObject2(a1); } else { /*SL:990*/this.bytecode.addLdc(this.bytecode.getConstPool().addClassInfo(a1)); } } @Override protected void atFieldPlusPlus(final int a3, final boolean a4, final ASTree a5, final Expr v1, final boolean v2) throws CompileError { final CtField v3 = /*EL:997*/this.fieldAccess(a5, false); final boolean v4 = /*EL:998*/this.resultStatic; /*SL:999*/if (!v4) { /*SL:1000*/this.bytecode.addOpcode(89); } final int v5 = /*EL:1002*/this.atFieldRead(v3, v4); final int v6 = /*EL:1003*/this.exprType; final boolean v7 = /*EL:1004*/CodeGen.is2word(v6, this.arrayDim); final int v8; /*SL:1007*/if (v4) { final int a6 = /*EL:1008*/v7 ? 92 : 89; } else { /*SL:1010*/v8 = (v7 ? 93 : 90); } /*SL:1012*/this.atPlusPlusCore(v8, v2, a3, a4, v1); /*SL:1013*/this.atFieldAssignCore(v3, v4, v5, v7); } protected CtField fieldAccess(final ASTree v-2, final boolean v-1) throws CompileError { /*SL:1023*/if (v-2 instanceof Member) { final String a2 = /*EL:1024*/((Member)v-2).get(); CtField v1 = /*EL:1025*/null; try { /*SL:1027*/v1 = this.thisClass.getField(a2); } catch (NotFoundException a2) { /*SL:1031*/throw new NoFieldException(a2, v-2); } final boolean v2 = /*EL:1034*/Modifier.isStatic(v1.getModifiers()); /*SL:1035*/if (!v2) { /*SL:1036*/if (this.inStaticMethod) { /*SL:1037*/throw new CompileError("not available in a static method: " + a2); } /*SL:1040*/this.bytecode.addAload(0); } /*SL:1042*/this.resultStatic = v2; /*SL:1043*/return v1; } /*SL:1045*/if (v-2 instanceof Expr) { final Expr v3 = /*EL:1046*/(Expr)v-2; final int v4 = /*EL:1047*/v3.getOperator(); /*SL:1048*/if (v4 == 35) { final CtField v5 = /*EL:1053*/this.resolver.lookupField(((Symbol)v3.oprand1()).get(), (Symbol)v3.oprand2()); /*SL:1055*/this.resultStatic = true; /*SL:1056*/return v5; } /*SL:1058*/if (v4 == 46) { CtField v5 = /*EL:1059*/null; try { /*SL:1061*/v3.oprand1().accept(this); /*SL:1066*/if (this.exprType == 307 && this.arrayDim == 0) { /*SL:1067*/v5 = this.resolver.lookupFieldByJvmName(this.className, (Symbol)v3.oprand2()); } else { /*SL:1069*/if (v-1 && this.arrayDim > 0 && ((Symbol)v3.oprand2()).get().equals(/*EL:1070*/"length")) { /*SL:1071*/return null; } badLvalue(); } final boolean v6 = /*EL:1075*/Modifier.isStatic(v5.getModifiers()); /*SL:1076*/if (v6) { /*SL:1077*/this.bytecode.addOpcode(87); } /*SL:1079*/this.resultStatic = v6; /*SL:1080*/return v5; } catch (NoFieldException v7) { /*SL:1083*/if (v7.getExpr() != v3.oprand1()) { /*SL:1084*/throw v7; } final Symbol v8 = /*EL:1090*/(Symbol)v3.oprand2(); final String v9 = /*EL:1091*/v7.getField(); /*SL:1092*/v5 = this.resolver.lookupFieldByJvmName2(v9, v8, v-2); /*SL:1093*/this.resultStatic = true; /*SL:1094*/return v5; } } badLvalue(); } else { badLvalue(); } /*SL:1103*/this.resultStatic = false; /*SL:1104*/return null; } private static void badLvalue() throws CompileError { /*SL:1108*/throw new CompileError("bad l-value"); } public CtClass[] makeParamList(final MethodDecl v-2) throws CompileError { ASTList v0 = /*EL:1113*/v-2.getParams(); final CtClass[] array; /*SL:1114*/if (v0 == null) { final CtClass[] a1 = /*EL:1115*/new CtClass[0]; } else { int v = /*EL:1117*/0; /*SL:1118*/array = new CtClass[v0.length()]; /*SL:1119*/while (v0 != null) { /*SL:1120*/array[v++] = this.resolver.lookupClass((Declarator)v0.head()); /*SL:1121*/v0 = v0.tail(); } } /*SL:1125*/return array; } public CtClass[] makeThrowsList(final MethodDecl v2) throws CompileError { ASTList v3 = /*EL:1130*/v2.getThrows(); /*SL:1131*/if (v3 == null) { /*SL:1132*/return null; } int a1 = /*EL:1134*/0; final CtClass[] v4 = /*EL:1135*/new CtClass[v3.length()]; /*SL:1136*/while (v3 != null) { /*SL:1137*/v4[a1++] = this.resolver.lookupClassByName((ASTList)v3.head()); /*SL:1138*/v3 = v3.tail(); } /*SL:1141*/return v4; } @Override protected String resolveClassName(final ASTList a1) throws CompileError { /*SL:1151*/return this.resolver.resolveClassName(a1); } @Override protected String resolveClassName(final String a1) throws CompileError { /*SL:1158*/return this.resolver.resolveJvmClassName(a1); } static class JsrHook extends ReturnHook { ArrayList jsrList; CodeGen cgen; int var; JsrHook(final CodeGen a1) { super(a1); this.jsrList = new ArrayList(); this.cgen = a1; this.var = -1; } private int getVar(final int a1) { /*SL:98*/if (this.var < 0) { /*SL:99*/this.var = this.cgen.getMaxLocals(); /*SL:100*/this.cgen.incMaxLocals(a1); } /*SL:103*/return this.var; } private void jsrJmp(final Bytecode a1) { /*SL:107*/a1.addOpcode(167); /*SL:108*/this.jsrList.add(new int[] { a1.currentPc(), this.var }); /*SL:109*/a1.addIndex(0); } @Override protected boolean doit(final Bytecode a1, final int a2) { /*SL:113*/switch (a2) { case 177: { /*SL:115*/this.jsrJmp(a1); /*SL:116*/break; } case 176: { /*SL:118*/a1.addAstore(this.getVar(1)); /*SL:119*/this.jsrJmp(a1); /*SL:120*/a1.addAload(this.var); /*SL:121*/break; } case 172: { /*SL:123*/a1.addIstore(this.getVar(1)); /*SL:124*/this.jsrJmp(a1); /*SL:125*/a1.addIload(this.var); /*SL:126*/break; } case 173: { /*SL:128*/a1.addLstore(this.getVar(2)); /*SL:129*/this.jsrJmp(a1); /*SL:130*/a1.addLload(this.var); /*SL:131*/break; } case 175: { /*SL:133*/a1.addDstore(this.getVar(2)); /*SL:134*/this.jsrJmp(a1); /*SL:135*/a1.addDload(this.var); /*SL:136*/break; } case 174: { /*SL:138*/a1.addFstore(this.getVar(1)); /*SL:139*/this.jsrJmp(a1); /*SL:140*/a1.addFload(this.var); /*SL:141*/break; } default: { /*SL:143*/throw new RuntimeException("fatal"); } } /*SL:146*/return false; } } static class JsrHook2 extends ReturnHook { int var; int target; JsrHook2(final CodeGen a1, final int[] a2) { super(a1); this.target = a2[0]; this.var = a2[1]; } @Override protected boolean doit(final Bytecode a1, final int a2) { /*SL:161*/switch (a2) { case 177: { /*SL:163*/break; } case 176: { /*SL:165*/a1.addAstore(this.var); /*SL:166*/break; } case 172: { /*SL:168*/a1.addIstore(this.var); /*SL:169*/break; } case 173: { /*SL:171*/a1.addLstore(this.var); /*SL:172*/break; } case 175: { /*SL:174*/a1.addDstore(this.var); /*SL:175*/break; } case 174: { /*SL:177*/a1.addFstore(this.var); /*SL:178*/break; } default: { /*SL:180*/throw new RuntimeException("fatal"); } } /*SL:183*/a1.addOpcode(167); /*SL:184*/a1.addIndex(this.target - a1.currentPc() + 3); /*SL:185*/return true; } } }
39.231068
177
0.489235
1a3b6e7528e0d07e012feab87fa98fb79b0dcfc0
4,276
package project6; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.Scanner; /*** TownGraphManager class for managing the Graph class functions * * @author Joseph Smith * */ public class TownGraphManager implements TownGraphManagerInterface { private Graph graph; public TownGraphManager() { graph = new Graph(); } @Override public boolean addRoad(String town1, String town2, int weight, String roadName) { try { return graph.addEdge(new Town(town1), new Town(town2), weight, roadName) != null; } catch (Exception e) { printException(e); return false; } } @Override public String getRoad(String town1, String town2) { return graph.getEdge(getTown(town1), getTown(town2)).toString(); } @Override public boolean addTown(String v) { try { return graph.addVertex(new Town(v)); } catch (NullPointerException e) { printException(e); return false; } } @Override public Town getTown(String name) { Iterator<Town> iterator = graph.vertexSet().iterator(); while (iterator.hasNext()) { Town t = iterator.next(); if (t.getName().equals(name)) return t; } return null; } @Override public boolean containsTown(String v) { return getTown(v) != null; } @Override public boolean containsRoadConnection(String town1, String town2) { return graph.containsEdge(getTown(town1), getTown(town2)); } @Override public ArrayList<String> allRoads() { ArrayList<String> roadList = new ArrayList<String>(); for (Road r : graph.edgeSet()) { roadList.add(r.toString()); } Collections.sort(roadList); return roadList; } @Override public boolean deleteRoadConnection(String town1, String town2, String road) { Town src = getTown(town1); Town dest = getTown(town2); Road r = graph.getEdge(src, dest); return graph.removeEdge(src, dest, r.getDistance(), r.toString()) != null; } @Override public boolean deleteTown(String v) { return graph.removeVertex(getTown(v)); } @Override public ArrayList<String> allTowns() { ArrayList<String> townList = new ArrayList<>(); for (Town t : graph.vertexSet()) { townList.add(t.toString()); } Collections.sort(townList); return townList; } @Override public ArrayList<String> getPath(String town1, String town2) { return graph.shortestPath(getTown(town1), getTown(town2)); } @Override public void populateTownGraph(File file) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String entry = scanner.nextLine(); if (entry.isBlank()) continue; String[] entries = entry.split(";"); try { if (entries.length != 3) { throw new IOException("Invalid entry format"); } } catch (IOException e) { printException(e, "for entry: '" + entry + "'"); continue; } String[] roadInfo = entries[0].split(","); try { if (roadInfo.length != 2) { throw new IOException("Invalid road info"); } } catch (IOException e) { printException(e, "for entry: '" + entry + "'"); continue; } String roadName = roadInfo[0]; Integer roadDistance; try { roadDistance = Integer.parseInt(roadInfo[1]); } catch (NumberFormatException e) { try { // TODO Throw Exception: Invalid road distance throw new IOException("Invalid road distance"); } catch (IOException e1) { printException(e, "for entry: '" + entry + "'"); continue; } } String srcTown = entries[1]; String destTown = entries[2]; addTown(srcTown); addTown(destTown); addRoad(srcTown, destTown, roadDistance, roadName); } scanner.close(); } /*** * Print exception to console * * @param e Exception */ private void printException(Exception e) { System.out.println("Exception thrown: " + e.getMessage()); } /*** * Print exception to console, with a following message * * @param e Exception * @param msg Message to follow exception */ private void printException(Exception e, String msg) { System.out.println("Exception thrown: " + e.getMessage() + " " + msg); } }
18.591304
85
0.667446
58bb330d606149811ccd00db09d900340248d6bc
2,463
package org.getopentest.actions.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.getopentest.base.TestAction; /** * An action that executes a SQL query statement against a database using JDBC. */ public class JdbcQuery extends TestAction { @Override public void run() { String jdbcUrl = this.readStringArgument("jdbcUrl"); String user = this.readStringArgument("user", null); String password = this.readStringArgument("password", null); String sql = this.readStringArgument("sql"); try { Connection conn; if (user != null && password != null) { conn = DriverManager.getConnection(jdbcUrl, user, password); } else { conn = DriverManager.getConnection(jdbcUrl); } Statement statement = conn.createStatement(); ResultSet resultSet = statement.executeQuery(sql); ResultSetMetaData rsMetaData = resultSet.getMetaData(); List<Map<String, Object>> rows = new ArrayList<>(); int columnCount = rsMetaData.getColumnCount(); while (resultSet.next()) { Map<String, Object> row = new HashMap<>(); for (int columnNo = 1; columnNo <= columnCount; columnNo++) { switch (rsMetaData.getColumnType(columnNo)) { case Types.DATE: case Types.TIME: case Types.TIME_WITH_TIMEZONE: case Types.TIMESTAMP: case Types.TIMESTAMP_WITH_TIMEZONE: row.put(rsMetaData.getColumnName(columnNo), resultSet.getObject(columnNo).toString()); break; default: row.put(rsMetaData.getColumnName(columnNo), resultSet.getObject(columnNo)); } } rows.add(row); } resultSet.close(); this.writeOutput("rows", rows); this.writeOutput("rowCount", rows.size()); } catch (SQLException ex) { throw new RuntimeException(ex); } } }
35.695652
114
0.576127
62bfd929640c092fa9767385bdfb9d0f9035ddfb
31,821
/* * 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 br.com.stefanini.control; import br.com.stefanini.control.dao.CustoDAO; import br.com.stefanini.model.entity.Atividade; import br.com.stefanini.model.entity.Custo; import br.com.stefanini.model.entity.ProgressoAtividade; import br.com.stefanini.model.entity.Projeto; import br.com.stefanini.model.enuns.Faturamento; import br.com.stefanini.model.enuns.TipoAtividade; import br.com.stefanini.model.util.DateUtil; import br.com.stefanini.model.util.DoubleConverter; import br.com.stefanini.model.util.MessageUtil; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.Tooltip; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; /** * FXML Controller class * * @author lucas */ public class StatusMensalComponentController extends ControllerBase implements Initializable { private Date inicio; private String idProjeto; private String idModulo; private String idPacote; private Projeto projetoObject; private List<Atividade> atividades = new ArrayList<>(); // private List<ProgressoAtividade> progressos = new ArrayList<>(); private Double paramContrato; private Double paramRepasse; private List<ProgressoAtividade> levantamentosAno = new ArrayList<>(); private List<ProgressoAtividade> desenvolvimentosAno = new ArrayList<>(); private List<ProgressoAtividade> testesAno = new ArrayList<>(); private List<ProgressoAtividade> servicosAno = new ArrayList<>(); private List<ProgressoAtividade> naoFaturados = new ArrayList<>(); @FXML private AnchorPane apPrincipal; @FXML private Button btAddCusto; @FXML private Label lbTotalPf; @FXML private Label lbTituloEstimada; @FXML private Label lbTituloDetalhada; @FXML private Label lbPlanejamentoRealizado; @FXML private Label lbTitulo; @FXML private Label lbPfEstimada; @FXML private Label lbValorContratoEstimada; @FXML private Label lbValorRepasseEstimada; @FXML private Label lbPfDetalhada; @FXML private Label lbValorContratoDetalhada; @FXML private Label lbValorRepasseDetalhada; // @FXML // private Label lbTotal; @FXML private Label lbLevantamento; @FXML private Label lbDesenvolvimento; @FXML private Label lbTeste; @FXML private Label lbProjeto; @FXML private Label lbCustoPlanejado; @FXML private Label lbCustoRealizado; @FXML private Label lbTipoPF; @FXML private Label lbRepasse; @FXML private Label lbResultadoTecnico; @FXML private Label lbFaturamento; @FXML private Label lbCustoComercial; @FXML private Label lbResultadoComercial; @FXML private Label lbResultadoCombinado; @FXML private Label lbRentabilidade; @FXML private GridPane gpLayout; private Custo custoMes; private Double repasse = 0.0; private Double contrato = 0.0; @FXML private VBox vbPlanejamento; private GerenciadorDeJanela gerenciadorDeJanela; Map<String, Object> params = new HashMap<>(); // private Stage stage; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { btAddCusto.setTooltip(new Tooltip("Atualizar Custos")); Platform.runLater(() -> { // stage = (Stage) apPrincipal.getScene().getWindow(); gerenciadorDeJanela = (GerenciadorDeJanela) params.get("gerenciador"); params = (Map) apPrincipal.getUserData(); }); } @FXML private void btAdicionarAction() { if (null == projetoObject.getDescricao()) { MessageUtil.messageInformation("Favor pesquisar com um projeto selecionado para atualizar custos."); } else { if (null != custoMes.getId()) { params.put("custo", CustoDAO.getInstance().pegarPorId(custoMes.getId())); } else { Custo custo = new Custo(); params.put("custo", custo); } params.put("dtInclusao", inicio); params.put("projeto", projetoObject); gerenciadorDeJanela.abrirModal("CustoModal", params, "Custo"); gerenciadorDeJanela = (GerenciadorDeJanela) params.get("gerenciador"); Custo custoAux = (Custo) params.get("CustoAux"); Double resultadoTecnico = 0.0; if (custoAux != null) { lbCustoPlanejado.setText("Téc. Planejado: " + DoubleConverter.doubleToString(custoAux.getCustoTecnicoPlanejado())); lbCustoRealizado.setText("Téc. Realizado: " + DoubleConverter.doubleToString(custoAux.getCustoTecnicoRealizado())); if (custoAux.getCustoTecnicoRealizado() > 0.0) { resultadoTecnico = repasse - custoAux.getCustoTecnicoRealizado(); lbResultadoTecnico.setText("Resultado Técnico: " + DoubleConverter.doubleToString(resultadoTecnico)); } else { resultadoTecnico = repasse - custoAux.getCustoTecnicoPlanejado(); lbResultadoTecnico.setText("Resultado Técnico: " + DoubleConverter.doubleToString(resultadoTecnico)); } } Double porcentagem = 26.5; Double custoComercial = ((contrato * porcentagem) / 100) + repasse; Double resultadoComercial = contrato - custoComercial; Double resultadoCombinado = resultadoTecnico + resultadoComercial; lbResultadoCombinado.setText("Resultado Combinado: " + DoubleConverter.doubleToString(resultadoCombinado)); } } public void teste() { gerenciadorDeJanela = (GerenciadorDeJanela) params.get("gerenciador"); Map param = (Map) apPrincipal.getUserData(); inicio = (Date) param.get("data"); idProjeto = (String) param.get("projeto"); idModulo = (String) param.get("modulo"); idPacote = (String) param.get("pacote"); projetoObject = (Projeto) param.get("projetoObject"); atividades = (List<Atividade>) param.get("atividades"); // progressos = (List<ProgressoAtividade>) param.get("progressos"); paramContrato = (Double) param.get("paramContrato"); paramRepasse = (Double) param.get("paramRepasse"); levantamentosAno = (List<ProgressoAtividade>) param.get("levantamentosAno"); desenvolvimentosAno = (List<ProgressoAtividade>) param.get("desenvolvimentosAno"); testesAno = (List<ProgressoAtividade>) param.get("testesAno"); servicosAno = (List<ProgressoAtividade>) param.get("servicosAno"); naoFaturados = (List<ProgressoAtividade>) param.get("naoFaturados"); String dataParam = DateUtil.formatterDate(inicio, "yyyy-MM-dd"); Double estimadaLevFaturado = 0.0; Double detalhadaLevFaturado = 0.0; List<ProgressoAtividade> levantamentosMesPrevisao = new ArrayList<>(); List<ProgressoAtividade> levantamentosMesFaturado = new ArrayList<>(); for (ProgressoAtividade progress : levantamentosAno) { String dataBanco = DateUtil.formatterDate(progress.getId().getAtividade().getPrevisaoInicio(), "yyyy-MM-dd"); String dataBancoAux = DateUtil.formatterDate(progress.getDataFaturamento(), "yyyy-MM-dd"); if ((dataBanco.equals(dataParam)) && ((progress.getFaturamento().equals(Faturamento.EF)) || (progress.getFaturamento().equals(Faturamento.FO)))) { levantamentosMesPrevisao.add(progress); } if((dataBancoAux.equals(dataParam)) && (progress.getFaturamento().equals(Faturamento.FO))){ levantamentosMesFaturado.add(progress); estimadaLevFaturado += progress.getId().getAtividade().getContagemEstimada() * .35; detalhadaLevFaturado += progress.getId().getAtividade().getContagemDetalhada()* .35; } } Double estimadaDevFaturado = 0.0; Double detalhadaDevFaturado = 0.0; Double estimadaAliFaturado = 0.0; Double detalhadaAliFaturado = 0.0; List<ProgressoAtividade> desenvolvimenetosMesPrevisao = new ArrayList<>(); List<ProgressoAtividade> desenvolvimenetosMesFaturado = new ArrayList<>(); for (ProgressoAtividade progress : desenvolvimentosAno) { String dataBanco = DateUtil.formatterDate(progress.getId().getAtividade().getPrevisaoInicio(), "yyyy-MM-dd"); String dataBancoAux = DateUtil.formatterDate(progress.getDataFaturamento(), "yyyy-MM-dd"); if ((dataBanco.equals(dataParam)) && ((progress.getFaturamento().equals(Faturamento.EF)) || (progress.getFaturamento().equals(Faturamento.FO)))) { desenvolvimenetosMesPrevisao.add(progress); } if ((dataBancoAux.equals(dataParam)) && (progress.getFaturamento().equals(Faturamento.FO))) { desenvolvimenetosMesFaturado.add(progress); estimadaDevFaturado += progress.getId().getAtividade().getContagemEstimada() * .4; detalhadaDevFaturado += progress.getId().getAtividade().getContagemDetalhada()* .4; estimadaAliFaturado += progress.getId().getAtividade().getAliEstimada(); detalhadaAliFaturado += progress.getId().getAtividade().getAliDetalhada(); } } Double estimadaTestFaturado = 0.0; Double detalhadaTestFaturado = 0.0; List<ProgressoAtividade> testesMesPrevisao = new ArrayList<>(); List<ProgressoAtividade> testesMesFaturado = new ArrayList<>(); for (ProgressoAtividade progress : testesAno) { String dataBanco = DateUtil.formatterDate(progress.getId().getAtividade().getPrevisaoInicio(), "yyyy-MM-dd"); String dataBancoAux = DateUtil.formatterDate(progress.getDataFaturamento(), "yyyy-MM-dd"); if ((dataBanco.equals(dataParam)) && ((progress.getFaturamento().equals(Faturamento.EF)) || (progress.getFaturamento().equals(Faturamento.FO)))) { testesMesPrevisao.add(progress); } if ((dataBancoAux.equals(dataParam)) && (progress.getFaturamento().equals(Faturamento.FO))) { testesMesFaturado.add(progress); estimadaTestFaturado += progress.getId().getAtividade().getContagemEstimada() * .25; detalhadaTestFaturado += progress.getId().getAtividade().getContagemDetalhada()* .25; } } Double estimadaServFaturado = 0.0; Double detalhadaServFaturado = 0.0; for (ProgressoAtividade progress : servicosAno) { String dataBancoAux = DateUtil.formatterDate(progress.getDataFaturamento(), "yyyy-MM-dd"); if ((dataBancoAux.equals(dataParam)) && (progress.getFaturamento().equals(Faturamento.FO))) { estimadaServFaturado += progress.getId().getAtividade().getContagemEstimada(); detalhadaServFaturado += progress.getId().getAtividade().getContagemDetalhada(); } } Double contagemEstimada = estimadaLevFaturado + estimadaDevFaturado + estimadaAliFaturado + estimadaTestFaturado + estimadaServFaturado; Double contagemDetalhada = detalhadaLevFaturado + detalhadaDevFaturado + detalhadaAliFaturado + detalhadaTestFaturado + detalhadaServFaturado; lbTitulo.setText(new SimpleDateFormat("MM - MMMM").format(inicio)); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 1); String dataAux = DateUtil.formatterDate(calendar.getTime(), "yyyy-MM-dd"); // PARTE 1 if(DateUtil.truncateDate(inicio).before(DateUtil.truncateDate(calendar.getTime())) && !dataParam.equals(dataAux)){ lbTotalPf.setVisible(false); Double totalContratoEstimada = contagemEstimada * paramContrato; Double totalRepasseEstimada = contagemEstimada * paramRepasse; Double totalContratoDetalhada = contagemDetalhada * paramContrato; Double totalRepasseDetalhada = contagemDetalhada * paramRepasse; int qtdLevantamentoLabelPrevisao = levantamentosMesPrevisao.size(); int qtdLevantamentoLabelFaturado = levantamentosMesFaturado.size(); int qtdDesenvolvimentoLabelPrevisao = desenvolvimenetosMesPrevisao.size(); int qtdDesenvolvimentoLabelFaturado = desenvolvimenetosMesFaturado.size(); int qtdTesteLabelPrevisao = testesMesPrevisao.size(); int qtdTesteLabelFaturado = testesMesFaturado.size(); repasse = totalRepasseDetalhada; contrato = totalContratoDetalhada; lbLevantamento.setText("Levantamentos: " + qtdLevantamentoLabelPrevisao + "/" + qtdLevantamentoLabelFaturado); lbDesenvolvimento.setText("Desenvolvimento: " + qtdDesenvolvimentoLabelPrevisao + "/" + qtdDesenvolvimentoLabelFaturado); lbTeste.setText("Testes/Homologação: " + qtdTesteLabelPrevisao + "/" + qtdTesteLabelFaturado); lbTituloEstimada.setText("Detalhada"); lbPfEstimada.setText("Pontos de função: " + DoubleConverter.doubleToString(contagemDetalhada)); lbValorContratoEstimada.setText("Valor Contrato: " + DoubleConverter.doubleToString(totalContratoDetalhada)); lbValorRepasseEstimada.setText("Valor Repasse: " + DoubleConverter.doubleToString(totalRepasseDetalhada)); lbPfDetalhada.setText("Pontos de função: " + DoubleConverter.doubleToString(contagemDetalhada)); lbValorContratoDetalhada.setText("Valor Contrato: " + DoubleConverter.doubleToString(totalContratoDetalhada)); lbValorRepasseDetalhada.setText("Valor Repasse: " + DoubleConverter.doubleToString(totalRepasseDetalhada)); lbTituloDetalhada.setVisible(false); lbPfDetalhada.setVisible(false); lbValorContratoDetalhada.setVisible(false); lbValorRepasseDetalhada.setVisible(false); // PARTE 2 lbPlanejamentoRealizado.setText("Realizado"); custoMes = (Custo) param.get("Custo"); if (null == projetoObject.getDescricao()) { lbProjeto.setText("Projeto: Todos"); } else { lbProjeto.setText("Projeto: " + projetoObject.getDescricao()); } if (!(0.0 == contagemEstimada) && !(0.0 == contagemDetalhada)) { lbCustoPlanejado.setText("Téc. Planejado: " + DoubleConverter.doubleToString(custoMes.getCustoTecnicoPlanejado())); lbCustoRealizado.setText("Téc. Realizado: " + DoubleConverter.doubleToString(custoMes.getCustoTecnicoRealizado())); Double resultadoTecnico = 0.0; if (custoMes.getCustoTecnicoRealizado() > 0.0) { resultadoTecnico = totalRepasseDetalhada - custoMes.getCustoTecnicoRealizado(); lbResultadoTecnico.setText("Resultado Técnico: " + DoubleConverter.doubleToString(resultadoTecnico)); } else { resultadoTecnico = totalRepasseDetalhada - custoMes.getCustoTecnicoPlanejado(); lbResultadoTecnico.setText("Resultado Técnico: " + DoubleConverter.doubleToString(resultadoTecnico)); } Double custoComercial; Double porcentagem = 26.5; Double resultadoComercial; Double resultadoCombinado; Double rentabilidade = 0.0; lbRentabilidade.setText("Rentabilidade: " + DoubleConverter.doubleToString(rentabilidade) + "%"); if (contagemDetalhada > 0.0) { lbTipoPF.setText("Tipo de Contagem PF: Detalhada"); lbRepasse.setText("Repasse: " + DoubleConverter.doubleToString(totalRepasseDetalhada)); lbFaturamento.setText("Faturamento: " + DoubleConverter.doubleToString(totalContratoDetalhada)); custoComercial = ((totalContratoDetalhada * porcentagem) / 100) + totalRepasseDetalhada; lbCustoComercial.setText("Custo Comercial: " + DoubleConverter.doubleToString(custoComercial)); resultadoComercial = totalContratoDetalhada - custoComercial; lbResultadoComercial.setText("Resultado Comercial: " + DoubleConverter.doubleToString(resultadoComercial)); resultadoCombinado = resultadoTecnico + resultadoComercial; lbResultadoCombinado.setText("Resultado Combinado: " + DoubleConverter.doubleToString(resultadoCombinado)); if (totalContratoDetalhada > 0) { rentabilidade = (resultadoCombinado / totalContratoDetalhada) * 100; lbRentabilidade.setText("Rentabilidade: " + DoubleConverter.doubleToString(rentabilidade) + "%"); } } else { lbTipoPF.setText("Tipo de Contagem PF: Estimada"); lbRepasse.setText("Repasse: " + DoubleConverter.doubleToString(totalRepasseEstimada)); lbFaturamento.setText("Faturamento: " + DoubleConverter.doubleToString(totalContratoEstimada)); custoComercial = ((totalContratoEstimada * porcentagem) / 100) + totalRepasseEstimada; lbCustoComercial.setText("Custo Comercial: " + DoubleConverter.doubleToString(custoComercial)); resultadoComercial = totalContratoEstimada - custoComercial; lbResultadoComercial.setText("Resultado Comercial: " + DoubleConverter.doubleToString(resultadoComercial)); resultadoCombinado = resultadoTecnico + resultadoComercial; lbResultadoCombinado.setText("Resultado Combinado: " + DoubleConverter.doubleToString(resultadoCombinado)); if (totalContratoEstimada > 0) { rentabilidade = (resultadoCombinado / totalContratoEstimada) * 100; lbRentabilidade.setText("Rentabilidade: " + DoubleConverter.doubleToString(rentabilidade) + "%"); } } }else{ lbCustoPlanejado.setText("Téc. Planejado: "); lbCustoRealizado.setText("Téc. Realizado: "); lbResultadoTecnico.setText("Resultado Técnico: "); lbRentabilidade.setText("Rentabilidade: "); lbTipoPF.setText("Tipo de Contagem PF: "); lbCustoComercial.setText("Custo Comercial: "); lbResultadoComercial.setText("Resultado Comercial: "); lbResultadoCombinado.setText("Resultado Combinado: "); lbRepasse.setText("Repasse: "); lbFaturamento.setText("Faturamento: "); } } else{ lbTotalPf.setVisible(true); Double pfAtvMes = 0d; for(Atividade atv : atividades){ String dt = DateUtil.formatterDate(atv.getPrevisaoInicio(), "yyyy-MM-dd"); if(dataParam.equals(dt)){ if(atv.getContagemDetalhada() > 0d){ pfAtvMes += atv.getContagemDetalhada(); }else{ pfAtvMes += atv.getContagemEstimada(); } } } Double levantamentosNaoFaturados = 0d; Double desenvolvimentosNaoFaturados = 0d; Double testesNaoFaturados = 0d; Double totalPfNaoFaturados; for(ProgressoAtividade progresso : naoFaturados){ if(progresso.getId().getTipoAtividade().equals(TipoAtividade.LE) && progresso.getId().getProgresso() != 100d){ levantamentosNaoFaturados += progresso.getId().getAtividade().getContagemDetalhada(); } else if (progresso.getId().getTipoAtividade().equals(TipoAtividade.DE) && progresso.getId().getProgresso() != 100d){ desenvolvimentosNaoFaturados += progresso.getId().getAtividade().getContagemDetalhada(); } else if (progresso.getId().getTipoAtividade().equals(TipoAtividade.TE) && progresso.getId().getProgresso() != 100d){ testesNaoFaturados += progresso.getId().getAtividade().getContagemDetalhada(); } } totalPfNaoFaturados = (levantamentosNaoFaturados * .35) + (desenvolvimentosNaoFaturados * .4) + (testesNaoFaturados * .25); lbTotalPf.setText("PF's retroativos para faturar: " + DoubleConverter.doubleToString(totalPfNaoFaturados)); Double detalhada = totalPfNaoFaturados + pfAtvMes; Double estimada = pfAtvMes; Double totalContratoEstimada = estimada * paramContrato; Double totalRepasseEstimada = estimada * paramRepasse; Double totalContratoDetalhada = detalhada * paramContrato; Double totalRepasseDetalhada = detalhada * paramRepasse; int qtdLevantamentoLabelPrevisao = levantamentosMesPrevisao.size(); int qtdLevantamentoLabelFaturado = levantamentosMesFaturado.size(); int qtdDesenvolvimentoLabelPrevisao = desenvolvimenetosMesPrevisao.size(); int qtdDesenvolvimentoLabelFaturado = desenvolvimenetosMesFaturado.size(); int qtdTesteLabelPrevisao = testesMesPrevisao.size(); int qtdTesteLabelFaturado = testesMesFaturado.size(); repasse = totalRepasseDetalhada; contrato = totalContratoDetalhada; lbLevantamento.setText("Levantamentos: " + qtdLevantamentoLabelPrevisao + "/" + qtdLevantamentoLabelFaturado); lbDesenvolvimento.setText("Desenvolvimento: " + qtdDesenvolvimentoLabelPrevisao + "/" + qtdDesenvolvimentoLabelFaturado); lbTeste.setText("Testes/Homologação: " + qtdTesteLabelPrevisao + "/" + qtdTesteLabelFaturado); lbPfEstimada.setText("Pontos de função: " + DoubleConverter.doubleToString(estimada)); lbValorContratoEstimada.setText("Valor Contrato: " + DoubleConverter.doubleToString(totalContratoEstimada)); lbValorRepasseEstimada.setText("Valor Repasse: " + DoubleConverter.doubleToString(totalRepasseEstimada)); lbPfDetalhada.setText("Pontos de função: " + DoubleConverter.doubleToString(detalhada)); lbValorContratoDetalhada.setText("Valor Contrato: " + DoubleConverter.doubleToString(totalContratoDetalhada)); lbValorRepasseDetalhada.setText("Valor Repasse: " + DoubleConverter.doubleToString(totalRepasseDetalhada)); lbTituloDetalhada.setVisible(true); // PARTE 2 lbPlanejamentoRealizado.setText("Planejamento/Realizado"); custoMes = (Custo) param.get("Custo"); if (null == projetoObject.getDescricao()) { lbProjeto.setText("Projeto: Todos"); } else { lbProjeto.setText("Projeto: " + projetoObject.getDescricao()); } if (estimada > 0d || detalhada > 0d) { lbCustoPlanejado.setText("Téc. Planejado: " + DoubleConverter.doubleToString(custoMes.getCustoTecnicoPlanejado())); lbCustoRealizado.setText("Téc. Realizado: " + DoubleConverter.doubleToString(custoMes.getCustoTecnicoRealizado())); Double resultadoTecnico = 0.0; if (custoMes.getCustoTecnicoRealizado() > 0.0) { resultadoTecnico = totalRepasseDetalhada - custoMes.getCustoTecnicoRealizado(); lbResultadoTecnico.setText("Resultado Técnico: " + DoubleConverter.doubleToString(resultadoTecnico)); } else { resultadoTecnico = totalRepasseDetalhada - custoMes.getCustoTecnicoPlanejado(); lbResultadoTecnico.setText("Resultado Técnico: " + DoubleConverter.doubleToString(resultadoTecnico)); } Double custoComercial; Double porcentagem = 26.5; Double resultadoComercial; Double resultadoCombinado; Double rentabilidade = 0.0; lbRentabilidade.setText("Rentabilidade: " + DoubleConverter.doubleToString(rentabilidade) + "%"); if (detalhada > 0.0) { lbTipoPF.setText("Tipo de Contagem PF: Detalhada"); lbRepasse.setText("Repasse: " + DoubleConverter.doubleToString(totalRepasseDetalhada)); lbFaturamento.setText("Faturamento: " + DoubleConverter.doubleToString(totalContratoDetalhada)); custoComercial = ((totalContratoDetalhada * porcentagem) / 100) + totalRepasseDetalhada; lbCustoComercial.setText("Custo Comercial: " + DoubleConverter.doubleToString(custoComercial)); resultadoComercial = totalContratoDetalhada - custoComercial; lbResultadoComercial.setText("Resultado Comercial: " + DoubleConverter.doubleToString(resultadoComercial)); resultadoCombinado = resultadoTecnico + resultadoComercial; lbResultadoCombinado.setText("Resultado Combinado: " + DoubleConverter.doubleToString(resultadoCombinado)); if (totalContratoDetalhada > 0) { rentabilidade = (resultadoCombinado / totalContratoDetalhada) * 100; lbRentabilidade.setText("Rentabilidade: " + DoubleConverter.doubleToString(rentabilidade) + "%"); } } else { lbTipoPF.setText("Tipo de Contagem PF: Estimada"); lbRepasse.setText("Repasse: " + DoubleConverter.doubleToString(totalRepasseEstimada)); lbFaturamento.setText("Faturamento: " + DoubleConverter.doubleToString(totalContratoEstimada)); custoComercial = ((totalContratoEstimada * porcentagem) / 100) + totalRepasseEstimada; lbCustoComercial.setText("Custo Comercial: " + DoubleConverter.doubleToString(custoComercial)); resultadoComercial = totalContratoEstimada - custoComercial; lbResultadoComercial.setText("Resultado Comercial: " + DoubleConverter.doubleToString(resultadoComercial)); resultadoCombinado = resultadoTecnico + resultadoComercial; lbResultadoCombinado.setText("Resultado Combinado: " + DoubleConverter.doubleToString(resultadoCombinado)); if (totalContratoEstimada > 0) { rentabilidade = (resultadoCombinado / totalContratoEstimada) * 100; lbRentabilidade.setText("Rentabilidade: " + DoubleConverter.doubleToString(rentabilidade) + "%"); } } }else{ lbCustoPlanejado.setText("Téc. Planejado: "); lbCustoRealizado.setText("Téc. Realizado: "); lbResultadoTecnico.setText("Resultado Técnico: "); lbRentabilidade.setText("Rentabilidade: "); lbTipoPF.setText("Tipo de Contagem PF: "); lbCustoComercial.setText("Custo Comercial: "); lbResultadoComercial.setText("Resultado Comercial: "); lbResultadoCombinado.setText("Resultado Combinado: "); lbRepasse.setText("Repasse: "); lbFaturamento.setText("Faturamento: "); } } } @FXML private void labelAtividadeActionEvent() { if (null == projetoObject.getDescricao()) { MessageUtil.messageInformation("Favor pesquisar com um projeto selecionado para visualizar atividades."); } else { GerenciadorDeJanela gerenciadorDeJanela = new GerenciadorDeJanela(); ScrollPane scrollPane = (ScrollPane) gerenciadorDeJanela.procurarComponente("spContainer", apPrincipal); params.put("dataInicio", inicio); params.put("projetoObject", projetoObject); scrollPane.setContent(gerenciadorDeJanela.carregarComponente("PesquisarAtividade", params)); } } @Override public void buildAnalista() { lbValorRepasseDetalhada.setVisible(false); lbValorRepasseEstimada.setVisible(false); gpLayout.getChildren().remove(vbPlanejamento); lbTotalPf.setVisible(false); } @Override public void buildBancoDados() { lbValorRepasseDetalhada.setVisible(false); lbValorRepasseEstimada.setVisible(false); gpLayout.getChildren().remove(vbPlanejamento); lbTotalPf.setVisible(false); } @Override public void buildBDMG() { lbValorRepasseDetalhada.setVisible(false); lbValorRepasseEstimada.setVisible(false); gpLayout.getChildren().remove(vbPlanejamento); lbTotalPf.setVisible(false); } @Override public void buildDesenvolvedor() { lbValorRepasseDetalhada.setVisible(false); lbValorRepasseEstimada.setVisible(false); gpLayout.getChildren().remove(vbPlanejamento); lbTotalPf.setVisible(false); } @Override public void buildGerente() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 1); String dataParam = DateUtil.formatterDate(calendar.getTime(), "yyyy-MM-dd"); String dataAux = DateUtil.formatterDate(inicio, "yyyy-MM-dd"); if(dataParam.equals(dataAux)){ lbValorRepasseDetalhada.setVisible(true); } else if(DateUtil.truncateDate(inicio).before(DateUtil.truncateDate(calendar.getTime()))){ lbValorRepasseDetalhada.setVisible(false); // lbValorRepasseEstimada.setVisible(false); } else{ lbValorRepasseDetalhada.setVisible(true); lbValorRepasseEstimada.setVisible(true); } } @Override public void buildQualidade() { lbValorRepasseDetalhada.setVisible(false); lbValorRepasseEstimada.setVisible(false); gpLayout.getChildren().remove(vbPlanejamento); lbTotalPf.setVisible(false); } @Override public void buildAdministrador() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 1); String dataParam = DateUtil.formatterDate(calendar.getTime(), "yyyy-MM-dd"); String dataAux = DateUtil.formatterDate(inicio, "yyyy-MM-dd"); if(dataParam.equals(dataAux)){ lbValorRepasseDetalhada.setVisible(true); } else if(DateUtil.truncateDate(inicio).before(DateUtil.truncateDate(calendar.getTime()))){ lbValorRepasseDetalhada.setVisible(false); // lbValorRepasseEstimada.setVisible(false); } else{ lbValorRepasseDetalhada.setVisible(true); lbValorRepasseEstimada.setVisible(true); } } }
51.324194
150
0.649822
4a6836b1d8bcd1131e4ce2f708adac5a1d753d60
442
package br.com.zupacademy.bruno.mercadolivre.controller.request; public class RequestRakingVendedores { private Long idCompra; private Long idVendedor; public RequestRakingVendedores(Long idCompra, Long idVendedor) { super(); this.idCompra = idCompra; this.idVendedor = idVendedor; } @Override public String toString() { return "RakingVendedoresRequest [idCompra=" + idCompra + ", idVendedor=" + idVendedor + "]"; } }
20.090909
94
0.739819
dd6feb3ff87a70fb5039d1b45613d8591d1efad0
11,094
/******************************************************************************* * Copyright (c) 2012, Institute for Pervasive Computing, ETH Zurich. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file is part of the Californium (Cf) CoAP framework. ******************************************************************************/ package ch.ethz.inf.vs.californium.coap; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import ch.ethz.inf.vs.californium.coap.Message.messageType; import ch.ethz.inf.vs.californium.endpoint.LocalResource; import ch.ethz.inf.vs.californium.layers.TransactionLayer; import ch.ethz.inf.vs.californium.util.Properties; /** * The TokenManager stores all tokens currently used in transfers. New transfers * can acquire unique tokens from the manager. * * @author Matthias Kovatsch */ public class ObservingManager { // Logging ///////////////////////////////////////////////////////////////////// private static final Logger LOG = Logger.getLogger(ObservingManager.class.getName()); // Inner class ///////////////////////////////////////////////////////////////// private class ObservingRelationship { public String clientID; public String resourcePath; public GETRequest request; public int lastMID; public ObservingRelationship(GETRequest request) { request.setMID(-1); this.clientID = request.getPeerAddress().toString(); this.resourcePath = request.getUriPath(); this.request = request; this.lastMID = -1; } } // Static Attributes /////////////////////////////////////////////////////////// private static ObservingManager singleton = new ObservingManager(); // Members ///////////////////////////////////////////////////////////////////// /** Maps a resource path string to the resource's observers stored by client address string. */ private Map<String, Map<String, ObservingRelationship>> observersByResource = new HashMap<String, Map<String, ObservingRelationship>>(); /** Maps a peer address string to the clients relationships stored by resource path. */ private Map<String, Map<String, ObservingRelationship>> observersByClient = new HashMap<String, Map<String, ObservingRelationship>>(); private int checkInterval = Properties.std.getInt("OBSERVING_REFRESH_INTERVAL"); private Map<String, Integer> intervalByResource = new HashMap<String, Integer>(); // Constructors //////////////////////////////////////////////////////////////// /** * Default singleton constructor. */ private ObservingManager() { } public static ObservingManager getInstance() { return singleton; } // Methods ///////////////////////////////////////////////////////////////////// public void setRefreshInterval(int interval) { this.checkInterval = interval; } public void notifyObservers(LocalResource resource) { Map<String, ObservingRelationship> resourceObservers = observersByResource.get(resource.getPath()); if (resourceObservers!=null && resourceObservers.size()>0) { LOG.info(String.format("Notifying observers: %d @ %s", resourceObservers.size(), resource.getPath())); int check = -1; // get/initialize if (!intervalByResource.containsKey(resource.getPath())) { check = checkInterval; } else { check = intervalByResource.get(resource.getPath()) - 1; } // update if (check <= 0) { intervalByResource.put(resource.getPath(), checkInterval); LOG.info(String.format("Refreshing observing relationship: %s", resource.getPath())); } else { intervalByResource.put(resource.getPath(), check); } for (ObservingRelationship observer : resourceObservers.values()) { GETRequest request = observer.request; // check if (check<=0) { request.setType(messageType.CON); } else { request.setType(messageType.NON); } // execute resource.performGET(request); prepareResponse(request); request.sendResponse(); } } } private void prepareResponse(Request request) { // consecutive response require new MID that must be stored for RST matching if (request.getResponse().getMID()==-1) { request.getResponse().setMID(TransactionLayer.nextMessageID()); } // 16-bit second counter int secs = (int) ((System.currentTimeMillis() - request.startTime) / 1000) & 0xFFFF; request.getResponse().setOption(new Option(secs, OptionNumberRegistry.OBSERVE)); // store MID for RST matching updateLastMID(request.getPeerAddress().toString(), request.getUriPath(), request.getResponse().getMID()); } public synchronized void addObserver(GETRequest request, LocalResource resource) { ObservingRelationship toAdd = new ObservingRelationship(request); // get clients map for the given resource path Map<String, ObservingRelationship> resourceObservers = observersByResource.get(resource.getPath()); if (resourceObservers==null) { // lazy creation resourceObservers = new HashMap<String, ObservingRelationship>(); observersByResource.put(resource.getPath(), resourceObservers); } // get resource map for given client address Map<String, ObservingRelationship> clientObservees = observersByClient.get(request.getPeerAddress().toString()); if (clientObservees==null) { // lazy creation clientObservees = new HashMap<String, ObservingRelationship>(); observersByClient.put(request.getPeerAddress().toString(), clientObservees); } // save relationship for notifications triggered by resource resourceObservers.put(request.getPeerAddress().toString(), toAdd); // save relationship for actions triggered by client clientObservees.put(resource.getPath(), toAdd); LOG.info(String.format("Established observing relationship: %s @ %s", request.getPeerAddress().toString(), resource.getPath())); // update response request.getResponse().setOption(new Option(0, OptionNumberRegistry.OBSERVE)); } public synchronized void removeObserver(String clientID) { Map<String, ObservingRelationship> clientObservees = observersByClient.get(clientID); if (clientObservees!=null) { for (Map<String, ObservingRelationship> entry : observersByResource.values()) { entry.remove(clientID); } observersByClient.remove(clientID); LOG.info(String.format("Terminated all observing relationships for client: %s", clientID)); } } /** * Remove an observer by missing Observe option in GET. * * @param clientID the peer address as string * @param resource the resource to un-observe. */ public void removeObserver(String clientID, LocalResource resource) { Map<String, ObservingRelationship> resourceObservers = observersByResource.get(resource.getPath()); Map<String, ObservingRelationship> clientObservees = observersByClient.get(clientID); if (resourceObservers!=null && clientObservees!=null) { if (resourceObservers.remove(clientID)!=null && clientObservees.remove(resource.getPath())!=null) { LOG.info(String.format("Terminated observing relationship by GET: %s @ %s", clientID, resource.getPath())); return; } } // should not be called if not existent LOG.warning(String.format("Cannot find observing relationship: %s @ %s", clientID, resource.getPath())); } /** * Remove an observer by MID from RST. * * @param clientID the peer address as string * @param mid the MID from the RST */ public void removeObserver(String clientID, int mid) { ObservingRelationship toRemove = null; Map<String, ObservingRelationship> clientObservees = observersByClient.get(clientID); if (clientObservees!=null) { for (ObservingRelationship entry : clientObservees.values()) { if (mid==entry.lastMID && clientID.equals(entry.clientID)) { // found it toRemove = entry; break; } } } if (toRemove!=null) { Map<String, ObservingRelationship> resourceObservers = observersByResource.get(toRemove.resourcePath); // FIXME Inconsistent state check if (resourceObservers==null) { LOG.severe(String.format("FIXME: ObservingManager has clientObservee, but no resourceObservers (%s @ %s)", clientID, toRemove.resourcePath)); } if (resourceObservers.remove(clientID)!=null && clientObservees.remove(toRemove.resourcePath)!=null) { LOG.info(String.format("Terminated observing relationship by RST: %s @ %s", clientID, toRemove.resourcePath)); return; } } LOG.warning(String.format("Cannot find observing relationship by MID: %s|%d", clientID, mid)); } public boolean isObserved(String clientID, LocalResource resource) { return observersByClient.containsKey(clientID) && observersByClient.get(clientID).containsKey(resource.getPath()); } public void updateLastMID(String clientID, String path, int mid) { Map<String, ObservingRelationship> clientObservees = observersByClient.get(clientID); if (clientObservees!=null) { ObservingRelationship toUpdate = clientObservees.get(path); if (toUpdate!=null) { toUpdate.lastMID = mid; LOG.finer(String.format("Updated last MID for observing relationship: %s @ %s", clientID, toUpdate.resourcePath)); return; } } LOG.warning(String.format("Cannot find observing relationship to update MID: %s @ %s", clientID, path)); } }
37.353535
146
0.67532
0af331b05291930d5e96adaa6475045eb1c92383
796
package gov.va.med.lom.avs.model; import java.io.Serializable; import javax.persistence.*; @Entity @Table(name="ckoHealthFactors") public class FacilityHealthFactor extends BaseModel implements Serializable { private String stationNo; private String type; private String ien; private String value; public String getStationNo() { return stationNo; } public void setStationNo(String stationNo) { this.stationNo = stationNo; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getIen() { return ien; } public void setIen(String ien) { this.ien = ien; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
19.414634
78
0.687186
8f8b4abb2494ef0bf9af303bbf23523ac6888ea8
487
public class DemoTestContainer extends TestContainer { public DemoTestContainer() { super(); appComponents = Arrays.asList( "com.haulmont.cuba" ); appPropertiesFiles = Arrays.asList( "com/company/demo/app.properties", "com/haulmont/cuba/testsupport/test-app.properties", "com/company/demo/test-app.properties" // your test properties ); autoConfigureDataSource(); }
32.466667
78
0.591376
fef39629fbca3d3dc856e54eeb7d3d510beeb139
5,896
/* * Copyright (c) Thomas Parker, 2009. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ package pcgen.cdom.facet; import java.util.ArrayList; import java.util.Collection; import java.util.List; import pcgen.cdom.base.CDOMObject; import pcgen.cdom.enumeration.CharID; import pcgen.cdom.enumeration.ListKey; import pcgen.cdom.facet.base.AbstractQualifiedListFacet; import pcgen.cdom.facet.event.DataFacetChangeEvent; import pcgen.cdom.facet.event.DataFacetChangeListener; import pcgen.cdom.helper.WeaponProfProvider; import pcgen.core.WeaponProf; /** * AutoWeaponProfFacet is a Facet that tracks the WeaponProfs that have been * granted to a Player Character. * * @author Thomas Parker (thpr [at] yahoo.com) */ public class AutoWeaponProfFacet extends AbstractQualifiedListFacet<WeaponProfProvider> implements DataFacetChangeListener<CharID, CDOMObject> { private CDOMObjectConsolidationFacet consolidationFacet; private PrerequisiteFacet prereqFacet = FacetLibrary .getFacet(PrerequisiteFacet.class); /** * Processes an added CDOMObject to extract WeaponProf objects which are * granted by AUTO:WEAPONPROF. These extracted WeaponProf objects are added * to the Player Character. * * Triggered when one of the Facets to which AutoWeaponProfFacet listens * fires a DataFacetChangeEvent to indicate a CDOMObject was added to a * Player Character. * * @param dfce * The DataFacetChangeEvent containing the information about the * change * * @see pcgen.cdom.facet.event.DataFacetChangeListener#dataAdded(pcgen.cdom.facet.event.DataFacetChangeEvent) */ @Override public void dataAdded(DataFacetChangeEvent<CharID, CDOMObject> dfce) { CDOMObject cdo = dfce.getCDOMObject(); List<WeaponProfProvider> weaponProfs = cdo.getListFor(ListKey.WEAPONPROF); if (weaponProfs != null) { addAll(dfce.getCharID(), weaponProfs, cdo); } } /** * Processes a removed CDOMObject to extract WeaponProf objects which are * granted by AUTO:WEAPONPROF. These extracted WeaponProf objects are * removed from the Player Character. * * Triggered when one of the Facets to which AutoWeaponProfFacet listens * fires a DataFacetChangeEvent to indicate a CDOMObject was removed from a * Player Character. * * @param dfce * The DataFacetChangeEvent containing the information about the * change * * @see pcgen.cdom.facet.event.DataFacetChangeListener#dataRemoved(pcgen.cdom.facet.event.DataFacetChangeEvent) */ @Override public void dataRemoved(DataFacetChangeEvent<CharID, CDOMObject> dfce) { removeAll(dfce.getCharID(), dfce.getCDOMObject()); } /** * Returns a non-null Collection of WeaponProf objects that have been * granted to a Player Character. * * This method is value-semantic in that ownership of the returned * Collection is transferred to the class calling this method. Modification * of the returned Collection will not modify this AutoWeaponProfFacet and * modification of this AutoWeaponProfFacet will not modify the returned * Collection. Modifications to the returned Collection will also not modify * any future or previous objects returned by this (or other) methods on * AutoWeaponProfFacet. If you wish to modify the information stored in this * AutoWeaponProfFacet, you must use the add*() and remove*() methods of * AutoWeaponProfFacet. * * @param id * The CharID identifying the Player Character for which the * Collection of granted WeaponProf objects should be returned * * @return A non-null Collection of WeaponProf objects that have been * granted to a Player Character. */ public Collection<WeaponProf> getWeaponProfs(CharID id) { Collection<WeaponProf> profs = new ArrayList<WeaponProf>(); for (WeaponProfProvider wpp : getQualifiedSet(id)) { profs.addAll(wpp.getContainedProficiencies(id)); } return profs; } /** * Check if the character has been granted a specific proficiency. This * will look only at a specific proficiency and not try to build the entire * list of automatic proficiencies based on their prereqs. * * @param id The id of the character. * @param wp The weapon proficiency to be checked. * @return true if the proficiency is granted, false if not. */ public boolean containsProf(CharID id, WeaponProf wp) { for (WeaponProfProvider wpp : getSet(id)) { if (wpp.getContainedProficiencies(id).contains(wp)) { if (prereqFacet.qualifies(id, wpp, wpp)) { return true; } } } return false; } public void setConsolidationFacet(CDOMObjectConsolidationFacet consolidationFacet) { this.consolidationFacet = consolidationFacet; } /** * Initializes the connections for AutoWeaponProfFacet to other facets. * * This method is automatically called by the Spring framework during * initialization of the AutoWeaponProfFacet. */ public void init() { consolidationFacet.addDataFacetChangeListener(this); } }
35.305389
113
0.726594
c5ad81fac1355eda00e790ee4979ec27918cfa2c
172
package me.ryandw11.octree; public class OutOfBoundsException extends RuntimeException { public OutOfBoundsException(String message){ super (message); } }
21.5
60
0.744186
8d90a647590078c351d635bb694ef3774a1f67be
8,751
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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.alibaba.nacos.istio.mcp; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.naming.core.v2.index.ServiceStorage; import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager; import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.core.v2.ServiceManager; import com.alibaba.nacos.naming.misc.GlobalExecutor; import com.google.protobuf.Any; import com.google.protobuf.Timestamp; import istio.mcp.v1alpha1.MetadataOuterClass; import istio.mcp.v1alpha1.ResourceOuterClass; import istio.networking.v1alpha3.GatewayOuterClass; import istio.networking.v1alpha3.ServiceEntryOuterClass; import istio.networking.v1alpha3.WorkloadEntryOuterClass; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; /** * Nacos MCP server. * * <p>This MCP serves as a ResourceSource defined by Istio. * * @author huaicheng.lzp * @since 1.2.1 */ @org.springframework.stereotype.Service public class NacosToMcpResources { private final Map<String, ResourceOuterClass.Resource> resourceMap = new ConcurrentHashMap<>(16); private final Map<String, Long> revisionMap = new ConcurrentHashMap<>(16); private static final String SERVICE_NAME_SPLITTER = "nacos"; private static final String MESSAGE_TYPE_URL = "type.googleapis.com/istio.networking.v1alpha3.ServiceEntry"; private static final long MCP_PUSH_PERIOD_MILLISECONDS = 10000L; private static final String SEPARATOR = "."; private static final String DEFAULT_SUFFIX = ".DEFAULT-GROUP"; private static final String PORT_PARAM = "http"; private static final String CLUSTER_PARAM = "cluster"; private static final String VIRTUAL_ANNOTATION = "virtual"; private static final String DEFAULT_VIRTUAL = "1"; private static final String HTTP = "HTTP"; @Autowired private NacosMcpOverXdsService nacosMcpOverXdsService; @Autowired private NacosMcpService nacosMcpService; @Autowired private ServiceStorage serviceStorage; @Autowired private NamingMetadataManager namingMetadataManager; public void start() { GlobalExecutor .scheduleMcpPushTask(new McpPushTask(), MCP_PUSH_PERIOD_MILLISECONDS * 2, MCP_PUSH_PERIOD_MILLISECONDS); } private class McpPushTask implements Runnable { @Override public void run() { ServiceManager serviceManager = ServiceManager.getInstance(); boolean changed = false; // Query all services to see if any of them have changes: Set<String> namespaces = serviceManager.getAllNamespaces(); Set<String> allServices = new HashSet<>(); for (String namespace : namespaces) { Set<Service> services = serviceManager.getSingletons(namespace); if (services.isEmpty()) { continue; } for (Service service : services) { String convertedName = convertName(service); allServices.add(convertedName); // Service not changed: if (revisionMap.containsKey(convertedName) && revisionMap.get(convertedName) .equals(service.getRevision())) { continue; } // Update the resource: ServiceInfo serviceInfo = serviceStorage.getData(service); changed = true; if (!serviceInfo.validate()) { resourceMap.remove(convertedName); revisionMap.remove(convertedName); continue; } resourceMap.put(convertedName, convertService(service)); revisionMap.put(convertedName, service.getRevision()); } } for (String key : resourceMap.keySet()) { if (!allServices.contains(key)) { changed = true; resourceMap.remove(key); revisionMap.remove(key); } } if (!changed) { // If no service changed, just return: return; } nacosMcpOverXdsService.sendResources(resourceMap); nacosMcpService.sendResources(resourceMap); } } private String convertName(Service service) { if (!Constants.DEFAULT_GROUP.equals(service.getGroup())) { return service.getName() + SEPARATOR + service.getGroup() + SEPARATOR + service.getNamespace(); } //DEFAULT_GROUP is invalid for istio,because the istio host only supports: [0-9],[A-Z],[a-z],-,* return service.getName() + DEFAULT_SUFFIX + SEPARATOR + service.getNamespace(); } private ResourceOuterClass.Resource convertService(Service service) { String serviceName = convertName(service); ServiceEntryOuterClass.ServiceEntry.Builder serviceEntryBuilder = ServiceEntryOuterClass.ServiceEntry .newBuilder().setResolution(ServiceEntryOuterClass.ServiceEntry.Resolution.STATIC) .setLocation(ServiceEntryOuterClass.ServiceEntry.Location.MESH_INTERNAL) .addHosts(serviceName + SEPARATOR + SERVICE_NAME_SPLITTER); ServiceInfo serviceInfo = serviceStorage.getData(service); List<Instance> hosts = serviceInfo.getHosts(); int port = 0; for (Instance instance : hosts) { if (port == 0) { port = instance.getPort(); } if (!instance.isHealthy() || !instance.isEnabled()) { continue; } Map<String, String> metadata = instance.getMetadata(); if (StringUtils.isNotEmpty(instance.getClusterName())) { metadata.put(CLUSTER_PARAM, instance.getClusterName()); } WorkloadEntryOuterClass.WorkloadEntry workloadEntry = WorkloadEntryOuterClass.WorkloadEntry.newBuilder() .setAddress(instance.getIp()).setWeight((int) instance.getWeight()).putAllLabels(metadata) .putPorts(PORT_PARAM, instance.getPort()).build(); serviceEntryBuilder.addEndpoints(workloadEntry); } serviceEntryBuilder.addPorts( GatewayOuterClass.Port.newBuilder().setNumber(port).setName(PORT_PARAM).setProtocol(HTTP).build()); ServiceEntryOuterClass.ServiceEntry serviceEntry = serviceEntryBuilder.build(); Optional<ServiceMetadata> serviceMetadata = namingMetadataManager.getServiceMetadata(service); ServiceMetadata serviceMetadataGetter = serviceMetadata.orElseGet(ServiceMetadata::new); Any any = Any.newBuilder().setValue(serviceEntry.toByteString()).setTypeUrl(MESSAGE_TYPE_URL).build(); MetadataOuterClass.Metadata metadata = MetadataOuterClass.Metadata.newBuilder() .setName(SERVICE_NAME_SPLITTER + "/" + serviceName) .putAllAnnotations(serviceMetadataGetter.getExtendData()).putAnnotations(VIRTUAL_ANNOTATION, DEFAULT_VIRTUAL) .setCreateTime(Timestamp.newBuilder().setSeconds(System.currentTimeMillis() / 1000).build()) .setVersion(serviceInfo.getChecksum()).build(); return ResourceOuterClass.Resource.newBuilder().setBody(any).setMetadata(metadata).build(); } }
41.084507
125
0.644041
127d650003dd0af8163a3e44aefd6e4455c53a4c
1,792
package common.db.base.test; import static org.junit.Assert.*; import java.util.Date; import javax.annotation.Resource; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.hibernate.service.spi.SessionFactoryServiceInitiator; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类 @ContextConfiguration(locations = {"classpath*:spring-mybatis.xml"}) public abstract class AbstractMyBatisTestCase { protected final Logger logger = LoggerFactory .getLogger(getClass()); //@Resource //private RoleDao roleDao; //private SqlSessionFactory sessionFactory; // @Before // public void before() { // ac = new ClassPathXmlApplicationContext("applicationContext.xml"); // userService = (IUserService) ac.getBean("userService"); // } //@Test //public void test1() { //Role role=new Role(); //role.setName("Mybatistest"+new Date().toString()); //role.setType(RoleTypeEnum.ADMIN); /* try(SqlSession session=sessionFactory.openSession()){ //session.getMapper获取的是一个代理对象 //RoleDao roleDao=session.getMapper(RoleDao.class); //20170808 这里的事务处理不完善 session.rollback(); }*/ //roleDao.insert(role); //User user= new User(); //user.setId(new Long(123)); //UserDao.insert(user); // System.out.println(user.getUserName()); // logger.info("值:"+user.getUserName()); //logger.info(JSON.toJSONString(user)); //} }
28.444444
77
0.698661
0c97f0b98d13e7d50dd98a14e497dcd1cd716e44
1,225
package com.sogokids.web.ctrl; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import java.util.regex.Pattern; @Controller public class ServiceController extends BaseController { private static final Pattern PATTERN = Pattern.compile("^/v\\d+/.+"); @RequestMapping(value = "/m/**", method = { RequestMethod.GET, RequestMethod.POST }) public String processMRequest(HttpServletRequest request) { return forward(request, request.getRequestURI().substring(2)); } private String forward(HttpServletRequest request, String uri) { if (PATTERN.matcher(uri).find()) return "forward:" + uri; return "forward:/v1" + uri; } @RequestMapping(value = "/**", method = { RequestMethod.GET, RequestMethod.POST }) public String processRequest(HttpServletRequest request) { return forward(request, request.getRequestURI()); } @RequestMapping(value = "/v{\\d+}/**", method = { RequestMethod.GET, RequestMethod.POST }) public String notFound() { return "forward:/error/404"; } }
36.029412
94
0.712653
56039211bc2c0935339e1c9d105eca67bbd7703c
65,931
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|tez package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|hive operator|. name|common operator|. name|util operator|. name|Ref import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|tez operator|. name|UserPoolMapping operator|. name|MappingInput import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Arrays import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collection import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collections import|; end_import begin_import import|import name|java operator|. name|util operator|. name|EnumSet import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|LinkedHashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|LinkedList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_import import|import name|javax operator|. name|annotation operator|. name|Nullable import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|classification operator|. name|InterfaceAudience operator|. name|Private import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|FileSystem import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|Path import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|common operator|. name|metrics operator|. name|common operator|. name|Metrics import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|common operator|. name|metrics operator|. name|common operator|. name|MetricsConstant import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|conf operator|. name|HiveConf import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|Context import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|FileSinkOperator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|Operator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|Task import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|Utilities import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|tez operator|. name|monitoring operator|. name|TezJobMonitor import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|log operator|. name|PerfLogger import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|HiveException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|BaseWork import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|MapWork import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|MergeJoinWork import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|OperatorDesc import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|ReduceWork import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|TezEdgeProperty import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|TezEdgeProperty operator|. name|EdgeType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|TezWork import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|UnionWork import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|api operator|. name|StageType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|session operator|. name|SessionState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|wm operator|. name|WmContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|mapred operator|. name|JobConf import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|UserGroupInformation import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|util operator|. name|StringUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|ApplicationReport import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|LocalResource import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|client operator|. name|CallerContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|client operator|. name|TezClient import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|common operator|. name|counters operator|. name|CounterGroup import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|common operator|. name|counters operator|. name|TezCounter import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|common operator|. name|counters operator|. name|TezCounters import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|common operator|. name|security operator|. name|DAGAccessControls import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|DAG import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|Edge import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|GroupInputEdge import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|SessionNotRunning import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|TezConfiguration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|TezException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|Vertex import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|VertexGroup import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|client operator|. name|DAGClient import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|client operator|. name|DAGStatus import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|client operator|. name|StatusGetOpts import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|dag operator|. name|api operator|. name|client operator|. name|VertexStatus import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|tez operator|. name|runtime operator|. name|library operator|. name|api operator|. name|TezRuntimeConfiguration import|; end_import begin_import import|import name|org operator|. name|json operator|. name|JSONObject import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|annotations operator|. name|VisibleForTesting import|; end_import begin_comment comment|/** * * TezTask handles the execution of TezWork. Currently it executes a graph of map and reduce work * using the Tez APIs directly. * */ end_comment begin_class annotation|@ name|SuppressWarnings argument_list|( block|{ literal|"serial" block|} argument_list|) specifier|public class|class name|TezTask extends|extends name|Task argument_list|< name|TezWork argument_list|> block|{ specifier|private specifier|static specifier|final name|String name|CLASS_NAME init|= name|TezTask operator|. name|class operator|. name|getName argument_list|() decl_stmt|; specifier|private specifier|static specifier|transient name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|CLASS_NAME argument_list|) decl_stmt|; specifier|private specifier|final name|PerfLogger name|perfLogger init|= name|SessionState operator|. name|getPerfLogger argument_list|() decl_stmt|; specifier|private specifier|static specifier|final name|String name|TEZ_MEMORY_RESERVE_FRACTION init|= literal|"tez.task.scale.memory.reserve-fraction" decl_stmt|; specifier|private name|TezCounters name|counters decl_stmt|; specifier|private specifier|final name|DagUtils name|utils decl_stmt|; specifier|private specifier|final name|Object name|dagClientLock init|= operator|new name|Object argument_list|() decl_stmt|; specifier|private specifier|volatile name|boolean name|isShutdown init|= literal|false decl_stmt|; specifier|private name|DAGClient name|dagClient init|= literal|null decl_stmt|; name|Map argument_list|< name|BaseWork argument_list|, name|Vertex argument_list|> name|workToVertex init|= operator|new name|HashMap argument_list|< name|BaseWork argument_list|, name|Vertex argument_list|> argument_list|() decl_stmt|; name|Map argument_list|< name|BaseWork argument_list|, name|JobConf argument_list|> name|workToConf init|= operator|new name|HashMap argument_list|< name|BaseWork argument_list|, name|JobConf argument_list|> argument_list|() decl_stmt|; specifier|public name|TezTask parameter_list|() block|{ name|this argument_list|( name|DagUtils operator|. name|getInstance argument_list|() argument_list|) expr_stmt|; block|} specifier|public name|TezTask parameter_list|( name|DagUtils name|utils parameter_list|) block|{ name|super argument_list|() expr_stmt|; name|this operator|. name|utils operator|= name|utils expr_stmt|; block|} specifier|public name|TezCounters name|getTezCounters parameter_list|() block|{ return|return name|counters return|; block|} annotation|@ name|Override specifier|public name|int name|execute parameter_list|() block|{ name|int name|rc init|= literal|1 decl_stmt|; name|boolean name|cleanContext init|= literal|false decl_stmt|; name|Context name|ctx init|= literal|null decl_stmt|; name|Ref argument_list|< name|TezSessionState argument_list|> name|sessionRef init|= name|Ref operator|. name|from argument_list|( literal|null argument_list|) decl_stmt|; try|try block|{ comment|// Get or create Context object. If we create it we have to clean it later as well. name|ctx operator|= name|context expr_stmt|; if|if condition|( name|ctx operator|== literal|null condition|) block|{ name|ctx operator|= operator|new name|Context argument_list|( name|conf argument_list|) expr_stmt|; name|cleanContext operator|= literal|true expr_stmt|; comment|// some DDL task that directly executes a TezTask does not setup Context and hence TriggerContext. comment|// Setting queryId is messed up. Some DDL tasks have executionId instead of proper queryId. name|String name|queryId init|= name|HiveConf operator|. name|getVar argument_list|( name|conf argument_list|, name|HiveConf operator|. name|ConfVars operator|. name|HIVEQUERYID argument_list|) decl_stmt|; name|WmContext name|wmContext init|= operator|new name|WmContext argument_list|( name|System operator|. name|currentTimeMillis argument_list|() argument_list|, name|queryId argument_list|) decl_stmt|; name|ctx operator|. name|setWmContext argument_list|( name|wmContext argument_list|) expr_stmt|; block|} comment|// Need to remove this static hack. But this is the way currently to get a session. name|SessionState name|ss init|= name|SessionState operator|. name|get argument_list|() decl_stmt|; comment|// Note: given that we return pool sessions to the pool in the finally block below, and that comment|// we need to set the global to null to do that, this "reuse" may be pointless. name|TezSessionState name|session init|= name|sessionRef operator|. name|value operator|= name|ss operator|. name|getTezSession argument_list|() decl_stmt|; if|if condition|( name|session operator|!= literal|null operator|&& operator|! name|session operator|. name|isOpen argument_list|() condition|) block|{ name|LOG operator|. name|warn argument_list|( literal|"The session: " operator|+ name|session operator|+ literal|" has not been opened" argument_list|) expr_stmt|; block|} comment|// We only need a username for UGI to use for groups; getGroups will fetch the groups comment|// based on Hadoop configuration, as documented at comment|// https://hadoop.apache.org/docs/r2.8.0/hadoop-project-dist/hadoop-common/GroupsMapping.html name|String name|userName init|= name|getUserNameForGroups argument_list|( name|ss argument_list|) decl_stmt|; name|List argument_list|< name|String argument_list|> name|groups init|= literal|null decl_stmt|; if|if condition|( name|userName operator|== literal|null condition|) block|{ name|userName operator|= literal|"anonymous" expr_stmt|; block|} else|else block|{ try|try block|{ name|groups operator|= name|UserGroupInformation operator|. name|createRemoteUser argument_list|( name|userName argument_list|) operator|. name|getGroups argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|ex parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Cannot obtain groups for " operator|+ name|userName argument_list|, name|ex argument_list|) expr_stmt|; block|} block|} name|MappingInput name|mi init|= operator|new name|MappingInput argument_list|( name|userName argument_list|, name|groups argument_list|, name|ss operator|. name|getHiveVariables argument_list|() operator|. name|get argument_list|( literal|"wmpool" argument_list|) argument_list|, name|ss operator|. name|getHiveVariables argument_list|() operator|. name|get argument_list|( literal|"wmapp" argument_list|) argument_list|) decl_stmt|; name|WmContext name|wmContext init|= name|ctx operator|. name|getWmContext argument_list|() decl_stmt|; comment|// jobConf will hold all the configuration for hadoop, tez, and hive, which are not set in AM defaults name|JobConf name|jobConf init|= name|utils operator|. name|createConfiguration argument_list|( name|conf argument_list|, literal|false argument_list|) decl_stmt|; comment|// Get all user jars from work (e.g. input format stuff). name|String index|[] name|allNonConfFiles init|= name|work operator|. name|configureJobConfAndExtractJars argument_list|( name|jobConf argument_list|) decl_stmt|; comment|// DAG scratch dir. We get a session from the pool so it may be different from Tez one. comment|// TODO: we could perhaps reuse the same directory for HiveResources? name|Path name|scratchDir init|= name|utils operator|. name|createTezDir argument_list|( name|ctx operator|. name|getMRScratchDir argument_list|() argument_list|, name|conf argument_list|) decl_stmt|; name|CallerContext name|callerContext init|= name|CallerContext operator|. name|create argument_list|( literal|"HIVE" argument_list|, name|queryPlan operator|. name|getQueryId argument_list|() argument_list|, literal|"HIVE_QUERY_ID" argument_list|, name|queryPlan operator|. name|getQueryStr argument_list|() argument_list|) decl_stmt|; name|perfLogger operator|. name|PerfLogBegin argument_list|( name|CLASS_NAME argument_list|, name|PerfLogger operator|. name|TEZ_GET_SESSION argument_list|) expr_stmt|; name|session operator|= name|sessionRef operator|. name|value operator|= name|WorkloadManagerFederation operator|. name|getSession argument_list|( name|sessionRef operator|. name|value argument_list|, name|conf argument_list|, name|mi argument_list|, name|getWork argument_list|() operator|. name|getLlapMode argument_list|() argument_list|, name|wmContext argument_list|) expr_stmt|; name|perfLogger operator|. name|PerfLogEnd argument_list|( name|CLASS_NAME argument_list|, name|PerfLogger operator|. name|TEZ_GET_SESSION argument_list|) expr_stmt|; try|try block|{ name|ss operator|. name|setTezSession argument_list|( name|session argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Subscribed to counters: {} for queryId: {}" argument_list|, name|wmContext operator|. name|getSubscribedCounters argument_list|() argument_list|, name|wmContext operator|. name|getQueryId argument_list|() argument_list|) expr_stmt|; comment|// Ensure the session is open and has the necessary local resources. comment|// This would refresh any conf resources and also local resources. name|ensureSessionHasResources argument_list|( name|session argument_list|, name|allNonConfFiles argument_list|) expr_stmt|; comment|// This is a combination of the jar stuff from conf, and not from conf. name|List argument_list|< name|LocalResource argument_list|> name|allNonAppResources init|= name|session operator|. name|getLocalizedResources argument_list|() decl_stmt|; name|logResources argument_list|( name|allNonAppResources argument_list|) expr_stmt|; name|Map argument_list|< name|String argument_list|, name|LocalResource argument_list|> name|allResources init|= name|DagUtils operator|. name|createTezLrMap argument_list|( name|session operator|. name|getAppJarLr argument_list|() argument_list|, name|allNonAppResources argument_list|) decl_stmt|; comment|// next we translate the TezWork to a Tez DAG name|DAG name|dag init|= name|build argument_list|( name|jobConf argument_list|, name|work argument_list|, name|scratchDir argument_list|, name|ctx argument_list|, name|allResources argument_list|) decl_stmt|; name|dag operator|. name|setCallerContext argument_list|( name|callerContext argument_list|) expr_stmt|; comment|// Note: we no longer call addTaskLocalFiles because all the resources are correctly comment|// updated in the session resource lists now, and thus added to vertices. comment|// If something breaks, dag.addTaskLocalFiles might need to be called here. comment|// Check isShutdown opportunistically; it's never unset. if|if condition|( name|this operator|. name|isShutdown condition|) block|{ throw|throw operator|new name|HiveException argument_list|( literal|"Operation cancelled" argument_list|) throw|; block|} name|DAGClient name|dagClient init|= name|submit argument_list|( name|dag argument_list|, name|sessionRef argument_list|) decl_stmt|; name|session operator|= name|sessionRef operator|. name|value expr_stmt|; name|boolean name|wasShutdown init|= literal|false decl_stmt|; synchronized|synchronized init|( name|dagClientLock init|) block|{ assert|assert name|this operator|. name|dagClient operator|== literal|null assert|; name|wasShutdown operator|= name|this operator|. name|isShutdown expr_stmt|; if|if condition|( operator|! name|wasShutdown condition|) block|{ name|this operator|. name|dagClient operator|= name|dagClient expr_stmt|; block|} block|} if|if condition|( name|wasShutdown condition|) block|{ name|closeDagClientOnCancellation argument_list|( name|dagClient argument_list|) expr_stmt|; throw|throw operator|new name|HiveException argument_list|( literal|"Operation cancelled" argument_list|) throw|; block|} comment|// finally monitor will print progress until the job is done name|TezJobMonitor name|monitor init|= operator|new name|TezJobMonitor argument_list|( name|work operator|. name|getAllWork argument_list|() argument_list|, name|dagClient argument_list|, name|conf argument_list|, name|dag argument_list|, name|ctx argument_list|) decl_stmt|; name|rc operator|= name|monitor operator|. name|monitorExecution argument_list|() expr_stmt|; if|if condition|( name|rc operator|!= literal|0 condition|) block|{ name|this operator|. name|setException argument_list|( operator|new name|HiveException argument_list|( name|monitor operator|. name|getDiagnostics argument_list|() argument_list|) argument_list|) expr_stmt|; block|} comment|// fetch the counters try|try block|{ name|Set argument_list|< name|StatusGetOpts argument_list|> name|statusGetOpts init|= name|EnumSet operator|. name|of argument_list|( name|StatusGetOpts operator|. name|GET_COUNTERS argument_list|) decl_stmt|; name|counters operator|= name|dagClient operator|. name|getDAGStatus argument_list|( name|statusGetOpts argument_list|) operator|. name|getDAGCounters argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|err parameter_list|) block|{ comment|// Don't fail execution due to counters - just don't print summary info name|LOG operator|. name|warn argument_list|( literal|"Failed to get counters. Ignoring, summary info will be incomplete. " operator|+ name|err argument_list|, name|err argument_list|) expr_stmt|; name|counters operator|= literal|null expr_stmt|; block|} block|} finally|finally block|{ comment|// Note: due to TEZ-3846, the session may actually be invalid in case of some errors. comment|// Currently, reopen on an attempted reuse will take care of that; we cannot tell comment|// if the session is usable until we try. comment|// We return this to the pool even if it's unusable; reopen is supposed to handle this. name|wmContext operator|= name|ctx operator|. name|getWmContext argument_list|() expr_stmt|; try|try block|{ if|if condition|( name|sessionRef operator|. name|value operator|!= literal|null condition|) block|{ name|sessionRef operator|. name|value operator|. name|returnToSessionManager argument_list|() expr_stmt|; block|} block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|LOG operator|. name|error argument_list|( literal|"Failed to return session: {} to pool" argument_list|, name|session argument_list|, name|e argument_list|) expr_stmt|; throw|throw name|e throw|; block|} if|if condition|( operator|! name|conf operator|. name|getVar argument_list|( name|HiveConf operator|. name|ConfVars operator|. name|TEZ_SESSION_EVENTS_SUMMARY argument_list|) operator|. name|equalsIgnoreCase argument_list|( literal|"none" argument_list|) operator|&& name|wmContext operator|!= literal|null condition|) block|{ if|if condition|( name|conf operator|. name|getVar argument_list|( name|HiveConf operator|. name|ConfVars operator|. name|TEZ_SESSION_EVENTS_SUMMARY argument_list|) operator|. name|equalsIgnoreCase argument_list|( literal|"json" argument_list|) condition|) block|{ name|wmContext operator|. name|printJson argument_list|( name|console argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|conf operator|. name|getVar argument_list|( name|HiveConf operator|. name|ConfVars operator|. name|TEZ_SESSION_EVENTS_SUMMARY argument_list|) operator|. name|equalsIgnoreCase argument_list|( literal|"text" argument_list|) condition|) block|{ name|wmContext operator|. name|print argument_list|( name|console argument_list|) expr_stmt|; block|} block|} block|} if|if condition|( name|LOG operator|. name|isInfoEnabled argument_list|() operator|&& name|counters operator|!= literal|null operator|&& operator|( name|HiveConf operator|. name|getBoolVar argument_list|( name|conf argument_list|, name|HiveConf operator|. name|ConfVars operator|. name|TEZ_EXEC_SUMMARY argument_list|) operator||| name|Utilities operator|. name|isPerfOrAboveLogging argument_list|( name|conf argument_list|) operator|) condition|) block|{ for|for control|( name|CounterGroup name|group range|: name|counters control|) block|{ name|LOG operator|. name|info argument_list|( name|group operator|. name|getDisplayName argument_list|() operator|+ literal|":" argument_list|) expr_stmt|; for|for control|( name|TezCounter name|counter range|: name|group control|) block|{ name|LOG operator|. name|info argument_list|( literal|" " operator|+ name|counter operator|. name|getDisplayName argument_list|() operator|+ literal|": " operator|+ name|counter operator|. name|getValue argument_list|() argument_list|) expr_stmt|; block|} block|} block|} name|updateNumRows argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|LOG operator|. name|error argument_list|( literal|"Failed to execute tez graph." argument_list|, name|e argument_list|) expr_stmt|; name|setException argument_list|( name|e argument_list|) expr_stmt|; comment|// rc will be 1 at this point indicating failure. block|} finally|finally block|{ name|Utilities operator|. name|clearWork argument_list|( name|conf argument_list|) expr_stmt|; comment|// Clear gWorkMap for|for control|( name|BaseWork name|w range|: name|work operator|. name|getAllWork argument_list|() control|) block|{ name|JobConf name|workCfg init|= name|workToConf operator|. name|get argument_list|( name|w argument_list|) decl_stmt|; if|if condition|( name|workCfg operator|!= literal|null condition|) block|{ name|Utilities operator|. name|clearWorkMapForConf argument_list|( name|workCfg argument_list|) expr_stmt|; block|} block|} if|if condition|( name|cleanContext condition|) block|{ try|try block|{ name|ctx operator|. name|clear argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ comment|/*best effort*/ name|LOG operator|. name|warn argument_list|( literal|"Failed to clean up after tez job" argument_list|, name|e argument_list|) expr_stmt|; block|} block|} comment|// need to either move tmp files or remove them name|DAGClient name|dagClient init|= literal|null decl_stmt|; synchronized|synchronized init|( name|dagClientLock init|) block|{ name|dagClient operator|= name|this operator|. name|dagClient expr_stmt|; name|this operator|. name|dagClient operator|= literal|null expr_stmt|; block|} comment|// TODO: not clear why we don't do the rest of the cleanup if dagClient is not created. comment|// E.g. jobClose will be called if we fail after dagClient creation but no before... comment|// DagClient as such should have no bearing on jobClose. if|if condition|( name|dagClient operator|!= literal|null condition|) block|{ comment|// rc will only be overwritten if close errors out name|rc operator|= name|close argument_list|( name|work argument_list|, name|rc argument_list|, name|dagClient argument_list|) expr_stmt|; block|} block|} return|return name|rc return|; block|} specifier|private name|void name|updateNumRows parameter_list|() block|{ if|if condition|( name|counters operator|!= literal|null condition|) block|{ name|TezCounter name|counter init|= name|counters operator|. name|findCounter argument_list|( name|conf operator|. name|getVar argument_list|( name|HiveConf operator|. name|ConfVars operator|. name|HIVECOUNTERGROUP argument_list|) argument_list|, name|FileSinkOperator operator|. name|TOTAL_TABLE_ROWS_WRITTEN argument_list|) decl_stmt|; if|if condition|( name|counter operator|!= literal|null condition|) block|{ name|queryState operator|. name|setNumModifiedRows argument_list|( name|counter operator|. name|getValue argument_list|() argument_list|) expr_stmt|; block|} block|} block|} specifier|private name|String name|getUserNameForGroups parameter_list|( name|SessionState name|ss parameter_list|) block|{ comment|// This should be removed when authenticator and the 2-username mess is cleaned up. if|if condition|( name|ss operator|. name|getAuthenticator argument_list|() operator|!= literal|null condition|) block|{ name|String name|userName init|= name|ss operator|. name|getAuthenticator argument_list|() operator|. name|getUserName argument_list|() decl_stmt|; if|if condition|( name|userName operator|!= literal|null condition|) return|return name|userName return|; block|} return|return name|ss operator|. name|getUserName argument_list|() return|; block|} specifier|private name|void name|closeDagClientOnCancellation parameter_list|( name|DAGClient name|dagClient parameter_list|) block|{ try|try block|{ name|dagClient operator|. name|tryKillDAG argument_list|() expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Waiting for Tez task to shut down: " operator|+ name|this argument_list|) expr_stmt|; name|dagClient operator|. name|waitForCompletion argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|ex parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Failed to shut down TezTask" operator|+ name|this argument_list|, name|ex argument_list|) expr_stmt|; block|} name|closeDagClientWithoutEx argument_list|( name|dagClient argument_list|) expr_stmt|; block|} specifier|private name|void name|logResources parameter_list|( name|List argument_list|< name|LocalResource argument_list|> name|additionalLr parameter_list|) block|{ comment|// log which resources we're adding (apart from the hive exec) if|if condition|( operator|! name|LOG operator|. name|isDebugEnabled argument_list|() condition|) return|return; if|if condition|( name|additionalLr operator|== literal|null operator||| name|additionalLr operator|. name|size argument_list|() operator|== literal|0 condition|) block|{ name|LOG operator|. name|debug argument_list|( literal|"No local resources to process (other than hive-exec)" argument_list|) expr_stmt|; block|} else|else block|{ for|for control|( name|LocalResource name|lr range|: name|additionalLr control|) block|{ name|LOG operator|. name|debug argument_list|( literal|"Adding local resource: " operator|+ name|lr operator|. name|getResource argument_list|() argument_list|) expr_stmt|; block|} block|} block|} comment|/** * Ensures that the Tez Session is open and the AM has all necessary jars configured. */ annotation|@ name|VisibleForTesting name|void name|ensureSessionHasResources parameter_list|( name|TezSessionState name|session parameter_list|, name|String index|[] name|nonConfResources parameter_list|) throws|throws name|Exception block|{ name|TezClient name|client init|= name|session operator|. name|getSession argument_list|() decl_stmt|; comment|// TODO null can also mean that this operation was interrupted. Should we really try to re-create the session in that case ? if|if condition|( name|client operator|== literal|null condition|) block|{ comment|// Note: the only sane case where this can happen is the non-pool one. We should get rid comment|// of it, in non-pool case perf doesn't matter so we might as well open at get time comment|// and then call update like we do in the else. comment|// Can happen if the user sets the tez flag after the session was established. name|LOG operator|. name|info argument_list|( literal|"Tez session hasn't been created yet. Opening session" argument_list|) expr_stmt|; name|session operator|. name|open argument_list|( name|nonConfResources argument_list|) expr_stmt|; block|} else|else block|{ name|LOG operator|. name|info argument_list|( literal|"Session is already open" argument_list|) expr_stmt|; name|session operator|. name|ensureLocalResources argument_list|( name|conf argument_list|, name|nonConfResources argument_list|) expr_stmt|; block|} block|} name|void name|checkOutputSpec parameter_list|( name|BaseWork name|work parameter_list|, name|JobConf name|jc parameter_list|) throws|throws name|IOException block|{ for|for control|( name|Operator argument_list|< name|? argument_list|> name|op range|: name|work operator|. name|getAllOperators argument_list|() control|) block|{ if|if condition|( name|op operator|instanceof name|FileSinkOperator condition|) block|{ operator|( operator|( name|FileSinkOperator operator|) name|op operator|) operator|. name|checkOutputSpecs argument_list|( literal|null argument_list|, name|jc argument_list|) expr_stmt|; block|} block|} block|} name|DAG name|build parameter_list|( name|JobConf name|conf parameter_list|, name|TezWork name|work parameter_list|, name|Path name|scratchDir parameter_list|, name|Context name|ctx parameter_list|, name|Map argument_list|< name|String argument_list|, name|LocalResource argument_list|> name|vertexResources parameter_list|) throws|throws name|Exception block|{ name|perfLogger operator|. name|PerfLogBegin argument_list|( name|CLASS_NAME argument_list|, name|PerfLogger operator|. name|TEZ_BUILD_DAG argument_list|) expr_stmt|; comment|// getAllWork returns a topologically sorted list, which we use to make comment|// sure that vertices are created before they are used in edges. name|List argument_list|< name|BaseWork argument_list|> name|ws init|= name|work operator|. name|getAllWork argument_list|() decl_stmt|; name|Collections operator|. name|reverse argument_list|( name|ws argument_list|) expr_stmt|; name|FileSystem name|fs init|= name|scratchDir operator|. name|getFileSystem argument_list|( name|conf argument_list|) decl_stmt|; comment|// the name of the dag is what is displayed in the AM/Job UI name|String name|dagName init|= name|utils operator|. name|createDagName argument_list|( name|conf argument_list|, name|queryPlan argument_list|) decl_stmt|; name|LOG operator|. name|info argument_list|( literal|"Dag name: " operator|+ name|dagName argument_list|) expr_stmt|; name|DAG name|dag init|= name|DAG operator|. name|create argument_list|( name|dagName argument_list|) decl_stmt|; comment|// set some info for the query name|JSONObject name|json init|= operator|new name|JSONObject argument_list|( operator|new name|LinkedHashMap argument_list|<> argument_list|() argument_list|) operator|. name|put argument_list|( literal|"context" argument_list|, literal|"Hive" argument_list|) operator|. name|put argument_list|( literal|"description" argument_list|, name|ctx operator|. name|getCmd argument_list|() argument_list|) decl_stmt|; name|String name|dagInfo init|= name|json operator|. name|toString argument_list|() decl_stmt|; if|if condition|( name|LOG operator|. name|isDebugEnabled argument_list|() condition|) block|{ name|LOG operator|. name|debug argument_list|( literal|"DagInfo: " operator|+ name|dagInfo argument_list|) expr_stmt|; block|} name|dag operator|. name|setDAGInfo argument_list|( name|dagInfo argument_list|) expr_stmt|; name|dag operator|. name|setCredentials argument_list|( name|conf operator|. name|getCredentials argument_list|() argument_list|) expr_stmt|; name|setAccessControlsForCurrentUser argument_list|( name|dag argument_list|, name|queryPlan operator|. name|getQueryId argument_list|() argument_list|, name|conf argument_list|) expr_stmt|; for|for control|( name|BaseWork name|w range|: name|ws control|) block|{ name|boolean name|isFinal init|= name|work operator|. name|getLeaves argument_list|() operator|. name|contains argument_list|( name|w argument_list|) decl_stmt|; comment|// translate work to vertex name|perfLogger operator|. name|PerfLogBegin argument_list|( name|CLASS_NAME argument_list|, name|PerfLogger operator|. name|TEZ_CREATE_VERTEX operator|+ name|w operator|. name|getName argument_list|() argument_list|) expr_stmt|; if|if condition|( name|w operator|instanceof name|UnionWork condition|) block|{ comment|// Special case for unions. These items translate to VertexGroups name|List argument_list|< name|BaseWork argument_list|> name|unionWorkItems init|= operator|new name|LinkedList argument_list|< name|BaseWork argument_list|> argument_list|() decl_stmt|; name|List argument_list|< name|BaseWork argument_list|> name|children init|= operator|new name|LinkedList argument_list|< name|BaseWork argument_list|> argument_list|() decl_stmt|; comment|// split the children into vertices that make up the union and vertices that are comment|// proper children of the union for|for control|( name|BaseWork name|v range|: name|work operator|. name|getChildren argument_list|( name|w argument_list|) control|) block|{ name|EdgeType name|type init|= name|work operator|. name|getEdgeProperty argument_list|( name|w argument_list|, name|v argument_list|) operator|. name|getEdgeType argument_list|() decl_stmt|; if|if condition|( name|type operator|== name|EdgeType operator|. name|CONTAINS condition|) block|{ name|unionWorkItems operator|. name|add argument_list|( name|v argument_list|) expr_stmt|; block|} else|else block|{ name|children operator|. name|add argument_list|( name|v argument_list|) expr_stmt|; block|} block|} name|JobConf name|parentConf init|= name|workToConf operator|. name|get argument_list|( name|unionWorkItems operator|. name|get argument_list|( literal|0 argument_list|) argument_list|) decl_stmt|; name|checkOutputSpec argument_list|( name|w argument_list|, name|parentConf argument_list|) expr_stmt|; comment|// create VertexGroup name|Vertex index|[] name|vertexArray init|= operator|new name|Vertex index|[ name|unionWorkItems operator|. name|size argument_list|() index|] decl_stmt|; name|int name|i init|= literal|0 decl_stmt|; for|for control|( name|BaseWork name|v range|: name|unionWorkItems control|) block|{ name|vertexArray index|[ name|i operator|++ index|] operator|= name|workToVertex operator|. name|get argument_list|( name|v argument_list|) expr_stmt|; block|} name|VertexGroup name|group init|= name|dag operator|. name|createVertexGroup argument_list|( name|w operator|. name|getName argument_list|() argument_list|, name|vertexArray argument_list|) decl_stmt|; comment|// For a vertex group, all Outputs use the same Key-class, Val-class and partitioner. comment|// Pick any one source vertex to figure out the Edge configuration. comment|// now hook up the children for|for control|( name|BaseWork name|v range|: name|children control|) block|{ comment|// finally we can create the grouped edge name|GroupInputEdge name|e init|= name|utils operator|. name|createEdge argument_list|( name|group argument_list|, name|parentConf argument_list|, name|workToVertex operator|. name|get argument_list|( name|v argument_list|) argument_list|, name|work operator|. name|getEdgeProperty argument_list|( name|w argument_list|, name|v argument_list|) argument_list|, name|v argument_list|, name|work argument_list|) decl_stmt|; name|dag operator|. name|addEdge argument_list|( name|e argument_list|) expr_stmt|; block|} block|} else|else block|{ comment|// Regular vertices name|JobConf name|wxConf init|= name|utils operator|. name|initializeVertexConf argument_list|( name|conf argument_list|, name|ctx argument_list|, name|w argument_list|) decl_stmt|; name|checkOutputSpec argument_list|( name|w argument_list|, name|wxConf argument_list|) expr_stmt|; name|Vertex name|wx init|= name|utils operator|. name|createVertex argument_list|( name|wxConf argument_list|, name|w argument_list|, name|scratchDir argument_list|, name|fs argument_list|, name|ctx argument_list|, operator|! name|isFinal argument_list|, name|work argument_list|, name|work operator|. name|getVertexType argument_list|( name|w argument_list|) argument_list|, name|vertexResources argument_list|) decl_stmt|; if|if condition|( name|work operator|. name|getChildren argument_list|( name|w argument_list|) operator|. name|size argument_list|() operator|> literal|1 condition|) block|{ name|String name|value init|= name|wxConf operator|. name|get argument_list|( name|TezRuntimeConfiguration operator|. name|TEZ_RUNTIME_IO_SORT_MB argument_list|) decl_stmt|; name|int name|originalValue init|= literal|0 decl_stmt|; if|if condition|( name|value operator|== literal|null condition|) block|{ name|originalValue operator|= name|TezRuntimeConfiguration operator|. name|TEZ_RUNTIME_IO_SORT_MB_DEFAULT expr_stmt|; block|} else|else block|{ name|originalValue operator|= name|Integer operator|. name|valueOf argument_list|( name|value argument_list|) expr_stmt|; block|} name|int name|newValue init|= call|( name|int call|) argument_list|( name|originalValue operator|/ name|work operator|. name|getChildren argument_list|( name|w argument_list|) operator|. name|size argument_list|() argument_list|) decl_stmt|; name|wxConf operator|. name|set argument_list|( name|TezRuntimeConfiguration operator|. name|TEZ_RUNTIME_IO_SORT_MB argument_list|, name|Integer operator|. name|toString argument_list|( name|newValue argument_list|) argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Modified " operator|+ name|TezRuntimeConfiguration operator|. name|TEZ_RUNTIME_IO_SORT_MB operator|+ literal|" to " operator|+ name|newValue argument_list|) expr_stmt|; block|} if|if condition|( name|w operator|. name|getReservedMemoryMB argument_list|() operator|> literal|0 condition|) block|{ comment|// If reversedMemoryMB is set, make memory allocation fraction adjustment as needed name|double name|frac init|= name|DagUtils operator|. name|adjustMemoryReserveFraction argument_list|( name|w operator|. name|getReservedMemoryMB argument_list|() argument_list|, name|super operator|. name|conf argument_list|) decl_stmt|; name|LOG operator|. name|info argument_list|( literal|"Setting " operator|+ name|TEZ_MEMORY_RESERVE_FRACTION operator|+ literal|" to " operator|+ name|frac argument_list|) expr_stmt|; name|wx operator|. name|setConf argument_list|( name|TEZ_MEMORY_RESERVE_FRACTION argument_list|, name|Double operator|. name|toString argument_list|( name|frac argument_list|) argument_list|) expr_stmt|; block|} comment|// Otherwise just leave it up to Tez to decide how much memory to allocate name|dag operator|. name|addVertex argument_list|( name|wx argument_list|) expr_stmt|; name|utils operator|. name|addCredentials argument_list|( name|w argument_list|, name|dag argument_list|) expr_stmt|; name|perfLogger operator|. name|PerfLogEnd argument_list|( name|CLASS_NAME argument_list|, name|PerfLogger operator|. name|TEZ_CREATE_VERTEX operator|+ name|w operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|workToVertex operator|. name|put argument_list|( name|w argument_list|, name|wx argument_list|) expr_stmt|; name|workToConf operator|. name|put argument_list|( name|w argument_list|, name|wxConf argument_list|) expr_stmt|; comment|// add all dependencies (i.e.: edges) to the graph for|for control|( name|BaseWork name|v range|: name|work operator|. name|getChildren argument_list|( name|w argument_list|) control|) block|{ assert|assert name|workToVertex operator|. name|containsKey argument_list|( name|v argument_list|) assert|; name|Edge name|e init|= literal|null decl_stmt|; name|TezEdgeProperty name|edgeProp init|= name|work operator|. name|getEdgeProperty argument_list|( name|w argument_list|, name|v argument_list|) decl_stmt|; name|e operator|= name|utils operator|. name|createEdge argument_list|( name|wxConf argument_list|, name|wx argument_list|, name|workToVertex operator|. name|get argument_list|( name|v argument_list|) argument_list|, name|edgeProp argument_list|, name|v argument_list|, name|work argument_list|) expr_stmt|; name|dag operator|. name|addEdge argument_list|( name|e argument_list|) expr_stmt|; block|} block|} block|} comment|// Clear the work map after build. TODO: remove caching instead? name|Utilities operator|. name|clearWorkMap argument_list|( name|conf argument_list|) expr_stmt|; name|perfLogger operator|. name|PerfLogEnd argument_list|( name|CLASS_NAME argument_list|, name|PerfLogger operator|. name|TEZ_BUILD_DAG argument_list|) expr_stmt|; return|return name|dag return|; block|} specifier|private specifier|static name|void name|setAccessControlsForCurrentUser parameter_list|( name|DAG name|dag parameter_list|, name|String name|queryId parameter_list|, name|Configuration name|conf parameter_list|) throws|throws name|IOException block|{ name|String name|user init|= name|SessionState operator|. name|getUserFromAuthenticator argument_list|() decl_stmt|; name|UserGroupInformation name|loginUserUgi init|= name|UserGroupInformation operator|. name|getLoginUser argument_list|() decl_stmt|; name|String name|loginUser init|= name|loginUserUgi operator|== literal|null condition|? literal|null else|: name|loginUserUgi operator|. name|getShortUserName argument_list|() decl_stmt|; name|boolean name|addHs2User init|= name|HiveConf operator|. name|getBoolVar argument_list|( name|conf argument_list|, name|HiveConf operator|. name|ConfVars operator|. name|HIVETEZHS2USERACCESS argument_list|) decl_stmt|; comment|// Temporarily re-using the TEZ AM View ACLs property for individual dag access control. comment|// Hive may want to setup it's own parameters if it wants to control per dag access. comment|// Setting the tez-property per dag should work for now. name|String name|viewStr init|= name|Utilities operator|. name|getAclStringWithHiveModification argument_list|( name|conf argument_list|, name|TezConfiguration operator|. name|TEZ_AM_VIEW_ACLS argument_list|, name|addHs2User argument_list|, name|user argument_list|, name|loginUser argument_list|) decl_stmt|; name|String name|modifyStr init|= name|Utilities operator|. name|getAclStringWithHiveModification argument_list|( name|conf argument_list|, name|TezConfiguration operator|. name|TEZ_AM_MODIFY_ACLS argument_list|, name|addHs2User argument_list|, name|user argument_list|, name|loginUser argument_list|) decl_stmt|; if|if condition|( name|LOG operator|. name|isDebugEnabled argument_list|() condition|) block|{ name|LOG operator|. name|debug argument_list|( literal|"Setting Tez DAG access for queryId={} with viewAclString={}, modifyStr={}" argument_list|, name|queryId argument_list|, name|viewStr argument_list|, name|modifyStr argument_list|) expr_stmt|; block|} comment|// set permissions for current user on DAG name|DAGAccessControls name|ac init|= operator|new name|DAGAccessControls argument_list|( name|viewStr argument_list|, name|modifyStr argument_list|) decl_stmt|; name|dag operator|. name|setAccessControls argument_list|( name|ac argument_list|) expr_stmt|; block|} specifier|private name|TezSessionState name|getNewTezSessionOnError parameter_list|( name|TezSessionState name|oldSession parameter_list|) throws|throws name|Exception block|{ comment|// Note: we don't pass the config to reopen. If the session was already open, it would comment|// have kept running with its current config - preserve that behavior. name|TezSessionState name|newSession init|= name|oldSession operator|. name|reopen argument_list|() decl_stmt|; name|console operator|. name|printInfo argument_list|( literal|"Session re-established." argument_list|) expr_stmt|; return|return name|newSession return|; block|} name|DAGClient name|submit parameter_list|( name|DAG name|dag parameter_list|, name|Ref argument_list|< name|TezSessionState argument_list|> name|sessionStateRef parameter_list|) throws|throws name|Exception block|{ name|perfLogger operator|. name|PerfLogBegin argument_list|( name|CLASS_NAME argument_list|, name|PerfLogger operator|. name|TEZ_SUBMIT_DAG argument_list|) expr_stmt|; name|DAGClient name|dagClient init|= literal|null decl_stmt|; name|TezSessionState name|sessionState init|= name|sessionStateRef operator|. name|value decl_stmt|; try|try block|{ try|try block|{ comment|// ready to start execution on the cluster name|dagClient operator|= name|sessionState operator|. name|getSession argument_list|() operator|. name|submitDAG argument_list|( name|dag argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|SessionNotRunning name|nr parameter_list|) block|{ name|console operator|. name|printInfo argument_list|( literal|"Tez session was closed. Reopening..." argument_list|) expr_stmt|; name|sessionStateRef operator|. name|value operator|= literal|null expr_stmt|; name|sessionStateRef operator|. name|value operator|= name|sessionState operator|= name|getNewTezSessionOnError argument_list|( name|sessionState argument_list|) expr_stmt|; name|console operator|. name|printInfo argument_list|( literal|"Session re-established." argument_list|) expr_stmt|; name|dagClient operator|= name|sessionState operator|. name|getSession argument_list|() operator|. name|submitDAG argument_list|( name|dag argument_list|) expr_stmt|; block|} block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ comment|// In case of any other exception, retry. If this also fails, report original error and exit. try|try block|{ name|console operator|. name|printInfo argument_list|( literal|"Dag submit failed due to " operator|+ name|e operator|. name|getMessage argument_list|() operator|+ literal|" stack trace: " operator|+ name|Arrays operator|. name|toString argument_list|( name|e operator|. name|getStackTrace argument_list|() argument_list|) operator|+ literal|" retrying..." argument_list|) expr_stmt|; name|sessionStateRef operator|. name|value operator|= literal|null expr_stmt|; name|sessionStateRef operator|. name|value operator|= name|sessionState operator|= name|getNewTezSessionOnError argument_list|( name|sessionState argument_list|) expr_stmt|; name|dagClient operator|= name|sessionState operator|. name|getSession argument_list|() operator|. name|submitDAG argument_list|( name|dag argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|retryException parameter_list|) block|{ comment|// we failed to submit after retrying. Destroy session and bail. name|sessionStateRef operator|. name|value operator|= literal|null expr_stmt|; name|sessionState operator|. name|destroy argument_list|() expr_stmt|; throw|throw name|retryException throw|; block|} block|} name|perfLogger operator|. name|PerfLogEnd argument_list|( name|CLASS_NAME argument_list|, name|PerfLogger operator|. name|TEZ_SUBMIT_DAG argument_list|) expr_stmt|; return|return operator|new name|SyncDagClient argument_list|( name|dagClient argument_list|) return|; block|} comment|/* * close will move the temp files into the right place for the fetch * task. If the job has failed it will clean up the files. */ annotation|@ name|VisibleForTesting name|int name|close parameter_list|( name|TezWork name|work parameter_list|, name|int name|rc parameter_list|, name|DAGClient name|dagClient parameter_list|) block|{ try|try block|{ name|List argument_list|< name|BaseWork argument_list|> name|ws init|= name|work operator|. name|getAllWork argument_list|() decl_stmt|; for|for control|( name|BaseWork name|w range|: name|ws control|) block|{ if|if condition|( name|w operator|instanceof name|MergeJoinWork condition|) block|{ name|w operator|= operator|( operator|( name|MergeJoinWork operator|) name|w operator|) operator|. name|getMainWork argument_list|() expr_stmt|; block|} for|for control|( name|Operator argument_list|< name|? argument_list|> name|op range|: name|w operator|. name|getAllOperators argument_list|() control|) block|{ name|op operator|. name|jobClose argument_list|( name|conf argument_list|, name|rc operator|== literal|0 argument_list|) expr_stmt|; block|} block|} block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ comment|// jobClose needs to execute successfully otherwise fail task if|if condition|( name|rc operator|== literal|0 condition|) block|{ name|rc operator|= literal|3 expr_stmt|; name|String name|mesg init|= literal|"Job Commit failed with exception '" operator|+ name|Utilities operator|. name|getNameMessage argument_list|( name|e argument_list|) operator|+ literal|"'" decl_stmt|; name|console operator|. name|printError argument_list|( name|mesg argument_list|, literal|"\n" operator|+ name|StringUtils operator|. name|stringifyException argument_list|( name|e argument_list|) argument_list|) expr_stmt|; block|} block|} if|if condition|( name|dagClient operator|!= literal|null condition|) block|{ comment|// null in tests name|closeDagClientWithoutEx argument_list|( name|dagClient argument_list|) expr_stmt|; block|} return|return name|rc return|; block|} comment|/** * Close DagClient, log warning if it throws any exception. * We don't want to fail query if that function fails. */ specifier|private specifier|static name|void name|closeDagClientWithoutEx parameter_list|( name|DAGClient name|dagClient parameter_list|) block|{ try|try block|{ name|dagClient operator|. name|close argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Failed to close DagClient" argument_list|, name|e argument_list|) expr_stmt|; block|} block|} annotation|@ name|Override specifier|public name|void name|updateTaskMetrics parameter_list|( name|Metrics name|metrics parameter_list|) block|{ name|metrics operator|. name|incrementCounter argument_list|( name|MetricsConstant operator|. name|HIVE_TEZ_TASKS argument_list|) expr_stmt|; block|} annotation|@ name|Override specifier|public name|boolean name|isMapRedTask parameter_list|() block|{ return|return literal|true return|; block|} annotation|@ name|Override specifier|public name|StageType name|getType parameter_list|() block|{ return|return name|StageType operator|. name|MAPRED return|; block|} annotation|@ name|Override specifier|public name|String name|getName parameter_list|() block|{ return|return literal|"TEZ" return|; block|} annotation|@ name|Override specifier|public name|boolean name|canExecuteInParallel parameter_list|() block|{ return|return literal|false return|; block|} annotation|@ name|Override specifier|public name|Collection argument_list|< name|MapWork argument_list|> name|getMapWork parameter_list|() block|{ name|List argument_list|< name|MapWork argument_list|> name|result init|= operator|new name|LinkedList argument_list|< name|MapWork argument_list|> argument_list|() decl_stmt|; name|TezWork name|work init|= name|getWork argument_list|() decl_stmt|; comment|// framework expects MapWork instances that have no physical parents (i.e.: union parent is comment|// fine, broadcast parent isn't) for|for control|( name|BaseWork name|w range|: name|work operator|. name|getAllWorkUnsorted argument_list|() control|) block|{ if|if condition|( name|w operator|instanceof name|MapWork condition|) block|{ name|List argument_list|< name|BaseWork argument_list|> name|parents init|= name|work operator|. name|getParents argument_list|( name|w argument_list|) decl_stmt|; name|boolean name|candidate init|= literal|true decl_stmt|; for|for control|( name|BaseWork name|parent range|: name|parents control|) block|{ if|if condition|( operator|! operator|( name|parent operator|instanceof name|UnionWork operator|) condition|) block|{ name|candidate operator|= literal|false expr_stmt|; block|} block|} if|if condition|( name|candidate condition|) block|{ name|result operator|. name|add argument_list|( operator|( name|MapWork operator|) name|w argument_list|) expr_stmt|; block|} block|} block|} return|return name|result return|; block|} annotation|@ name|Override specifier|public name|Operator argument_list|< name|? extends|extends name|OperatorDesc argument_list|> name|getReducer parameter_list|( name|MapWork name|mapWork parameter_list|) block|{ name|List argument_list|< name|BaseWork argument_list|> name|children init|= name|getWork argument_list|() operator|. name|getChildren argument_list|( name|mapWork argument_list|) decl_stmt|; if|if condition|( name|children operator|. name|size argument_list|() operator|!= literal|1 condition|) block|{ return|return literal|null return|; block|} if|if condition|( operator|! operator|( name|children operator|. name|get argument_list|( literal|0 argument_list|) operator|instanceof name|ReduceWork operator|) condition|) block|{ return|return literal|null return|; block|} return|return operator|( operator|( name|ReduceWork operator|) name|children operator|. name|get argument_list|( literal|0 argument_list|) operator|) operator|. name|getReducer argument_list|() return|; block|} annotation|@ name|Override specifier|public name|void name|shutdown parameter_list|() block|{ name|super operator|. name|shutdown argument_list|() expr_stmt|; name|DAGClient name|dagClient init|= literal|null decl_stmt|; synchronized|synchronized init|( name|dagClientLock init|) block|{ name|isShutdown operator|= literal|true expr_stmt|; name|dagClient operator|= name|this operator|. name|dagClient expr_stmt|; comment|// Don't set dagClient to null here - execute will only clean up operators if it's set. block|} name|LOG operator|. name|info argument_list|( literal|"Shutting down Tez task " operator|+ name|this operator|+ literal|" " operator|+ operator|( operator|( name|dagClient operator|== literal|null operator|) condition|? literal|" before submit" else|: literal|"" operator|) argument_list|) expr_stmt|; if|if condition|( name|dagClient operator|== literal|null condition|) return|return; name|closeDagClientOnCancellation argument_list|( name|dagClient argument_list|) expr_stmt|; block|} comment|/** DAG client that does dumb global sync on all the method calls; * Tez DAG client is not thread safe and getting the 2nd one is not recommended. */ specifier|public class|class name|SyncDagClient extends|extends name|DAGClient block|{ specifier|private specifier|final name|DAGClient name|dagClient decl_stmt|; specifier|public name|SyncDagClient parameter_list|( name|DAGClient name|dagClient parameter_list|) block|{ name|super argument_list|() expr_stmt|; name|this operator|. name|dagClient operator|= name|dagClient expr_stmt|; block|} annotation|@ name|Override specifier|public name|void name|close parameter_list|() throws|throws name|IOException block|{ name|dagClient operator|. name|close argument_list|() expr_stmt|; comment|// Don't sync. block|} specifier|public name|String name|getDagIdentifierString parameter_list|() block|{ comment|// TODO: Implement this when tez is upgraded. TEZ-3550 return|return literal|null return|; block|} specifier|public name|String name|getSessionIdentifierString parameter_list|() block|{ comment|// TODO: Implement this when tez is upgraded. TEZ-3550 return|return literal|null return|; block|} annotation|@ name|Override specifier|public name|String name|getExecutionContext parameter_list|() block|{ return|return name|dagClient operator|. name|getExecutionContext argument_list|() return|; comment|// Don't sync. block|} annotation|@ name|Override annotation|@ name|Private specifier|protected name|ApplicationReport name|getApplicationReportInternal parameter_list|() block|{ throw|throw operator|new name|UnsupportedOperationException argument_list|() throw|; comment|// The method is not exposed, and we don't use it. block|} annotation|@ name|Override specifier|public name|DAGStatus name|getDAGStatus parameter_list|( annotation|@ name|Nullable name|Set argument_list|< name|StatusGetOpts argument_list|> name|statusOptions parameter_list|) throws|throws name|IOException throws|, name|TezException block|{ synchronized|synchronized init|( name|dagClient init|) block|{ return|return name|dagClient operator|. name|getDAGStatus argument_list|( name|statusOptions argument_list|) return|; block|} block|} annotation|@ name|Override specifier|public name|DAGStatus name|getDAGStatus parameter_list|( annotation|@ name|Nullable name|Set argument_list|< name|StatusGetOpts argument_list|> name|statusOptions parameter_list|, name|long name|timeout parameter_list|) throws|throws name|IOException throws|, name|TezException block|{ synchronized|synchronized init|( name|dagClient init|) block|{ return|return name|dagClient operator|. name|getDAGStatus argument_list|( name|statusOptions argument_list|, name|timeout argument_list|) return|; block|} block|} annotation|@ name|Override specifier|public name|VertexStatus name|getVertexStatus parameter_list|( name|String name|vertexName parameter_list|, name|Set argument_list|< name|StatusGetOpts argument_list|> name|statusOptions parameter_list|) throws|throws name|IOException throws|, name|TezException block|{ synchronized|synchronized init|( name|dagClient init|) block|{ return|return name|dagClient operator|. name|getVertexStatus argument_list|( name|vertexName argument_list|, name|statusOptions argument_list|) return|; block|} block|} annotation|@ name|Override specifier|public name|void name|tryKillDAG parameter_list|() throws|throws name|IOException throws|, name|TezException block|{ synchronized|synchronized init|( name|dagClient init|) block|{ name|dagClient operator|. name|tryKillDAG argument_list|() expr_stmt|; block|} block|} annotation|@ name|Override specifier|public name|DAGStatus name|waitForCompletion parameter_list|() throws|throws name|IOException throws|, name|TezException throws|, name|InterruptedException block|{ synchronized|synchronized init|( name|dagClient init|) block|{ return|return name|dagClient operator|. name|waitForCompletion argument_list|() return|; block|} block|} annotation|@ name|Override specifier|public name|DAGStatus name|waitForCompletionWithStatusUpdates parameter_list|( annotation|@ name|Nullable name|Set argument_list|< name|StatusGetOpts argument_list|> name|statusGetOpts parameter_list|) throws|throws name|IOException throws|, name|TezException throws|, name|InterruptedException block|{ synchronized|synchronized init|( name|dagClient init|) block|{ return|return name|dagClient operator|. name|waitForCompletionWithStatusUpdates argument_list|( name|statusGetOpts argument_list|) return|; block|} block|} block|} block|} end_class end_unit
14.142214
813
0.796211
2d3488ad2b8ccde1d506e84bc83ba84f7d484043
3,004
package us.vicentini.hackerrank.security.cryptography; import java.util.Random; import java.util.Scanner; /** * https://www.hackerrank.com/challenges/prng-sequence-guessing * https://www.hackerrank.com/challenges/prng-sequence-guessing/submissions/code/21558839 * * Sample Input * 2 * 1374037200 1374123600 * 643 * 953 * 522 * 277 * 464 * 366 * 321 * 409 * 227 * 702 * 1374037299 1374143600 * 877 * 654 * 2 * 715 * 229 * 255 * 712 * 267 * 19 * 832 * * Sample Output * 1374037200 877 633 491 596 839 875 923 461 27 826 * 1374037459 101 966 573 339 784 718 949 934 62 368 * * @author Shulander */ public class PRNGSequenceGuessing { public static void main(String[] args) { Scanner in = new Scanner(System.in); int nTests = in.nextInt(); while (nTests-- > 0) { try { int startTimestamp = in.nextInt(); int finishTimestamp = in.nextInt(); int[] randomValues = new int[10]; for (int i = 0; i < randomValues.length; i++) { randomValues[i] = in.nextInt(); } Thread thread = new Thread(new PRNGSequenceSolver(startTimestamp, finishTimestamp, randomValues)); thread.start(); thread.join(); } catch (InterruptedException ex) { System.out.println("Error, Interrupted Exception: " + ex.getMessage()); } } } private static class PRNGSequenceSolver implements Runnable { private final int iniTime; private final int endTime; private final int[] generatedValues; private PRNGSequenceSolver(int iniTimestamp, int endTimestamp, int[] randomValues) { this.iniTime = iniTimestamp; this.endTime = endTimestamp; this.generatedValues = randomValues; } @Override public void run() { int seed = -1; Random random = null; for (int i = iniTime; i <= endTime && seed == -1; i++) { random = new Random(i); if (checkSeed(random)) { seed = i; } } generateOutput(seed, random); } private boolean checkSeed(Random random) { for (int i = 0; i < generatedValues.length; i++) { int newGenerated = random.nextInt(1000); if (newGenerated != generatedValues[i]) { return false; } } return true; } private void generateOutput(int seed, Random random) { StringBuilder sb = new StringBuilder(); sb.append(seed); if (seed > 0) { for (int i = 0; i < 10; i++) { sb.append(" "); sb.append(random.nextInt(1000)); } } System.out.println(sb.toString()); } } }
26.584071
114
0.526964
c1e1ed55c6a1259d9edb278e5951c30d103d4ada
11,101
package daiBeans; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.EventListener; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.awt.Rectangle; public class BrowserPanel extends JPanel { // These make up the navigation bar JButton backButton = new JButton(new ImageIcon("left.gif")); JButton forwardButton = new JButton(new ImageIcon("right.gif")); JButton refreshButton = new JButton(new ImageIcon("refresh.gif")); JButton printButton = new JButton(new ImageIcon("printer.gif")); JLabel addrLabel = new JLabel("Address:"); JTextField urlField = new JTextField(); // These make up the content BrowserPane content = new BrowserPane(); JScrollPane scrollPane = new JScrollPane(content); Vector URLCache = new Vector(); int cacheIndex = 0; //BorderLayout borderLayout1 = new BorderLayout(); JPanel jPanel_navPanel = new JPanel(); //XYLayout xYLayout1 = new XYLayout(); public BrowserPanel() { super(); try { jbInit(); } catch (Exception e) { System.out.println(e); } } private void jbInit() throws Exception { this.setLayout(null); this.setPreferredSize(new Dimension(600, 450)); // Set up GUI stuff... //setLayout(borderLayout1); // Back Button this.setSize(new Dimension(531, 347)); backButton.setLocation(new Point(0, 0)); backButton.setSize(new Dimension(20, 20)); backButton.setVisible(true); backButton.setToolTipText("Go Back"); //backButton.setEnabled(false); jPanel_navPanel.setLayout(null); jPanel_navPanel.setBounds(new Rectangle(0, 0, 495, 30)); backButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { backButtonActionPerformed(e); } }); // Forward Button forwardButton.setLocation(new Point(20, 0)); forwardButton.setSize(new Dimension(20, 20)); forwardButton.setVisible(true); forwardButton.setToolTipText("Go Forward"); //forwardButton.setEnabled(false); forwardButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { forwardButtonActionPerformed(e); } }); // refresh Button refreshButton.setLocation(new Point(40, 0)); refreshButton.setSize(new Dimension(20, 20)); refreshButton.setVisible(true); refreshButton.setToolTipText("Refresh Page"); //refreshButton.setEnabled(false); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { refreshButtonActionPerformed(e); } }); // Print Button printButton.setLocation(new Point(65, 0)); printButton.setSize(new Dimension(20, 20)); printButton.setVisible(true); printButton.setToolTipText("Print"); printButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { printButtonActionPerformed(e); } }); // Address Label addrLabel.setLocation(new Point(90, 0)); addrLabel.setVisible(true); addrLabel.setSize(new Dimension(50, 20)); // URL Field urlField.setLocation(new Point(140, 0)); urlField.setVisible(true); urlField.setPreferredSize(new Dimension(150, 21)); urlField.setBounds(new Rectangle(140, 0, 250, 25)); urlField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { urlFieldActionPerformed(e); } }); // Content Scroll Pane scrollPane.setLocation(new Point(0, 20)); scrollPane.getViewport().setBackground(Color.white); scrollPane.setVisible(true); scrollPane.setBounds(new Rectangle(0, 35, 485, 290)); content.setBounds(new Rectangle(30, 25, 125, 265)); this.add(jPanel_navPanel, null); // jPanel_navPanel.add(backButton, new Rectangle(0, 0, 26, 21));/ // jPanel_navPanel.add(urlField, new Rectangle(165, 0, 231, -1)); // jPanel_navPanel.add(forwardButton, new Rectangle(26, 0, 26, 21)); // jPanel_navPanel.add(refreshButton, new Rectangle(53, 0, 26, 21)); // jPanel_navPanel.add(addrLabel, new Rectangle(114, 1, 66, 21)); // jPanel_navPanel.add(printButton, new Rectangle(80, 0, 26, 21)); add(scrollPane, null); //this.add(content, null); jPanel_navPanel.add(backButton, null); jPanel_navPanel.add(urlField, null); jPanel_navPanel.add(forwardButton, null); jPanel_navPanel.add(refreshButton, null); jPanel_navPanel.add(addrLabel, null); jPanel_navPanel.add(printButton, null); updateButtons(); // Register for HyperlinkEvents from content pane content.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { try { setURL(e.getURL().toString(), true); } catch (Exception ioe) { ioe.printStackTrace(); } } }); } public void setURL(String url, boolean caching) { try { //System.out.println("Setting URL to " + urlField.getText()); urlField.setText(url); content.setPage(url); // add URL to cache if (caching) addToCache(url); } catch (Exception e) { e.printStackTrace(); } } public void setHTMLText(String text) { content.setContentType("text/html"); content.setText(text); } public void hideNavBar(boolean b) { if (b) { jPanel_navPanel.setVisible(false); } else { jPanel_navPanel.setVisible(true); } } private void updateButtons() { // Back Button if (cacheIndex > 0) { //if (!backButton.isEnabled()) backButton.setEnabled(true); } else //if (backButton.isEnabled()); backButton.setEnabled(false); // Forward Button if (cacheIndex < URLCache.size() - 1) { //if (!forwardButton.isEnabled()) forwardButton.setEnabled(true); } else //if (forwardButton.isEnabled()) forwardButton.setEnabled(false); // refresh Button if (URLCache.size() > 0) refreshButton.setEnabled(true); else refreshButton.setEnabled(false); // Print Button if (URLCache.size() > 0) printButton.setEnabled(true); else printButton.setEnabled(false); } private void addToCache(String url) { URLCache.addElement(url); cacheIndex = URLCache.size() - 1; updateButtons(); } private void urlFieldActionPerformed(ActionEvent e) { try { String url = urlField.getText(); //System.out.println("Setting URL to " + url); content.setURL(url); // add URL to cache addToCache(url); } catch (Exception ioe) { ioe.printStackTrace(); } } private void backButtonActionPerformed(ActionEvent e) { //System.out.println("Back button pressed."); try { if (cacheIndex > 0) { cacheIndex--; setURL((String)URLCache.elementAt(cacheIndex), false); } updateButtons(); } catch (Exception ex) { ex.printStackTrace(); } } private void forwardButtonActionPerformed(ActionEvent e) { //System.out.println("Forward button pressed."); try { if (cacheIndex < URLCache.size() - 1) { cacheIndex++; setURL((String)URLCache.elementAt(cacheIndex), false); } updateButtons(); } catch (Exception ex) { ex.printStackTrace(); } } private void refreshButtonActionPerformed(ActionEvent e) { //System.out.println("Forward button pressed."); try { if (URLCache.size() > 0) { setURL((String)URLCache.elementAt(cacheIndex), false); } } catch (Exception ex) { ex.printStackTrace(); } } private void printButtonActionPerformed(ActionEvent e) { //System.out.println("Print button pressed."); try { if (URLCache.size() > 0) { // print! System.out.println("Spooling to the nearest printer...\n (just kidding)"); /* PrinterJob job = PrinterJob.getPrinterJob(); job.setJobName("BrowserPanel (" + (String)URLCache.elementAt(cacheIndex) + ")"); if (!job.printDialog()) return; */ } } catch (Exception ex) { ex.printStackTrace(); } } private void adjustSize(int width, int height) { scrollPane.setBounds(0, 20, width, height - 20); //content.setBounds(0, 0, width, height-20); urlField.setBounds(140, 0, width - 140, 20); } class BrowserPane extends JEditorPane implements EventListener { String url; public BrowserPane() { init(); } public BrowserPane(String url) { init(); this.url = url; try { setURL(url); } catch (IOException ioe) { ioe.printStackTrace(); url = null; } } private void init() { setEditable(false); } public String getURL() { return url; } public void setURL(String url) throws IOException { try { setPage(url); } catch (IOException ioe) { url = null; throw ioe; } } } }
31.717143
92
0.553914
7a7b85e48b45661c039e35ac966d0708d4ecfbfb
7,577
/* * 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.openmeetings.util.mail; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.openmeetings.util.mail.MailUtil.MAILTO; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.fortuna.ical4j.data.CalendarOutputter; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.ComponentList; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.ParameterList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import net.fortuna.ical4j.model.component.VEvent; import net.fortuna.ical4j.model.parameter.Cn; import net.fortuna.ical4j.model.parameter.CuType; import net.fortuna.ical4j.model.parameter.PartStat; import net.fortuna.ical4j.model.parameter.Role; import net.fortuna.ical4j.model.parameter.Rsvp; import net.fortuna.ical4j.model.parameter.XParameter; import net.fortuna.ical4j.model.property.Attendee; import net.fortuna.ical4j.model.property.CalScale; import net.fortuna.ical4j.model.property.Created; import net.fortuna.ical4j.model.property.Description; import net.fortuna.ical4j.model.property.LastModified; import net.fortuna.ical4j.model.property.Location; import net.fortuna.ical4j.model.property.Method; import net.fortuna.ical4j.model.property.Organizer; import net.fortuna.ical4j.model.property.ProdId; import net.fortuna.ical4j.model.property.Sequence; import net.fortuna.ical4j.model.property.Status; import net.fortuna.ical4j.model.property.Transp; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.model.property.Version; import net.fortuna.ical4j.validate.ValidationException; /** * * @author o.becherer, seba.wagner * */ public class IcalHandler { private static final Logger log = LoggerFactory.getLogger(IcalHandler.class); public static final TimeZoneRegistry TZ_REGISTRY = TimeZoneRegistryFactory.getInstance().createRegistry(); /** ICal instance */ private final Calendar icsCalendar; private TimeZone timeZone; private VEvent meeting; private List<Property> meetingProperties = new ArrayList<>(); private Method method; /** Creation of a new Event */ public static final Method ICAL_METHOD_REQUEST = Method.REQUEST; public static final Method ICAL_METHOD_CANCEL = Method.CANCEL; public static final Method ICAL_METHOD_REFRESH = Method.REFRESH; /** * Constructor * * @param method * (@see IcalHandler) constants */ public IcalHandler(Method method) { this.method = method; log.debug("Icalhandler method type : {}", method); icsCalendar = new Calendar(new PropertyList(List.of( new ProdId("-//Apache Openmeetings//OM Calendar//EN") , Version.VERSION_2_0 , CalScale.GREGORIAN , method )), new ComponentList<>()); } public IcalHandler createVEvent(ZonedDateTime start, ZonedDateTime end, String name) { timeZone = TZ_REGISTRY.getTimeZone(start.getZone().getId()); if (timeZone == null) { throw new NoSuchElementException("Unable to get time zone by id provided: " + start.getZone()); } meeting = new VEvent(start, end, name); meetingProperties.addAll(meeting.getProperties()); meetingProperties.addAll(List.of(Transp.OPAQUE, Status.VEVENT_CONFIRMED)); return this; } public IcalHandler setCreated(ZonedDateTime date) { meetingProperties.add(new Created(date.toInstant())); return this; } public IcalHandler setModified(ZonedDateTime date) { meetingProperties.add(new LastModified((date == null ? ZonedDateTime.now() : date).toInstant())); return this; } public IcalHandler setDescription(String description) { meetingProperties.add(new Description(description)); return this; } public IcalHandler setLocation(String location) { meetingProperties.add(new Location(location)); return this; } public IcalHandler setSequence(int seq) { meetingProperties.add(new Sequence(seq)); return this; } public IcalHandler setUid(String uid) { meetingProperties.add(new Uid(uid)); return this; } private static URI getMailto(String email) { return URI.create(MAILTO + email); } public IcalHandler addOrganizer(String email, String name) { meetingProperties.add(new Organizer(new ParameterList(List.of(new Cn(name))), getMailto(email))); return this; } public IcalHandler addAttendee(String email, String display, boolean chair) { List<Parameter> params = new ArrayList<>(List.of( CuType.INDIVIDUAL , chair ? Role.CHAIR : Role.REQ_PARTICIPANT , new XParameter("X-NUM-GUESTS", "0") , new Cn(display))); if (Method.CANCEL == method) { params.add(PartStat.DECLINED); } else { params.add(chair ? PartStat.ACCEPTED : PartStat.NEEDS_ACTION); params.add(Rsvp.TRUE); } meetingProperties.add(new Attendee(new ParameterList(params), URI.create(MAILTO + email))); return this; } public IcalHandler build() { meeting.setPropertyList(new PropertyList(meetingProperties)); icsCalendar.setComponentList(new ComponentList<>(List.of(timeZone.getVTimeZone(), meeting))); return this; } public Method getMethod() { return method; } /** * Write iCal to File * * @param inFilerPath * - path to '*.ics' file * @throws Exception * - in case of error during writing to the file */ public void toFile(String inFilerPath) throws Exception { String filerPath = inFilerPath.endsWith(".ics") ? inFilerPath : String.format("%s.ics", inFilerPath); try (FileOutputStream fout = new FileOutputStream(filerPath)) { CalendarOutputter outputter = new CalendarOutputter(); outputter.output(icsCalendar, fout); } } /** * Get IcalBody as ByteArray * * @return - calendar in ICS format as byte[] * @throws IOException * - in case of error during writing to byte array * @throws ValidationException * - in case of invalid calendar properties */ public byte[] toByteArray() throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); CalendarOutputter outputter = new CalendarOutputter(); outputter.output(icsCalendar, bout); return bout.toByteArray(); } /** * Retrieving Data as String */ @Override public String toString() { if (icsCalendar == null) { return null; } try { return new String(toByteArray(), UTF_8); } catch (IOException e) { log.error("Unexpected error", e); } return null; } }
32.242553
107
0.750033
915821137cc48da5c4e3f37e049627a869397057
8,888
package org.tyuan.service.dao.mapper; import org.apache.ibatis.annotations.*; import org.apache.ibatis.type.JdbcType; import org.tyuan.service.dao.model.SysParam; import org.tyuan.service.dao.model.SysParamExample; import java.util.List; public interface SysParamMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @SelectProvider(type=SysParamSqlProvider.class, method="countByExample") long countByExample(SysParamExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @DeleteProvider(type=SysParamSqlProvider.class, method="deleteByExample") int deleteByExample(SysParamExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @Delete({ "delete from sys_param", "where id = #{id,jdbcType=BIGINT}" }) int deleteByPrimaryKey(Long id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @Insert({ "insert into sys_param (create_time, update_time, ", "param_name, param_key, ", "is_sys, create_by, update_by, ", "remarks, param_val)", "values (#{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}, ", "#{paramName,jdbcType=VARCHAR}, #{paramKey,jdbcType=VARCHAR}, ", "#{isSys,jdbcType=BIT}, #{createBy,jdbcType=VARCHAR}, #{updateBy,jdbcType=VARCHAR}, ", "#{remarks,jdbcType=VARCHAR}, #{paramVal,jdbcType=LONGVARCHAR})" }) @SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Long.class) int insert(SysParam record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @InsertProvider(type=SysParamSqlProvider.class, method="insertSelective") @SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Long.class) int insertSelective(SysParam record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @SelectProvider(type=SysParamSqlProvider.class, method="selectByExampleWithBLOBs") @Results({ @Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true), @Result(column="create_time", property="createTime", jdbcType=JdbcType.TIMESTAMP), @Result(column="update_time", property="updateTime", jdbcType=JdbcType.TIMESTAMP), @Result(column="param_name", property="paramName", jdbcType=JdbcType.VARCHAR), @Result(column="param_key", property="paramKey", jdbcType=JdbcType.VARCHAR), @Result(column="is_sys", property="isSys", jdbcType=JdbcType.BIT), @Result(column="create_by", property="createBy", jdbcType=JdbcType.VARCHAR), @Result(column="update_by", property="updateBy", jdbcType=JdbcType.VARCHAR), @Result(column="remarks", property="remarks", jdbcType=JdbcType.VARCHAR), @Result(column="param_val", property="paramVal", jdbcType=JdbcType.LONGVARCHAR) }) List<SysParam> selectByExampleWithBLOBs(SysParamExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @SelectProvider(type=SysParamSqlProvider.class, method="selectByExample") @Results({ @Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true), @Result(column="create_time", property="createTime", jdbcType=JdbcType.TIMESTAMP), @Result(column="update_time", property="updateTime", jdbcType=JdbcType.TIMESTAMP), @Result(column="param_name", property="paramName", jdbcType=JdbcType.VARCHAR), @Result(column="param_key", property="paramKey", jdbcType=JdbcType.VARCHAR), @Result(column="is_sys", property="isSys", jdbcType=JdbcType.BIT), @Result(column="create_by", property="createBy", jdbcType=JdbcType.VARCHAR), @Result(column="update_by", property="updateBy", jdbcType=JdbcType.VARCHAR), @Result(column="remarks", property="remarks", jdbcType=JdbcType.VARCHAR) }) List<SysParam> selectByExample(SysParamExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @Select({ "select", "id, create_time, update_time, param_name, param_key, is_sys, create_by, update_by, ", "remarks, param_val", "from sys_param", "where id = #{id,jdbcType=BIGINT}" }) @Results({ @Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true), @Result(column="create_time", property="createTime", jdbcType=JdbcType.TIMESTAMP), @Result(column="update_time", property="updateTime", jdbcType=JdbcType.TIMESTAMP), @Result(column="param_name", property="paramName", jdbcType=JdbcType.VARCHAR), @Result(column="param_key", property="paramKey", jdbcType=JdbcType.VARCHAR), @Result(column="is_sys", property="isSys", jdbcType=JdbcType.BIT), @Result(column="create_by", property="createBy", jdbcType=JdbcType.VARCHAR), @Result(column="update_by", property="updateBy", jdbcType=JdbcType.VARCHAR), @Result(column="remarks", property="remarks", jdbcType=JdbcType.VARCHAR), @Result(column="param_val", property="paramVal", jdbcType=JdbcType.LONGVARCHAR) }) SysParam selectByPrimaryKey(Long id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @UpdateProvider(type=SysParamSqlProvider.class, method="updateByExampleSelective") int updateByExampleSelective(@Param("record") SysParam record, @Param("example") SysParamExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @UpdateProvider(type=SysParamSqlProvider.class, method="updateByExampleWithBLOBs") int updateByExampleWithBLOBs(@Param("record") SysParam record, @Param("example") SysParamExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @UpdateProvider(type=SysParamSqlProvider.class, method="updateByExample") int updateByExample(@Param("record") SysParam record, @Param("example") SysParamExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @UpdateProvider(type=SysParamSqlProvider.class, method="updateByPrimaryKeySelective") int updateByPrimaryKeySelective(SysParam record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @Update({ "update sys_param", "set create_time = #{createTime,jdbcType=TIMESTAMP},", "update_time = #{updateTime,jdbcType=TIMESTAMP},", "param_name = #{paramName,jdbcType=VARCHAR},", "param_key = #{paramKey,jdbcType=VARCHAR},", "is_sys = #{isSys,jdbcType=BIT},", "create_by = #{createBy,jdbcType=VARCHAR},", "update_by = #{updateBy,jdbcType=VARCHAR},", "remarks = #{remarks,jdbcType=VARCHAR},", "param_val = #{paramVal,jdbcType=LONGVARCHAR}", "where id = #{id,jdbcType=BIGINT}" }) int updateByPrimaryKeyWithBLOBs(SysParam record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_param * * @mbg.generated */ @Update({ "update sys_param", "set create_time = #{createTime,jdbcType=TIMESTAMP},", "update_time = #{updateTime,jdbcType=TIMESTAMP},", "param_name = #{paramName,jdbcType=VARCHAR},", "param_key = #{paramKey,jdbcType=VARCHAR},", "is_sys = #{isSys,jdbcType=BIT},", "create_by = #{createBy,jdbcType=VARCHAR},", "update_by = #{updateBy,jdbcType=VARCHAR},", "remarks = #{remarks,jdbcType=VARCHAR}", "where id = #{id,jdbcType=BIGINT}" }) int updateByPrimaryKey(SysParam record); }
41.339535
110
0.670455
1653e6ace044223d34e220faeaadba12a2e18898
914
package com.devops.groupb.harbourmaster.test.repository; import static org.junit.jupiter.api.Assertions.*; import com.devops.groupb.harbourmaster.dao.OrderDAO; import com.devops.groupb.harbourmaster.HarbourMaster; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; @SpringBootTest(classes=HarbourMaster.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @Transactional public class OrderDAOTest { private transient final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(this.getClass()); @Autowired private OrderDAO orderDAO; @BeforeAll public void daoCheck() { log.debug("Checking whether orderDAO is null."); assertNotNull(orderDAO); } }
31.517241
124
0.821663
9f21b985b19e08ebae92606047887f517364565d
1,173
package com.exasol.datatype.type; import com.exasol.sql.ColumnDefinitionVisitor; /** * This class implements the Exasol-proprietary data type interval year to month */ public class IntervalYearToMonth implements DataType { private static final String NAME = "INTERVAL YEAR(%s) TO MONTH"; private final int yearPrecision; /** * Create a new instance of an {@link IntervalYearToMonth} data type * * @param yearPrecision year precision value */ public IntervalYearToMonth(final int yearPrecision) { validatePrecision(yearPrecision); this.yearPrecision = yearPrecision; } private void validatePrecision(final int yearPrecision) { if (yearPrecision < 1 || yearPrecision > 9) { throw new IllegalArgumentException("Year precision must be a number between 1 and 9."); } } @Override public void accept(final ColumnDefinitionVisitor visitor) { visitor.visit(this); } @Override public String getName() { return NAME; } /** * @return year precision */ public int getYearPrecision() { return this.yearPrecision; } }
26.659091
99
0.666667
442603a586582bf2a4aba184cd9017bd47032027
2,087
package net.joelinn.quartz; import net.joelinn.quartz.jobstore.RedisJobStore; import org.junit.Test; import org.quartz.JobDetail; import org.quartz.Trigger; import java.util.Map; import java.util.Properties; import java.util.Set; import static org.junit.Assert.assertEquals; /** * Joe Linn * 7/22/2014 */ public class RedisJobStoreTest extends BaseTest{ @Test public void redisJobStoreWithScheduler() throws Exception { Properties quartzProperties = new Properties(); quartzProperties.setProperty("org.quartz.scheduler.instanceName", "testScheduler"); quartzProperties.setProperty("org.quartz.threadPool.threadCount", "3"); quartzProperties.setProperty("org.quartz.jobStore.class", RedisJobStore.class.getName()); quartzProperties.setProperty("org.quartz.jobStore.host", host); quartzProperties.setProperty("org.quartz.jobStore.port", Integer.toString(port)); quartzProperties.setProperty("org.quartz.jobStore.lockTimeout", "2000"); quartzProperties.setProperty("org.quartz.jobStore.database", "1"); testJobStore(quartzProperties); } @Test public void clearAllSchedulingData() throws Exception { // create and store some jobs, triggers, and calendars Map<JobDetail, Set<? extends Trigger>> jobsAndTriggers = getJobsAndTriggers(2, 2, 2, 2); jobStore.storeJobsAndTriggers(jobsAndTriggers, false); // ensure that the jobs, triggers, and calendars were stored assertEquals(2, (long) jedis.scard(schema.jobGroupsSet())); assertEquals(4, (long) jedis.scard(schema.jobsSet())); assertEquals(8, (long) jedis.scard(schema.triggerGroupsSet())); assertEquals(16, (long) jedis.scard(schema.triggersSet())); jobStore.clearAllSchedulingData(); assertEquals(0, (long) jedis.scard(schema.jobGroupsSet())); assertEquals(0, (long) jedis.scard(schema.jobsSet())); assertEquals(0, (long) jedis.scard(schema.triggerGroupsSet())); assertEquals(0, (long) jedis.scard(schema.triggersSet())); } }
37.267857
97
0.708673
12d290863e167064cd19f96cf5e8e02aac2f30c5
6,173
package org.develnext.jphp.zend.ext.standard.date; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import php.runtime.Memory; import php.runtime.annotation.Reflection.Arg; import php.runtime.annotation.Reflection.Name; import php.runtime.annotation.Reflection.Property; import php.runtime.annotation.Reflection.Signature; import php.runtime.common.HintType; import php.runtime.common.Messages; import php.runtime.env.Environment; import php.runtime.env.TraceInfo; import php.runtime.lang.BaseObject; import php.runtime.memory.ArrayMemory; import php.runtime.memory.LongMemory; import php.runtime.memory.ObjectMemory; import php.runtime.memory.StringMemory; import php.runtime.reflection.ClassEntity; @Name("DateTimeZone") public class DateTimeZone extends BaseObject { @Property public static final int AFRICA = 1; @Property public static final int AMERICA = 2; @Property public static final int ANTARCTICA = 4; @Property public static final int ARCTIC = 8; @Property public static final int ASIA = 16; @Property public static final int ATLANTIC = 32; @Property public static final int AUSTRALIA = 64; @Property public static final int EUROPE = 128; @Property public static final int INDIAN = 256; @Property public static final int PACIFIC = 512; @Property public static final int UTC = 1024; @Property public static final int ALL = 2047; @Property public static final int ALL_WITH_BC = 4095; @Property public static final int PER_COUNTRY = 4096; private static final Memory ZERO_OFFSET = StringMemory.valueOf("+00:00"); @Property("timezone_type") Memory type = Memory.UNDEFINED; @Property("timezone") Memory timezone = Memory.UNDEFINED; private ZoneId nativeZone; public DateTimeZone(Environment env) { super(env); } public DateTimeZone(Environment env, ClassEntity clazz) { super(env, clazz); } @Signature(value = @Arg(value = "array", type = HintType.ARRAY), result = @Arg(type = HintType.OBJECT)) public static Memory __set_state(Environment env, TraceInfo traceInfo, ArrayMemory arg) { DateTimeZone dateTimeZone = new DateTimeZone(env); StringMemory timezone = arg.get(StringMemory.valueOf("timezone")).toValue(StringMemory.class); return dateTimeZone.__construct(env, traceInfo, timezone); } @Signature public static Memory listAbbreviations(Environment env, TraceInfo traceInfo) { return ZoneIdFactory.listAbbreviations(); } @Signature(result = @Arg(type = HintType.ARRAY)) public static Memory listIdentifiers(Environment env, TraceInfo traceInfo) { return listIdentifiers(env, traceInfo, DateTimeZone.ALL); } @Signature(result = @Arg(type = HintType.ARRAY)) public static Memory listIdentifiers(Environment env, TraceInfo traceInfo, int what) { return listIdentifiers(env, traceInfo, DateTimeZone.ALL, null); } @Signature(result = @Arg(type = HintType.ARRAY)) public static Memory listIdentifiers(Environment env, TraceInfo traceInfo, int what, String country) { String[] identifiers = ZoneIdFactory.listIdentifiers(what, country); ArrayMemory array = ArrayMemory.createListed(identifiers.length); for (String identifier : identifiers) { Memory memory = StringMemory.valueOf(identifier); array.add(memory); } return array; } static int getTimeZoneType(ZoneId zoneId) { if (zoneId == null) return -1; if (zoneId instanceof ZoneOffset) { return 1; } else { String id = zoneId.getId(); if (!id.equals("GMT") && zoneId.getClass().getSimpleName().equals("ZoneRegion")) { return 3; } } return 2; } ZoneId getNativeZone() { return nativeZone; } @Signature(value = { @Arg(value = "timezone", type = HintType.STRING) }, result = @Arg(type = HintType.OBJECT)) public Memory __construct(Environment env, TraceInfo traceInfo, StringMemory arg) { String zone = arg.toString(); if (zone.indexOf('\0') != -1) { env.exception(traceInfo, Messages.ERR_TIMEZONE_NULL_BYTE, "DateTimeZone::__construct()"); } init(zone); getProperties(); return ObjectMemory.valueOf(this); } private void init(String zone) { this.nativeZone = ZoneIdFactory.of(zone); if (nativeZone instanceof ZoneOffset && zone.equals("Z")) { this.timezone = ZERO_OFFSET; } else { this.timezone = StringMemory.valueOf(zone); } type = LongMemory.valueOf(getTimeZoneType(nativeZone)); } @Signature public Memory __wakeup(Environment env, TraceInfo traceInfo) { return Memory.UNDEFINED; } @Signature public Memory getLocation(Environment env, TraceInfo traceInfo) { return Memory.UNDEFINED; } @Signature public Memory getName(Environment env, TraceInfo traceInfo) { return timezone; } @Signature public Memory getOffset(Environment env, TraceInfo traceInfo, Memory datetime) { DateTimeInterface dateTime = datetime.toObject(DateTimeInterface.class); long timestamp = dateTime.getTimestamp(env, traceInfo).toLong(); ZoneOffset offset = nativeZone.getRules().getOffset(Instant.ofEpochSecond(timestamp)); int totalSeconds = offset.getTotalSeconds(); return LongMemory.valueOf(totalSeconds); } @Signature public Memory getTransitions(Environment env, TraceInfo traceInfo) { return Memory.UNDEFINED; } @Override public ArrayMemory getProperties() { ArrayMemory props = super.getProperties(); if (type.toInteger() == 1) { props.refOfIndex("timezone").assign(nativeZone.toString()); } else { props.refOfIndex("timezone").assign(timezone); } props.refOfIndex("timezone_type").assign(type); return props; } }
31.494898
107
0.671959
415d97d4e8f77c5bd8513076fef1bdab99be90b2
2,178
// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0 package pl.morgwai.samples.guiced_servlet_jpa.domain; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class ChatLogEntry implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; public static final String ID = "id"; public Long getId() { return id; } String username; public static final String USERNAME = "username"; public String getUsername() { return username; } String message; public static final String MESSAGE = "message"; public String getMessage() { return message; } @Override public int hashCode() { return (id == null ? 0 : id.hashCode()) + 13 * (username == null ? 0 : username.hashCode() + 31 * (message == null ? 0 : message.hashCode())); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null) return false; if (other.getClass() != ChatLogEntry.class) return false; ChatLogEntry otherEntry = (ChatLogEntry) other; return (id == null ? otherEntry.getId() == null : id.equals(otherEntry.getId())) && (username == null ? otherEntry.getUsername() == null : username.equals(otherEntry.getUsername())) && (message == null ? otherEntry.getMessage() == null : message.equals(otherEntry.getMessage())); } protected ChatLogEntry() {} public ChatLogEntry(String username, String message) { this.username = username; this.message = message; } public ChatLogEntry(Long id, String username, String message) { this.id = id; this.username = username; this.message = message; } static { // unit-test/deploy time check if there are no typos in field names try { ChatLogEntry.class.getDeclaredField(ID); ChatLogEntry.class.getDeclaredField(USERNAME); ChatLogEntry.class.getDeclaredField(MESSAGE); } catch (NoSuchFieldException | SecurityException e) { throw new RuntimeException(e); } } private static final long serialVersionUID = 2177348762809760267L; }
25.928571
90
0.717631