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
6cdd444f1c83e933dc9f8c9d97e735067fea1335
212
package com.honeybee.mapper; import java.util.List; import com.honeybee.domain.SubscribeVO; public interface SubscribeMapper { public List<SubscribeVO> getSubscribeList(String id); //내가 구독한 회원 리스트 가져오기 }
17.666667
76
0.778302
c0e3d3cb53471d60051fd49f9fb3b898f02006e9
552
import java.util.HashMap; import java.util.Map; /** * @author dns007 * @version 1.0 * @date 2020/3/24 */ public class MyCharacterFactory { private Map<Character, MyCharacter> pool; public MyCharacterFactory(){ pool = new HashMap<Character, MyCharacter>(); } public MyCharacter getMyCharacter(Character character){ MyCharacter myChar = pool.get(character); if(myChar == null){ myChar = new MyCharacter(character); pool.put(character, myChar); } return myChar; } }
23
59
0.630435
a39f379a24dd0a6d0c33be25aa9571ab2fb06d2d
2,366
package cn.wizzer.app.sys.modules.services.impl; import cn.wizzer.app.sys.modules.models.Sys_unit; import cn.wizzer.app.sys.modules.services.SysUnitService; import cn.wizzer.framework.base.service.BaseServiceImpl; import com.alibaba.dubbo.config.annotation.Service; import org.nutz.aop.interceptor.ioc.TransAop; import org.nutz.dao.Chain; import org.nutz.dao.Cnd; import org.nutz.dao.Dao; import org.nutz.dao.Sqls; import org.nutz.ioc.aop.Aop; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.lang.Strings; /** * Created by wizzer on 2016/12/22. */ @IocBean(args = {"refer:dao"}) @Service(interfaceClass=SysUnitService.class) public class SysUnitServiceImpl extends BaseServiceImpl<Sys_unit> implements SysUnitService { public SysUnitServiceImpl(Dao dao) { super(dao); } /** * 新增单位 * * @param unit * @param pid */ @Aop(TransAop.READ_COMMITTED) public void save(Sys_unit unit, String pid) { String path = ""; if (!Strings.isEmpty(pid)) { Sys_unit pp = this.fetch(pid); path = pp.getPath(); } unit.setPath(getSubPath("sys_unit", "path", path)); unit.setParentId(pid); dao().insert(unit); if (!Strings.isEmpty(pid)) { this.update(Chain.make("hasChildren", true), Cnd.where("id", "=", pid)); } } /** * 级联删除单位 * * @param unit */ @Aop(TransAop.READ_COMMITTED) public void deleteAndChild(Sys_unit unit) { dao().execute(Sqls.create("delete from sys_unit where path like @path").setParam("path", unit.getPath() + "%")); dao().execute(Sqls.create("delete from sys_user_unit where unitId=@id or unitId in(SELECT id FROM sys_unit WHERE path like @path)").setParam("id", unit.getId()).setParam("path", unit.getPath() + "%")); dao().execute(Sqls.create("delete from sys_role where unitid=@id or unitid in(SELECT id FROM sys_unit WHERE path like @path)").setParam("id", unit.getId()).setParam("path", unit.getPath() + "%")); if (!Strings.isEmpty(unit.getParentId())) { int count = count(Cnd.where("parentId", "=", unit.getParentId())); if (count < 1) { dao().execute(Sqls.create("update sys_unit set hasChildren=0 where id=@pid").setParam("pid", unit.getParentId())); } } } }
36.4
209
0.640744
41e1ac99f40093a1fece28baca918c814892065b
2,711
package ar.edu.itba.cep.executor.client; import ar.edu.itba.cep.executor.api.ExecutionResponseHandler; import ar.edu.itba.cep.executor.api.ExecutionResponseIdData; import ar.edu.itba.cep.executor.dtos.ExecutionResponseDto; import ar.edu.itba.cep.executor.models.ExecutionResponse; import com.bellotapps.the_messenger.commons.Message; import com.bellotapps.the_messenger.commons.payload.PayloadDeserializer; import com.bellotapps.the_messenger.consumer.DeserializerMessageHandler; /** * A {@link com.bellotapps.the_messenger.consumer.MessageHandler} that can process {@link ExecutionResponseDto}s. * * @param <I> The concrete type of {@link ExecutionResponseIdData} needed to identify a received {@link Message}. */ public class TheMessengerExecutionResponseMessageHandler<I extends ExecutionResponseIdData> extends DeserializerMessageHandler<ExecutionResponseDto> { /** * The {@link ExecutionResponseHandler} that is in charge of processing a {@link ExecutionResponse}s. */ private final ExecutionResponseHandler<I> executionResponseProcessor; /** * An {@link ExecutionResponseIdDataFactory} * needed to create {@link ExecutionResponseIdData} instances from the received {@link Message}s. */ private final ExecutionResponseIdDataFactory<I> identificationDataFactory; /** * Constructor. * * @param payloadDeserializer A {@link PayloadDeserializer} of {@link ExecutionResponseDto}. * @param executionResponseProcessor The {@link ExecutionResponseHandler} * that is in charge of processing a {@link ExecutionResponse}s. * @param identificationDataFactory An {@link ExecutionResponseIdDataFactory} * needed to create {@link ExecutionResponseIdData} * instances from the received {@link Message}s. */ public TheMessengerExecutionResponseMessageHandler( final PayloadDeserializer<ExecutionResponseDto> payloadDeserializer, final ExecutionResponseHandler<I> executionResponseProcessor, final ExecutionResponseIdDataFactory<I> identificationDataFactory) { super(payloadDeserializer); this.executionResponseProcessor = executionResponseProcessor; this.identificationDataFactory = identificationDataFactory; } @Override protected void andThen(final ExecutionResponseDto executionResponseDto, final Message message) { executionResponseProcessor.processExecutionResponse( executionResponseDto.getExecutionResponse(), identificationDataFactory.buildFromMessage(message) ); } }
46.741379
113
0.732571
5238760cb03f3bcb270377c22f99b0214078436d
1,215
package nl._42.heph.shared; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import nl._42.heph.BeanSaver; /** * "Repository" which stores all entities of a type T in a map (by ID) * Demonstrates the working of Heph with a non-Spring repository. * @param <T> Entity type to store in this class. */ public abstract class MockRepository<T extends AbstractEntity> implements BeanSaver<T, Long> { private final AtomicLong idSequence = new AtomicLong(0); private final Map<Long, T> entities = new HashMap<>(); public void clear() { entities.clear(); } public Collection<T> findAll() { return entities.values(); } public T findOne(Long id) { return entities.get(id); } public T save(T entity) { // Add the ID to the entity if it is a new entity. if (entity.getId() == null) { entity.setId(idSequence.addAndGet(1)); } // Place the entity in the repository entities.put(entity.getId(), entity); return entity; } public void delete(AbstractEntity entity) { entities.remove(entity.getId()); } }
25.3125
94
0.649383
089ff404b3c39c07b74fb0d94f86108008c157da
1,797
package com.simibubi.create.content.contraptions.components.structureMovement.pulley; import com.simibubi.create.content.contraptions.components.structureMovement.AssemblyException; import com.simibubi.create.content.contraptions.components.structureMovement.ContraptionLighter; import com.simibubi.create.content.contraptions.components.structureMovement.ContraptionType; import com.simibubi.create.content.contraptions.components.structureMovement.TranslatingContraption; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class PulleyContraption extends TranslatingContraption { int initialOffset; @Override protected ContraptionType getType() { return ContraptionType.PULLEY; } public PulleyContraption() {} public PulleyContraption(int initialOffset) { this.initialOffset = initialOffset; } @Override public boolean assemble(World world, BlockPos pos) throws AssemblyException { if (!searchMovedStructure(world, pos, null)) return false; startMoving(world); return true; } @Override protected boolean isAnchoringBlockAt(BlockPos pos) { if (pos.getX() != anchor.getX() || pos.getZ() != anchor.getZ()) return false; int y = pos.getY(); if (y <= anchor.getY() || y > anchor.getY() + initialOffset + 1) return false; return true; } @Override public CompoundTag writeNBT(boolean spawnPacket) { CompoundTag tag = super.writeNBT(spawnPacket); tag.putInt("InitialOffset", initialOffset); return tag; } @Override public void readNBT(World world, CompoundTag nbt, boolean spawnData) { initialOffset = nbt.getInt("InitialOffset"); super.readNBT(world, nbt, spawnData); } @Override public ContraptionLighter<?> makeLighter() { return new PulleyLighter(this); } }
28.983871
100
0.775737
80d260d7bba0deca7f74f80d55b809713ca7a794
201
import java.util.List; public class Modul { String name; List<ModulBestandteil> bestandteile; int modulPunkteGesamt; boolean bestanden; String datumUndSemester; int versuch; }
18.272727
40
0.716418
f2cdb03a2020c51e0f6c608d6ffed91950ae0a0c
2,825
package iurii.job.interview.algorithms2.coursera; import iurii.job.interview.graph.structure.DirectedEdge; import iurii.job.interview.graph.structure.DirectedEdgeComparator; import iurii.job.interview.graph.structure.OrderedWeightedGraph; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.PriorityQueue; public class BellmanFord { private final int[] distTo; private final int[] edgeTo; private boolean isNegativeCycle = false; public BellmanFord(OrderedWeightedGraph graph, int source) { edgeTo = new int[graph.verticesCount()]; distTo = new int[graph.verticesCount()]; for (int i = 0; i < graph.verticesCount(); i++) { edgeTo[i] = -1; distTo[i] = Integer.MAX_VALUE; } distTo[source] = 0; edgeTo[source] = 0; PriorityQueue<DirectedEdge> prevDirectedEdges = new PriorityQueue<DirectedEdge>( 10, new DirectedEdgeComparator()); addEdges(graph, source, prevDirectedEdges); for (int i = 0; i < graph.verticesCount() - 1; i++) { PriorityQueue<DirectedEdge> nextDirectedEdges = new PriorityQueue<DirectedEdge>( 10, new DirectedEdgeComparator()); //System.out.println("vertex" + i); while (!prevDirectedEdges.isEmpty()) { DirectedEdge top = prevDirectedEdges.poll(); if (edgeTo[top.to()] == -1 || distTo[top.from()] + top.weight() < distTo[top.to()]) { edgeTo[top.to()] = top.from(); distTo[top.to()] = distTo[top.from()] + top.weight(); addEdges(graph, top.to(), nextDirectedEdges); } } prevDirectedEdges = nextDirectedEdges; } // cycle check while (!prevDirectedEdges.isEmpty()) { DirectedEdge top = prevDirectedEdges.poll(); if (edgeTo[top.to()] == -1 || distTo[top.from()] + top.weight() < distTo[top.to()]) { isNegativeCycle = true; break; } } } private void addEdges(OrderedWeightedGraph graph, int source, PriorityQueue<DirectedEdge> directedEdges) { Iterable<DirectedEdge> adj = graph.adj(source); for (DirectedEdge edge : adj) { directedEdges.add(edge); } } public Integer minDistance() { if (isNegativeCycle) { return null; } else { List<Integer> distances = new ArrayList<Integer>(); for (int i = 0; i < distTo.length; i++) { distances.add(distTo[i]); } return Collections.min(distances); } } }
38.175676
102
0.562478
9403f1fd9ae019a0977a14aa7b60b2b06f25a23b
430
import java.util.ArrayList; public class BinaryGenerator { public ArrayList<Integer> GenerateBinaryFormat(long number) { ArrayList<Integer> binary = new ArrayList(); int index = 0; int bineq = 0; while(number > 0) { bineq = (int)number%2; binary.add(new Integer(bineq)); number = number/2; } return binary; } }
17.2
63
0.532558
0941e3c5dbf50998291f947c54cd442fa6331615
669
package org.instantlogic.designer.flow; import org.instantlogic.designer.DesignerApplicationGenerator; import org.instantlogic.designer.FlowDesign; import org.instantlogic.designer.FragmentTemplateDesignEntityGenerator; public class InsertFragmentTemplateBelowFlowGenerator extends FlowDesign { public static final InsertFragmentTemplateBelowFlowGenerator FLOW = new InsertFragmentTemplateBelowFlowGenerator(); private InsertFragmentTemplateBelowFlowGenerator() { DesignerApplicationGenerator.APPLICATION.addToFlows(this); setName("InsertFragmentTemplateBelow"); setIsCustomized(true); addToParameters(FragmentTemplateDesignEntityGenerator.ENTITY); } }
37.166667
116
0.865471
1437963f9c43908293199c246ba71509f0aec2db
2,911
/******************************************************************************* * Copyright 2013 Geoscience Australia * * 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 au.gov.ga.earthsci.bookmark.ui; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerDropAdapter; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.TransferData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import au.gov.ga.earthsci.bookmark.model.IBookmark; /** * Drop adapter for the {@link BookmarksPart} * * @author James Navin (james.navin@ga.gov.au) */ class BookmarksDropAdapter extends ViewerDropAdapter { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(BookmarksDropAdapter.class); private IBookmarksController controller; protected BookmarksDropAdapter(Viewer viewer, IBookmarksController controller) { super(viewer); this.controller = controller; } @Override public boolean performDrop(Object data) { if (data == null) { return false; } if (isBookmarkDrop()) { return doBookmarkDrop(data); } return false; } private boolean isBookmarkDrop() { return BookmarkTransfer.getInstance().isSupportedType(getCurrentEvent().currentDataType); } private boolean doBookmarkDrop(Object data) { BookmarkTransferData btd = (BookmarkTransferData) data; int index = getDropIndex(); if (getCurrentOperation() == DND.DROP_MOVE) { controller.moveBookmarks(btd.getBookmarks(), index); return true; } else if (getCurrentOperation() == DND.DROP_COPY) { controller.copyBookmarks(btd.getBookmarks(), index); return true; } return false; } private int getDropIndex() { IBookmark target = (IBookmark) getCurrentTarget(); if (target == null) { return controller.getCurrentList().getBookmarks().size(); } int location = getCurrentLocation(); if (location == LOCATION_NONE) { return controller.getCurrentList().getBookmarks().size(); } int indexOf = controller.getCurrentList().getBookmarks().indexOf(target); return location == LOCATION_BEFORE ? indexOf : indexOf + 1; } @Override public boolean validateDrop(Object target, int operation, TransferData transferType) { return BookmarkTransfer.getInstance().isSupportedType(transferType); } }
25.991071
91
0.70079
e4c40dbd0ae8bc3b8761465d032f4bd580b61cce
698
package com.javase.myenum; public class EnumTest { public static void main(String[] args) { System.out.println(Sex.MEN); switch (Season.SPRING){ case SPRING: System.out.println(Season.SPRING); break; case SUMMER: System.out.println(Season.SUMMER); break; case AUTUMN: System.out.println(Season.AUTUMN); break; case WINTER: System.out.println(Season.WINTER); break; default: break; } } } enum Sex{ MEN,WOMEN } enum Season{ SPRING,SUMMER,AUTUMN,WINTER }
22.516129
50
0.492837
920f4eaf83b79ede508f01c71c9f36c157232ebc
3,709
/* * Copyright © 2018 Library For All * * 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 one.lfa.opdsget.tests.vanilla; import one.lfa.opdsget.tests.TestDirectories; import one.lfa.opdsget.vanilla.OPDSArchiver; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static java.nio.charset.StandardCharsets.*; public final class OPDSArchiverTest { private Path output; private Path file; private Path file_tmp; private Path files; @Rule public ExpectedException expected = ExpectedException.none(); @Before public void setUp() throws IOException { this.output = TestDirectories.temporaryDirectory(); this.files = TestDirectories.temporaryDirectory(); this.file = Files.createTempFile(this.files, "output", ".zip"); this.file_tmp = Files.createTempFile(this.files, "output", ".zip.tmp"); } @After public void tearDown() { } @Test public void testArchiverEmptyTempExists() throws Exception { this.expected.expect(FileAlreadyExistsException.class); OPDSArchiver.createArchive(this.output, this.file, this.file_tmp); } @Test public void testArchiverEmpty() throws Exception { Files.deleteIfExists(this.file_tmp); OPDSArchiver.createArchive(this.output, this.file, this.file_tmp); Assert.assertTrue( this.file + " must exist", Files.exists(this.file)); Assert.assertTrue( this.file_tmp + " must not exist", !Files.exists(this.file_tmp)); final var zip = new ZipFile(this.file.toFile()); final List<ZipEntry> entries = zip.stream() .collect(Collectors.toList()); Assert.assertEquals("Must have no entries", 0L, (long) entries.size()); } @Test public void testArchiverBasic() throws Exception { Files.deleteIfExists(this.file_tmp); Files.write(this.output.resolve("hello0.txt"), "Hello 0".getBytes(UTF_8)); Files.write(this.output.resolve("hello1.txt"), "Hello 1".getBytes(UTF_8)); Files.write(this.output.resolve("hello2.txt"), "Hello 2".getBytes(UTF_8)); OPDSArchiver.createArchive(this.output, this.file, this.file_tmp); final var zip = new ZipFile(this.file.toFile()); final List<ZipEntry> entries = zip.stream() .collect(Collectors.toList()); Assert.assertTrue(entries.get(0).getName().contains("hello0.txt")); Assert.assertTrue(entries.get(1).getName().contains("hello1.txt")); Assert.assertTrue(entries.get(2).getName().contains("hello2.txt")); Assert.assertEquals( "Hello 0", new String(zip.getInputStream(entries.get(0)).readAllBytes(), UTF_8)); Assert.assertEquals( "Hello 1", new String(zip.getInputStream(entries.get(1)).readAllBytes(), UTF_8)); Assert.assertEquals( "Hello 2", new String(zip.getInputStream(entries.get(2)).readAllBytes(), UTF_8)); } }
29.672
78
0.715287
bba5600a947277ff8cb14f5b16e762b349e0ba9a
5,704
/* * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.core.thread; import org.graalvm.nativeimage.IsolateThread; import com.oracle.svm.core.SubstrateOptions; import com.oracle.svm.core.SubstrateUtil; import com.oracle.svm.core.SubstrateUtil.Thunk; import com.oracle.svm.core.annotate.RestrictHeapAccess; import com.oracle.svm.core.annotate.Uninterruptible; import com.oracle.svm.core.util.VMError; import com.oracle.svm.core.jdk.SplittableRandomAccessors; /** * The abstract base class for all VM operations that are allocated on the Java heap. Allocating the * VM operation on the Java heap is preferable but not always possible (see * {@link NativeVMOperation}). {@link JavaVMOperation} objects should be short lived and only * enqueued/executed once. For increased thread safety, it is prohibited to allocate * {@link JavaVMOperation}s that live in the image heap (see note below). * <p> * Note: the VM operation infrastructure supports that {@link JavaVMOperation}s are reused and * executed multiple times. However, extra care must be taken as each VM operation object can only * be in the VM operation queue once. Therefore, it must be guaranteed that the VM operation is * executed before it is enqueued again. Otherwise, this could result in various race conditions, * especially if {@linkplain SubstrateOptions#UseDedicatedVMOperationThread} is enabled. */ public abstract class JavaVMOperation extends VMOperation implements VMOperationControl.JavaAllocationFreeQueue.Element<JavaVMOperation> { protected IsolateThread queuingThread; private JavaVMOperation next; private volatile boolean finished; protected JavaVMOperation(String name, SystemEffect systemEffect) { super(name, systemEffect); /* * Calling SplittableRandomAccessors#getDefaultGen() here to prevent * SplittableRandomAccessors#initialize synchronized method call inside VMOperation lock, * that can leads to deadlock. */ SplittableRandomAccessors.getDefaultGen(); VMError.guarantee(!SubstrateUtil.HOSTED, "must not be created at image build time"); } @Override public JavaVMOperation getNext() { return next; } @Override public void setNext(JavaVMOperation value) { next = value; } public void enqueue() { VMOperationControl.get().enqueue(this); } @Override protected IsolateThread getQueuingThread(NativeVMOperationData data) { return queuingThread; } @Override @Uninterruptible(reason = "Called from uninterruptible code.", mayBeInlined = true) protected void setQueuingThread(NativeVMOperationData data, IsolateThread thread) { queuingThread = thread; } @Override protected boolean isFinished(NativeVMOperationData data) { return finished; } @Override @Uninterruptible(reason = "Called from uninterruptible code.", mayBeInlined = true) protected void setFinished(NativeVMOperationData data, boolean value) { finished = value; } @Override protected final boolean hasWork(NativeVMOperationData data) { return hasWork(); } protected boolean hasWork() { return true; } /** Convenience method for thunks that can be run by allocating a VMOperation. */ public static void enqueueBlockingSafepoint(String name, Thunk thunk) { ThunkOperation vmOperation = new ThunkOperation(name, SystemEffect.SAFEPOINT, thunk); vmOperation.enqueue(); } /** Convenience method for thunks that can be run by allocating a VMOperation. */ public static void enqueueBlockingNoSafepoint(String name, Thunk thunk) { ThunkOperation vmOperation = new ThunkOperation(name, SystemEffect.NONE, thunk); vmOperation.enqueue(); } @Override public final void operate(NativeVMOperationData data) { operate(); } @RestrictHeapAccess(access = RestrictHeapAccess.Access.UNRESTRICTED, overridesCallers = true, reason = "Whitelisted because some operations may allocate.") protected abstract void operate(); /** A VMOperation that executes a thunk. */ public static class ThunkOperation extends JavaVMOperation { private Thunk thunk; ThunkOperation(String name, SystemEffect systemEffect, Thunk thunk) { super(name, systemEffect); this.thunk = thunk; } @Override public void operate() { thunk.invoke(); } } }
39.068493
159
0.727034
d0e1c430f56ad2e222f38c2bdbc3692dca780dad
6,730
/* * Copyright 2015 Kevin Liu * * 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.github.airk.tool.sobitmap; import android.graphics.Bitmap; /** * Created by kevin on 15/3/24. * <p/> * Bitmap hunt options */ public final class Options { /** * 1. Use max input\output and step together */ int maxInput = -1; // we are in kb int maxOutput = -1; /** * Bitmap compress quality */ int qualityStep = -1; /** * 2. Only use the level param then make SoBitmap auto decide all the things inside. */ QualityLevel level = null; /** * Whether ignore other parameters but only use the level for auto deciding while hunting. */ boolean onlyLevel = false; /** * The max output bitmap size for width and height in pixel. * It's an approximate value, cause the inSampleSize always take the rounded down value nearest power of 2. * (http://developer.android.com/intl/en-us/reference/android/graphics/BitmapFactory.Options.html#inSampleSize) */ int maxSize; /** * JPG, PNG, WEBP, if possible, highly recommend WEBP, fast and small for storage. */ final Bitmap.CompressFormat format; public enum QualityLevel { HIGH { @Override int getStep() { return 5; } @Override float getMemoryFactor() { return 0.8f; } }, MEDIUM { @Override int getStep() { return 15; } @Override float getMemoryFactor() { return 0.5f; } }, LOW { @Override int getStep() { return 20; } @Override float getMemoryFactor() { return 0.35f; } }; /** * compress quality step */ abstract int getStep(); /** * memory usage factor of total */ abstract float getMemoryFactor(); } Options(int maxSize, Bitmap.CompressFormat format) { this.maxSize = maxSize; this.format = format; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Options options = (Options) o; if (maxInput != options.maxInput) return false; if (maxOutput != options.maxOutput) return false; if (maxSize != options.maxSize) return false; if (qualityStep != options.qualityStep) return false; if (format != options.format) return false; if (level != options.level) return false; return true; } @Override public int hashCode() { int result = (int) (maxInput ^ (maxInput >>> 32)); result = 31 * result + (int) (maxOutput ^ (maxOutput >>> 32)); result = 31 * result + maxSize; result = 31 * result + qualityStep; result = 31 * result + (format != null ? format.hashCode() : 0); result = 31 * result + (level != null ? level.hashCode() : 0); return result; } public static class ExactOptionsBuilder { private Options opts; private int maxInput = -1; private int maxOutput = -1; private int step = -1; private int size = -1; private Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG; public ExactOptionsBuilder maxSize(int size) { if (size < 0) { throw new IllegalArgumentException("Max size must greater than 0."); } this.size = size; return this; } public ExactOptionsBuilder maxInput(int kb) { if (kb < 0) { throw new IllegalArgumentException("Max input must greater than 0 and remember it's in KB."); } this.maxInput = kb; return this; } public ExactOptionsBuilder maxOutput(int kb) { if (kb < 0) { throw new IllegalArgumentException("Max output must greater than 0 and remember it's in KB."); } this.maxOutput = kb; return this; } public ExactOptionsBuilder step(int step) { if (step <= 0 || step >= 100) { throw new IllegalArgumentException("Wrong step (" + step + "), please keep it in 0 ~ 100."); } this.step = step; return this; } public ExactOptionsBuilder format(Bitmap.CompressFormat f) { format = f; return this; } public Options build() { if (maxOutput == -1) { throw new IllegalArgumentException("If you sure about using Exact options," + " at least you should set the max output memory size, otherwise you are recommended to use the FuzzyOptions."); } opts = new Options(size, format); opts.maxOutput = maxOutput; opts.maxInput = maxInput; opts.qualityStep = step; opts.onlyLevel = false; opts.level = null; return opts; } } public static class FuzzyOptionsBuilder { private Options opts; private int size = -1; private QualityLevel level = QualityLevel.MEDIUM; private Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG; public FuzzyOptionsBuilder maxSize(int size) { if (size < 0) { throw new IllegalArgumentException("Max size must greater than 0."); } this.size = size; return this; } public FuzzyOptionsBuilder format(Bitmap.CompressFormat f) { format = f; return this; } public FuzzyOptionsBuilder level(QualityLevel l) { level = l; return this; } public Options build() { opts = new Options(size, format); opts.level = level; opts.onlyLevel = true; return opts; } } }
29.517544
135
0.551412
7ff63843d03394dc33e5384822132c6e86444df3
5,618
package info.loenwind.enderioaddons.machine.afarm.module; import static info.loenwind.enderioaddons.config.Config.farmRFperAnalyzing; import info.loenwind.enderioaddons.machine.afarm.Notif; import info.loenwind.enderioaddons.machine.afarm.SlotDefinitionAfarm; import info.loenwind.enderioaddons.machine.afarm.SlotDefinitionAfarm.SLOT; import info.loenwind.enderioaddons.machine.afarm.WorkTile; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.oredict.OreDictionary; import com.InfinityRaider.AgriCraft.api.v1.ISeedStats; import com.enderio.core.common.util.ItemUtil; public class SeedAnalyzerModule implements IAfarmControlModule { @Override public void doWork(WorkTile workTile) { final SlotDefinitionAfarm slotDef = (SlotDefinitionAfarm) workTile.farm.getSlotDefinition(); boolean foundSeeds = false; for (int slot = slotDef.getMinSlot(SLOT.SEED); slot <= slotDef.getMaxSlot(SLOT.SEED); slot++) { final ItemStack stack = workTile.farm.getStackInSlot(slot); if (stack != null && stack.getItem() != null) { workTile.farm.notifications.remove(Notif.NO_SEEDS); foundSeeds = true; ISeedStats seedStats = workTile.agricraft.getSeedStats(stack); if (seedStats != null) { if (!isAnalyzed(stack)) { if (workTile.farm.canUsePower(farmRFperAnalyzing.getInt())) { workTile.farm.notifications.remove(Notif.NO_POWER); workTile.farm.usePower(farmRFperAnalyzing.getInt()); analyze(stack); reStack(workTile, slotDef, slot, stack); workTile.farm.markDirty(); return; // analyze one stack per work only } else { workTile.farm.notifications.add(Notif.NO_POWER); return; } } } } } if (!foundSeeds) { workTile.farm.notifications.add(Notif.NO_SEEDS); } } private static void reStack(WorkTile workTile, final SlotDefinitionAfarm slotDef, int slot, final ItemStack stack) { for (int slot2 = slotDef.getMinSlot(SLOT.SEED); slot2 <= slotDef.getMaxSlot(SLOT.SEED); slot2++) { if (slot2 != slot) { final ItemStack stack2 = workTile.farm.getStackInSlot(slot2); if (ItemUtil.areStackMergable(stack, stack2) && stack2.stackSize < stack2.getMaxStackSize()) { int free = stack2.getMaxStackSize() - stack2.stackSize; if (free >= stack.stackSize) { stack2.stackSize += stack.stackSize; stack.stackSize = 0; workTile.farm.setInventorySlotContents(slot, null); return; } else { stack2.stackSize = stack2.getMaxStackSize(); stack.stackSize -= free; } } } } } private static final String growth = "growth"; private static final String gain = "gain"; private static final String strength = "strength"; private static final String analyzed = "analyzed"; private static void analyze(ItemStack specimen) { NBTTagCompound tag; if (specimen.hasTagCompound()) { tag = specimen.getTagCompound(); if (tag.hasKey(growth) && tag.hasKey(gain) && tag.hasKey(strength)) { tag.setBoolean(analyzed, true); return; } } else { tag = new NBTTagCompound(); specimen.setTagCompound(tag); } tag.setShort(growth, (short) 1); tag.setShort(gain, (short) 1); tag.setShort(strength, (short) 1); tag.setBoolean(analyzed, true); } public static boolean isAnalyzed(ItemStack specimen) { if (specimen.hasTagCompound()) { NBTTagCompound tag = specimen.getTagCompound(); if (tag.hasKey(analyzed)) { return tag.getBoolean(analyzed); } } return false; } @Override public int getPriority() { return -1; } @Override public boolean isCompatibleWith(IAfarmControlModule other) { return !(other instanceof SeedAnalyzerModule); } static boolean isSameSeed(ItemStack seed1, ItemStack seed2) { if (seed1.getItem() == seed2.getItem()) { if (seed1.getItemDamage() != OreDictionary.WILDCARD_VALUE && seed2.getItemDamage() != OreDictionary.WILDCARD_VALUE && seed1.getItemDamage() != seed2.getItemDamage()) { return false; } else { if (seed1.stackTagCompound == seed2.stackTagCompound || seed1.stackTagCompound == null || seed2.stackTagCompound == null || ItemStack.areItemStackTagsEqual(seed1, seed2)) { return true; } for (Object key : seed1.stackTagCompound.func_150296_c()) { if (!growth.equals(key) && !gain.equals(key) && !strength.equals(key) && !analyzed.equals(key)) { Object o1 = seed1.stackTagCompound.getTag((String) key); Object o2 = seed2.stackTagCompound.getTag((String) key); if ((o1 == null) != (o2 == null)) { return false; } if (o1 != null && !o1.equals(o2)) { return false; } } } for (Object key : seed2.stackTagCompound.func_150296_c()) { if (!growth.equals(key) && !gain.equals(key) && !strength.equals(key) && !analyzed.equals(key)) { Object o1 = seed1.stackTagCompound.getTag((String) key); Object o2 = seed2.stackTagCompound.getTag((String) key); if ((o1 == null) != (o2 == null)) { return false; } if (o1 != null && !o1.equals(o2)) { return false; } } } return true; } } return false; } }
37.205298
180
0.631007
b6b6dd350a5464f5a4146be1e9e27157b4d48c9f
1,780
/* * Author: Jose Canahui */ package model; public class FoodCategoryLinkedList { private FoodCategoryNode head; public FoodCategoryLinkedList(FoodCategoryNode head) { this.head = head; } public FoodCategoryLinkedList() { this.head = null; } public void add(FoodCategoryNode toAdd){ FoodCategoryNode current = head; while(current.getNext()!= null) { current = current.getNext(); } current.setNext(toAdd); } public void add(String category, FoodItemLinkedList items){ FoodCategoryNode toAdd = new FoodCategoryNode(category, items); FoodCategoryNode current = head; while(current.getNext()!= null) { current = current.getNext(); } current.setNext(toAdd); } public void add(String category){ FoodCategoryNode toAdd = new FoodCategoryNode(category); FoodCategoryNode current = head; while(current.getNext()!= null) { current = current.getNext(); } current.setNext(toAdd); } public FoodCategoryNode get(int index) { if (index <= 0) return null; FoodCategoryNode current = head.getNext(); for (int i = 1; i < index; i++) { if(curent.getNext() == null) return null; current = current.getNext(); } return current; } public boolean delete(int index){ if (index < 1 || index > size()) return false FoodCategoryNode current = head; for (int i = 1; i < index; i++) { if (current.getNext() == null) return false; current = current.getNext(); } current.setNext(current.getNext().getNext()); return true; } /* * Utility */ public void setNext(FoodCategoryNode toAdd, FoodCategoryNode current){ curent = current.getNext(); if(current.getNext() = null) current.setNext(item); else setNext(item, current); } }
20.697674
71
0.660674
5f7987963ab97c0fb065fd15712a422d7830c4d5
77
package ryulib; public enum Direction { NoWhere, Left, Right, Up, Down }
9.625
23
0.701299
c2ddec7e79557eef2a3a11016fa1e5d9ce5f79ae
8,500
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.application; import com.yahoo.config.model.api.Model; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ApplicationName; import com.yahoo.config.provision.InstanceName; import com.yahoo.config.provision.TenantName; import com.yahoo.config.provision.Version; import com.yahoo.container.jdisc.HttpResponse; import com.yahoo.vespa.config.server.ServerCache; import com.yahoo.vespa.config.server.http.SessionHandlerTest; import com.yahoo.vespa.config.server.monitoring.MetricUpdater; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; import static com.yahoo.vespa.config.server.application.FileDistributionStatus.HostStatus; import static com.yahoo.vespa.config.server.application.FileDistributionStatus.Status; /** * @author hmusum */ public class FileDistributionStatusTest { private final Duration timeout = Duration.ofMillis(100); private TenantName tenant = TenantName.from("mytenant"); private ApplicationId appId = ApplicationId.from(tenant, ApplicationName.from("myapp"), InstanceName.from("myinstance")); private Application application; @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void require_status_finished() throws IOException { Map<String, Double> fileReferenceStatuses = new HashMap<>(); fileReferenceStatuses.put("1234", 1.0); FileDistributionStatus status = new MockStatus(statusFinished("localhost", Status.FINISHED, fileReferenceStatuses)); application = createApplication("localhost"); HttpResponse response = getStatus(status, application); assertResponse(200, "{" + "\"hosts\":[" + "{\"hostname\":\"localhost\"," + "\"status\":\"FINISHED\"," + "\"fileReferences\":[" + "{\"1234\":1.0}]}" + "]," + "\"status\":\"FINISHED\"}", response); } @Test public void require_status_in_progress_one_host() throws IOException { Map<String, Double> fileReferenceStatuses = new HashMap<>(); fileReferenceStatuses.put("1234", 0.2); FileDistributionStatus status = new MockStatus(statusWithError("localhost2", Status.IN_PROGRESS, fileReferenceStatuses, "")); application = createApplication("localhost2"); HttpResponse response = getStatus(status, application); assertResponse(200, "{" + "\"hosts\":[" + "{\"hostname\":\"localhost2\"," + "\"status\":\"IN_PROGRESS\"," + "\"message\":\"\"," + "\"fileReferences\":[" + "{\"1234\":0.2}]}" + "]," + "\"status\":\"IN_PROGRESS\"}", response); } @Test public void require_status_unknown_one_host() throws IOException { Map<String, Double> fileReferenceStatuses = new HashMap<>(); fileReferenceStatuses.put("1234", 0.2); FileDistributionStatus status = new MockStatus(statusWithError("localhost", Status.UNKNOWN, fileReferenceStatuses, "connection error")); application = createApplication("localhost"); HttpResponse response = getStatus(status, application); assertResponse(200, "{" + "\"hosts\":[" + "{\"hostname\":\"localhost\"," + "\"status\":\"UNKNOWN\"," + "\"message\":\"connection error\"," + "\"fileReferences\":[" + "{\"1234\":0.2}]}" + "]," + "\"status\":\"UNKNOWN\"}", response); } @Test public void require_different_statuses_many_hosts() throws IOException { application = createApplication("localhost", "localhost2"); Map<String, Double> fileReferenceStatuses = new HashMap<>(); fileReferenceStatuses.put("1234", 0.2); fileReferenceStatuses.put("abcd", 1.0); HostStatus localhost = statusWithError("localhost", Status.IN_PROGRESS, fileReferenceStatuses, "connection timed out"); Map<String, Double> fileReferenceStatuses2 = new HashMap<>(); fileReferenceStatuses2.put("1234", 1.0); HostStatus localhost2 = statusFinished("localhost2", Status.FINISHED, fileReferenceStatuses2); FileDistributionStatus status = new MockStatus(new HashSet<>(Arrays.asList(localhost, localhost2))); application = createApplication("localhost", "localhost2"); HttpResponse response = getStatus(status, application); assertResponse(200, "{" + "\"hosts\":[" + "{\"hostname\":\"localhost\"," + "\"status\":\"IN_PROGRESS\"," + "\"message\":\"connection timed out\"," + "\"fileReferences\":[" + "{\"1234\":0.2},{\"abcd\":1.0}]}," + "{\"hostname\":\"localhost2\"," + "\"status\":\"FINISHED\"," + "\"fileReferences\":[" + "{\"1234\":1.0}]}" + "]," + "\"status\":\"IN_PROGRESS\"}", response); } private void assertResponse(int statusCode, String expectedResponse, HttpResponse response) throws IOException { assertEquals(statusCode, response.getStatus()); assertEquals(expectedResponse, SessionHandlerTest.getRenderedString(response)); } private HostStatus statusFinished(String hostname, Status status, Map<String, Double> fileReferenceStatuses) { return new HostStatus(hostname, status, fileReferenceStatuses); } private HostStatus statusWithError(String hostname, Status status, Map<String, Double> fileReferenceStatuses, String errorMessage) { return new HostStatus(hostname, status, fileReferenceStatuses, errorMessage); } private Application createApplication(String... hostname) { return createApplication(Arrays.asList(hostname)); } private Application createApplication(List<String> hostnames) { Model mockModel = MockModel.createConfigProxies(hostnames, 1337); return new Application(mockModel, new ServerCache(), 3, false, Version.fromIntValues(0, 0, 0), MetricUpdater.createTestUpdater(), appId); } HttpResponse getStatus(FileDistributionStatus fileDistributionStatus, Application application) { return fileDistributionStatus.status(application, timeout); } private static class MockStatus extends FileDistributionStatus { private final Map<String, HostStatus> statuses = new HashMap<>(); // host status to be returned in getHostStatus() MockStatus(HostStatus status) { this(Collections.singleton(status)); } // host status per host to be returned in getHostStatus() MockStatus(Set<HostStatus> status) { status.forEach(s -> statuses.put(s.hostname(), s)); } @Override HostStatus getHostStatus(String hostname, int port, Duration timeout) { return statuses.get(hostname); } } }
42.929293
144
0.568824
6d45f3bd5e6a8275c76efd212bebcf67f39dc22a
751
public class Solution7 { public int maxProfit(int[] prices) { int len = prices.length; if (len < 2) { return 0; } // 差分数组比原始数组的长度少 1 int[] diff = new int[len - 1]; for (int i = 0; i < len - 1; i++) { diff[i] = prices[i + 1] - prices[i]; } // dp[i] 以 diff[i] 结尾的子序列的和的最大值 int[] dp = new int[len - 1]; dp[0] = diff[0]; for (int i = 1; i < len - 1; i++) { dp[i] = Math.max(diff[i], dp[i - 1] + diff[i]); } // 还是要考虑到 [7 , 6, 5, 4, 3] 这种不交易的情况 // 初值应该赋值成 0 int res = 0; for (int i = 0; i < len - 1; i++) { res = Math.max(res, dp[i]); } return res; } }
24.225806
59
0.396804
d1729f6668584342313c9ae2a8ee2db1049c0261
2,073
package ru.tasks.task_005.solution; import org.junit.Test; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import static org.junit.Assert.assertThat; import static org.hamcrest.core.Is.is; /** * Created on 25.01.2018. * * @author Aleks Sidorenko (alek.sidorenko1979@gmail.com). * @version $Id$. * @since 0.1. */ public class StatisticsTest { @Test public void whenStatisticsScoreFive() throws IOException { Statistics statistics = new Statistics(); FileWriter fwInput = new FileWriter("C:\\Users\\Александр\\OneDrive\\Документы\\IdeaProject\\" + "Acmp.ru\\Tasks_001_050\\src\\main\\java\\ru\\tasks\\task_005\\solution\\input.txt"); fwInput.write("5\r"); fwInput.write("4 16 19 31 2"); fwInput.close(); boolean expected = statistics.init(); FileReader frOutput = new FileReader("C:\\Users\\Александр\\OneDrive\\Документы\\IdeaProject\\" + "Acmp.ru\\Tasks_001_050\\src\\main\\java\\ru\\tasks\\task_005\\solution\\output.txt"); Scanner scanner = new Scanner(frOutput); boolean output = scanner.hasNextLine(); assertThat(expected, is(output)); } @Test public void whenStatisticsScoreEight() throws IOException { Statistics statistics = new Statistics(); FileWriter fwInput = new FileWriter("C:\\Users\\Александр\\OneDrive\\Документы\\IdeaProject\\" + "Acmp.ru\\Tasks_001_050\\src\\main\\java\\ru\\tasks\\task_005\\solution\\input.txt"); fwInput.write("8\r"); fwInput.write("29 4 7 12 15 17 24 1"); fwInput.close(); boolean expected = statistics.init(); FileReader frOutput = new FileReader("C:\\Users\\Александр\\OneDrive\\Документы\\IdeaProject\\" + "Acmp.ru\\Tasks_001_050\\src\\main\\java\\ru\\tasks\\task_005\\solution\\output.txt"); Scanner scanner = new Scanner(frOutput); boolean output = scanner.hasNextLine(); assertThat(expected, is(output)); } }
38.388889
105
0.65316
a84b25bc369be2902f60d56349b9394f829b1867
6,566
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.MoreObjects; import java.io.Serializable; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * This class represents options for methods that wait for changes in the status of a resource. */ public abstract class WaitForOption implements Serializable { private static final long serialVersionUID = 8443451708032349243L; private final OptionType optionType; enum OptionType { CHECKING_PERIOD, TIMEOUT } private WaitForOption(OptionType optionType) { this.optionType = optionType; } /** * This class represents an option to set how frequently the resource status should be checked. * Objects of this class keep the actual period and related time unit for the checking period. */ public static final class CheckingPeriod extends WaitForOption { private static final long serialVersionUID = -2481062893220539210L; private static final CheckingPeriod DEFAULT = new CheckingPeriod(500, TimeUnit.MILLISECONDS); private final long period; private final TimeUnit unit; private CheckingPeriod(long period, TimeUnit unit) { super(OptionType.CHECKING_PERIOD); this.period = period; this.unit = unit; } /** * Returns the checking period. */ public long getPeriod() { return period; } /** * Returns the time unit for {@link #getPeriod()}. */ public TimeUnit getUnit() { return unit; } /** * Blocks the current thread for the amount of time specified by this object. * * @throws InterruptedException if the current thread was interrupted */ public void sleep() throws InterruptedException { unit.sleep(period); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || !(obj instanceof CheckingPeriod)) { return false; } CheckingPeriod other = (CheckingPeriod) obj; return baseEquals(other) && Objects.equals(period, other.period) && Objects.equals(unit, other.unit); } @Override public int hashCode() { return Objects.hash(baseHashCode(), period, unit); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("period", period) .add("unit", unit) .toString(); } /** * Returns the {@code CheckingPeriod} option specified in {@code options}. If no * {@code CheckingPeriod} could be found among {@code options}, the default checking period (500 * milliseconds) is used. */ public static CheckingPeriod getOrDefault(WaitForOption... options) { return getOrDefaultInternal(OptionType.CHECKING_PERIOD, DEFAULT, options); } } /** * This class represents an option to set the maximum time to wait for the resource's status to * reach the desired state. */ public static final class Timeout extends WaitForOption { private static final long serialVersionUID = -7120401111985321932L; private static final Timeout DEFAULT = new Timeout(-1); private final long timeoutMillis; private Timeout(long timeoutMillis) { super(OptionType.TIMEOUT); this.timeoutMillis = timeoutMillis; } /** * Returns the timeout in milliseconds. */ public long getTimeoutMillis() { return timeoutMillis; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || !(obj instanceof Timeout)) { return false; } Timeout other = (Timeout) obj; return baseEquals(other) && Objects.equals(timeoutMillis, other.timeoutMillis); } @Override public int hashCode() { return Objects.hash(baseHashCode(), timeoutMillis); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("timeoutMillis", timeoutMillis) .toString(); } /** * Returns the {@code Timeout} option specified in {@code options}. If no {@code Timeout} could * be found among {@code options}, no timeout will be used. */ public static Timeout getOrDefault(WaitForOption... options) { return getOrDefaultInternal(OptionType.TIMEOUT, DEFAULT, options); } } OptionType getOptionType() { return optionType; } final boolean baseEquals(WaitForOption option) { return Objects.equals(option.optionType, option.optionType); } final int baseHashCode() { return Objects.hash(optionType); } @SuppressWarnings("unchecked") private static <T extends WaitForOption> T getOrDefaultInternal(OptionType optionType, T defaultValue, WaitForOption... options) { T foundOption = null; for (WaitForOption option : options) { if (option.optionType.equals(optionType)) { checkArgument(foundOption == null, "Duplicate option %s", option); foundOption = (T) option; } } return foundOption != null ? foundOption : defaultValue; } /** * Returns an option to set how frequently the resource status should be checked. * * @param checkEvery the checking period * @param unit the time unit of the checking period */ public static CheckingPeriod checkEvery(long checkEvery, TimeUnit unit) { checkArgument(checkEvery >= 0, "checkEvery must be >= 0"); return new CheckingPeriod(checkEvery, unit); } /** * Returns an option to set the maximum time to wait. * * @param timeout the maximum time to wait, expressed in {@code unit} * @param unit the time unit of the timeout */ public static Timeout timeout(long timeout, TimeUnit unit) { checkArgument(timeout >= 0, "timeout must be >= 0"); return new Timeout(unit.toMillis(timeout)); } }
28.672489
100
0.673774
2a4891639219e4ed66b74797dc81f1d5b21106ec
2,267
/* * Copyright (c) 2021 Huawei Device Co., Ltd.All rights reserved. * Licensed under the Apache License,Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ohos.samples.tictactoegame.connections; import ohos.hiviewdfx.HiLog; import ohos.hiviewdfx.HiLogLabel; import ohos.rpc.IRemoteBroker; import ohos.rpc.IRemoteObject; import ohos.rpc.MessageOption; import ohos.rpc.MessageParcel; import ohos.rpc.RemoteException; /** * MyRemoteProxy class */ public class MyRemoteProxy implements IRemoteBroker { private static final int COMMAND_PLUS = IRemoteObject.MIN_TRANSACTION_ID; private static final int ERR_OK = 0; private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, ""); private static final String LOG_FORMAT = "%{public}s: %{public}s"; private final IRemoteObject remote; /** * MyRemoteProxy * * @param remote the remote */ public MyRemoteProxy(IRemoteObject remote) { this.remote = remote; } /** * asObject: get the IRemote Object * * @return IRemote Object */ public IRemoteObject asObject() { return remote; } /** * sendCmd * * @param cmd the cmd to send */ public void sendCmd(int cmd) { MessageParcel data = MessageParcel.obtain(); data.writeInt(cmd); MessageParcel reply = MessageParcel.obtain(); MessageOption option = new MessageOption(MessageOption.TF_SYNC); try { remote.sendRequest(COMMAND_PLUS, data, reply, option); int ec = reply.readInt(); if (ec != ERR_OK) { throw new RemoteException(); } } catch (RemoteException e) { HiLog.error(LABEL_LOG, LOG_FORMAT, "MyRemoteProxy", "" + e); } } }
27.987654
77
0.663873
34d82d0d239f63e65d5e28bbb43c786dcff73fac
1,225
package com.smartcodeltd.jenkinsci.plugins.buildmonitor.order; import hudson.model.AbstractProject; import java.io.Serializable; import java.util.Comparator; import java.util.List; public class ByEstimatedDuration implements Comparator<AbstractProject<?, ?>>, Serializable { @Override public int compare(AbstractProject<?, ?> a, AbstractProject<?,?> b) { return compareEstimatedDuration(a, b); } /** * Returns a sum of the estimated duration for a project and all upstream projects * * @return time */ private long getTotalEstimatedDuration(AbstractProject<?, ?> project) { long time = project.getEstimatedDuration(); if(!project.getUpstreamProjects().isEmpty()) { List<AbstractProject> upStreamProjects = project.getUpstreamProjects(); for (AbstractProject upStreamProject : upStreamProjects) { time += getTotalEstimatedDuration((AbstractProject<?, ?>) upStreamProject); } } return time; } private int compareEstimatedDuration(AbstractProject<?, ?> a, AbstractProject<?, ?> b) { return Long.compare(getTotalEstimatedDuration(a), getTotalEstimatedDuration(b)); } }
32.236842
93
0.682449
a1c44f778f832b1192381505a95ec7e0ab9de3b6
520
package io.github.greyp9.arwo.core.expr.eval; import io.github.greyp9.arwo.core.expr.Node; import io.github.greyp9.arwo.core.expr.op.MultiOperator; import java.util.List; public abstract class Evaluator { protected abstract Node evaluate(MultiOperator multiOperator); protected final void validateSize(final int size, final List<Node> nodes) { if (size != nodes.size()) { throw new IllegalArgumentException(String.format("Expected=%d, Actual=%d", size, nodes.size())); } } }
28.888889
108
0.709615
26fb7819bfdcbe36fa55bb13b902f16af41790b9
1,345
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.athenz.client.zts.utils; import com.yahoo.vespa.athenz.api.AthenzIdentity; import com.yahoo.vespa.athenz.api.AthenzService; import com.yahoo.vespa.athenz.client.zts.ZtsClient; import com.yahoo.security.Pkcs10Csr; import com.yahoo.security.Pkcs10CsrBuilder; import javax.security.auth.x500.X500Principal; import java.security.KeyPair; import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_RSA; /** * Generates a {@link Pkcs10Csr} instance for use with {@link ZtsClient#getServiceIdentity(AthenzIdentity, String, Pkcs10Csr)} * * @author bjorncs */ public class IdentityCsrGenerator { private final String dnsSuffix; public IdentityCsrGenerator(String dnsSuffix) { this.dnsSuffix = dnsSuffix; } public Pkcs10Csr generateIdentityCsr(AthenzIdentity identity, KeyPair keypair) { return Pkcs10CsrBuilder.fromKeypair(new X500Principal("CN=" + identity.getFullName()), keypair, SHA256_WITH_RSA) .addSubjectAlternativeName(String.format( "%s.%s.%s", identity.getName(), identity.getDomainName().replace(".", "-"), dnsSuffix)) .build(); } }
34.487179
126
0.695911
44a551dd2adb96214a1952a75d7db99a07b4548c
5,548
package tech.harmonysoft.oss.traute.test.impl.expectation; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import tech.harmonysoft.oss.traute.test.api.expectation.Expectation; import tech.harmonysoft.oss.traute.test.api.model.RunResult; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; public class RunResultExpectation implements Expectation<RunResult> { @Nullable private final String exceptionClass; @Nullable private final String exceptionMessageSnippet; @Nullable private final String exceptionMessageText; @Nullable private final Integer thrownAtLine; public RunResultExpectation(@Nullable String exceptionClass, @Nullable String exceptionMessageSnippet, @Nullable String exceptionMessageText, @Nullable Integer thrownAtLine) { this.exceptionClass = exceptionClass; this.exceptionMessageSnippet = exceptionMessageSnippet; this.exceptionMessageText = exceptionMessageText; this.thrownAtLine = thrownAtLine; } @Override public void match(@NotNull RunResult actual) { boolean expectException = exceptionClass != null || exceptionMessageSnippet != null || exceptionMessageText != null; Optional<Throwable> exceptionOptional = actual.getException(); if (exceptionOptional.isPresent()) { if (!expectException) { fail(String.format( "Expected that running the program below doesn't produce any exception but got %s.%n%s", exceptionOptional.get(), actual.getInput() )); } matchException(exceptionOptional.get(), actual.getInput()); } else { if (expectException) { fail(String.format( "Expected that running the program below produces %s but it is executed successfully.%n%s", getExpectedExceptionDetails(), actual.getInput())); } } } private void matchException(@NotNull Throwable actual, @NotNull Object input) { String exceptionDescription; if (exceptionClass == null) { exceptionDescription = "an exception"; } else { if (!exceptionClass.equals(actual.getClass().getName())) { fail(String.format( "Expected that running the program below throws a %s but got a %s.%n%s", exceptionClass, actual.getClass().getName(), input )); } exceptionDescription = "a " + exceptionClass; } if (exceptionMessageSnippet != null) { String message = actual.getMessage(); if (message == null) { fail(String.format( "Expected that running the program below throws %s with a text which contains '%s'. " + "However, the exception has no text.%n%s", exceptionDescription, exceptionMessageSnippet, input )); } if (!message.contains(exceptionMessageSnippet)) { fail(String.format( "Expected that running the program below throws %s with a text which contains '%s'. " + "However, the text is different: '%s'.%n%s", exceptionDescription, exceptionMessageSnippet, message, input )); } } if (exceptionMessageText != null) { String message = actual.getMessage(); if (!exceptionMessageText.equalsIgnoreCase(message)) { assertEquals(exceptionMessageText, message, () -> String.format( "Expected that running the program below throws %s with particular error message.%n%s", exceptionDescription, input )); } } if (thrownAtLine != null) { StringWriter stringWriter = new StringWriter(); actual.printStackTrace(new PrintWriter(stringWriter)); stringWriter.flush(); int lineNumber = actual.getStackTrace()[0].getLineNumber(); if (lineNumber != thrownAtLine) { fail(String.format( "Expected that running the program below throws %s exception from line %d but it's thrown " + "from line %d:%n%s%n%s", exceptionDescription, thrownAtLine, lineNumber, stringWriter, input )); } } } @NotNull private String getExpectedExceptionDetails() { StringBuilder result = new StringBuilder(); if (exceptionClass == null) { result.append("an exception"); } else { result.append("an exception of class ").append(exceptionClass); } if (exceptionMessageSnippet != null) { result.append(" which message has '").append(exceptionMessageSnippet).append("' snippet"); } if (exceptionMessageText != null) { result.append(" with message '").append(exceptionMessageText).append("'"); } return result.toString(); } }
41.096296
115
0.581291
97b76a666f2ce13737c6c5ed1ae2bfb050b131f8
124
package com.xuanyue.db.xuan.core.table; public interface IStringEncoding { public String encoding(Object value); }
17.714286
40
0.75
cc87bde9ff68ea7a9539ce03f64805648a54496b
4,219
/** * 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.sqoop.shell; import jline.ConsoleReader; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.OptionBuilder; import org.apache.sqoop.common.Direction; import org.apache.sqoop.model.MJob; import org.apache.sqoop.shell.core.Constants; import org.apache.sqoop.shell.utils.ConfigDisplayer; import org.apache.sqoop.shell.utils.ConfigOptions; import org.apache.sqoop.shell.utils.JobDynamicConfigOptions; import org.apache.sqoop.validation.Status; import java.io.IOException; import java.util.List; import java.util.ResourceBundle; import static org.apache.sqoop.shell.ShellEnvironment.*; import static org.apache.sqoop.shell.utils.ConfigFiller.*; /** * Handles creation of new job objects. */ @SuppressWarnings("serial") public class CreateJobFunction extends SqoopFunction { @SuppressWarnings("static-access") public CreateJobFunction() { this.addOption(OptionBuilder .withDescription(resourceString(Constants.RES_PROMPT_LINK_ID)) .withLongOpt(Constants.OPT_FROM) .isRequired() .hasArg() .create(Constants.OPT_FROM_CHAR) ); this.addOption(OptionBuilder .withDescription(resourceString(Constants.RES_PROMPT_LINK_ID)) .withLongOpt(Constants.OPT_TO) .isRequired() .hasArg() .create(Constants.OPT_TO_CHAR) ); } @Override @SuppressWarnings("unchecked") public Object executeFunction(CommandLine line, boolean isInteractive) throws IOException { return createJob(getLong(line, Constants.OPT_FROM), getLong(line, Constants.OPT_TO), line.getArgList(), isInteractive); } private Status createJob(Long fromLinkId, Long toLinkId, List<String> args, boolean isInteractive) throws IOException { printlnResource(Constants.RES_CREATE_CREATING_JOB, fromLinkId, toLinkId); ConsoleReader reader = new ConsoleReader(); MJob job = client.createJob(fromLinkId, toLinkId); ResourceBundle fromConfigBundle = client.getConnectorConfigBundle( job.getFromConnectorId()); ResourceBundle toConfigBundle = client.getConnectorConfigBundle( job.getToConnectorId()); ResourceBundle driverConfigBundle = client.getDriverConfigBundle(); Status status = Status.OK; if (isInteractive) { printlnResource(Constants.RES_PROMPT_FILL_JOB_CONFIG); do { // Print error introduction if needed if( !status.canProceed() ) { errorIntroduction(); } // Fill in data from user if(!fillJobWithBundle(reader, job, fromConfigBundle, toConfigBundle, driverConfigBundle)) { return null; } // Try to create status = client.saveJob(job); } while(!status.canProceed()); } else { JobDynamicConfigOptions options = new JobDynamicConfigOptions(); options.prepareOptions(job); CommandLine line = ConfigOptions.parseOptions(options, 0, args, false); if (fillJob(line, job)) { status = client.saveJob(job); if (!status.canProceed()) { printJobValidationMessages(job); return null; } } else { printJobValidationMessages(job); return null; } } ConfigDisplayer.displayConfigWarning(job); printlnResource(Constants.RES_CREATE_JOB_SUCCESSFUL, status.name(), job.getPersistenceId()); return status; } }
34.300813
121
0.713439
5d052e9e745904984209562a9d7560355a2d7f8c
2,695
/** * Copyright (c) 2004-2011 Wang Jinbao(Julian Wong), http://www.ralasafe.com * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php */ package org.ralasafe.servlet; import java.util.HashMap; import java.util.Map; import org.ralasafe.EntityExistException; import org.ralasafe.SystemConstant; import org.ralasafe.db.sql.xml.DefineVariable; import org.ralasafe.db.sql.xml.ExprGroup; import org.ralasafe.db.sql.xml.BusinessData; import org.ralasafe.db.sql.xml.BusinessDataType; import org.ralasafe.entitle.ScriptTestResult; import org.ralasafe.entitle.BusinessDataManager; import org.ralasafe.script.AbstractPolicy; import org.ralasafe.script.ScriptFactory; import org.ralasafe.user.User; public class BusinessDataPolicyDesignHandler extends AbstractPolicyDesignHandler { private final BusinessDataManager manager; final BusinessDataType xml; public String getPolicyType() { return "businessData"; } public String getManagePage() { return "./businessDataMng.rls"; } public BusinessDataPolicyDesignHandler( BusinessDataManager manager, BusinessDataType xmlUc ) { this.manager=manager; this.xml=xmlUc; } public String getDesignPageTitle() { return "Design Business Data: " + xml.getName(); } public String getRawPageTitle() { return "Edit Business Data manually: " + xml.getName(); } public DefineVariable[] getVariables() { return xml.getDefineVariable(); } public void deleteVariable( int id ) { xml.removeDefineVariableAt( id ); } public void addVariable( DefineVariable var ) { xml.addDefineVariable( var ); } public void updateVariable( int varIndex, DefineVariable var ) { xml.setDefineVariable( varIndex, var ); } public ExprGroup getExprGroup() { return xml.getExprGroup(); } public void save( int id ) throws EntityExistException { manager.updateBusinessData( id, (BusinessData) xml ); } public void setDesignMode() { xml.setIsRawScript( false ); } public void setRawMode() { xml.setIsRawScript( true ); } public void setRawScript( String script ) { xml.getRawScript().setContent( script ); } public String getRawScript() { return xml.getRawScript().getContent(); } public ScriptTestResult run( User user, Object businessData, Map context ) { AbstractPolicy policy2=getPolicy(); org.ralasafe.script.BusinessData script=(org.ralasafe.script.BusinessData) policy2; if( context==null ) { context=new HashMap(); } context.put(SystemConstant.BUSINESS_DATA, businessData); return script.test( user, context, getQueryManager() ); } public AbstractPolicy transferXml2Policy() { return ScriptFactory.getBusinessData( xml, getQueryManager() ); } }
25.913462
85
0.75436
9f4c9f9a9240eaedf9c3bed10bab506d04c068a4
438
class Solution { public List<Integer> preorder(Node root) { if (root == null) return new ArrayList<>(); List<Integer> ans = new ArrayList<>(); Deque<Node> stack = new ArrayDeque<>(); stack.push(root); while (!stack.isEmpty()) { root = stack.pop(); ans.add(root.val); for (int i = root.children.size() - 1; i >= 0; --i) stack.push(root.children.get(i)); } return ans; } }
21.9
57
0.554795
e5f2dea0cd0c0bb798010a1d07948e245f9ce8cb
3,103
/** * 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.crunch.types.avro; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableList; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.crunch.Pair; import org.apache.crunch.test.Person; import org.apache.crunch.test.StringWrapper; import org.apache.hadoop.conf.Configuration; import org.junit.Test; import com.google.common.collect.Lists; import java.util.List; public class AvroTableTypeTest { @Test public void testGetDetachedValue() { Integer integerValue = 42; Person person = new Person(); person.name = "John Doe"; person.age = 42; person.siblingnames = Lists.<CharSequence> newArrayList(); Pair<Integer, Person> pair = Pair.of(integerValue, person); AvroTableType<Integer, Person> tableType = Avros.tableOf(Avros.ints(), Avros.specifics(Person.class)); tableType.initialize(new Configuration()); Pair<Integer, Person> detachedPair = tableType.getDetachedValue(pair); assertSame(integerValue, detachedPair.first()); assertEquals(person, detachedPair.second()); assertNotSame(person, detachedPair.second()); } @Test public void testUnionValueType() { List<Schema> schemas = Lists.newArrayList(); schemas.add(Schema.create(Schema.Type.BOOLEAN)); schemas.add(Schema.create(Schema.Type.INT)); Schema union = Schema.createUnion(schemas); boolean success = false; try { Avros.tableOf(Avros.longs(), Avros.generics(union)); success = true; } catch (Exception shouldNotBeThrown) { } assertTrue("Union type was properly made nullable", success); } @Test public void testIsReflect_ContainsReflectKey() { assertTrue(Avros.tableOf(Avros.reflects(StringWrapper.class), Avros.ints()).hasReflect()); } @Test public void testIsReflect_ContainsReflectValue() { assertTrue(Avros.tableOf(Avros.ints(), Avros.reflects(StringWrapper.class)).hasReflect()); } @Test public void testReflect_NoReflectKeyOrValue() { assertFalse(Avros.tableOf(Avros.ints(), Avros.ints()).hasReflect()); } }
33.365591
94
0.741218
39ff7ca31425ae709408ae4fb4d48d20b041610d
671
package nl.osrs.model.player.packets; import nl.osrs.model.player.Client; import nl.osrs.model.player.PacketType; /** * Magic on items **/ @SuppressWarnings("all") public class MagicOnItems implements PacketType { @Override public void processPacket(Client c, int packetType, int packetSize) { int slot = c.getInStream().readSignedWord(); int itemId = c.getInStream().readSignedWordA(); int junk = c.getInStream().readSignedWord(); int spellId = c.getInStream().readSignedWordA(); c.getTaskScheduler().stopTasks(); c.getPA().removeAllWindows(); c.usingMagic = true; c.getPA().magicOnItems(slot, itemId, spellId); c.usingMagic = false; } }
23.137931
70
0.721311
edb24fe829ae46a077b69add0e2014de1467f87e
2,016
/* * * 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.github.adejanovski.cassandra.jdbc; import java.nio.ByteBuffer; import java.sql.Types; public class JdbcShort extends AbstractJdbcType<Short> { public static final JdbcShort instance = new JdbcShort(); JdbcShort() { } public boolean isCaseSensitive() { return false; } public int getScale(Short obj) { return 0; } public int getPrecision(Short obj) { // max size is -32768 return (obj == null) ? 6 : obj.toString().length(); } public boolean isCurrency() { return false; } public boolean isSigned() { return true; } public String toString(Short obj) { return (obj == null) ? null : obj.toString(); } public boolean needsQuotes() { return false; } public String getString(ByteBuffer bytes) { if ((bytes == null) || !bytes.hasRemaining()) { return null; } else if (bytes.remaining() != 2) { throw new MarshalException( "A short is exactly 2 bytes: " + bytes.remaining()); } return toString(compose(bytes)); } public Class<Short> getType() { return Short.class; } public int getJdbcType() { return Types.SMALLINT; } public Short compose(Object obj) { return (Short) obj; } public Object decompose(Short value) { return value; } }
24.585366
77
0.616071
0861c7064f0b4216ba89e3dce906735291057e0d
2,034
package io.jenkins.plugins.analysis.warnings; import javax.annotation.Nonnull; import java.util.Collection; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; import edu.hm.hafner.analysis.IssueParser; import edu.hm.hafner.analysis.parser.EclipseParser; import edu.hm.hafner.analysis.parser.EclipseXMLParser; import io.jenkins.plugins.analysis.core.model.ReportScanningToolSuite; import hudson.Extension; /** * Provides a parser and customized messages for the Eclipse Compiler. * * @author Ullrich Hafner */ public class Eclipse extends ReportScanningToolSuite { private static final long serialVersionUID = -2312612497121380654L; static final String ID = "eclipse"; /** Creates a new instance of {@link Eclipse}. */ @DataBoundConstructor public Eclipse() { super(); // empty constructor required for stapler } @Override protected Collection<? extends IssueParser> getParsers() { return asList(new EclipseParser(), new EclipseXMLParser()); } /** Descriptor for this static analysis tool. */ @Symbol("eclipse") @Extension public static class Descriptor extends ReportScanningToolDescriptor { /** Creates the descriptor instance. */ public Descriptor() { super(ID); } @Override public String getHelp() { return "<p><p>Create an output file that contains Eclipse ECJ output, in either XML or text format.</p><p>To log in XML format, specify &quot;.xml&quot; as the file extension to the -log argument:</p><p><code>java -jar ecj.jar -log &lt;logfile&gt;.xml &lt;other arguments&gt;</code></p><p>To log in text format, specify any file extension except &quot;.xml&quot; to the -log argument:</p><p><code>java -jar ecj.jar -log &lt;logfile&gt;.log &lt;other arguments&gt;</code></p></p>"; } @Nonnull @Override public String getDisplayName() { return Messages.Warnings_EclipseParser_ParserName(); } } }
35.068966
492
0.69174
2a4a2a1d08534390172346340ee792f17f1817ad
641
package com.ruoyi.framework.config; import com.ruoyi.common.utils.OrderNoUtil; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 订单编号生成配置 * * @author wyt */ @Configuration public class OrderNoConfig { /** * 机房id */ @Value("${orderNo.datacenterId}") private long datacenterId; /** * 机器id */ @Value("${orderNo.machineId}") private long machineId; @Bean public OrderNoUtil orderNoUtil() { return new OrderNoUtil(datacenterId, machineId); } }
18.852941
60
0.684867
24ae9db4dde231384d8387e3d1d14ecb48d4bb6d
278
package xyz.mydev.mq.delay.constant; import lombok.Getter; /** * @author ZSP */ @Getter public enum MqPlatform { // mq平台 1 RocketMQ 2 RabbitMQ 3 Kafka 4其他 RocketMQ(1), RabbitMQ(2), Kafka(3); private int code; MqPlatform(int code) { this.code = code; } }
13.238095
43
0.651079
e3f8068ba41bf18ad82c25f5199f04cec313f2bb
2,724
/** ------------------------------------------------------------------- Copyright (c) 2014 SyncFree Consortium. All Rights Reserved. This file is provided 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. ------------------------------------------------------------------- **/ /***************************************************************************** * Copyright 2011-2012 INRIA * Copyright 2011-2012 Universidade Nova de Lisboa * * 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 swift.indigo.proto; import swift.api.CRDTIdentifier; import swift.clocks.CausalityClock; import swift.proto.ClientRequest; import sys.net.api.Envelope; import sys.net.api.MessageHandler; /** * Client request to fetch a particular version of an object. * * @author smduarte */ public class FetchObjectRequest extends ClientRequest { protected CRDTIdentifier uid; protected boolean subscribe; protected CausalityClock dcClock; public FetchObjectRequest() { } private FetchObjectRequest(String clientId, CRDTIdentifier uid, boolean subscribe) { super(clientId); this.uid = uid; this.subscribe = subscribe; } public FetchObjectRequest(CausalityClock dcClock, String clientId, CRDTIdentifier uid, boolean subscribe) { this(clientId, uid, subscribe); this.dcClock = dcClock.clone(); } public boolean hasSubscription() { return subscribe; } /** * @return id of the requested object */ public CRDTIdentifier getUid() { return uid; } public CausalityClock getDcClock() { return dcClock; } @Override public void deliverTo(Envelope src, MessageHandler handler) { ((IndigoProtocolHandler) handler).onReceive(src, this); } }
29.934066
108
0.67768
f069a21ee832c4f762afe8f38aa03a9d620c50c5
314
package providers; import org.glassfish.hk2.api.Factory; import services.authentication.Guard; import services.authentication.JwtGuard; public class GuardProvider implements Factory<Guard> { @Override public Guard provide() { return new JwtGuard(); } @Override public void dispose(Guard instance) { } }
18.470588
54
0.773885
c2f1c1d29c6ef0cb8efb24498c3e1c499d71482a
4,335
package s1.block11; import java.util.Arrays; /** * * @author s@scalingbits.com * @ version 1.1 */ public class TestEuro { public static void main(String[] args) { System.out.println("Phase 1: Einfache Tests"); Euro konto1 = new Euro(172, 12); long d1 = konto1.longValue(); System.out.println(" Euro.longValue().Sollwert 172; Istwert: " + d1); double d2 = konto1.doubleValue(); System.out.println(" Euro.doubleValue().Sollwert 172.12; Istwert: " + d2); float d3 = konto1.floatValue(); System.out.println(" Euro.floatValue().Sollwert 172.12; Istwert: " + d3); System.out.println(" Euro.symbol().Sollwert €; Istwert: " + konto1.symbol()); System.out.println(" Euro.toString().Sollwert 172.12€; Istwert: " + konto1); System.out.println("Phase 2: Härtere Tests"); Euro konto2 = new Euro(-380, 25); d1 = konto2.longValue(); System.out.println(" Euro.longValue().Sollwert -380; Istwert: " + d1); d2 = konto2.doubleValue(); System.out.println(" Euro.doubleValue().Sollwert -380.25; Istwert: " + d2); d3 = konto2.floatValue(); System.out.println(" Euro.floatValue().Sollwert -380.25; Istwert: " + d3); Euro konto3 = new Euro (-382,225); d1 = konto3.longValue(); System.out.println(" Euro.longValue().Sollwert -382; Istwert: " + d1); d2 = konto3.doubleValue(); System.out.println(" Euro.doubleValue().Sollwert -382; Istwert: " + d2); d3 = konto3.floatValue(); System.out.println(" Euro.floatValue().Sollwert -382; Istwert: " + d3); System.out.println("Phase 3: Multiplikation testen"); Waehrung konto10 = new Euro(1,23); double m1 = 2; Waehrung konto11 = konto10.mult(m1); System.out.println(" Euro.mult(): "+konto10 +" * "+ m1 + " = " + konto11); Waehrung konto20 = new Euro(1,98); double m2 = 2; Waehrung konto21 = konto20.mult(m2); System.out.println(" Euro.mult(): "+konto20 +" * "+ m2 + " = " + konto21); Waehrung konto30 = new Euro(-1,98); double m3 = 2; Waehrung konto31 = konto30.mult(m3); System.out.println(" Euro.mult(): "+konto30 +" * "+ m3 + " = " + konto31); Waehrung konto40 = new Euro(-1,98); double m4 = -2; Waehrung konto41 = konto40.mult(m4); System.out.println(" Euro.mult(): "+konto40 +" * "+ m4 + " = " + konto41); Waehrung konto50 = new Euro(10,10); double m5 = -2.01; Waehrung konto51 = konto50.mult(m5); System.out.println(" Euro.mult(): "+konto50 +" * "+ m5 + " = " + konto51); Waehrung konto60 = new Euro(10,1); double m6 = -2.001; Waehrung konto61 = konto60.mult(m6); System.out.println(" Euro.mult(): "+konto60 +" * "+ m6 + " = " + konto61); System.out.println("Phase 4: Einfache Tests für Comparable"); if (konto1.compareTo(konto2) >0) {System.out.println(" "+konto1 + " ist groeßer als " + konto2);} else {System.out.println(" "+konto1 + " ist nicht groeßer als " + konto2);} if (konto3.compareTo(konto2) >0) {System.out.println(" "+konto3 + " ist groeßer als " + konto2);} else {System.out.println(" "+konto3 + " ist nicht groeßer als " + konto2);} sortierTest(); } public static void sortierTest() { System.out.println("Phase 4: Testen der Schnittstelle Comparable"); Euro[] bank = { new Euro(99,99), new Euro(66,66), new Euro(33,33), new Euro(11,11), new Euro(22,22), new Euro(88,88), new Euro(55,55), new Euro(22,22), new Euro(44,44), new Euro(0,0)}; System.out.println(" Unsortiertes Feld:"); for (Euro konto : bank) System.out.println(" "+konto); // Diese Methode sortiert ein Feld in seiner natürlichen Ordnung // Die ntürliche Ordnung wird durch die Schnittstelle Comparable // festgelegt Arrays.sort(bank); System.out.println(" Sortiertes Feld:"); for (Euro konto : bank) System.out.println(" "+konto); } }
45.15625
87
0.555017
c08272cf61e66ba67f1d92c2e18d3aa06acabc50
484
package com.wsk.dao; import com.wsk.pojo.GoodsOfOrderForm; import java.util.List; public interface GoodsOfOrderFormMapper { int deleteByPrimaryKey(Integer id); int insert(GoodsOfOrderForm record); int insertSelective(GoodsOfOrderForm record); GoodsOfOrderForm selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(GoodsOfOrderForm record); int updateByPrimaryKey(GoodsOfOrderForm record); List<GoodsOfOrderForm> selectByOFid(int ofid); }
23.047619
61
0.78719
35c21fb67ad2a52e70f427f44b97bd67456f1bdc
6,547
package org.codemucker.orientdb; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import ru.vyarus.guice.persist.orient.db.DbType; import ru.vyarus.guice.persist.orient.db.scheme.annotation.EdgeType; import ru.vyarus.guice.persist.orient.db.scheme.annotation.VertexType; import com.google.common.base.Preconditions; import com.google.inject.Provider; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.object.db.OObjectDatabaseTx; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientVertex; public class EntityManager { private Map<Class<?>, BeanProxyFactory> factoryByBeanClass = new ConcurrentHashMap<>(); private final Provider<OrientGraph> dbProvider; private Map<String, SchemaClass> schemaClasses = new HashMap<String, SchemaClass>(); private static final Logger logger = LogManager.getLogger(EntityManager.class); // private final Provider<OrientGraph> dbProvider; class SchemaClass { private Class<?> beanClass; private String parentSchemaClassName; public SchemaClass(Class<?> beanClass, Class<?> parentSchemaClass) { this(beanClass, parentSchemaClass.getSimpleName()); } public SchemaClass(Class<?> beanClass, String parentSchemaClass) { super(); this.beanClass = beanClass; this.parentSchemaClassName = parentSchemaClass; } public Class<?> getBeanClass() { return beanClass; } public String getParentSchemaClassName() { return parentSchemaClassName; } public String getBeanSchemaClassName(){ return beanClass.getSimpleName(); } } // @Inject // public EntityManager(Provider<OrientGraph> dbProvider) { // this.dbProvider = dbProvider; // } public EntityManager(Provider<OrientGraph> dbProvider) { this.dbProvider = dbProvider; } public Class<?>[] getRegistedBeanClasses(){ return factoryByBeanClass.keySet().toArray(new Class[]{}); } public <T> void register(Class<T> beanClass) { BeanProxyFactory beanProxyFactory = factoryByBeanClass.get(beanClass); if (beanProxyFactory == null) { beanProxyFactory = new BeanProxyFactory(beanClass); factoryByBeanClass.put(beanClass, beanProxyFactory); // dbProvider.get().getRawGraph().get //registerAsSchemaClass(beanClass); } } /** * If class annotated with @Edge or @Vertex will create. * * @param modelClass * model class to map to scheme */ @SuppressWarnings("unchecked") protected void registerAsSchemaClass(final Class modelClass) { logger.info("Registering model class: {}", modelClass); final VertexBean vertex = (VertexBean) modelClass.getAnnotation(VertexBean.class); final EdgeBean edge = (EdgeBean) modelClass.getAnnotation(EdgeBean.class); Preconditions.checkState(vertex == null || edge == null, "You can't use both Vertex and Edge annotations together, choose one."); final boolean isVertex = vertex != null; if (!isVertex && edge == null) { throw new IllegalArgumentException("Model class " + modelClass.getName() + " has neither " + VertexBean.class.getName() + " or " + EdgeBean.class.getName() + " annotations"); } List<SchemaClass> toCreate = new ArrayList<>(); Class<?> currentType = modelClass; Class<?> supertype = modelClass; while (!Object.class.equals(supertype) && supertype != null) { currentType = supertype; supertype = supertype.getSuperclass(); if(!schemaClasses.containsKey(currentType.getSimpleName())){ if(!Object.class.equals(supertype) ){ toCreate.add(new SchemaClass(currentType, supertype)); } else { toCreate.add(new SchemaClass(currentType, isVertex?"V":"E")); } } } for (int i = toCreate.size() - 1; i > 0; i--) { SchemaClass sc = toCreate.get(i); logger.info("Creating model class scheme {} as extension to {}", sc.getBeanSchemaClassName(), sc.getParentSchemaClassName()); getDb().command(new OCommandSQL("create class " + sc.getBeanSchemaClassName() + " extends " + sc.getParentSchemaClassName())).execute(); schemaClasses.put(sc.getBeanSchemaClassName(), sc); } } private OrientGraph getDb() { return dbProvider.get(); } private Class<?> findRootType(final Class<?> type) { // hierarchy support (topmost class must be vertex) Class<?> supertype = type; Class<?> baseType = type; while (!Object.class.equals(supertype) && supertype != null) { baseType = supertype; supertype = supertype.getSuperclass(); } return baseType; } @SuppressWarnings("unchecked") protected <T> T addVertex(Class<T> beanClass, OrientGraph graph) { BeanProxyFactory beanProxyFactory = factoryByBeanClass.get(beanClass); String clsName = beanProxyFactory.getLogicalName(); OrientVertex v = graph.addVertex("class:" + clsName); Object bean = beanProxyFactory.newBeanInstance(v); return (T) bean; } @SuppressWarnings("unchecked") protected <T> T wrapVertex(Class<T> beanClass, Vertex v) { BeanProxyFactory beanProxyFactory = getBeanFactoryForType(beanClass); Object bean = beanProxyFactory.newBeanInstance(v); return (T) bean; } protected BeanProxyFactory getBeanFactoryForType(Class<?> beanClass) { BeanProxyFactory beanProxyFactory = factoryByBeanClass.get(beanClass); if (beanProxyFactory == null) { throw new IllegalStateException("no bean proxy registered for class" + beanClass.getName()); } return beanProxyFactory; } }
39.203593
150
0.640293
ef6e73bb3ec702598303f661177d508eca7cd05a
2,212
package com.acme.api.company.service; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.acme.api.company.mapper.CompanyMapperImpl; import com.acme.api.company.mapper.struct.CompanyMapperStruct; import com.acme.api.company.service.impl.CompanyPagingServiceImpl; import com.acme.architecture.core.constant.DefaultSpringConfigConstant; import com.acme.model.api.company.entity.CompanyResponse; @ExtendWith(SpringExtension.class) @SpringBootTest @ActiveProfiles(profiles = { DefaultSpringConfigConstant.SPRING_PROFILE_LOCAL }) public class CompanyPagingServiceContextLoadTest { private static final Integer PAGE_NUMBER = 0; private static final Integer PAGE_SIZE = 1; private static final String SORT_PROPERTY = "companyId"; private static final String SORT_ORDER_DESC = "desc"; private static final String SORT_ORDER_ASC = "asc"; @Autowired private CompanyPagingServiceImpl companyPagingServiceImpl; @Autowired private CompanyMapperStruct mapperStruct; @Autowired private CompanyMapperImpl companyMapper; @BeforeEach public void init() { companyMapper.setMapperStruct(mapperStruct); } @Test public void whenCallFindAllOrderDesc_thenInvokeTheDaoMethodFindAll() { Page<CompanyResponse> pageResponse = companyPagingServiceImpl.findAll(PAGE_NUMBER, PAGE_SIZE, SORT_PROPERTY, SORT_ORDER_DESC); assertTrue(pageResponse.getContent().size() == 1); assertTrue(pageResponse.getContent().get(0).getId() > 1); } @Test public void whenCallFindAllOrderAsc_thenInvokeTheDaoMethodFindAll() { Page<CompanyResponse> pageResponse = companyPagingServiceImpl.findAll(PAGE_NUMBER, PAGE_SIZE, SORT_PROPERTY, SORT_ORDER_ASC); assertTrue(pageResponse.getContent().size() == 1); assertTrue(pageResponse.getContent().get(0).getId() == 1); } }
34.5625
110
0.81736
65dfc56446992cb69f518218ae12bcae3adfbdc4
2,127
/* * Copyright (c) 2020-2021 Software AG, Darmstadt, Germany and/or its licensors * * 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.apama.e2a; import java.util.HashMap; import java.util.Map; /** Handles Esper 'create schema' declarations */ public class TranslateSchemaDecl extends EsperBaseVisitor<EPLOutput> { public TranslateSchemaDecl(Scope scope) { this.scope = scope; } private Scope scope; /** Esper schema declaration turns into a very simple equivalent EPL 'event' declaration, except for the typedef-style "create schema Foo as Bar" which we don't translate */ public EPLOutput visitSchemaDecl(EsperParser.SchemaDeclContext ctx) { if(ctx.typedef != null) { return EPLOutput.cannotTranslate(ctx, "Schemas defined as aliases to other types"); } EPLOutput members = new EPLOutput(); // Map of member field name to the member type. Map<String, Type> membersMap = new HashMap<String, Type>(); for(int i = 0; i < ctx.fieldNames.size(); i++) { Type t = Type.getByEsperName(ctx.fieldTypes.get(i)); scope.getFile().addUsing(t); members.addLine(t.getEPLName()).add(" ").add(ctx.fieldNames.get(i)).add(";"); String fieldName = ctx.fieldNames.get(i).getText(); membersMap.put(fieldName, t); // Add warning for fields which are not exact mapping. Eg : BigDecimal to float if(Misc.APPROXIMATE_TYPE_MATCHING.containsKey(t.getNameInEsper())) { members.addWarning(Misc.APPROXIMATE_TYPE_MATCHING.get(t.getNameInEsper())); } } Type.declType(new Type.CustomSchema(ctx.schemaName, membersMap)); return new EPLOutput().add("event ").add(ctx.schemaName).addBlock(members); } }
46.23913
308
0.74142
c8e6f6a64194952393d563c95c01b2273b954e91
3,909
package com.yeah.android.activity.camera.adapter; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.yeah.android.R; import com.yeah.android.activity.camera.EffectService; import com.yeah.android.activity.camera.effect.FilterEffect; import com.yeah.android.activity.camera.util.GPUImageFilterTools; import com.yeah.android.impl.IFilterChange; import java.util.ArrayList; import java.util.List; import jp.co.cyberagent.android.gpuimage.GPUImageFilter; /** * Created by liuchao on 10/14/15. * 滤镜 * */ public class CameraFilterAdapter extends PagerAdapter implements OnPageChangeListener{ private List<FilterBundle> mFilterBundles; private List<View> mEmptyPageViews = new ArrayList<>(); private IFilterChange mIFilterChange; private Context mContext; private View.OnClickListener mOnClickListener; public CameraFilterAdapter(Context context, LinearLayout tabContainer, IFilterChange filterChange, View.OnClickListener onClickListener){ mFilterBundles = new ArrayList<>(); List<FilterEffect> effects = EffectService.getInst().getLocalFilters(); for(FilterEffect filterEffect : effects){ mFilterBundles.add(new FilterBundle(filterEffect.getTitle(), GPUImageFilterTools.createFilterForType(context, filterEffect.getType()))); } mContext = context; if(tabContainer != null){ tabContainer.removeAllViews(); for(FilterEffect filterEffect : effects){ TextView tv = (TextView) LayoutInflater.from(mContext) .inflate(R.layout.camera_filter_tab_text, null, false); tv.setText(filterEffect.getTitle()); tabContainer.addView(tv); } } for(FilterBundle filterBundle : mFilterBundles){ View view = new View(mContext); view.setOnClickListener(onClickListener); mEmptyPageViews.add(view); } this.mIFilterChange = filterChange; } public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels){ } public void onPageSelected(int position){ if(mIFilterChange != null){ mIFilterChange.onFilterChange(mFilterBundles.get(position).getGpuImageFilter()); } } public void onPageScrollStateChanged(int state){ } @Override public int getCount() { return mFilterBundles.size(); } @Override public Object instantiateItem(ViewGroup container, int position){ container.addView(mEmptyPageViews.get(position)); return mEmptyPageViews.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mEmptyPageViews.get(position)); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public int getItemPosition(Object object) { return super.getItemPosition(object); } @Override public CharSequence getPageTitle(int position) { return mFilterBundles.get(position).getFilterName(); } public static class FilterBundle{ private String mFilterName; private GPUImageFilter mGpuImageFilter; public FilterBundle(String filterName, GPUImageFilter gpuImageFilter){ this.mFilterName = filterName; this.mGpuImageFilter = gpuImageFilter; } public String getFilterName() { return mFilterName; } public GPUImageFilter getGpuImageFilter() { return mGpuImageFilter; } } }
30.539063
148
0.695318
7d964afd4e42338bb0ba2b8fa1c44904359ed75c
938
package com.kevadiyakrunalk.recycleadapter.animator; import android.support.v7.widget.RecyclerView; /** * ItemAnimator for Draggable item. This animator is required to work animations properly on drop an item. */ public class DraggableItemAnimator extends RefactoredDefaultItemAnimator { @Override protected void onSetup() { super.onSetup(); super.setSupportsChangeAnimations(false); } @Override public boolean animateChange(RecyclerView.ViewHolder oldHolder, RecyclerView.ViewHolder newHolder, int fromX, int fromY, int toX, int toY) { if (oldHolder == newHolder && fromX == toX && fromY == toY) { // WORKAROUND: Skip animateChange() for the dropped item. Should be implemented better approach. dispatchChangeFinished(oldHolder, true); return false; } return super.animateChange(oldHolder, newHolder, fromX, fromY, toX, toY); } }
34.740741
144
0.702559
4cbee1135d05b9ab9cec3a2947b41bd249e764eb
516
package com.qmplus.v3.api.models.request; import com.qmplus.v3.api.models.util.RestConstants; /** * LanguageRequest which needs to invoke from mobile device to send data to * server side. * * @author gaurav.chugh * */ public class LanguageRequest extends BaseRequest { @Override public void setAuthTokenKey(String authTokenKey) { if (authTokenKey == null || authTokenKey.equals("")) { authTokenKey = RestConstants.DEFAULT_AUTH_TOKEN_KEY; } this.authTokenKey = authTokenKey; } }
21.5
75
0.718992
0f7e61fc76c9a14cc20dace1631efdf9a360eff1
3,185
package tools.dynamia.zk.addons.chartjs; public class Labels extends LazyJSONObject { private Integer boxWidth; private Integer fontSize; private String fontStyle; private String fontColor; private String fontFamily; private Integer padding; private Boolean usePointStyle; public Integer getBoxWidth() { return boxWidth; } public void setBoxWidth(Integer boxWidth) { this.boxWidth = boxWidth; } public Integer getFontSize() { return fontSize; } public void setFontSize(Integer fontSize) { this.fontSize = fontSize; } public String getFontStyle() { return fontStyle; } public void setFontStyle(String fontStyle) { this.fontStyle = fontStyle; } public String getFontColor() { return fontColor; } public void setFontColor(String fontColor) { this.fontColor = fontColor; } public String getFontFamily() { return fontFamily; } public void setFontFamily(String fontFamily) { this.fontFamily = fontFamily; } public Integer getPadding() { return padding; } public void setPadding(Integer padding) { this.padding = padding; } public Boolean getUsePointStyle() { return usePointStyle; } public void setUsePointStyle(Boolean usePointStyle) { this.usePointStyle = usePointStyle; } public static final class Builder { private Integer boxWidth; private Integer fontSize; private String fontStyle; private String fontColor; private String fontFamily; private Integer padding; private Boolean usePointStyle; private Builder() { } public static Builder init() { return new Builder(); } public Builder boxWidth(Integer boxWidth) { this.boxWidth = boxWidth; return this; } public Builder fontSize(Integer fontSize) { this.fontSize = fontSize; return this; } public Builder fontStyle(String fontStyle) { this.fontStyle = fontStyle; return this; } public Builder fontColor(String fontColor) { this.fontColor = fontColor; return this; } public Builder fontFamily(String fontFamily) { this.fontFamily = fontFamily; return this; } public Builder padding(Integer padding) { this.padding = padding; return this; } public Builder usePointStyle(Boolean usePointStyle) { this.usePointStyle = usePointStyle; return this; } public Labels build() { Labels labels = new Labels(); labels.setBoxWidth(boxWidth); labels.setFontSize(fontSize); labels.setFontStyle(fontStyle); labels.setFontColor(fontColor); labels.setFontFamily(fontFamily); labels.setPadding(padding); labels.setUsePointStyle(usePointStyle); return labels; } } }
23.947368
61
0.597802
c98007956cc665c9e53cf599f902a103327b970c
642
/* * Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2.ft; /** * Single nested PointFeatureCollection * * @author caron * @since 9/23/2015. */ public interface PointFeatureCC extends DsgFeatureCollection { /** * General way to handle iterations on all classes that implement this interface. * Generally, one uses class specific foreach * * @return Iterator over PointFeatureCollection which may throw an IOException */ IOIterator<PointFeatureCollection> getCollectionIterator() throws java.io.IOException; }
27.913043
97
0.753894
14ff82d908ffe752baa4e49f32ce090bf7f53a0a
41
package com.subho.wipro.pjp.tm07.proj.sb;
41
41
0.804878
b05efcb5f41123bed984ca341ced3a0bae608a70
2,213
package UI; import API.GloAPIHandler; import callbacks.JGloCallback; import com.intellij.openapi.ui.Messages; import models.Glo.Board; import models.JGloHelper; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AddBoardDialog extends JDialog { private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; private JTextField textFieldBoardName; private JGloCallback callback; public AddBoardDialog(JGloCallback callback) { this.callback = callback; setTitle("New board"); setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonOK); setPreferredSize(new Dimension(400, 150)); setMinimumSize(new Dimension(300, 150)); buttonOK.addActionListener(e -> onOK()); buttonCancel.addActionListener(e -> onCancel()); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); setToSize(); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } private void setToSize() { Toolkit toolkit = Toolkit.getDefaultToolkit(); final Dimension screenSize = toolkit.getScreenSize(); final int x = (screenSize.width - this.getWidth()) / 2; final int y = (screenSize.height - this.getHeight()) / 2; setLocation(x, y); } private void onOK() { String boardName = textFieldBoardName.getText().trim(); if (boardName.isEmpty()) { JGloHelper.showMessage("A name should be specified", "Error", Messages.getErrorIcon()); return; } GloAPIHandler gloAPIHandler = new GloAPIHandler(); Board board = new Board(boardName); gloAPIHandler.createBoard(board, callback); dispose(); } private void onCancel() { callback.cancelled(); dispose(); } }
27.6625
154
0.649345
0410843029ea7d232e41ff4ea43d72d66fa5c382
34,629
package com.weychain.erp.service.Impl; import com.alibaba.fastjson.JSONObject; <<<<<<< HEAD import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; ======= import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.sun.org.apache.bcel.internal.generic.NEW; >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 import com.weychain.erp.constants.BusinessConstants; import com.weychain.erp.constants.ExceptionConstants; import com.weychain.erp.domain.DO.*; import com.weychain.erp.domain.VO.AccountVo4InOutList; import com.weychain.erp.domain.VO.AccountVo4List; import com.weychain.erp.domain.example.AccountExample; import com.weychain.erp.domain.example.AccountHeadExample; import com.weychain.erp.domain.example.AccountItemExample; import com.weychain.erp.domain.example.DepotHeadExample; import com.weychain.erp.exception.BusinessRunTimeException; import com.weychain.erp.exception.JshException; import com.weychain.erp.mapper.*; import com.weychain.erp.service.AccountService; import com.weychain.erp.service.LogService; import com.weychain.erp.service.UserService; <<<<<<< HEAD ======= import com.weychain.erp.utils.Constants; import com.weychain.erp.utils.QueryUtils; >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 import com.weychain.erp.utils.StringUtil; import com.weychain.erp.utils.Tools; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; <<<<<<< HEAD ======= import java.util.Map; >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 @Service @Slf4j public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService { @Resource private AccountMapper accountMapper; @Resource private AccountMapperEx accountMapperEx; @Resource private DepotHeadMapper depotHeadMapper; @Resource private DepotHeadMapperEx depotHeadMapperEx; @Resource private AccountHeadMapper accountHeadMapper; @Resource private AccountHeadMapperEx accountHeadMapperEx; @Resource private AccountItemMapper accountItemMapper; @Resource private AccountItemMapperEx accountItemMapperEx; @Resource private LogService logService; @Resource private UserService userService; @Override public Account getAccount(long id) throws Exception{ return accountMapper.selectById(id); } @Override public List<Account> getAccount() throws Exception{ List<Account> list=null; try{ list=accountMapper.selectList( new QueryWrapper<Account>().lambda().ne(Account::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED)); }catch(Exception e){ JshException.readFail(log, e); } return list; } @Override public List<AccountVo4List> select(String name, String serialNo, String remark, int offset, int rows) throws Exception{ List<AccountVo4List> resList = new ArrayList<AccountVo4List>(); List<AccountVo4List> list=null; try{ list = accountMapperEx.selectByConditionAccount(name, serialNo, remark, offset, rows); }catch(Exception e){ JshException.readFail(log, e); } String timeStr = Tools.getCurrentMonth(); if (null != list && null !=timeStr) { for (AccountVo4List al : list) { DecimalFormat df = new DecimalFormat(".##"); BigDecimal thisMonthAmount = getAccountSum(al.getId(), timeStr, "month").add(getAccountSumByHead(al.getId(), timeStr, "month")).add(getAccountSumByDetail(al.getId(), timeStr, "month")).add(getManyAccountSum(al.getId(), timeStr, "month")); String thisMonthAmountFmt = "0"; if ((thisMonthAmount.compareTo(BigDecimal.ZERO))!=0) { thisMonthAmountFmt = df.format(thisMonthAmount); } al.setThismonthamount(thisMonthAmountFmt); //本月发生额 BigDecimal currentAmount = getAccountSum(al.getId(), "", "month").add(getAccountSumByHead(al.getId(), "", "month")).add(getAccountSumByDetail(al.getId(), "", "month")).add(getManyAccountSum(al.getId(), "", "month")) .add(al.getInitialamount()) ; al.setCurrentamount(currentAmount); resList.add(al); } } return resList; } @Override public Long countAccount(String name, String serialNo, String remark)throws Exception { Long result=null; try{ result=accountMapperEx.countsByAccount(name, serialNo, remark); }catch(Exception e){ JshException.readFail(log, e); } return result; } @Override @Transactional(value = "transactionManager", rollbackFor = Exception.class) public int insertAccount(String beanJson, HttpServletRequest request)throws Exception { Account account = JSONObject.parseObject(beanJson, Account.class); if(account.getInitialamount() == null) { account.setInitialamount(BigDecimal.ZERO); } account.setIsdefault(false); int result=0; try{ result = accountMapper.insertSelective(account); }catch(Exception e){ JshException.writeFail(log, e); } return result; } @Override @Transactional(value = "transactionManager", rollbackFor = Exception.class) public int updateAccount(String beanJson, Long id)throws Exception { Account account = JSONObject.parseObject(beanJson, Account.class); account.setId(id); int result=0; try{ result = accountMapper.updateByPrimaryKeySelective(account); }catch(Exception e){ JshException.writeFail(log, e); } return result; } @Override @Transactional(value = "transactionManager", rollbackFor = Exception.class) public int deleteAccount(Long id) throws Exception{ int result=0; try{ result = accountMapper.deleteByPrimaryKey(id); }catch(Exception e){ JshException.writeFail(log, e); } return result; } @Override @Transactional(value = "transactionManager", rollbackFor = Exception.class) public int batchDeleteAccount(String ids)throws Exception { List<Long> idList = StringUtil.strToLongList(ids); <<<<<<< HEAD AccountExample example = new AccountExample(); example.createCriteria().andIdIn(idList); int result=0; try{ result = accountMapper.deleteByExample(example); ======= // AccountExample example = new AccountExample(); // example.createCriteria().andIdIn(idList); int result=0; try{ result = accountMapper.delete(new QueryWrapper<Account>().lambda().in(Account::getId, idList)); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 }catch(Exception e){ JshException.writeFail(log, e); } return result; } @Override public int checkIsNameExist(Long id, String name)throws Exception { <<<<<<< HEAD AccountExample example = new AccountExample(); example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); List<Account> list=null; try{ list = accountMapper.selectByExample(example); ======= // AccountExample example = new AccountExample(); QueryWrapper<Account> wrapper = new QueryWrapper<>(); // example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().ne(Account::getId,id).eq(Account::getName,name).ne(Account::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); List<Account> list=null; try{ list = accountMapper.selectList(wrapper); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 }catch(Exception e){ JshException.readFail(log, e); } return list==null?0:list.size(); } @Override public List<Account> findBySelect()throws Exception { <<<<<<< HEAD AccountExample example = new AccountExample(); example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); example.setOrderByClause("id desc"); List<Account> list=null; try{ list = accountMapper.selectByExample(example); ======= // AccountExample example = new AccountExample(); QueryWrapper<Account> wrapper = new QueryWrapper<>(); // example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().ne(Account::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED).orderByDesc(Account::getId); // example.setOrderByClause("id desc"); List<Account> list=null; try{ list = accountMapper.selectList(wrapper); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 }catch(Exception e){ JshException.readFail(log, e); } return list; } /** * 单个账户的金额求和-入库和出库 * * @param id * @return */ @Override public BigDecimal getAccountSum(Long id, String timeStr, String type) throws Exception{ BigDecimal accountSum = BigDecimal.ZERO; try { <<<<<<< HEAD DepotHeadExample example = new DepotHeadExample(); ======= QueryWrapper<DepotHead> wrapper = new QueryWrapper<>(); // DepotHeadExample example = new DepotHeadExample(); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 if (!timeStr.equals("")) { Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null); Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null); Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null); if (type.equals("month")) { <<<<<<< HEAD example.createCriteria().andAccountidEqualTo(id).andPaytypeNotEqualTo("预付款") .andOpertimeGreaterThanOrEqualTo(bTime).andOpertimeLessThanOrEqualTo(eTime) .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } else if (type.equals("date")) { example.createCriteria().andAccountidEqualTo(id).andPaytypeNotEqualTo("预付款") .andOpertimeLessThanOrEqualTo(mTime).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } } else { example.createCriteria().andAccountidEqualTo(id).andPaytypeNotEqualTo("预付款") .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } List<DepotHead> dataList=null; try{ dataList = depotHeadMapper.selectByExample(example); ======= // example.createCriteria().andAccountidEqualTo(id).andPaytypeNotEqualTo("预付款") // .andOpertimeGreaterThanOrEqualTo(bTime).andOpertimeLessThanOrEqualTo(eTime) // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().eq(DepotHead::getAccountid,id).ne(DepotHead::getPaytype,"预付款").ge(DepotHead::getOpertime,bTime).ne(DepotHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } else if (type.equals("date")) { // example.createCriteria().andAccountidEqualTo(id).andPaytypeNotEqualTo("预付款") // .andOpertimeLessThanOrEqualTo(mTime).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().eq(DepotHead::getAccountid,id).ne(DepotHead::getPaytype,"预付款").le(DepotHead::getOpertime,bTime).ne(DepotHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } } else { // example.createCriteria().andAccountidEqualTo(id).andPaytypeNotEqualTo("预付款") // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().eq(DepotHead::getAccountid,id).ne(DepotHead::getPaytype,"预付款").ne(DepotHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } List<DepotHead> dataList=null; try{ dataList = depotHeadMapper.selectList(wrapper); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 }catch(Exception e){ JshException.readFail(log, e); } if (dataList != null) { for (DepotHead depotHead : dataList) { if(depotHead.getChangeamount()!=null) { accountSum = accountSum .add(depotHead.getChangeamount()) ; } } } } catch (DataAccessException e) { log.error(">>>>>>>>>查找进销存信息异常", e); } return accountSum; } /** * 单个账户的金额求和-收入、支出、转账的单据表头的合计 * * @param id * @return */ @Override public BigDecimal getAccountSumByHead(Long id, String timeStr, String type) throws Exception{ BigDecimal accountSum = BigDecimal.ZERO; try { <<<<<<< HEAD AccountHeadExample example = new AccountHeadExample(); ======= QueryWrapper<AccountHead> wrapper = new QueryWrapper<>(); // AccountHeadExample example = new AccountHeadExample(); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 if (!timeStr.equals("")) { Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null); Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null); Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null); if (type.equals("month")) { <<<<<<< HEAD example.createCriteria().andAccountidEqualTo(id) .andBilltimeGreaterThanOrEqualTo(bTime).andBilltimeLessThanOrEqualTo(eTime) .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } else if (type.equals("date")) { example.createCriteria().andAccountidEqualTo(id) .andBilltimeLessThanOrEqualTo(mTime) .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } } else { example.createCriteria().andAccountidEqualTo(id) .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } List<AccountHead> dataList=null; try{ dataList = accountHeadMapper.selectByExample(example); ======= // example.createCriteria().andAccountidEqualTo(id) // .andBilltimeGreaterThanOrEqualTo(bTime).andBilltimeLessThanOrEqualTo(eTime) // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().eq(AccountHead::getAccountid,id).ge(AccountHead::getBilltime,bTime).le(AccountHead::getBilltime,eTime).ne(AccountHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } else if (type.equals("date")) { // example.createCriteria().andAccountidEqualTo(id) // .andBilltimeLessThanOrEqualTo(mTime) // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().eq(AccountHead::getAccountid,id).le(AccountHead::getBilltime,mTime).ne(AccountHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } } else { // example.createCriteria().andAccountidEqualTo(id) // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().eq(AccountHead::getAccountid,id).ne(AccountHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } List<AccountHead> dataList=null; try{ dataList = accountHeadMapper.selectList(wrapper); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 }catch(Exception e){ JshException.readFail(log, e); } if (dataList != null) { for (AccountHead accountHead : dataList) { if(accountHead.getChangeamount()!=null) { accountSum = accountSum.add(accountHead.getChangeamount()); } } } } catch (DataAccessException e) { log.error(">>>>>>>>>查找进销存信息异常", e); } return accountSum; } /** * 单个账户的金额求和-收款、付款、转账、收预付款的单据明细的合计 * * @param id * @return */ @Override public BigDecimal getAccountSumByDetail(Long id, String timeStr, String type)throws Exception { BigDecimal accountSum =BigDecimal.ZERO ; try { <<<<<<< HEAD AccountHeadExample example = new AccountHeadExample(); ======= QueryWrapper<AccountHead> queryWrapper = new QueryWrapper<>(); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 if (!timeStr.equals("")) { Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null); Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null); Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null); if (type.equals("month")) { <<<<<<< HEAD example.createCriteria().andBilltimeGreaterThanOrEqualTo(bTime).andBilltimeLessThanOrEqualTo(eTime) .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } else if (type.equals("date")) { example.createCriteria().andBilltimeLessThanOrEqualTo(mTime) .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); ======= // example.createCriteria().andBilltimeGreaterThanOrEqualTo(bTime).andBilltimeLessThanOrEqualTo(eTime) // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); queryWrapper.lambda().ge(AccountHead::getBilltime,bTime).le(AccountHead::getBilltime,eTime).ne(AccountHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } else if (type.equals("date")) { // example.createCriteria().andBilltimeLessThanOrEqualTo(mTime) // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); queryWrapper.lambda().le(AccountHead::getBilltime,mTime).ne(AccountHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 } } List<AccountHead> dataList=null; try{ <<<<<<< HEAD dataList = accountHeadMapper.selectByExample(example); ======= dataList = accountHeadMapper.selectList(queryWrapper); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 }catch(Exception e){ JshException.readFail(log, e); } if (dataList != null) { String ids = ""; for (AccountHead accountHead : dataList) { ids = ids + accountHead.getId() + ","; } if (!ids.equals("")) { ids = ids.substring(0, ids.length() - 1); } <<<<<<< HEAD AccountItemExample exampleAi = new AccountItemExample(); if (!ids.equals("")) { List<Long> idList = StringUtil.strToLongList(ids); exampleAi.createCriteria().andAccountidEqualTo(id).andHeaderidIn(idList) .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } else { exampleAi.createCriteria().andAccountidEqualTo(id) .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } List<AccountItem> dataListOne = accountItemMapper.selectByExample(exampleAi); ======= QueryWrapper<AccountItem> wrapper = new QueryWrapper(); // AccountItemExample exampleAi = new AccountItemExample(); if (!ids.equals("")) { List<Long> idList = StringUtil.strToLongList(ids); // exampleAi.createCriteria().andAccountidEqualTo(id).andHeaderidIn(idList) // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().eq(AccountItem::getAccountid,id).in(AccountItem::getHeaderid,idList).ne(AccountItem::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } else { // exampleAi.createCriteria().andAccountidEqualTo(id) // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().eq(AccountItem::getAccountid,id).ne(AccountItem::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } List<AccountItem> dataListOne = accountItemMapper.selectList(wrapper); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 if (dataListOne != null) { for (AccountItem accountItem : dataListOne) { if(accountItem.getEachamount()!=null) { accountSum = accountSum.add(accountItem.getEachamount()); } } } } } catch (DataAccessException e) { log.error(">>>>>>>>>查找进销存信息异常", e); } catch (Exception e) { log.error(">>>>>>>>>异常信息:", e); } return accountSum; } /** * 单个账户的金额求和-多账户的明细合计 * * @param id * @return */ @Override public BigDecimal getManyAccountSum(Long id, String timeStr, String type)throws Exception { BigDecimal accountSum = BigDecimal.ZERO; try { <<<<<<< HEAD DepotHeadExample example = new DepotHeadExample(); ======= // tryDepotHeadExample example = new DepotHeadExample(); QueryWrapper<DepotHead> wrapper = new QueryWrapper<>(); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 if (!timeStr.equals("")) { Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null); Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null); Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null); if (type.equals("month")) { <<<<<<< HEAD example.createCriteria().andAccountidlistLike("%" +id.toString() + "%") .andOpertimeGreaterThanOrEqualTo(bTime).andOpertimeLessThanOrEqualTo(eTime) .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } else if (type.equals("date")) { example.createCriteria().andAccountidlistLike("%" +id.toString() + "%") .andOpertimeLessThanOrEqualTo(mTime) .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } } else { example.createCriteria().andAccountidlistLike("%" +id.toString() + "%") .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); } List<DepotHead> dataList=null; try{ dataList = depotHeadMapper.selectByExample(example); ======= // example.createCriteria().andAccountidlistLike("%" +id.toString() + "%") // .andOpertimeGreaterThanOrEqualTo(bTime).andOpertimeLessThanOrEqualTo(eTime) // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().like(DepotHead::getAccountidlist,"%" +id.toString() + "%").ge(DepotHead::getOpertime,bTime) .le(DepotHead::getOpertime,eTime).ne(DepotHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } else if (type.equals("date")) { // example.createCriteria().andAccountidlistLike("%" +id.toString() + "%") // .andOpertimeLessThanOrEqualTo(mTime) // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().like(DepotHead::getAccountidlist,"%" +id.toString() + "%").le(DepotHead::getOpertime,eTime).ne(DepotHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } } else { // example.createCriteria().andAccountidlistLike("%" +id.toString() + "%") // .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED); wrapper.lambda().like(DepotHead::getAccountidlist,"%" +id.toString() + "%").ne(DepotHead::getDeleteFlag,BusinessConstants.DELETE_FLAG_DELETED); } List<DepotHead> dataList=null; try{ dataList = depotHeadMapper.selectList(wrapper); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 }catch(Exception e){ JshException.readFail(log, e); } if (dataList != null) { for (DepotHead depotHead : dataList) { String accountIdList = depotHead.getAccountidlist(); String accountMoneyList = depotHead.getAccountmoneylist(); accountIdList = accountIdList.replace("[", "").replace("]", "").replace("\"", ""); accountMoneyList = accountMoneyList.replace("[", "").replace("]", "").replace("\"", ""); String[] aList = accountIdList.split(","); String[] amList = accountMoneyList.split(","); for (int i = 0; i < aList.length; i++) { if (aList[i].toString().equals(id.toString())) { accountSum = accountSum .add(new BigDecimal(amList[i])); } } } } } catch (DataAccessException e) { log.error(">>>>>>>>>查找信息异常", e); } return accountSum; } @Override public List<AccountVo4InOutList> findAccountInOutList(Long accountId, Integer offset, Integer rows) throws Exception{ List<AccountVo4InOutList> list=null; try{ list = accountMapperEx.findAccountInOutList(accountId, offset, rows); }catch(Exception e){ JshException.readFail(log, e); } return list; } @Override public int findAccountInOutListCount(Long accountId) throws Exception{ int result=0; try{ result = accountMapperEx.findAccountInOutListCount(accountId); }catch(Exception e){ JshException.readFail(log, e); } return result; } @Override @Transactional(value = "transactionManager", rollbackFor = Exception.class) public int updateAmountIsDefault(Boolean isDefault, Long accountId) throws Exception{ logService.insertLog(BusinessConstants.LOG_INTERFACE_NAME_ACCOUNT,BusinessConstants.LOG_OPERATION_TYPE_EDIT+accountId, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()); Account account = new Account(); account.setIsdefault(isDefault); <<<<<<< HEAD AccountExample example = new AccountExample(); example.createCriteria().andIdEqualTo(accountId); int result=0; try{ result = accountMapper.updateByExampleSelective(account, example); ======= QueryWrapper< Account> wrapper = new QueryWrapper<>(); // AccountExample example = new AccountExample(); // example.createCriteria().andIdEqualTo(accountId); wrapper.lambda().eq(Account::getId,accountId); int result=0; try{ result = accountMapper.update(account, wrapper); >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 }catch(Exception e){ JshException.writeFail(log, e); } return result; } @Override @Transactional(value = "transactionManager", rollbackFor = Exception.class) public int batchDeleteAccountByIds(String ids) throws Exception{ logService.insertLog(BusinessConstants.LOG_INTERFACE_NAME_ACCOUNT, new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(ids).toString(), ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()); User userInfo= userService.getCurrentUser(); String [] idArray=ids.split(","); int result=0; try{ result = accountMapperEx.batchDeleteAccountByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray); }catch(Exception e){ JshException.writeFail(log, e); } return result; } /** * create by: qiankunpingtai * website:https://qiankunpingtai.cn * description: * 正常删除,要考虑数据完整性,进行完整性校验 * create time: 2019/4/10 10:31 * @Param: ids * @return int */ @Override @Transactional(value = "transactionManager", rollbackFor = Exception.class) public int batchDeleteAccountByIdsNormal(String ids) throws Exception{ /** * 校验: * 1、财务主表 jsh_accounthead * 2、财务子表 jsh_accountitem * 3、单据主表 jsh_depothead * 是否有相关数据 * */ int deleteTotal=0; if(StringUtils.isEmpty(ids)){ return deleteTotal; } String [] idArray=ids.split(","); /** * 校验财务主表 jsh_accounthead * */ List<AccountHead> accountHeadList=null; try{ accountHeadList = accountHeadMapperEx.getAccountHeadListByAccountIds(idArray); }catch(Exception e){ JshException.readFail(log, e); } if(accountHeadList!=null&&accountHeadList.size()>0){ log.error("异常码[{}],异常提示[{}],参数,AccountIds[{}]", ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids); throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE, ExceptionConstants.DELETE_FORCE_CONFIRM_MSG); } /** * 校验财务子表 jsh_accountitem * */ List<AccountItem> accountItemList=null; try{ accountItemList = accountItemMapperEx.getAccountItemListByAccountIds(idArray); }catch(Exception e){ JshException.readFail(log, e); } if(accountItemList!=null&&accountItemList.size()>0){ log.error("异常码[{}],异常提示[{}],参数,AccountIds[{}]", ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids); throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE, ExceptionConstants.DELETE_FORCE_CONFIRM_MSG); } /** * 校验单据主表 jsh_depothead * */ List<DepotHead> depotHeadList =null; try{ depotHeadList = depotHeadMapperEx.getDepotHeadListByAccountIds(idArray); }catch(Exception e){ JshException.readFail(log, e); } if(depotHeadList!=null&&depotHeadList.size()>0){ log.error("异常码[{}],异常提示[{}],参数,AccountIds[{}]", ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids); throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE, ExceptionConstants.DELETE_FORCE_CONFIRM_MSG); } /** * 校验通过执行删除操作 * */ deleteTotal= batchDeleteAccountByIds(ids); return deleteTotal; } <<<<<<< HEAD ======= @Override public Object selectOne(Long id) throws Exception { return getAccount(id); } @Override public List<?> select(Map<String, String> map)throws Exception { return getAccountList(map); } @Override public List<?> getAccountList(Map<String, String> map) throws Exception{ String search = map.get(Constants.SEARCH); String name = StringUtil.getInfo(search, "name"); String serialNo = StringUtil.getInfo(search, "serialNo"); String remark = StringUtil.getInfo(search, "remark"); String order = QueryUtils.order(map); return select(name, serialNo, remark, QueryUtils.offset(map), QueryUtils.rows(map)); } @Override public Long counts(Map<String, String> map) throws Exception{ String search = map.get(Constants.SEARCH); String name = StringUtil.getInfo(search, "name"); String serialNo = StringUtil.getInfo(search, "serialNo"); String remark = StringUtil.getInfo(search, "remark"); return countAccount(name, serialNo, remark); } @Override public int insert(String beanJson, HttpServletRequest request) throws Exception{ return insertAccount(beanJson, request); } @Override public int update(String beanJson, Long id)throws Exception { return updateAccount(beanJson, id); } @Override public int delete(Long id)throws Exception { return deleteAccount(id); } @Override public int batchDelete(String ids)throws Exception { return batchDeleteAccount(ids); } >>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6 }
44.510283
261
0.623119
30fe75abfb7cd555de223de9b7456cd9c009e950
4,447
package com.Da_Technomancer.crossroads.API.effects; import com.Da_Technomancer.crossroads.API.beams.EnumBeamAlignments; import com.Da_Technomancer.crossroads.CRConfig; import com.Da_Technomancer.crossroads.Crossroads; import com.Da_Technomancer.crossroads.blocks.BlockSalt; import com.Da_Technomancer.crossroads.crafting.CRItemTags; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.TagKey; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.EntitySelector; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraftforge.registries.ForgeRegistries; import javax.annotation.Nullable; import java.util.List; public class GrowEffect extends BeamEffect{ //Crop types can be blacklisted from growth through the beam using the grow_blacklist tag. Intended for things like magical crops private static final TagKey<Block> growBlacklist = CRItemTags.getTagKey(ForgeRegistries.Keys.BLOCKS, new ResourceLocation(Crossroads.MODID, "grow_blacklist")); protected static final DamageSource POTENTIAL_VOID = new DamageSource("potentialvoid").setMagic().bypassArmor(); protected static final DamageSource POTENTIAL_VOID_ABSOLUTE = new DamageSource("potentialvoid").setMagic().bypassArmor().bypassMagic(); @Override public void doBeamEffect(EnumBeamAlignments align, boolean voi, int power, Level worldIn, BlockPos pos, @Nullable Direction dir){ if(!performTransmute(align, voi, power, worldIn, pos)){ if(voi){ //Kill plants if(!BlockSalt.salinate(worldIn, pos)){ //Also target the plant on this block so we can hit the soil and affect the plant on it BlockSalt.salinate(worldIn, pos.above()); } aoeKill(power, worldIn, pos); }else{ double range = calcRange(power); List<LivingEntity> ents = worldIn.getEntitiesOfClass(LivingEntity.class, new AABB(pos.getX() - range, pos.getY() - range, pos.getZ() - range, pos.getX() + range, pos.getY() + range, pos.getZ() + range), EntitySelector.ENTITY_STILL_ALIVE); boolean absoluteDamage = CRConfig.beamDamageAbsolute.get(); for(LivingEntity ent : ents){ if(ent.isInvertedHealAndHarm()){ ent.hurt(absoluteDamage ? POTENTIAL_VOID_ABSOLUTE : POTENTIAL_VOID, power / 2F); }else{ ent.heal(power / 2F); } } //Optional config option to nerf the bonemeal effect int growMultiplier = CRConfig.growMultiplier.get(); if(growMultiplier > 1){ power = power / growMultiplier + ((worldIn.random.nextInt(growMultiplier) < power % growMultiplier) ? 1 : 0); } BlockState state = worldIn.getBlockState(pos); //We check above the hit block if it isn't growable, as that allows growing plants by hitting the soil if(!(state.getBlock() instanceof BonemealableBlock)){ pos = pos.above(); state = worldIn.getBlockState(pos); } for(int i = 0; i < power; i++){ if(!(state.getBlock() instanceof BonemealableBlock growable)){ return; } if(CRItemTags.tagContains(growBlacklist, state.getBlock())){ return; } if(growable.isValidBonemealTarget(worldIn, pos, state, false)){ growable.performBonemeal((ServerLevel) worldIn, worldIn.random, pos, state); } //The state must be queried every loop because some plants could break themselves upon growing state = worldIn.getBlockState(pos); } } } } private static double calcRange(int power){ return Math.sqrt(power) / 2D; } public static void aoeKill(int power, Level worldIn, BlockPos pos){ double range = calcRange(power); List<LivingEntity> ents = worldIn.getEntitiesOfClass(LivingEntity.class, new AABB(pos.getX() - range, pos.getY() - range, pos.getZ() - range, pos.getX() + range + 1, pos.getY() + range + 1, pos.getZ() + range + 1), EntitySelector.ENTITY_STILL_ALIVE); boolean absoluteDamage = CRConfig.beamDamageAbsolute.get(); for(LivingEntity ent : ents){ if(ent.isInvertedHealAndHarm()){ ent.heal(power * 3F / 4F); }else{ ent.hurt(absoluteDamage ? POTENTIAL_VOID_ABSOLUTE : POTENTIAL_VOID, power * 3F / 4F); } } } }
42.759615
252
0.742073
3fbc2c11dbbafa4ed1f68776c9069717eb7173b5
3,274
/** * 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.geronimo.testsuite.console; import org.testng.annotations.Test; /** * @version $Rev$ $Date$ */ public class JMSResourcesTest extends TestSupport { @Test public void testNewJMSResource() throws Exception { //selenium.click(getNavigationTreeNodeLocation("Services")); selenium.click("link=JMS Resources"); waitForPageLoad(); selenium.click("link=For ActiveMQ"); waitForPageLoad(); selenium.type("instanceName", "UniqueName"); selenium.click("//input[@value='Next']"); waitForPageLoad(); selenium.click("//input[@value='Add Connection Factory']"); waitForPageLoad(); selenium.select("factoryType", "label=javax.jms.QueueConnectionFactory"); selenium.click("//input[@value='Next']"); waitForPageLoad(); selenium.type("factory.0.instanceName", "ConnectionFactory"); selenium.click("//input[@value='Next']"); waitForPageLoad(); selenium.click("//input[@value='Add Destination']"); waitForPageLoad(); selenium.click("//input[@value='Next']"); waitForPageLoad(); selenium.type("destination.0.name", "mdb/Unique"); selenium.type("destination.0.instance-config-0", "mdb/Unique"); selenium.click("//input[@value='Next']"); waitForPageLoad(); selenium.click("//input[@value='Deploy Now']"); waitForPageLoad(); assertTrue(selenium.isTextPresent("UniqueName (console.jms/UniqueName/1.0/car)")); selenium.click("link=Java EE Connectors"); waitForPageLoad(); selenium.click("link=Uninstall"); selenium.getConfirmation().matches("Are you certain you wish to uninstallconsole.jms/UniqueName/1.0/car[\\s\\S]?"); //selenium.selectWindow("null"); //assertTrue("timed out waiting for button", waitForButton()); //waitForButton(); //selenium.click("dijit_form_Button_0"); waitForPageLoad(); selenium.click("link=JMS Resources"); waitForPageLoad(); assertFalse(selenium.isTextPresent("UniqueName (console.jms/UniqueName/1.0/car)")); } private boolean waitForButton() throws InterruptedException { for (int i = 0; i < 12; i++) { if (selenium.isElementPresent("dijit_form_Button_0")) { return true; } Thread.sleep(10 * 1000); } return false; } }
40.419753
123
0.651497
f66ea5716b47bf26be267dc470bb00513f3da395
2,151
package org.andstatus.app.graphics; import android.graphics.BitmapFactory; import android.graphics.Point; import org.andstatus.app.context.MyContextHolder; import org.andstatus.app.context.TestSuite; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class AttachedImageScalingTest { @Before public void setUp() throws Exception { TestSuite.initialize(this); } @Test public void testScaling() { ImageCaches.initialize(MyContextHolder.get().context()); ImageCache cache = ImageCaches.getCache(CacheName.ATTACHED_IMAGE); Point exactlyMaxSize = new Point(cache.getMaxBitmapWidth(), cache.getMaxBitmapWidth()); BitmapFactory.Options options = cache.calculateScaling(this, exactlyMaxSize); assertEquals(1, options.inSampleSize); Point largerSize = new Point(exactlyMaxSize.y + 10, exactlyMaxSize.x + 30); options = cache.calculateScaling(this, largerSize); assertEquals(2, options.inSampleSize); Point imageSize = new Point(largerSize.x * 2, largerSize.y * 2); options = cache.calculateScaling(this, imageSize); assertEquals(4, options.inSampleSize); imageSize = new Point(largerSize.x + largerSize.x / 2, largerSize.y + largerSize.y / 2); options = cache.calculateScaling(this, imageSize); assertEquals(2, options.inSampleSize); imageSize = new Point(largerSize.x * 3, largerSize.y); options = cache.calculateScaling(this, imageSize); assertEquals(4, options.inSampleSize); imageSize = new Point(largerSize.x, largerSize.y * 3); options = cache.calculateScaling(this, imageSize); assertEquals(4, options.inSampleSize); imageSize = new Point(largerSize.x / 2, largerSize.y); options = cache.calculateScaling(this, imageSize); assertEquals(2, options.inSampleSize); imageSize = new Point(largerSize.x / 2, largerSize.y / 2); options = cache.calculateScaling(this, imageSize); assertTrue(options.inSampleSize < 2); } }
41.365385
96
0.701999
6b2f62f1648d26b02f132476a23495e1894e8ea0
4,631
package com.telescent.afox.global; import com.telescent.afox.utils.FlatSerialize; import com.telescent.afox.utils.UnflatSerialize; public class SMConnectedTo { public String Status; //Allocation status public String ByUser; //The last user to cause this current state or pending state public boolean Allocated; //Allocation status (retundant for now) public String ConnectedToAFOXName; //AFOX Name of the connector to which this connector is connected. public String ConnectedToCustomerName;//Customer Name of the connector to which this connector is connected. public int ConnectedToConnectorNum;//Number the connector to which this connector is connected. public int ConnectedToRow; //Row number of the connected connector public int ConnectedToCol; //Column number of the connected connector public String toString() { StringBuilder b = new StringBuilder(); b.append("SMCOnnectedTo[ "); b.append("Status=").append(Status); b.append(" Allocated=").append(Allocated); b.append(" ConnectedToConnectorNum=").append(ConnectedToConnectorNum); b.append(" ConnectedToAFOX=").append(ConnectedToAFOXName); b.append(" ConnectedToRow=").append(ConnectedToRow); b.append(" ConnectedToCol=").append(ConnectedToCol); b.append("]"); return b.toString(); } public SMConnectedTo(int dummy) { //trick to force a constructor for the struct Status = ""; ByUser = ""; Allocated = false; ConnectedToAFOXName = ""; ConnectedToCustomerName = ""; ConnectedToConnectorNum = -1; ConnectedToRow = -1; ConnectedToCol = -1; } private SMConnectedTo() { // TODO Auto-generated constructor stub } /*************************************************************************** * * * Custom Memory Efficient Serializer/Deserialzer * * All variables very flat. No headers etc. * * * * byte[] ToFlatSer() : returns byte array of serialized data * * * * FromFlatSer(UnflatSerialize uf) : returns an instance of this class * * when supplied with the flattened serialized data stream. uf has * * its own internal pointer and will start in the data stream where * * it left off in any previous call. An error will be returned if * * uf cannot deserialize an input. If a deserialization failure * * occurs, uf will no longer deseriaize data. Therefore at the first * * failure, the operation should be abondened. * * * ***************************************************************************/ //Serialzer public byte[] FlatSer() { FlatSerialize f = new FlatSerialize(); Object [] items = new Object[8]; items[0]=FlatSerialize.NoNull(Status); items[1]=FlatSerialize.NoNull(ByUser); items[2]=Allocated; items[3]=FlatSerialize.NoNull(ConnectedToAFOXName); items[4]= FlatSerialize.NoNull(ConnectedToCustomerName); items[5]= ConnectedToConnectorNum; items[6]= ConnectedToRow; items[7]= ConnectedToCol; f.AddItems(items); return f.serializedData; } //extract and populate structure and return the rest of the byte stream public static SMConnectedTo FromFlatSer(UnflatSerialize uf) { //si = struct instance SMConnectedTo si = new SMConnectedTo(); //init struct boolean success; while(true) { //only done one time. a "trick" for quick branching out if any step fails. success = uf.getString(); if(!success) break; si.Status = uf.stringVal; success = uf.getString(); if(!success) break; si.ByUser = uf.stringVal; success = uf.getBoolean(); if(!success) break; si.Allocated = uf.boolVal; success = uf.getString(); if(!success) break; si.ConnectedToAFOXName = uf.stringVal; success = uf.getString(); if(!success) break; si.ConnectedToCustomerName = uf.stringVal; success = uf.getInt(); if(!success) break; si.ConnectedToConnectorNum = uf.intVal; success = uf.getInt(); if(!success) break; si.ConnectedToRow = uf.intVal; success = uf.getInt(); if(!success) break; si.ConnectedToCol = uf.intVal; break; //always finish with break so we only do the while loop once. } if(!success) si = null; //If failure, reinit structure return si; } }
38.591667
109
0.615634
fcaaa7c1764e978567bea31c5c2a0a6d2ede75ec
3,610
package org.alicebot.ab; /* Program AB Reference AIML 2.1 implementation Copyright (C) 2013 ALICE A.I. Foundation Contact: info@alicebot.org This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class NodemapperOperator { /** * number of branches from node * * @param node Nodemapper object * @return number of branches */ static int size(Nodemapper node) { final HashSet<String> set = new HashSet<String>(); if (node.shortCut) { set.add("<THAT>"); } if (node.key != null) { set.add(node.key); } if (node.map != null) { set.addAll(node.map.keySet()); } return set.size(); } /** * insert a new link from this node to another, by adding a key, value pair * * @param node Nodemapper object * @param key key word * @param value word maps to this next node */ static void put(Nodemapper node, String key, Nodemapper value) { if (node.map != null) { node.map.put(key, value); } else { // node.type == unary_node_mapper node.key = key; node.value = value; } } /** * get the node linked to this one by the word key * * @param node Nodemapper object * @param key key word to map * @return the mapped node or null if the key is not found */ static Nodemapper get(Nodemapper node, String key) { if (node.map != null) { return node.map.get(key); } else {// node.type == unary_node_mapper if (key.equals(node.key)) { return node.value; } else { return null; } } } /** * check whether a node contains a particular key * * @param node Nodemapper object * @param key key to test * @return true or false */ static boolean containsKey(Nodemapper node, String key) { // log.info("containsKey: Node="+node+" Map="+node.map); if (node.map != null) { return node.map.containsKey(key); } else {// node.type == unary_node_mapper if (key.equals(node.key)) { return true; } else { return false; } } } /** * get key set of a node * * @param node Nodemapper object * @return set of keys */ static Set<String> keySet(Nodemapper node) { if (node.map != null) { return node.map.keySet(); } else {// node.type == unary_node_mapper final HashSet<String> set = new HashSet<String>(); if (node.key != null) { set.add(node.key); } return set; } } /** * test whether a node is a leaf * * @param node Nodemapper object * @return true or false */ static boolean isLeaf(Nodemapper node) { return (node.category != null); } /** * upgrade a node from a singleton to a multi-way map * * @param node Nodemapper object */ static void upgrade(Nodemapper node) { // log.info("Upgrading "+node.id); // node.type = Properties.hash_node_mapper; node.map = new HashMap<String, Nodemapper>(); node.map.put(node.key, node.value); node.key = null; node.value = null; } }
24.391892
76
0.665374
677c786a53a9fdf0ffeef8e793143ca746b99b58
663
package gnu.kawa.functions; import gnu.expr.Language; import gnu.mapping.Procedure; import gnu.mapping.Procedure1; public class Not extends Procedure1 { Language language; public Not(Language language) { this.language = language; setProperty(Procedure.validateApplyKey, "gnu.kawa.functions.CompileMisc:validateApplyNot"); Procedure.compilerKey.set(this, "*gnu.kawa.functions.CompileMisc:forNot"); } public Not(Language language, String name) { this(language); setName(name); } public Object apply1(Object arg1) { return this.language.booleanObject(!this.language.isTrue(arg1)); } }
26.52
99
0.701357
6d5b880f645dee0c9bb0c90c3b1978f15d8b5be8
751
package com.example; import dagger.BindsInstance; import dagger.Component; import dagger.Module; import dagger.Provides; import dagger.Subcomponent; @Component(modules = ModuleSubcomponentBindsBuilder.StringModule.class) public interface ModuleSubcomponentBindsBuilder { String string(); @Module(subcomponents = StringSubcomponent.class) abstract class StringModule { @Provides static String string(StringSubcomponent.Builder builder) { return builder.longValue(5L).build().value().toString(); } } @Subcomponent interface StringSubcomponent { Long value(); @Subcomponent.Builder interface Builder { @BindsInstance Builder longValue(Long value); StringSubcomponent build(); } } }
22.088235
71
0.740346
55b752ff44191c742b2ff20559f335c3fca9b92a
754
package de.isuret.polos.AetherOnePi.utils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpUtils { public static String get(String urlPath) throws Exception { StringBuilder result = new StringBuilder(); URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = rd.readLine()) != null) { result.append(line + "\n"); } rd.close(); return result.toString().trim(); } }
26
102
0.655172
21e7a9d043ba7f361d23ae6a4c8cd52030d7b082
1,861
package org.tayrona.dbserver.services; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.h2.tools.Server; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.tayrona.dbserver.config.H2Configuration; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.sql.SQLException; @Data @Slf4j @Service public class EmbeddedServer{ private static final String CLASS_NAME = EmbeddedServer.class.getSimpleName(); private H2Configuration h2Config; private static Server server; @PostConstruct public void initialize() throws SQLException { // start the server, allows to access the database remotely log.info("{}.initialize() - Using server options: '{}'", CLASS_NAME, h2Config.getServer().getOptions()); String[] args = h2Config.getServer().getOptions().split(" "); server = new Server(); server.runTool(args); } @PreDestroy public void shutdown() { if (server != null) { log.info("{}.shutdown", CLASS_NAME); delay(h2Config.getServer().getShutdownDelay()); log.info("{}.shutdown server shutdown Now", CLASS_NAME); server.stop(); server = null; } } private void delay(long millisec) { if (millisec < 0){ millisec = 0; } log.debug("{}.delay({})", CLASS_NAME, millisec); try { if (millisec > 0) { Thread.sleep(millisec); } else { Thread.yield(); } } catch (InterruptedException e) { log.warn("{}.delay() interrupted", CLASS_NAME); } } @Autowired public void setH2Config(H2Configuration h2Config) { this.h2Config = h2Config; } }
27.776119
112
0.623321
484f4d0147761393f2e99d53025ab6b8bd8f884f
11,162
/**************************************************************** * 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.james.protocols.smtp.core; import java.util.ArrayList; import java.util.List; import org.apache.james.protocols.api.Request; import org.apache.james.protocols.api.Response; import org.apache.james.protocols.api.handler.CommandHandler; import org.apache.james.protocols.api.handler.ExtensibleHandler; import org.apache.james.protocols.smtp.SMTPResponse; import org.apache.james.protocols.smtp.SMTPRetCode; import org.apache.james.protocols.smtp.SMTPSession; import org.apache.james.protocols.smtp.hook.HookResult; import org.apache.james.protocols.smtp.hook.HookResultHook; import org.apache.james.protocols.smtp.hook.HookReturnCode; /** * Abstract class which Handle hook-aware CommanHandler. * */ public abstract class AbstractHookableCmdHandler<Hook extends org.apache.james.protocols.smtp.hook.Hook> implements CommandHandler<SMTPSession>, ExtensibleHandler { private List<Hook> hooks; private List<HookResultHook> rHooks; /** * Handle command processing * * @see org.apache.james.protocols.api.handler.CommandHandler * #onCommand(org.apache.james.protocols.api.ProtocolSession, Request) */ public Response onCommand(SMTPSession session, Request request) { String command = request.getCommand(); String parameters = request.getArgument(); Response response = doFilterChecks(session, command, parameters); if (response == null) { response = processHooks(session, command, parameters); if (response == null) { return doCoreCmd(session, command, parameters); } else { return response; } } else { return response; } } /** * Process all hooks for the given command * * @param session * the SMTPSession object * @param command * the command * @param parameters * the paramaters * @return SMTPResponse */ private Response processHooks(SMTPSession session, String command, String parameters) { List<Hook> hooks = getHooks(); if (hooks != null) { int count = hooks.size(); for (int i = 0; i < count; i++) { Hook rawHook = hooks.get(i); session.getLogger().debug("executing hook " + rawHook.getClass().getName()); long start = System.currentTimeMillis(); HookResult hRes = callHook(rawHook, session, parameters); long executionTime = System.currentTimeMillis() - start; if (rHooks != null) { for (int i2 = 0; i2 < rHooks.size(); i2++) { Object rHook = rHooks.get(i2); session.getLogger().debug("executing hook " + rHook); hRes = ((HookResultHook) rHook).onHookResult(session, hRes, executionTime, rawHook); } } // call the core cmd if we receive a ok return code of the hook so no other hooks are executed if ((hRes.getResult() & HookReturnCode.OK) == HookReturnCode.OK) { final Response response = doCoreCmd(session, command, parameters); if ((hRes.getResult() & HookReturnCode.DISCONNECT) == HookReturnCode.DISCONNECT) { return new Response() { /* * (non-Javadoc) * @see org.apache.james.protocols.api.Response#isEndSession() */ public boolean isEndSession() { return true; } /* * (non-Javadoc) * @see org.apache.james.protocols.api.Response#getRetCode() */ public String getRetCode() { return response.getRetCode(); } /* * (non-Javadoc) * @see org.apache.james.protocols.api.Response#getLines() */ public List<CharSequence> getLines() { return response.getLines(); } }; } return response; } else { SMTPResponse res = calcDefaultSMTPResponse(hRes); if (res != null) { return res; } } } } return null; } /** * Must be implemented by hookable cmd handlers to make the effective call to an hook. * * @param rawHook the hook * @param session the session * @param parameters the parameters * @return the HookResult, will be calculated using HookResultToSMTPResponse. */ protected abstract HookResult callHook(Hook rawHook, SMTPSession session, String parameters); /** * Convert the HookResult to SMTPResponse using default values. Should be override for using own values * * @param result HookResult * @return SMTPResponse */ public static SMTPResponse calcDefaultSMTPResponse(HookResult result) { if (result != null) { int rCode = result.getResult(); String smtpRetCode = result.getSmtpRetCode(); String smtpDesc = result.getSmtpDescription(); if ((rCode &HookReturnCode.DENY) == HookReturnCode.DENY) { if (smtpRetCode == null) smtpRetCode = SMTPRetCode.TRANSACTION_FAILED; if (smtpDesc == null) smtpDesc = "Email rejected"; SMTPResponse response = new SMTPResponse(smtpRetCode, smtpDesc); if ((rCode & HookReturnCode.DISCONNECT) == HookReturnCode.DISCONNECT) { response.setEndSession(true); } return response; } else if ((rCode & HookReturnCode.DENYSOFT) == HookReturnCode.DENYSOFT) { if (smtpRetCode == null) smtpRetCode = SMTPRetCode.LOCAL_ERROR; if (smtpDesc == null) smtpDesc = "Temporary problem. Please try again later"; SMTPResponse response = new SMTPResponse(smtpRetCode, smtpDesc); if ((rCode & HookReturnCode.DISCONNECT) == HookReturnCode.DISCONNECT) { response.setEndSession(true); } return response; } else if ((rCode & HookReturnCode.OK) == HookReturnCode.OK) { if (smtpRetCode == null) smtpRetCode = SMTPRetCode.MAIL_OK; if (smtpDesc == null) smtpDesc = "Command accepted"; SMTPResponse response = new SMTPResponse(smtpRetCode, smtpDesc); if ((rCode & HookReturnCode.DISCONNECT) == HookReturnCode.DISCONNECT) { response.setEndSession(true); } return response; } else if ((rCode & HookReturnCode.DISCONNECT) == HookReturnCode.DISCONNECT) { if (smtpRetCode == null) smtpRetCode = SMTPRetCode.TRANSACTION_FAILED; if (smtpDesc == null) smtpDesc = "Server disconnected"; SMTPResponse response = new SMTPResponse(smtpRetCode, smtpDesc); response.setEndSession(true); return response; } else { // Return null as default return null; } } else { return null; } } /** * Execute Syntax checks and return a SMTPResponse if a syntax error was * detected, otherwise null. * * @param session * @param command * @param parameters * @return smtp response if a syntax error was detected, otherwise <code>null</code> */ protected abstract Response doFilterChecks(SMTPSession session, String command, String parameters); /** * Execute the core commandHandling. * * @param session * @param command * @param parameters * @return smtp response */ protected abstract Response doCoreCmd(SMTPSession session, String command, String parameters); /** * @see org.apache.james.protocols.api.handler.ExtensibleHandler#getMarkerInterfaces() */ public List<Class<?>> getMarkerInterfaces() { List<Class<?>> classes = new ArrayList<Class<?>>(2); classes.add(getHookInterface()); classes.add(HookResultHook.class); return classes; } /** * Return the interface which hooks need to implement to hook in * * @return interface */ protected abstract Class<Hook> getHookInterface(); /** * @see org.apache.james.protocols.api.handler.ExtensibleHandler#wireExtensions(java.lang.Class, * java.util.List) */ @SuppressWarnings("unchecked") public void wireExtensions(Class<?> interfaceName, List<?> extension) { if (getHookInterface().equals(interfaceName)) { this.hooks = (List<Hook>) extension; } else if (HookResultHook.class.equals(interfaceName)) { this.rHooks = (List<HookResultHook>) extension; } } /** * Return a list which holds all hooks for the cmdHandler * * @return list containing all hooks for the cmd handler */ protected List<Hook> getHooks() { return hooks; } }
39.302817
164
0.542555
32df63d1d8982bca57397ef4f95f9e05c5dd1838
1,555
package modux.plugin.classutils; import org.apache.xbean.classloader.NamedClassLoader; import java.io.IOException; import java.net.URL; import java.util.Enumeration; public class AssetClassLoader extends ClassLoader { private NamedClassLoader delegated; private URL[] paths; public AssetClassLoader(ClassLoader parent, URL[] paths) { super(parent); this.paths = paths; } public void killDelegated() { try { if (this.delegated != null) { this.delegated.destroy(); this.delegated.close(); } } catch (Exception e) { e.printStackTrace(); } } public void reload() { setDelegated(new NamedClassLoader("resources-classloader", paths, getParent())); } public void setDelegated(NamedClassLoader delegated) { killDelegated(); this.delegated = delegated; } @Override public URL getResource(String name) { URL resource = delegated.getResource(name); return resource == null ? super.getResource(name) : resource; } @Override protected Enumeration<URL> findResources(String name) throws IOException { Enumeration<URL> resource = delegated.getResources(name); return resource == null ? getParent().getResources(name) : resource; } @Override protected URL findResource(String name) { URL resources = delegated.getResource(name); return resources == null ? getParent().getResource(name) : resources; } }
26.810345
88
0.641801
82c3ec1db63c5a25a8390ff87e149c92c4171797
17,527
/* $This file is distributed under the terms of the license in LICENSE$ */ package edu.cornell.mannlib.vitro.webapp.rdfservice.impl; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jena.atlas.io.StringWriterI; import org.apache.jena.graph.Node; import org.apache.jena.graph.NodeFactory; import org.apache.jena.graph.Triple; import org.apache.jena.query.Query; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.QueryParseException; import org.apache.jena.query.QuerySolution; import org.apache.jena.query.Syntax; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelChangedListener; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StmtIterator; import org.apache.jena.riot.out.NodeFormatter; import org.apache.jena.riot.out.NodeFormatterTTL; import org.apache.jena.vocabulary.RDF; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet; import edu.cornell.mannlib.vitro.webapp.rdfservice.ModelChange; import edu.cornell.mannlib.vitro.webapp.rdfservice.ModelChange.Operation; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException; import edu.cornell.mannlib.vitro.webapp.rdfservice.ResultSetConsumer; import edu.cornell.mannlib.vitro.webapp.utils.logging.ToString; public abstract class RDFServiceImpl implements RDFService { private static final Log log = LogFactory.getLog(RDFServiceImpl.class); protected static final String BNODE_ROOT_QUERY = "SELECT DISTINCT ?s WHERE { ?s ?p ?o OPTIONAL { ?ss ?pp ?s } FILTER (!isBlank(?s) || !bound(?ss)) }"; protected String defaultWriteGraphURI; protected List<ChangeListener> registeredListeners = new CopyOnWriteArrayList<ChangeListener>(); protected List<ModelChangedListener> registeredJenaListeners = new CopyOnWriteArrayList<ModelChangedListener>(); @Override public void newIndividual(String individualURI, String individualTypeURI) throws RDFServiceException { newIndividual(individualURI, individualTypeURI, defaultWriteGraphURI); } @Override public void newIndividual(String individualURI, String individualTypeURI, String graphURI) throws RDFServiceException { StringBuilder containsQuery = new StringBuilder("ASK { \n"); if (graphURI != null) { containsQuery.append(" GRAPH <").append(graphURI).append("> { "); } containsQuery.append("<"); containsQuery.append(individualURI); containsQuery.append("> "); containsQuery.append("?p ?o"); if (graphURI != null) { containsQuery.append(" } \n"); } containsQuery.append("\n}"); if (sparqlAskQuery(containsQuery.toString())) { throw new RDFServiceException("individual already exists"); } else { Triple triple = new Triple(NodeFactory.createURI(individualURI), RDF.type.asNode(), NodeFactory.createURI(individualTypeURI)); //addTriple(triple, graphURI); ChangeSet cs = this.manufactureChangeSet(); cs.addAddition(new ByteArrayInputStream( sparqlTriple(triple).getBytes()), ModelSerializationFormat.N3, graphURI); changeSetUpdate(cs); } } @Override public String getDefaultWriteGraphURI() throws RDFServiceException { return defaultWriteGraphURI; } @Override public synchronized void registerListener(ChangeListener changeListener) throws RDFServiceException { if (!registeredListeners.contains(changeListener)) { registeredListeners.add(changeListener); } } @Override public synchronized void unregisterListener(ChangeListener changeListener) throws RDFServiceException { registeredListeners.remove(changeListener); } @Override public synchronized void registerJenaModelChangedListener(ModelChangedListener changeListener) throws RDFServiceException { if (!registeredJenaListeners.contains(changeListener)) { registeredJenaListeners.add(changeListener); } } @Override public synchronized void unregisterJenaModelChangedListener(ModelChangedListener changeListener) throws RDFServiceException { registeredJenaListeners.remove(changeListener); } public synchronized List<ChangeListener> getRegisteredListeners() { return this.registeredListeners; } public synchronized List<ModelChangedListener> getRegisteredJenaModelChangedListeners() { return this.registeredJenaListeners; } @Override public ChangeSet manufactureChangeSet() { return new ChangeSetImpl(); } protected void notifyListenersOfChanges(ChangeSet changeSet) throws IOException { if (registeredListeners.isEmpty() && registeredJenaListeners.isEmpty()) { return; } for (ModelChange modelChange: changeSet.getModelChanges()) { notifyListeners(modelChange); } } protected void notifyListeners(ModelChange modelChange) throws IOException { for (ChangeListener listener : registeredListeners) { modelChange.getSerializedModel().reset(); listener.notifyModelChange(modelChange); } log.debug(registeredJenaListeners.size() + " registered Jena listeners"); if (registeredJenaListeners.isEmpty()) { return; } modelChange.getSerializedModel().reset(); Model tempModel = ModelFactory.createDefaultModel(); Iterator<ModelChangedListener> jenaIter = registeredJenaListeners.iterator(); while (jenaIter.hasNext()) { ModelChangedListener listener = jenaIter.next(); log.debug("\t" + listener.getClass().getSimpleName()); tempModel.register(listener); } if (Operation.ADD.equals(modelChange.getOperation())) { tempModel.read(modelChange.getSerializedModel(), null, RDFServiceUtils.getSerializationFormatString( modelChange.getSerializationFormat())); } else if (Operation.REMOVE.equals(modelChange.getOperation())) { tempModel.remove(RDFServiceUtils.parseModel( modelChange.getSerializedModel(), modelChange.getSerializationFormat())); } while (jenaIter.hasNext()) { tempModel.unregister(jenaIter.next()); } } public void notifyListenersOfEvent(Object event) { for (ChangeListener listener : registeredListeners) { // TODO what is the graphURI parameter for? listener.notifyEvent(null, event); } for (ModelChangedListener listener : registeredJenaListeners) { listener.notifyEvent(null, event); } } protected boolean isPreconditionSatisfied(String query, RDFService.SPARQLQueryType queryType) throws RDFServiceException { Model model = ModelFactory.createDefaultModel(); switch (queryType) { case DESCRIBE: model.read(sparqlDescribeQuery(query,RDFService.ModelSerializationFormat.N3), null); return !model.isEmpty(); case CONSTRUCT: model.read(sparqlConstructQuery(query,RDFService.ModelSerializationFormat.N3), null); return !model.isEmpty(); case SELECT: return sparqlSelectQueryHasResults(query); case ASK: return sparqlAskQuery(query); default: throw new RDFServiceException("unrecognized SPARQL query type"); } } protected static String getSerializationFormatString(RDFService.ModelSerializationFormat format) { switch (format) { case RDFXML: return "RDF/XML"; case N3: return "TTL"; case NTRIPLE: return "N-TRIPLE"; default: log.error("unexpected format in getFormatString"); return null; } } protected boolean sparqlSelectQueryHasResults(String queryStr) throws RDFServiceException { ResultSetConsumer.HasResult hasResult = new ResultSetConsumer.HasResult(); sparqlSelectQuery(queryStr, hasResult); return hasResult.hasResult(); } protected static String sparqlTriple(Triple triple) { StringBuilder serializedTriple = new StringBuilder(); serializedTriple.append(sparqlNodeUpdate(triple.getSubject(), "")); serializedTriple.append(" "); serializedTriple.append(sparqlNodeUpdate(triple.getPredicate(), "")); serializedTriple.append(" "); serializedTriple.append(sparqlNodeUpdate(triple.getObject(), "")); serializedTriple.append(" ."); return serializedTriple.toString(); } protected static String sparqlNodeUpdate(Node node, String varName) { if (node.isBlank()) { return "_:" + node.getBlankNodeLabel().replaceAll("\\W", ""); } else { return sparqlNode(node, varName); } } protected static String sparqlNode(Node node, String varName) { if (node == null || node.isVariable()) { return varName; } else if (node.isBlank()) { return "<fake:blank>"; // or throw exception? } else if (node.isURI()) { StringBuilder uriBuff = new StringBuilder(); return uriBuff.append("<").append(node.getURI()).append(">").toString(); } else if (node.isLiteral()) { StringBuffer literalBuff = new StringBuffer(); literalBuff.append("\""); pyString(literalBuff, node.getLiteralLexicalForm()); literalBuff.append("\""); if (node.getLiteralLanguage() != null && node.getLiteralLanguage().length() > 0) { literalBuff.append("@").append(node.getLiteralLanguage()); } else if (node.getLiteralDatatypeURI() != null) { literalBuff.append("^^<").append(node.getLiteralDatatypeURI()).append(">"); } return literalBuff.toString(); } else { return varName; } } // see http://www.python.org/doc/2.5.2/ref/strings.html // or see jena's n3 grammar jena/src/org.apache/jena/n3/n3.g protected static void pyString(StringBuffer sbuff, String s) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // Escape escapes and quotes if (c == '\\' || c == '"' ) { sbuff.append('\\') ; sbuff.append(c) ; continue ; } // Whitespace if (c == '\n'){ sbuff.append("\\n");continue; } if (c == '\t'){ sbuff.append("\\t");continue; } if (c == '\r'){ sbuff.append("\\r");continue; } if (c == '\f'){ sbuff.append("\\f");continue; } if (c == '\b'){ sbuff.append("\\b");continue; } if( c == 7 ) { sbuff.append("\\a");continue; } // Output as is (subject to UTF-8 encoding on output that is) sbuff.append(c) ; } } /** * Returns a pair of models. The first contains any statement containing at * least one blank node. The second contains all remaining statements. * @param gm Jena model */ protected Model[] separateStatementsWithBlankNodes(Model gm) { Model blankNodeModel = ModelFactory.createDefaultModel(); Model nonBlankNodeModel = ModelFactory.createDefaultModel(); StmtIterator sit = gm.listStatements(); while (sit.hasNext()) { Statement stmt = sit.nextStatement(); if (!stmt.getSubject().isAnon() && !stmt.getObject().isAnon()) { nonBlankNodeModel.add(stmt); } else { blankNodeModel.add(stmt); } } Model[] result = new Model[2]; result[0] = blankNodeModel; result[1] = nonBlankNodeModel; return result; } protected Query createQuery(String queryString) throws RDFServiceException { List<Syntax> syntaxes = Arrays.asList( Syntax.defaultQuerySyntax, Syntax.syntaxSPARQL_11, Syntax.syntaxSPARQL_10, Syntax.syntaxSPARQL, Syntax.syntaxARQ); Query q = null; Iterator<Syntax> syntaxIt = syntaxes.iterator(); while (q == null) { Syntax syntax = syntaxIt.next(); try { q = QueryFactory.create(queryString, syntax); } catch (QueryParseException e) { if (!syntaxIt.hasNext()) { throw new RDFServiceException("Failed to parse query \"" + queryString + "\"", e); } } } return q; } @Override public String toString() { return ToString.simpleName(this) + "[" + ToString.hashHex(this) + "]"; } @Override public long countTriples(RDFNode subject, RDFNode predicate, RDFNode object) throws RDFServiceException { StringBuilder whereClause = new StringBuilder(); if ( subject != null ) { appendNode(whereClause.append(' '), subject); } else { whereClause.append(" ?s"); } if ( predicate != null ) { appendNode(whereClause.append(' '), predicate); } else { whereClause.append(" ?p"); } if ( object != null ) { appendNode(whereClause.append(' '), object); } else { whereClause.append(" ?o"); } long estimate = -1; StringBuilder count = new StringBuilder(); count.append("SELECT (COUNT(*) AS ?count) WHERE { "); count.append(whereClause.toString()); count.append(" . "); count.append(" }"); CountConsumer countConsumer = new CountConsumer(); this.sparqlSelectQuery(count.toString(), countConsumer); return countConsumer.count; } @Override public Model getTriples(RDFNode subject, RDFNode predicate, RDFNode object, long limit, long offset) throws RDFServiceException { StringBuilder whereClause = new StringBuilder(); StringBuilder orderBy = new StringBuilder(); if ( subject != null ) { appendNode(whereClause.append(' '), subject); } else { whereClause.append(" ?s"); orderBy.append(" ?s"); } if ( predicate != null ) { appendNode(whereClause.append(' '), predicate); } else { whereClause.append(" ?p"); orderBy.append(" ?p"); } if ( object != null ) { appendNode(whereClause.append(' '), object); } else { whereClause.append(" ?o"); orderBy.append(" ?o"); } StringBuilder constructQuery = new StringBuilder(); constructQuery.append("CONSTRUCT { "); constructQuery.append(whereClause.toString()); constructQuery.append(" } WHERE { "); constructQuery.append(whereClause.toString()).append(" . "); constructQuery.append(" }"); if (orderBy.length() > 0) { constructQuery.append(" ORDER BY").append(orderBy.toString()); } if (limit > 0) { constructQuery.append(" LIMIT ").append(limit); } if (offset > 0) { constructQuery.append(" OFFSET ").append(offset); } Model triples = ModelFactory.createDefaultModel(); this.sparqlConstructQuery(constructQuery.toString(), triples); return triples; } private void appendNode(StringBuilder builder, RDFNode node) { if (node.isLiteral()) { builder.append(literalToString(node.asLiteral())); } else if (node.isURIResource()) { builder.append('<').append(node.asResource().getURI()).append('>'); } } private String literalToString(Literal l) { StringWriterI sw = new StringWriterI(); NodeFormatter fmt = new NodeFormatterTTL(null, null); fmt.formatLiteral(sw, l.asNode()); return sw.toString(); } class CountConsumer extends ResultSetConsumer { public long count = -1; @Override protected void processQuerySolution(QuerySolution qs) { if (count == -1) { Literal literal = qs.getLiteral("count"); count = literal.getLong(); } } } /* * UQAM Useful among other things to transport the linguistic context in the service * (non-Javadoc) * @see edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService#setVitroRequest(edu.cornell.mannlib.vitro.webapp.controller.VitroRequest) */ private VitroRequest vitroRequest; public void setVitroRequest(VitroRequest vitroRequest) { this.vitroRequest = vitroRequest; } public VitroRequest getVitroRequest() { return vitroRequest; } }
36.976793
138
0.633137
262d3a9eb86e99c49878c75eacf8d52195a37c84
3,461
package noppes.npcs.ai; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.player.EntityPlayer; import noppes.npcs.constants.AiMutex; import noppes.npcs.constants.EnumStandingType; import noppes.npcs.entity.EntityNPCInterface; import java.util.Iterator; public class EntityAILook extends EntityAIBase { private final EntityNPCInterface npc; boolean rotatebody; private int idle = 0; private double lookX; private double lookZ; public EntityAILook(EntityNPCInterface npc) { this.npc = npc; this.setMutexBits(AiMutex.LOOK); } /** * Returns whether the EntityAIBase should begin execution. */ @Override public boolean shouldExecute() { return !npc.isAttacking() && npc.getNavigator().noPath() && !npc.isPlayerSleeping() && npc.isEntityAlive(); } /** * Execute a one shot task or start executing a continuous task */ @Override public void startExecuting() { rotatebody = npc.ai.standingType == EnumStandingType.RotateBody || npc.ai.standingType == EnumStandingType.HeadRotation; } /** * Resets the task */ @Override public void resetTask() { rotatebody = false; } /** * Updates the task */ @Override public void updateTask() { if (npc.ai.standingType == EnumStandingType.Stalking) { EntityPlayer player = npc.worldObj.getClosestPlayerToEntity(npc, 16); if (player == null) rotatebody = true; else npc.getLookHelper().setLookPositionWithEntity(player, 10F, npc.getVerticalFaceSpeed()); } if (npc.isInteracting()) { Iterator<EntityLivingBase> ita = npc.interactingEntities.iterator(); EntityLivingBase closest = null; double closestDistance = 12; while (ita.hasNext()) { EntityLivingBase entity = ita.next(); double distance = entity.getDistanceSqToEntity(npc); if (distance < closestDistance) { closestDistance = entity.getDistanceSqToEntity(npc); closest = entity; } else if (distance > 12) ita.remove(); } if (closest != null) { npc.getLookHelper().setLookPositionWithEntity(closest, 10F, npc.getVerticalFaceSpeed()); return; } } if (rotatebody) { if (idle == 0 && npc.getRNG().nextFloat() < 0.02F) { double var1 = (Math.PI * 2D) * this.npc.getRNG().nextDouble(); if (npc.ai.standingType == EnumStandingType.HeadRotation) var1 = Math.PI / 180 * npc.ai.orientation + Math.PI * 0.2 + Math.PI * 0.6 * this.npc.getRNG().nextDouble(); this.lookX = Math.cos(var1); this.lookZ = Math.sin(var1); this.idle = 20 + this.npc.getRNG().nextInt(20); } if (idle > 0) { idle--; npc.getLookHelper().setLookPosition(npc.posX + lookX, npc.posY + npc.getEyeHeight(), npc.posZ + lookZ, 10F, npc.getVerticalFaceSpeed()); } } if (npc.ai.standingType == EnumStandingType.NoRotation) { npc.rotationYawHead = npc.rotationYaw = npc.renderYawOffset = npc.ai.orientation; } } }
34.61
152
0.589714
9d43605f3b9e0d2fcb100f02381f495e2de93a3e
2,987
package org.app.events.volunteer.controllers; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.control.TextField; import org.app.events.event.model.Event; import org.app.events.event.services.EventService; import org.app.events.lists.controllers.AdminToAllEvents; import org.app.events.registration.model.User; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.app.events.login.controllers.LoginController.activeUser; public class showEventVolunteersController { @FXML private Label volunteerFirstNameLbl, volunteerLastNameLbl, emailLbl; public static int k; public ObservableList<String> list; @FXML public void initialize() { k=0; if(EventService.events.get(AdminToAllEvents.indexATE).volunteers.size() > 0) { volunteerFirstNameLbl.setText(EventService.events.get(AdminToAllEvents.indexATE).volunteers.get(k).getFirstname()); volunteerLastNameLbl.setText(EventService.events.get(AdminToAllEvents.indexATE).volunteers.get(k).getLastname()); emailLbl.setText(EventService.events.get(AdminToAllEvents.indexATE).volunteers.get(k).getEmail()); } else emailLbl.setText("NO VOLUNTEERS"); } @FXML public void changeToNextVolunteer() { if(k < (EventService.events.get(AdminToAllEvents.indexATE).volunteers.size()-1)) { k++; volunteerFirstNameLbl.setText(EventService.events.get(AdminToAllEvents.indexATE).volunteers.get(k).getFirstname()); volunteerLastNameLbl.setText(EventService.events.get(AdminToAllEvents.indexATE).volunteers.get(k).getLastname()); emailLbl.setText(EventService.events.get(AdminToAllEvents.indexATE).volunteers.get(k).getEmail()); } } @FXML public void changeToPreviousVolunteer() { if(k > 0) { k--; volunteerFirstNameLbl.setText(EventService.events.get(AdminToAllEvents.indexATE).volunteers.get(k).getFirstname()); volunteerLastNameLbl.setText(EventService.events.get(AdminToAllEvents.indexATE).volunteers.get(k).getLastname()); emailLbl.setText(EventService.events.get(AdminToAllEvents.indexATE).volunteers.get(k).getEmail()); } } @FXML public TextField moveTo; @FXML public void moveVolunteer() throws IOException { for(Event event: EventService.events) { System.out.println(moveTo.getText()); if((moveTo.getText()).equals(event.getName())) { event.volunteers.add(EventService.events.get(AdminToAllEvents.indexATE).volunteers.get(k)); EventService.events.get(AdminToAllEvents.indexATE).volunteers.remove(k); EventService.persistEvents(); } } } }
36.876543
127
0.701038
002cb9ee3299d44b7c84b15f26238c900ee29559
1,141
package com.weijiaxing.logcatviewer; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import com.weijiaxing.logcatviewer.ui.UseFloatingLogcatServiceActivity; import com.weijiaxing.logcatviewer.ui.UseLogcatActivity; import com.weijiaxing.logcatviewer.ui.UseLogcatControlActivity; public class MainActivity extends AppCompatActivity { private static String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void Logcat(View view) { Log.e(TAG, "Logcat"); startActivity(new Intent(this, UseLogcatActivity.class)); } public void FloatingLogcat(View view) { Log.e(TAG, "FloatingLogcat"); startActivity(new Intent(this, UseFloatingLogcatServiceActivity.class)); } public void LogcatControl(View view) { Log.e(TAG, "LogcatControl"); startActivity(new Intent(this, UseLogcatControlActivity.class)); } }
25.355556
80
0.736196
54e86ed5ed480d78d009e1af83d00915fc507e2f
3,839
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.naming.deployment; import java.util.List; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.naming.service.NamingService; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; /** * Adds a service that depends on all JNDI bindings from the deployment to be up. * <p/> * As binding services are not children of the root deployment unit service this service * is necessary to ensure the deployment is not considered complete until add bindings are up * * @author Stuart Douglas */ public class JndiNamingDependencyProcessor implements DeploymentUnitProcessor { private static final ServiceName JNDI_DEPENDENCY_SERVICE = ServiceName.of("jndiDependencyService"); @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); ServiceName namingStoreServiceName = support.getCapabilityServiceName(NamingService.CAPABILITY_NAME); //this will always be up but we need to make sure the naming service is //not shut down before the deployment is undeployed when the container is shut down phaseContext.addToAttachmentList(Attachments.NEXT_PHASE_DEPS, namingStoreServiceName); List<ServiceName> dependencies = deploymentUnit.getAttachmentList(Attachments.JNDI_DEPENDENCIES); final ServiceName serviceName = serviceName(deploymentUnit.getServiceName()); final ServiceBuilder<?> serviceBuilder = phaseContext.getServiceTarget().addService(serviceName, new RuntimeBindReleaseService()); serviceBuilder.addDependencies(dependencies); if(deploymentUnit.getParent() != null) { serviceBuilder.addDependencies(deploymentUnit.getParent().getAttachment(Attachments.JNDI_DEPENDENCIES)); } serviceBuilder.addDependency(namingStoreServiceName); serviceBuilder.install(); } public static ServiceName serviceName(final ServiceName deploymentUnitServiceName) { return deploymentUnitServiceName.append(JNDI_DEPENDENCY_SERVICE); } public static ServiceName serviceName(final DeploymentUnit deploymentUnit) { return serviceName(deploymentUnit.getServiceName()); } @Override public void undeploy(final DeploymentUnit context) { } }
46.253012
138
0.776765
f00359e55cda6d0fd63bd20cca0a7813ce75027d
4,063
package com.moonymango.snare.ui.widgets; import com.moonymango.snare.events.EventManager; import com.moonymango.snare.events.ITouchEvent; import com.moonymango.snare.events.IWidgetTouchedBeginEvent; import com.moonymango.snare.events.IWidgetTouchedEndEvent; import com.moonymango.snare.game.IGame; import com.moonymango.snare.proc.ProcessManager.BaseProcess; import com.moonymango.snare.proc.ProcessManager.IOnProcessKilledListener; import com.moonymango.snare.ui.TouchAction; /** * Extends {@link BaseWidget} so it can act as button. */ public abstract class BaseTouchWidget extends BaseWidget implements IOnProcessKilledListener { private boolean mRunsClickAnimation; private BaseProcess mClickAnimation; private final TouchSetting mSetting; private boolean mIsEnabled = true; public BaseTouchWidget(IGame game, TouchSetting setting) { super(game); mSetting = setting; if (setting == TouchSetting.TOUCHABLE) { setDefaultAnimation(); } } /** * Set a user defined animation for this button. Animation is played when * the button catches a touch DOWN event. * is called after the animation process chain has finished. * * @param proc * Animation process or null if no animation desired. */ public BaseTouchWidget setAnimation(BaseProcess proc) { if (proc != null) { proc.findLast().setListener(this); } mClickAnimation = proc; return this; } /** * Restores the default animation. */ public BaseTouchWidget setDefaultAnimation() { WidgetScaleModifier min = new WidgetScaleModifier(mGame, this, 0.8f, 0.8f, 60, null); WidgetScaleModifier mag = new WidgetScaleModifier(mGame, this, 1.25f, 1.25f, 60, null); min.setNext(mag); setAnimation(min); return this; } /** * @return True if widget responds to touch events, false otherwise. */ public boolean isEnabled() { return mSetting == TouchSetting.TOUCHABLE && mIsEnabled; } /** * Enables/disables touch event handling. * @param enable * @return */ public BaseTouchWidget enable(boolean enable) { mIsEnabled = enable; return this; } @Override public boolean onTouchEvent(ITouchEvent e) { if (mSetting != TouchSetting.TOUCHABLE || !mIsEnabled || e.getTouchAction() != TouchAction.DOWN || mRunsClickAnimation) { // Only do something if it's a DOWN action, we have a listener // and animation is not already running. Return true anyway, // so that event is not delivered to another widget because it // was actually meant for this one. return true; } // play animation if we have one if (mClickAnimation != null) { mRunsClickAnimation = true; mClickAnimation.run(); // send event final EventManager em = mGame.getEventManager(); final IWidgetTouchedBeginEvent evt = em.obtain(IWidgetTouchedBeginEvent.EVENT_TYPE); evt.setWidgetData(this); em.queueEvent(evt); } else { // no animation, send end event immediately final EventManager em = mGame.getEventManager(); final IWidgetTouchedEndEvent evt = em.obtain(IWidgetTouchedEndEvent.EVENT_TYPE); evt.setWidgetData(this); em.queueEvent(evt); } return true; } @Override public void onProcessKilled(BaseProcess proc) { // gets called when animation is finished mRunsClickAnimation = false; // send end event final EventManager em = mGame.getEventManager(); final IWidgetTouchedEndEvent evt = em.obtain(IWidgetTouchedEndEvent.EVENT_TYPE); evt.setWidgetData(this); em.queueEvent(evt); } public enum TouchSetting { TOUCHABLE, NOT_TOUCHABLE } }
32.246032
95
0.642875
3d171d33d692fc2307daae130ac2ee398a4e5a94
721
package beyblade; public class Dragon extends Beyblade{ private String sacredMonster; private String secretAbility; Dragon(String beybladesName, Integer rotationSpeed, Integer attackPower, String sacredMonster, String secretAbility) { super(beybladesName, rotationSpeed, attackPower); this.sacredMonster=sacredMonster; this.secretAbility=secretAbility; } @Override public void inquireInformation() { super.inquireInformation(); System.out.println("Sacred Monster Name " + sacredMonster); } @Override public void inquireSacredMonster() { System.out.println(getBeybladesName() + sacredMonster + " revealing"); } }
24.862069
122
0.692094
f7bd8b12c2e03d68213107c32415527d3520330d
13,491
/* * Copyright [2007] [University Corporation for Advanced Internet Development, 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.opensaml.xml.security; import java.security.GeneralSecurityException; import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.util.Arrays; import javax.crypto.Mac; import org.bouncycastle.util.encoders.Hex; import org.opensaml.xml.security.credential.Credential; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A utility class for computing and verifying raw signatures and MAC values. */ public final class SigningUtil { /** Class logger. */ private static Logger log = LoggerFactory.getLogger(SigningUtil.class); /** Constructor. */ private SigningUtil() { } /** * Compute the signature or MAC value over the supplied input. * * It is up to the caller to ensure that the specified algorithm URI is consistent with the type of signing key * supplied in the signing credential. * * @param signingCredential the credential containing the signing key * @param algorithmURI the algorithm URI to use * @param input the input over which to compute the signature * @return the computed signature or MAC value * @throws SecurityException throw if the computation process results in an error */ public static byte[] signWithURI(Credential signingCredential, String algorithmURI, byte[] input) throws SecurityException { String jcaAlgorithmID = SecurityHelper.getAlgorithmIDFromURI(algorithmURI); if (jcaAlgorithmID == null) { throw new SecurityException("Could not derive JCA algorithm identifier from algorithm URI"); } boolean isHMAC = SecurityHelper.isHMAC(algorithmURI); return sign(signingCredential, jcaAlgorithmID, isHMAC, input); } /** * Compute the signature or MAC value over the supplied input. * * It is up to the caller to ensure that the specified algorithm ID and isMAC flag are consistent with the type of * signing key supplied in the signing credential. * * @param signingCredential the credential containing the signing key * @param jcaAlgorithmID the Java JCA algorithm ID to use * @param isMAC flag indicating whether the operation to be performed is a signature or MAC computation * @param input the input over which to compute the signature * @return the computed signature or MAC value * @throws SecurityException throw if the computation process results in an error */ public static byte[] sign(Credential signingCredential, String jcaAlgorithmID, boolean isMAC, byte[] input) throws SecurityException { Key signingKey = SecurityHelper.extractSigningKey(signingCredential); if (signingKey == null) { log.error("No signing key supplied in signing credential for signature computation"); throw new SecurityException("No signing key supplied in signing credential"); } if (isMAC) { return signMAC(signingKey, jcaAlgorithmID, input); } else if (signingKey instanceof PrivateKey) { return sign((PrivateKey) signingKey, jcaAlgorithmID, input); } else { log.error("No PrivateKey present in signing credential for signature computation"); throw new SecurityException("No PrivateKey supplied for signing"); } } /** * Compute the raw signature value over the supplied input. * * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of signing key * supplied. * * @param signingKey the private key with which to compute the signature * @param jcaAlgorithmID the Java JCA algorithm ID to use * @param input the input over which to compute the signature * @return the computed signature value * @throws SecurityException thrown if the signature computation results in an error */ public static byte[] sign(PrivateKey signingKey, String jcaAlgorithmID, byte[] input) throws SecurityException { log.debug("Computing signature over input using private key of type {} and JCA algorithm ID {}", signingKey .getAlgorithm(), jcaAlgorithmID); try { Signature signature = Signature.getInstance(jcaAlgorithmID); signature.initSign(signingKey); signature.update(input); byte[] rawSignature = signature.sign(); log.debug("Computed signature: {}", new String(Hex.encode(rawSignature))); return rawSignature; } catch (GeneralSecurityException e) { log.error("Error during signature generation", e); throw new SecurityException("Error during signature generation", e); } } /** * Compute the Message Authentication Code (MAC) value over the supplied input. * * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of signing key * supplied. * * @param signingKey the key with which to compute the MAC * @param jcaAlgorithmID the Java JCA algorithm ID to use * @param input the input over which to compute the MAC * @return the computed MAC value * @throws SecurityException thrown if the MAC computation results in an error */ public static byte[] signMAC(Key signingKey, String jcaAlgorithmID, byte[] input) throws SecurityException { log.debug("Computing MAC over input using key of type {} and JCA algorithm ID {}", signingKey.getAlgorithm(), jcaAlgorithmID); try { Mac mac = Mac.getInstance(jcaAlgorithmID); mac.init(signingKey); mac.update(input); byte[] rawMAC = mac.doFinal(); log.debug("Computed MAC: {}", new String(Hex.encode(rawMAC))); return rawMAC; } catch (GeneralSecurityException e) { log.error("Error during MAC generation", e); throw new SecurityException("Error during MAC generation", e); } } /** * Verify the signature value computed over the supplied input against the supplied signature value. * * It is up to the caller to ensure that the specified algorithm URI are consistent with the type of verification * credential supplied. * * @param verificationCredential the credential containing the verification key * @param algorithmURI the algorithm URI to use * @param signature the computed signature value received from the signer * @param input the input over which the signature is computed and verified * @return true if the signature value computed over the input using the supplied key and algorithm ID is identical * to the supplied signature value * @throws SecurityException thrown if the signature computation or verification process results in an error */ public static boolean verifyWithURI(Credential verificationCredential, String algorithmURI, byte[] signature, byte[] input) throws SecurityException { String jcaAlgorithmID = SecurityHelper.getAlgorithmIDFromURI(algorithmURI); if (jcaAlgorithmID == null) { throw new SecurityException("Could not derive JCA algorithm identifier from algorithm URI"); } boolean isHMAC = SecurityHelper.isHMAC(algorithmURI); return verify(verificationCredential, jcaAlgorithmID, isHMAC, signature, input); } /** * Verify the signature value computed over the supplied input against the supplied signature value. * * It is up to the caller to ensure that the specified algorithm ID and isMAC flag are consistent with the type of * verification credential supplied. * * @param verificationCredential the credential containing the verification key * @param jcaAlgorithmID the Java JCA algorithm ID to use * @param isMAC flag indicating whether the operation to be performed is a signature or MAC computation * @param signature the computed signature value received from the signer * @param input the input over which the signature is computed and verified * @return true if the signature value computed over the input using the supplied key and algorithm ID is identical * to the supplied signature value * @throws SecurityException thrown if the signature computation or verification process results in an error */ public static boolean verify(Credential verificationCredential, String jcaAlgorithmID, boolean isMAC, byte[] signature, byte[] input) throws SecurityException { Key verificationKey = SecurityHelper.extractVerificationKey(verificationCredential); if (verificationKey == null) { log.error("No verification key supplied in verification credential for signature verification"); throw new SecurityException("No verification key supplied in verification credential"); } if (isMAC) { return verifyMAC(verificationKey, jcaAlgorithmID, signature, input); } else if (verificationKey instanceof PublicKey) { return verify((PublicKey) verificationKey, jcaAlgorithmID, signature, input); } else { log.error("No PublicKey present in verification credential for signature verification"); throw new SecurityException("No PublicKey supplied for signature verification"); } } /** * Verify the signature value computed over the supplied input against the supplied signature value. * * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of verification key * supplied. * * @param verificationKey the key with which to compute and verify the signature * @param jcaAlgorithmID the Java JCA algorithm ID to use * @param signature the computed signature value received from the signer * @param input the input over which the signature is computed and verified * @return true if the signature value computed over the input using the supplied key and algorithm ID is identical * to the supplied signature value * @throws SecurityException thrown if the signature computation or verification process results in an error */ public static boolean verify(PublicKey verificationKey, String jcaAlgorithmID, byte[] signature, byte[] input) throws SecurityException { log.debug("Verifying signature over input using public key of type {} and JCA algorithm ID {}", verificationKey .getAlgorithm(), jcaAlgorithmID); try { Signature sig = Signature.getInstance(jcaAlgorithmID); sig.initVerify(verificationKey); sig.update(input); return sig.verify(signature); } catch (GeneralSecurityException e) { log.error("Error during signature verification", e); throw new SecurityException("Error during signature verification", e); } } /** * Verify the Message Authentication Code (MAC) value computed over the supplied input against the supplied MAC * value. * * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of verification key * supplied. * * @param verificationKey the key with which to compute and verify the MAC * @param jcaAlgorithmID the Java JCA algorithm ID to use * @param signature the computed MAC value received from the signer * @param input the input over which the MAC is computed and verified * @return true if the MAC value computed over the input using the supplied key and algorithm ID is identical to the * supplied MAC signature value * @throws SecurityException thrown if the MAC computation or verification process results in an error */ public static boolean verifyMAC(Key verificationKey, String jcaAlgorithmID, byte[] signature, byte[] input) throws SecurityException { log.debug("Verifying MAC over input using key of type {} and JCA algorithm ID {}", verificationKey .getAlgorithm(), jcaAlgorithmID); // Java JCA/JCE Mac interface doesn't have a verification op, // so have to compute the Mac and compare the byte arrays manually. byte[] computed = signMAC(verificationKey, jcaAlgorithmID, input); return Arrays.equals(computed, signature); } }
48.182143
121
0.682455
c414441214afba96c298ce7c1dbdf4bf1f0d4fda
758
package org.aio.gui.task_panels; import org.aio.tasks.TaskType; public class TaskPanelFactory { public static TaskPanel createTaskPanel(final TaskType taskType) { switch (taskType) { case RESOURCE: return new ResourceTaskPanel(); case LEVEL: return new LevelTaskPanel(); case LOOP: return new LoopTaskPanel(); case TIMED: return new TimedTaskPanel(); case QUEST: return new QuestTaskPanel(); case GRAND_EXCHANGE: return new GETaskPanel(); case BREAK: return new BreakTaskPanel(); default: return null; } } }
28.074074
70
0.529024
88af8c9a56bdb309faccd4887342f1f3fb6f8594
7,693
package com.zdawn.commons.sysmodel.persistence.spring; import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zdawn.commons.sysmodel.persistence.PersistenceException; import com.zdawn.commons.sysmodel.persistence.SqlSession; import com.zdawn.commons.sysmodel.persistence.SqlSessionFactory; public class SqlSessionTemplate implements SqlSession { private static final Logger log = LoggerFactory.getLogger(SqlSessionTemplate.class); private SqlSessionFactory sqlSessionFactory; private SqlSession sqlSessionProxy; public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory){ this.sqlSessionFactory = sqlSessionFactory; this.sqlSessionProxy = (SqlSession) Proxy.newProxyInstance( SqlSessionFactory.class.getClassLoader(), new Class[] { SqlSession.class }, new SqlSessionInterceptor()); } @Override public Serializable save(String entityName, Map<String, Object> data) throws PersistenceException { return sqlSessionProxy.save(entityName, data); } @Override public <T> Serializable save(String entityName, T object) throws PersistenceException { return sqlSessionProxy.save(entityName, object); } @Override public void update(String entityName, Map<String, Object> data) throws PersistenceException { sqlSessionProxy.update(entityName, data); } @Override public <T> void update(String entityName, T object) throws PersistenceException { sqlSessionProxy.update(entityName, object); } @Override public void delete(String entityName, Object id) throws PersistenceException { sqlSessionProxy.delete(entityName, id); } @Override public Map<String, Object> getData(String entityName, Object id) throws PersistenceException { return sqlSessionProxy.getData(entityName, id); } @Override public <T> T get(Class<T> clazz, String entityName, Object id) throws PersistenceException { return sqlSessionProxy.get(clazz, entityName, id); } @Override public Connection getConnection() { return sqlSessionProxy.getConnection(); } @Override public Map<String, Object> getData(String entityName, Object id, boolean excludeChildEntity) throws PersistenceException { return sqlSessionProxy.getData(entityName, id, excludeChildEntity); } @Override public <T> T get(Class<T> clazz, String entityName, Object id, boolean excludeChildEntity) throws PersistenceException { return sqlSessionProxy.get(clazz, entityName, id, excludeChildEntity); } @Override public Map<String, Object> getData(String entityName, String propertyName, Object uniqueValue) throws PersistenceException { return sqlSessionProxy.getData(entityName, propertyName, uniqueValue); } @Override public Map<String, Object> getData(String entityName, String propertyName, Object uniqueValue, boolean excludeChildEntity) throws PersistenceException { return sqlSessionProxy.getData(entityName, propertyName, uniqueValue, excludeChildEntity); } @Override public <T> T get(Class<T> clazz, String entityName, String propertyName, Object uniqueValue) throws PersistenceException { return sqlSessionProxy.get(clazz, entityName, propertyName, uniqueValue); } @Override public <T> T get(Class<T> clazz, String entityName, String propertyName, Object uniqueValue, boolean excludeChildEntity) throws PersistenceException { return sqlSessionProxy.get(clazz, entityName, propertyName, uniqueValue, excludeChildEntity); } @Override public Map<String, Object> getData(String entityName, Object id, String... loadChildEntity) throws PersistenceException { return sqlSessionProxy.getData(entityName, id, loadChildEntity); } @Override public <T> T get(Class<T> clazz, String entityName, Object id, String... loadChildEntity) throws PersistenceException { return sqlSessionProxy.get(clazz, entityName, id, loadChildEntity); } @Override public int executeSql(String sql, Object... para) throws PersistenceException { return sqlSessionProxy.executeSql(sql, para); } @Override public int[] executeArraySql(List<String> sqls) throws PersistenceException { return sqlSessionProxy.executeArraySql(sqls); } @Override public void batchSaveData(String entityName, List<Map<String, Object>> data) throws PersistenceException { sqlSessionProxy.batchSaveData(entityName, data); } @Override public void batchUpdateData(String entityName, List<Map<String, Object>> data) throws PersistenceException { sqlSessionProxy.batchUpdateData(entityName, data); } @Override public <T> void batchSaveClazz(String entityName, List<T> data) throws PersistenceException { sqlSessionProxy.batchSaveClazz(entityName, data); } @Override public <T> void batchUpdateClazz(String entityName, List<T> data) throws PersistenceException { sqlSessionProxy.batchUpdateClazz(entityName, data); } @Override public String[] searchOneRow(String sql, Object... para) throws PersistenceException { return sqlSessionProxy.searchOneRow(sql, para); } @Override public List<String[]> getSearchResult(String sql, Object... para) throws PersistenceException { return sqlSessionProxy.getSearchResult(sql, para); } @Override public List<Object[]> getSearchResult(String sql, String[] objectTypes, Object... para) throws PersistenceException { return sqlSessionProxy.getSearchResult(sql, objectTypes, para); } @Override public List<Map<String, Object>> getSearchResult(String sql, String[] objectTypes, String[] keyAlias, Object... para) throws PersistenceException { return sqlSessionProxy.getSearchResult(sql, objectTypes, keyAlias, para); } @Override public <T> List<T> getSearchResult(Class<T> clazz, String sql, Map<String, String> specialType, Object... para) throws PersistenceException { return sqlSessionProxy.getSearchResult(clazz, sql, specialType, para); } @Override public long getFunctionNumber(String sql, Object... para) throws PersistenceException { return sqlSessionProxy.getFunctionNumber(sql, para); } @Override public void setAutoCommit(boolean commit) { throw new UnsupportedOperationException("Manual set auto commit is not allowed over a Spring managed SqlSession"); } @Override public boolean isAutoCommit() { throw new UnsupportedOperationException("Manual get auto commit is not allowed over a Spring managed SqlSession"); } @Override public void commit() { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } @Override public void rollback() { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } @Override public void close() { throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession"); } private class SqlSessionInterceptor implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { SqlSession sqlSession = SqlSessionUtils.getSqlSession(sqlSessionFactory); try { Object result = method.invoke(sqlSession, args); return result; } catch (Exception e) { log.error("invoke", e); throw SqlSessionUtils.unwrapThrowable(e); } } } }
31.789256
117
0.748993
b2e0099b776a233abae75dc055a32b5233f263d2
2,811
package com.kshrd.derphsar_api.rest.message; import org.apache.ibatis.annotations.Select; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component public class MessageProperties { private MessageSource source; private MessageSourceAccessor accessor; @Autowired public void setSource(MessageSource source) { this.source = source; } @PostConstruct private void init(){ accessor = new MessageSourceAccessor(source); } public String selected(String resourceName){ return accessor.getMessage("message.selected", new Object[] {resourceName}); } public String selectedOne(String resourceName){ return accessor.getMessage("message.selected-one", new Object[] {resourceName}); } public String inserted(String resourceName){ return accessor.getMessage("message.inserted", new Object[] {resourceName}); } public String updated(String resourceName){ return accessor.getMessage("message.updated", new Object[] {resourceName}); } public String deleted(String resourceName){ return accessor.getMessage("message.deleted", new Object[] {resourceName}); } public String insertError(String resourceName){ return accessor.getMessage("message.insert-error", new Object[] {resourceName}); } public String updateError(String resourceName){ return accessor.getMessage("message.update-error", new Object[] {resourceName}); } public String deleteError(String resourceName){ return accessor.getMessage("message.delete-error", new Object[] {resourceName}); } public String hasEmptyValue(String resourceName){ return accessor.getMessage("message.has-empty-value", new Object[] {resourceName}); } public String hasNoRecords(String resourceName){ return accessor.getMessage("message.has-no-records", new Object[] {resourceName}); } public String hasNullValue(String resourceName){ return accessor.getMessage("message.has-null-value", new Object[] {resourceName}); } public String hasNoRecord(String resourceName){ return accessor.getMessage("message.has-no-record", new Object[] {resourceName}); } public String loginSuccess(String resourceName){ return accessor.getMessage("message.login-success", new Object[] {resourceName}); } }
28.979381
65
0.666311
e6fb0c5ef735fbe99eb42dd639cac6316a1109bc
1,247
package cn.chuanwise.xiaoming.group; import cn.chuanwise.common.api.OriginalTagMarkable; import cn.chuanwise.common.util.CollectionUtil; import cn.chuanwise.common.util.StringUtil; import cn.chuanwise.common.util.Tags; import cn.chuanwise.xiaoming.object.XiaoMingObject; import cn.chuanwise.xiaoming.contact.contact.GroupContact; import java.util.Optional; import java.util.Set; public interface GroupInformation extends XiaoMingObject, OriginalTagMarkable { long getCode(); default String getCodeString() { return String.valueOf(getCode()); } String getAlias(); void setAlias(String alias); default String getAliasAndCode() { final String alias = getAlias(); if (StringUtil.isEmpty(alias)) { return getCodeString(); } else { return alias + "(" + getCodeString() + ")"; } } default Optional<GroupContact> getContact() { return getXiaoMingBot().getContactManager().getGroupContact(getCode()); } @Override default Set<String> getOriginalTags() { return originalTagsOf(getCode()); } static Set<String> originalTagsOf(long group) { return CollectionUtil.asSet(String.valueOf(group), Tags.ALL); } }
27.711111
79
0.692863
079747aef3b4bc9e68311157197f9d066567ec6d
4,830
/* * Copyright 2009-2019 TMD-Maker Project <https://www.tmdmaker.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tmdmaker.ui.views.properties.gef3; import org.eclipse.gef.commands.Command; import org.eclipse.gef.commands.CommandStack; import org.eclipse.ui.views.properties.ComboBoxPropertyDescriptor; import org.eclipse.ui.views.properties.IPropertyDescriptor; import org.eclipse.ui.views.properties.PropertyDescriptor; import org.eclipse.ui.views.properties.TextPropertyDescriptor; import org.tmdmaker.core.model.AbstractEntityModel; import org.tmdmaker.core.model.CombinationTable; import org.tmdmaker.core.model.Detail; import org.tmdmaker.core.model.Laputa; import org.tmdmaker.core.model.MappingList; import org.tmdmaker.core.model.MultivalueOrEntity; import org.tmdmaker.core.model.RecursiveTable; import org.tmdmaker.core.model.SubsetEntity; import org.tmdmaker.core.model.VirtualEntity; import org.tmdmaker.ui.Messages; import org.tmdmaker.ui.views.properties.gef3.commands.PropertyChangeCommand; /** * Abstract class of entity model's property source. */ public class AbstractEntityModelPropertySource extends AbstractPropertySource { protected static final String[] IMPLEMENT_LABELS = { Messages.Implementation, Messages.NotToImplement }; protected static final int IMPLEMENTATION_INDEX = 0; protected static final int NOT_IMPLEMEN_INDEX = 1; protected static final String IMPLEMENT = "notImplement"; //$NON-NLS-1$ protected static final String ENTITY_TYPE = "entityType"; //$NON-NLS-1$ protected static final String IMPLEMENT_NAME = "implementName"; //$NON-NLS-1$ protected static final String NAME = "name"; //$NON-NLS-1$ protected AbstractEntityModel model; protected IPropertyDescriptor[] propertyFields; public AbstractEntityModelPropertySource(CommandStack commandStack, AbstractEntityModel model) { super(commandStack); this.model = model; this.propertyFields = buildPropertyDescriptors(); } @Override public Object getEditableValue() { return this.model; } protected IPropertyDescriptor[] buildPropertyDescriptors() { return new IPropertyDescriptor[] { new TextPropertyDescriptor(NAME, Messages.ModelName), new TextPropertyDescriptor(IMPLEMENT_NAME, Messages.ImplementationName), new PropertyDescriptor(ENTITY_TYPE, Messages.EntityType), new ComboBoxPropertyDescriptor(IMPLEMENT, Messages.Implementation, IMPLEMENT_LABELS), }; } @Override public IPropertyDescriptor[] getPropertyDescriptors() { return propertyFields; } @Override public Object getPropertyValue(Object id) { if (id.equals(ENTITY_TYPE)) { return getEntityType(); } if (id.equals(IMPLEMENT)) { return model.isNotImplement() ? NOT_IMPLEMEN_INDEX : IMPLEMENTATION_INDEX; } return getPropertyValue(this.model, id.toString()); } protected Object getEntityType() { if (model instanceof CombinationTable) { return Messages.CombinationTable; } else if (model instanceof SubsetEntity) { return Messages.Subset; } else if (model instanceof VirtualEntity) { return Messages.VirtualEntity; } else if (model instanceof MultivalueOrEntity) { return Messages.MultivalueOR; } else if (model instanceof Detail) { return Messages.MultivalueAndDetail; } else if (model instanceof RecursiveTable) { return Messages.RecursiveTable; } else if (model instanceof MappingList) { return Messages.MappingList; } else if (model instanceof Laputa) { return Messages.Laputa; } return null; } @Override protected Command createSetPropertyCommand(Object id, Object value) { String propertyName = id.toString(); Object oldValue = getPropertyValue(this.model, propertyName); oldValue = handleOldPropertyValue(propertyName, oldValue, value); value = handleSetNewPropertyValue(propertyName, oldValue, value); return new PropertyChangeCommand(this.model, propertyName, oldValue, value); } protected Object handleOldPropertyValue(String propertyName, Object oldValue, Object newValue) { if (propertyName.equals(IMPLEMENT)) { return this.model.isNotImplement(); } return oldValue; } protected Object handleSetNewPropertyValue(String propertyName, Object oldValue, Object newValue) { if (propertyName.equals(IMPLEMENT)) { return ((Integer) newValue) == NOT_IMPLEMEN_INDEX; } return newValue; } }
37.153846
105
0.780331
5d395e4567b5fcfc9624426434f09ec0ac8b259b
43
hi this shakeer starting with git classs.
21.5
42
0.790698
55a6f996a4857a903d759b4910bffc917286b086
52,380
/* * ProGuardCORE -- library to process Java bytecode. * * Copyright (c) 2002-2020 Guardsquare NV * * 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 proguard.classfile.visitor; import proguard.classfile.*; import proguard.classfile.attribute.*; import proguard.classfile.attribute.annotation.*; import proguard.classfile.attribute.annotation.target.*; import proguard.classfile.attribute.annotation.target.visitor.*; import proguard.classfile.attribute.annotation.visitor.*; import proguard.classfile.attribute.module.*; import proguard.classfile.attribute.module.visitor.*; import proguard.classfile.attribute.preverification.*; import proguard.classfile.attribute.preverification.visitor.*; import proguard.classfile.attribute.visitor.*; import proguard.classfile.constant.*; import proguard.classfile.constant.visitor.ConstantVisitor; import proguard.classfile.instruction.*; import proguard.classfile.instruction.visitor.InstructionVisitor; import proguard.classfile.util.*; import proguard.util.Processable; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; /** * This {@link ClassVisitor} prints out the complete internal * structure of the classes it visits. * * @author Eric Lafortune */ public class ClassPrinter implements ClassVisitor, ConstantVisitor, MemberVisitor, AttributeVisitor, BootstrapMethodInfoVisitor, RecordComponentInfoVisitor, InnerClassesInfoVisitor, ExceptionInfoVisitor, StackMapFrameVisitor, VerificationTypeVisitor, LineNumberInfoVisitor, ParameterInfoVisitor, LocalVariableInfoVisitor, LocalVariableTypeInfoVisitor, RequiresInfoVisitor, ExportsInfoVisitor, OpensInfoVisitor, ProvidesInfoVisitor, AnnotationVisitor, TypeAnnotationVisitor, TargetInfoVisitor, LocalVariableTargetElementVisitor, TypePathInfoVisitor, ElementValueVisitor, InstructionVisitor { private static final String INDENTATION = " "; private final PrintWriter pw; private int indentation; /** * Creates a new ClassPrinter that prints to the standard output. */ public ClassPrinter() { // We're using the system's default character encoding for writing to // the standard output. this(new PrintWriter(System.out, true)); } /** * Creates a new ClassPrinter that prints to the given writer. */ public ClassPrinter(PrintWriter printWriter) { pw = printWriter; } // Implementations for ClassVisitor. @Override public void visitAnyClass(Clazz clazz) { throw new UnsupportedOperationException(this.getClass().getName() + " does not support " + clazz.getClass().getName()); } @Override public void visitProgramClass(ProgramClass programClass) { println("_____________________________________________________________________"); println(processingInfo(programClass) + " " + "Program class: " + programClass.getName()); indent(); println("Superclass: " + programClass.getSuperName()); println("Major version: 0x" + Integer.toHexString(ClassUtil.internalMajorClassVersion(programClass.u4version))); println("Minor version: 0x" + Integer.toHexString(ClassUtil.internalMinorClassVersion(programClass.u4version))); println(" = target " + ClassUtil.externalClassVersion(programClass.u4version)); println("Access flags: 0x" + Integer.toHexString(programClass.u2accessFlags)); println(" = " + ClassUtil.externalClassAccessFlags(programClass.u2accessFlags) + ((programClass.u2accessFlags & (AccessConstants.ENUM | AccessConstants.INTERFACE | AccessConstants.MODULE)) == 0 ? "class " : "") + ClassUtil.externalClassName(programClass.getName()) + (programClass.u2superClass == 0 ? "" : " extends " + ClassUtil.externalClassName(programClass.getSuperName()))); outdent(); println(); println("Interfaces (count = " + programClass.u2interfacesCount + "):"); indent(); programClass.interfaceConstantsAccept(this); outdent(); println(); println("Constant Pool (count = " + programClass.u2constantPoolCount + "):"); indent(); programClass.constantPoolEntriesAccept(this); outdent(); println(); println("Fields (count = " + programClass.u2fieldsCount + "):"); indent(); programClass.fieldsAccept(this); outdent(); println(); println("Methods (count = " + programClass.u2methodsCount + "):"); indent(); programClass.methodsAccept(this); outdent(); println(); println("Class file attributes (count = " + programClass.u2attributesCount + "):"); indent(); programClass.attributesAccept(this); outdent(); println(); } @Override public void visitLibraryClass(LibraryClass libraryClass) { println("_____________________________________________________________________"); println(processingInfo(libraryClass) + " " + "Library class: " + libraryClass.getName()); indent(); println("Superclass: " + libraryClass.getSuperName()); println("Access flags: 0x" + Integer.toHexString(libraryClass.u2accessFlags)); println(" = " + ClassUtil.externalClassAccessFlags(libraryClass.u2accessFlags) + ((libraryClass.u2accessFlags & (AccessConstants.ENUM | AccessConstants.INTERFACE | AccessConstants.MODULE)) == 0 ? "class " : "") + ClassUtil.externalClassName(libraryClass.getName()) + (libraryClass.getSuperName() == null ? "" : " extends " + ClassUtil.externalClassName(libraryClass.getSuperName()))); outdent(); println(); println("Interfaces (count = " + libraryClass.interfaceClasses.length + "):"); for (int index = 0; index < libraryClass.interfaceClasses.length; index++) { Clazz interfaceClass = libraryClass.interfaceClasses[index]; if (interfaceClass != null) { println(" + " + interfaceClass.getName()); } } println("Fields (count = " + libraryClass.fields.length + "):"); libraryClass.fieldsAccept(this); println("Methods (count = " + libraryClass.methods.length + "):"); libraryClass.methodsAccept(this); } // Implementations for ConstantVisitor. public void visitIntegerConstant(Clazz clazz, IntegerConstant integerConstant) { println(processingInfo(integerConstant) + " Integer [" + integerConstant.getValue() + "]"); } public void visitLongConstant(Clazz clazz, LongConstant longConstant) { println(processingInfo(longConstant) + " Long [" + longConstant.getValue() + "]"); } public void visitFloatConstant(Clazz clazz, FloatConstant floatConstant) { println(processingInfo(floatConstant) + " Float [" + floatConstant.getValue() + "]"); } public void visitDoubleConstant(Clazz clazz, DoubleConstant doubleConstant) { println(processingInfo(doubleConstant) + " Double [" + doubleConstant.getValue() + "]"); } public void visitPrimitiveArrayConstant(Clazz clazz, PrimitiveArrayConstant primitiveArrayConstant) { println(processingInfo(primitiveArrayConstant) + " PrimitiveArray " + primitiveArrayConstant.getPrimitiveType() + "[" + primitiveArrayConstant.getLength() + "]"); } public void visitStringConstant(Clazz clazz, StringConstant stringConstant) { println(processingInfo(stringConstant) + " String [" + stringConstant.getString(clazz) + "]"); } public void visitUtf8Constant(Clazz clazz, Utf8Constant utf8Constant) { println(processingInfo(utf8Constant) + " Utf8 [" + utf8Constant.getString() + "]"); } public void visitDynamicConstant(Clazz clazz, DynamicConstant dynamicConstant) { println(processingInfo(dynamicConstant) + " Dynamic [bootstrap method index = " + dynamicConstant.u2bootstrapMethodAttributeIndex + "]:"); indent(); clazz.constantPoolEntryAccept(dynamicConstant.u2nameAndTypeIndex, this); outdent(); } public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant) { println(processingInfo(invokeDynamicConstant) + " InvokeDynamic [bootstrap method index = " + invokeDynamicConstant.u2bootstrapMethodAttributeIndex + "]:"); indent(); clazz.constantPoolEntryAccept(invokeDynamicConstant.u2nameAndTypeIndex, this); outdent(); } public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant) { println(processingInfo(methodHandleConstant) + " MethodHandle [kind = " + methodHandleConstant.u1referenceKind + "]:"); indent(); clazz.constantPoolEntryAccept(methodHandleConstant.u2referenceIndex, this); outdent(); } public void visitModuleConstant(Clazz clazz, ModuleConstant moduleConstant) { println(processingInfo(moduleConstant) + " Module [" + moduleConstant.getName(clazz) + "]"); } public void visitPackageConstant(Clazz clazz, PackageConstant packageConstant) { println(processingInfo(packageConstant) + " Package [" + packageConstant.getName(clazz) + "]"); } public void visitFieldrefConstant(Clazz clazz, FieldrefConstant fieldrefConstant) { println(processingInfo(fieldrefConstant) + " Fieldref [" + clazz.getClassName(fieldrefConstant.u2classIndex) + "." + clazz.getName(fieldrefConstant.u2nameAndTypeIndex) + " " + clazz.getType(fieldrefConstant.u2nameAndTypeIndex) + "]"); } public void visitInterfaceMethodrefConstant(Clazz clazz, InterfaceMethodrefConstant interfaceMethodrefConstant) { println(processingInfo(interfaceMethodrefConstant) + " InterfaceMethodref [" + clazz.getClassName(interfaceMethodrefConstant.u2classIndex) + "." + clazz.getName(interfaceMethodrefConstant.u2nameAndTypeIndex) + " " + clazz.getType(interfaceMethodrefConstant.u2nameAndTypeIndex) + "]"); } public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant) { println(processingInfo(methodrefConstant) + " Methodref [" + clazz.getClassName(methodrefConstant.u2classIndex) + "." + clazz.getName(methodrefConstant.u2nameAndTypeIndex) + " " + clazz.getType(methodrefConstant.u2nameAndTypeIndex) + "]"); } public void visitClassConstant(Clazz clazz, ClassConstant classConstant) { println(processingInfo(classConstant) + " Class [" + classConstant.getName(clazz) + "]"); } public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant) { println(processingInfo(methodTypeConstant) + " MethodType [" + methodTypeConstant.getType(clazz) + "]"); } public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant) { println(processingInfo(nameAndTypeConstant) + " NameAndType [" + nameAndTypeConstant.getName(clazz) + " " + nameAndTypeConstant.getType(clazz) + "]"); } // Implementations for MemberVisitor. public void visitProgramField(ProgramClass programClass, ProgramField programField) { println(processingInfo(programField) + " " + "Field: " + programField.getName(programClass) + " " + programField.getDescriptor(programClass)); indent(); println("Access flags: 0x" + Integer.toHexString(programField.u2accessFlags)); println(" = " + ClassUtil.externalFullFieldDescription(programField.u2accessFlags, programField.getName(programClass), programField.getDescriptor(programClass))); visitMember(programClass, programField); outdent(); } public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod) { println(processingInfo(programMethod) + " " + "Method: " + programMethod.getName(programClass) + programMethod.getDescriptor(programClass)); indent(); println("Access flags: 0x" + Integer.toHexString(programMethod.u2accessFlags)); println(" = " + ClassUtil.externalFullMethodDescription(programClass.getName(), programMethod.u2accessFlags, programMethod.getName(programClass), programMethod.getDescriptor(programClass))); visitMember(programClass, programMethod); outdent(); } private void visitMember(ProgramClass programClass, ProgramMember programMember) { if (programMember.u2attributesCount > 0) { println("Class member attributes (count = " + programMember.u2attributesCount + "):"); programMember.attributesAccept(programClass, this); } } public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField) { println(processingInfo(libraryField) + " " + "Field: " + libraryField.getName(libraryClass) + " " + libraryField.getDescriptor(libraryClass)); indent(); println("Access flags: 0x" + Integer.toHexString(libraryField.u2accessFlags)); println(" = " + ClassUtil.externalFullFieldDescription(libraryField.u2accessFlags, libraryField.getName(libraryClass), libraryField.getDescriptor(libraryClass))); outdent(); } public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod) { println(processingInfo(libraryMethod) + " " + "Method: " + libraryMethod.getName(libraryClass) + " " + libraryMethod.getDescriptor(libraryClass)); indent(); println("Access flags: 0x" + Integer.toHexString(libraryMethod.u2accessFlags)); println(" = " + ClassUtil.externalFullMethodDescription(libraryClass.getName(), libraryMethod.u2accessFlags, libraryMethod.getName(libraryClass), libraryMethod.getDescriptor(libraryClass))); outdent(); } // Implementations for AttributeVisitor. // Note that attributes are typically only referenced once, so we don't // test if they are marked already. public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute) { println(processingInfo(unknownAttribute) + " Unknown attribute (" + unknownAttribute.getAttributeName(clazz) + ")"); } public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute) { println(processingInfo(bootstrapMethodsAttribute) + " Bootstrap methods attribute (count = " + bootstrapMethodsAttribute.u2bootstrapMethodsCount + "):"); indent(); bootstrapMethodsAttribute.bootstrapMethodEntriesAccept(clazz, this); outdent(); } public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute) { println(processingInfo(sourceFileAttribute) + " Source file attribute:"); indent(); clazz.constantPoolEntryAccept(sourceFileAttribute.u2sourceFileIndex, this); outdent(); } public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute) { println(processingInfo(sourceDirAttribute) + " Source dir attribute:"); indent(); clazz.constantPoolEntryAccept(sourceDirAttribute.u2sourceDirIndex, this); outdent(); } public void visitSourceDebugExtensionAttribute(Clazz clazz, SourceDebugExtensionAttribute sourceDebugExtensionAttribute) { println(processingInfo(sourceDebugExtensionAttribute) + " Source debug extension attribute: " + new String(sourceDebugExtensionAttribute.info, StandardCharsets.UTF_8)); } public void visitRecordAttribute(Clazz clazz, RecordAttribute recordAttributeAttribute) { println(processingInfo(recordAttributeAttribute) + " Record attribute (count = " + recordAttributeAttribute.u2componentsCount + "):"); indent(); recordAttributeAttribute.componentsAccept(clazz, this); outdent(); } public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute) { println(processingInfo(innerClassesAttribute) + " Inner classes attribute (count = " + innerClassesAttribute.u2classesCount + "):"); indent(); innerClassesAttribute.innerClassEntriesAccept(clazz, this); outdent(); } public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute) { println(processingInfo(enclosingMethodAttribute) + " Enclosing method attribute:"); indent(); clazz.constantPoolEntryAccept(enclosingMethodAttribute.u2classIndex, this); if (enclosingMethodAttribute.u2nameAndTypeIndex != 0) { clazz.constantPoolEntryAccept(enclosingMethodAttribute.u2nameAndTypeIndex, this); } outdent(); } public void visitNestHostAttribute(Clazz clazz, NestHostAttribute nestHostAttribute) { println(processingInfo(nestHostAttribute) + " Nest host attribute:"); indent(); clazz.constantPoolEntryAccept(nestHostAttribute.u2hostClassIndex, this); outdent(); } public void visitNestMembersAttribute(Clazz clazz, NestMembersAttribute nestMembersAttribute) { println(processingInfo(nestMembersAttribute) + " Nest members attribute:"); indent(); nestMembersAttribute.memberClassConstantsAccept(clazz, this); outdent(); } public void visitPermittedSubclassesAttribute(Clazz clazz, PermittedSubclassesAttribute permittedSubclassesAttribute) { println(processingInfo(permittedSubclassesAttribute) + " Permitted subclasses attribute:"); indent(); permittedSubclassesAttribute.permittedSubclassConstantsAccept(clazz, this); outdent(); } public void visitModuleAttribute(Clazz clazz, ModuleAttribute moduleAttribute) { println(processingInfo(moduleAttribute) + " Module attribute:"); indent(); clazz.constantPoolEntryAccept(moduleAttribute.u2moduleNameIndex, this); println("Access flags: 0x" + Integer.toHexString(moduleAttribute.u2moduleFlags) + " = " + ClassUtil.externalModuleAccessFlags(moduleAttribute.u2moduleFlags)); if (moduleAttribute.u2moduleVersionIndex != 0) { clazz.constantPoolEntryAccept(moduleAttribute.u2moduleVersionIndex, this); } println("Requires:"); moduleAttribute.requiresAccept(clazz, this); println("Exports:"); moduleAttribute.exportsAccept(clazz, this); println("Opens:"); moduleAttribute.opensAccept(clazz, this); println("Uses services:"); for (int index = 0; index < moduleAttribute.u2usesCount; index++) { clazz.constantPoolEntryAccept(moduleAttribute.u2uses[index], this); } println("Provides services:"); moduleAttribute.providesAccept(clazz, this); outdent(); } public void visitModuleMainClassAttribute(Clazz clazz, ModuleMainClassAttribute moduleMainClassAttribute) { println(processingInfo(moduleMainClassAttribute) + " Module main class attribute:"); indent(); clazz.constantPoolEntryAccept(moduleMainClassAttribute.u2mainClass, this); outdent(); } public void visitModulePackagesAttribute(Clazz clazz, ModulePackagesAttribute modulePackagesAttribute) { println(processingInfo(modulePackagesAttribute) + " Module packages attribute (count = " + modulePackagesAttribute.u2packagesCount + "):"); indent(); modulePackagesAttribute.packagesAccept(clazz, this); outdent(); } public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute) { println(processingInfo(deprecatedAttribute) + " Deprecated attribute"); } public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute) { println(processingInfo(syntheticAttribute) + " Synthetic attribute"); } public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute) { println(processingInfo(signatureAttribute) + " Signature attribute:"); indent(); clazz.constantPoolEntryAccept(signatureAttribute.u2signatureIndex, this); outdent(); } public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute) { println(processingInfo(constantValueAttribute) + " Constant value attribute:"); clazz.constantPoolEntryAccept(constantValueAttribute.u2constantValueIndex, this); } public void visitMethodParametersAttribute(Clazz clazz, Method method, MethodParametersAttribute methodParametersAttribute) { println(processingInfo(methodParametersAttribute) + " Method parameters attribute (count = " + methodParametersAttribute.u1parametersCount + "):"); indent(); methodParametersAttribute.parametersAccept(clazz, method, this); outdent(); } public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute) { println(processingInfo(exceptionsAttribute) + " Exceptions attribute (count = " + exceptionsAttribute.u2exceptionIndexTableLength + "):"); indent(); exceptionsAttribute.exceptionEntriesAccept(clazz, this); outdent(); } public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute) { println(processingInfo(codeAttribute) + " Code attribute instructions (code length = "+ codeAttribute.u4codeLength + ", locals = "+ codeAttribute.u2maxLocals + ", stack = "+ codeAttribute.u2maxStack + "):"); indent(); codeAttribute.instructionsAccept(clazz, method, this); println("Code attribute exceptions (count = " + codeAttribute.u2exceptionTableLength + "):"); codeAttribute.exceptionsAccept(clazz, method, this); println("Code attribute attributes (attribute count = " + codeAttribute.u2attributesCount + "):"); codeAttribute.attributesAccept(clazz, method, this); outdent(); } public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute) { println(processingInfo(codeAttribute) + " Stack map attribute (count = "+ stackMapAttribute.u2stackMapFramesCount + "):"); indent(); stackMapAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this); outdent(); } public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute) { println(processingInfo(codeAttribute) + " Stack map table attribute (count = "+ stackMapTableAttribute.u2stackMapFramesCount + "):"); indent(); stackMapTableAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this); outdent(); } public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute) { println(processingInfo(lineNumberTableAttribute) + " Line number table attribute (count = " + lineNumberTableAttribute.u2lineNumberTableLength + "):"); indent(); lineNumberTableAttribute.lineNumbersAccept(clazz, method, codeAttribute, this); outdent(); } public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute) { println(processingInfo(localVariableTableAttribute) + " Local variable table attribute (count = " + localVariableTableAttribute.u2localVariableTableLength + "):"); indent(); localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this); outdent(); } public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute) { println(processingInfo(localVariableTypeTableAttribute) + " Local variable type table attribute (count = "+ localVariableTypeTableAttribute.u2localVariableTypeTableLength + "):"); indent(); localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this); outdent(); } public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute) { println(processingInfo(runtimeVisibleAnnotationsAttribute) + " Runtime visible annotations attribute:"); indent(); runtimeVisibleAnnotationsAttribute.annotationsAccept(clazz, this); outdent(); } public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute) { println(processingInfo(runtimeInvisibleAnnotationsAttribute) + " Runtime invisible annotations attribute:"); indent(); runtimeInvisibleAnnotationsAttribute.annotationsAccept(clazz, this); outdent(); } public void visitRuntimeVisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute) { println(processingInfo(runtimeVisibleParameterAnnotationsAttribute) + " Runtime visible parameter annotations attribute (parameter count = " + runtimeVisibleParameterAnnotationsAttribute.u1parametersCount + "):"); indent(); runtimeVisibleParameterAnnotationsAttribute.annotationsAccept(clazz, method, this); outdent(); } public void visitRuntimeInvisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute) { println(processingInfo(runtimeInvisibleParameterAnnotationsAttribute) + " Runtime invisible parameter annotations attribute (parameter count = " + runtimeInvisibleParameterAnnotationsAttribute.u1parametersCount + "):"); indent(); runtimeInvisibleParameterAnnotationsAttribute.annotationsAccept(clazz, method, this); outdent(); } public void visitRuntimeVisibleTypeAnnotationsAttribute(Clazz clazz, RuntimeVisibleTypeAnnotationsAttribute runtimeVisibleTypeAnnotationsAttribute) { println(processingInfo(runtimeVisibleTypeAnnotationsAttribute) + " Runtime visible type annotations attribute"); indent(); runtimeVisibleTypeAnnotationsAttribute.typeAnnotationsAccept(clazz, this); outdent(); } public void visitRuntimeInvisibleTypeAnnotationsAttribute(Clazz clazz, RuntimeInvisibleTypeAnnotationsAttribute runtimeInvisibleTypeAnnotationsAttribute) { println(processingInfo(runtimeInvisibleTypeAnnotationsAttribute) + " Runtime invisible type annotations attribute"); indent(); runtimeInvisibleTypeAnnotationsAttribute.typeAnnotationsAccept(clazz, this); outdent(); } public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute) { println(processingInfo(annotationDefaultAttribute) + " Annotation default attribute:"); indent(); annotationDefaultAttribute.defaultValueAccept(clazz, this); outdent(); } // Implementations for BootstrapMethodInfoVisitor. public void visitBootstrapMethodInfo(Clazz clazz, BootstrapMethodInfo bootstrapMethodInfo) { println(processingInfo(bootstrapMethodInfo) + " BootstrapMethodInfo (argument count = " + bootstrapMethodInfo.u2methodArgumentCount+ "):"); indent(); clazz.constantPoolEntryAccept(bootstrapMethodInfo.u2methodHandleIndex, this); bootstrapMethodInfo.methodArgumentsAccept(clazz, this); outdent(); } // Implementations for RecordComponentInfoVisitor. public void visitRecordComponentInfo(Clazz clazz, RecordComponentInfo recordComponentInfo) { println(processingInfo(recordComponentInfo) + " RecordComponentInfo: " + recordComponentInfo.getName(clazz) + " " + recordComponentInfo.getDescriptor(clazz)); indent(); if (recordComponentInfo.u2attributesCount > 0) { println("Record component attributes (attribute count = " + recordComponentInfo.u2attributesCount + "):"); recordComponentInfo.attributesAccept(clazz, this); } outdent(); } // Implementations for InnerClassesInfoVisitor. public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo) { println(processingInfo(innerClassesInfo) + " InnerClassesInfo:"); indent(); println("Access flags: 0x" + Integer.toHexString(innerClassesInfo.u2innerClassAccessFlags) + " = " + ClassUtil.externalClassAccessFlags(innerClassesInfo.u2innerClassAccessFlags)); innerClassesInfo.innerClassConstantAccept(clazz, this); innerClassesInfo.outerClassConstantAccept(clazz, this); innerClassesInfo.innerNameConstantAccept(clazz, this); outdent(); } // Implementations for InstructionVisitor. public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) { println(instruction.toString(clazz, offset)); } public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction) { println(constantInstruction.toString(clazz, offset)); } public void visitTableSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TableSwitchInstruction tableSwitchInstruction) { println(tableSwitchInstruction.toString(clazz, offset)); indent(); int[] jumpOffsets = tableSwitchInstruction.jumpOffsets; for (int index = 0; index < jumpOffsets.length; index++) { int jumpOffset = jumpOffsets[index]; println(Integer.toString(tableSwitchInstruction.lowCase + index) + ": offset = " + jumpOffset + ", target = " + (offset + jumpOffset)); } int defaultOffset = tableSwitchInstruction.defaultOffset; println("default: offset = " + defaultOffset + ", target = "+ (offset + defaultOffset)); outdent(); } public void visitLookUpSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LookUpSwitchInstruction lookUpSwitchInstruction) { println(lookUpSwitchInstruction.toString(clazz, offset)); indent(); int[] cases = lookUpSwitchInstruction.cases; int[] jumpOffsets = lookUpSwitchInstruction.jumpOffsets; for (int index = 0; index < jumpOffsets.length; index++) { int jumpOffset = jumpOffsets[index]; println(Integer.toString(cases[index]) + ": offset = " + jumpOffset + ", target = " + (offset + jumpOffset)); } int defaultOffset = lookUpSwitchInstruction.defaultOffset; println("default: offset = " + defaultOffset + ", target = "+ (offset + defaultOffset)); outdent(); } // Implementations for ExceptionInfoVisitor. public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo) { println(processingInfo(exceptionInfo) + " ExceptionInfo (" + exceptionInfo.u2startPC + " -> " + exceptionInfo.u2endPC + ": " + exceptionInfo.u2handlerPC + "):"); if (exceptionInfo.u2catchType != 0) { clazz.constantPoolEntryAccept(exceptionInfo.u2catchType, this); } } // Implementations for StackMapFrameVisitor. public void visitSameZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameZeroFrame sameZeroFrame) { println(processingInfo(sameZeroFrame) + " [" + offset + "]" + " Var: ..., Stack: (empty)"); } public void visitSameOneFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameOneFrame sameOneFrame) { print(processingInfo(sameOneFrame) + " [" + offset + "]" + " Var: ..., Stack: "); sameOneFrame.stackItemAccept(clazz, method, codeAttribute, offset, this); println(); } public void visitLessZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LessZeroFrame lessZeroFrame) { println(processingInfo(lessZeroFrame) + " [" + offset + "]" + " Var: -" + lessZeroFrame.choppedVariablesCount + ", Stack: (empty)"); } public void visitMoreZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, MoreZeroFrame moreZeroFrame) { print(processingInfo(moreZeroFrame) + " [" + offset + "]" + " Var: ..."); moreZeroFrame.additionalVariablesAccept(clazz, method, codeAttribute, offset, this); pw.println(", Stack: (empty)"); } public void visitFullFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FullFrame fullFrame) { print(processingInfo(fullFrame) + " [" + offset + "]" + " Var: "); fullFrame.variablesAccept(clazz, method, codeAttribute, offset, this); pw.print(", Stack: "); fullFrame.stackAccept(clazz, method, codeAttribute, offset, this); println(); } // Implementations for VerificationTypeVisitor. public void visitIntegerType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, IntegerType integerType) { pw.print("[i]"); } public void visitFloatType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FloatType floatType) { pw.print("[f]"); } public void visitLongType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LongType longType) { pw.print("[l]"); } public void visitDoubleType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, DoubleType doubleType) { pw.print("[d]"); } public void visitTopType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TopType topType) { pw.print("[T]"); } public void visitObjectType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ObjectType objectType) { pw.print("[a:" + clazz.getClassName(objectType.u2classIndex) + "]"); } public void visitNullType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, NullType nullType) { pw.print("[n]"); } public void visitUninitializedType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, UninitializedType uninitializedType) { pw.print("[u:" + uninitializedType.u2newInstructionOffset + "]"); } public void visitUninitializedThisType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, UninitializedThisType uninitializedThisType) { pw.print("[u:this]"); } // Implementations for LineNumberInfoVisitor. public void visitLineNumberInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberInfo lineNumberInfo) { println("[" + lineNumberInfo.u2startPC + "] -> line " + lineNumberInfo.u2lineNumber + (lineNumberInfo.getSource() == null ? "" : " [" + lineNumberInfo.getSource() + "]")); } // Implementations for ParameterInfoVisitor. public void visitParameterInfo(Clazz clazz, Method method, int parameterIndex, ParameterInfo parameterInfo) { println("p" + parameterIndex + ": Access flags: 0x" + Integer.toHexString(parameterInfo.u2accessFlags) + " = " + ClassUtil.externalParameterAccessFlags(parameterInfo.u2accessFlags) + " [" + (parameterInfo.u2nameIndex == 0 ? "" : parameterInfo.getName(clazz)) + "]"); } // Implementations for LocalVariableInfoVisitor. public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo) { println("v" + localVariableInfo.u2index + ": " + localVariableInfo.u2startPC + " -> " + (localVariableInfo.u2startPC + localVariableInfo.u2length) + " [" + localVariableInfo.getDescriptor(clazz) + " " + localVariableInfo.getName(clazz) + "]"); } // Implementations for LocalVariableTypeInfoVisitor. public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo) { println("v" + localVariableTypeInfo.u2index + ": " + localVariableTypeInfo.u2startPC + " -> " + (localVariableTypeInfo.u2startPC + localVariableTypeInfo.u2length) + " [" + localVariableTypeInfo.getSignature(clazz) + " " + localVariableTypeInfo.getName(clazz) + "]"); } // Implementations for RequiresInfoVisitor public void visitRequiresInfo(Clazz clazz, RequiresInfo requiresInfo) { println(processingInfo(requiresInfo) + " RequiresInfo:"); indent(); requiresInfo.moduleAccept(clazz, this); println("Access flags: 0x" + Integer.toHexString(requiresInfo.u2requiresFlags) + " = " + ClassUtil.externalRequiresAccessFlags(requiresInfo.u2requiresFlags)); requiresInfo.versionAccept(clazz, this); outdent(); } // Implementations for ExportsInfoVisitor public void visitExportsInfo(Clazz clazz, ExportsInfo exportsInfo) { println(processingInfo(exportsInfo) + " ExportsInfo (targets count = " + exportsInfo.u2exportsToCount + "):"); indent(); exportsInfo.packageAccept(clazz, this); println("Access flags: 0x" + Integer.toHexString(exportsInfo.u2exportsFlags) + " = " + ClassUtil.externalExportsAccessFlags(exportsInfo.u2exportsFlags)); for (int index = 0; index < exportsInfo.u2exportsToCount; index++) { clazz.constantPoolEntryAccept(exportsInfo.u2exportsToIndex[index], this); } outdent(); } // Implementations for ExportsOpensVisitor public void visitOpensInfo(Clazz clazz, OpensInfo opensInfo) { println(processingInfo(opensInfo) + " OpensInfo (targets count = " + opensInfo.u2opensToCount + "):"); indent(); clazz.constantPoolEntryAccept(opensInfo.u2opensIndex, this); println("Access flags: 0x" + Integer.toHexString(opensInfo.u2opensFlags) + " = " + ClassUtil.externalOpensAccessFlags(opensInfo.u2opensFlags)); for (int index = 0; index < opensInfo.u2opensToCount; index++) { clazz.constantPoolEntryAccept(opensInfo.u2opensToIndex[index], this); } outdent(); } // Implementations for ProvidesInfoVisitor public void visitProvidesInfo(Clazz clazz, ProvidesInfo providesInfo) { println(processingInfo(providesInfo) + " ProvidesInfo (with count = " + providesInfo.u2providesWithCount + "):"); indent(); clazz.constantPoolEntryAccept(providesInfo.u2providesIndex, this); for (int index = 0; index < providesInfo.u2providesWithCount; index++) { clazz.constantPoolEntryAccept(providesInfo.u2providesWithIndex[index], this); } outdent(); } // Implementations for AnnotationVisitor. public void visitAnnotation(Clazz clazz, Annotation annotation) { println(processingInfo(annotation) + " Annotation [" + annotation.getType(clazz) + "]:"); indent(); annotation.elementValuesAccept(clazz, this); outdent(); } public void visitAnnotation(Clazz clazz, Method method, int parameterIndex, Annotation annotation) { println(processingInfo(annotation) + " Parameter #"+parameterIndex+", annotation [" + annotation.getType(clazz) + "]:"); indent(); annotation.elementValuesAccept(clazz, this); outdent(); } // Implementations for TypeAnnotationVisitor. public void visitTypeAnnotation(Clazz clazz, TypeAnnotation typeAnnotation) { println(processingInfo(typeAnnotation) + " Type annotation [" + typeAnnotation.getType(clazz) + "]:"); indent(); typeAnnotation.targetInfoAccept(clazz, this); println("Type path (count = " + typeAnnotation.typePath.length + "):"); indent(); typeAnnotation.typePathInfosAccept(clazz, this); outdent(); typeAnnotation.elementValuesAccept(clazz, this); outdent(); } // Implementations for TargetInfoVisitor. public void visitTypeParameterTargetInfo(Clazz clazz, TypeAnnotation typeAnnotation, TypeParameterTargetInfo typeParameterTargetInfo) { println("Target (type = 0x" + Integer.toHexString(typeParameterTargetInfo.u1targetType) + "): Parameter #" + typeParameterTargetInfo.u1typeParameterIndex); } public void visitSuperTypeTargetInfo(Clazz clazz, TypeAnnotation typeAnnotation, SuperTypeTargetInfo superTypeTargetInfo) { println("Target (type = 0x" + Integer.toHexString(superTypeTargetInfo.u1targetType) + "): " + (superTypeTargetInfo.u2superTypeIndex == SuperTypeTargetInfo.EXTENDS_INDEX ? "super class" : "interface #" + superTypeTargetInfo.u2superTypeIndex)); } public void visitTypeParameterBoundTargetInfo(Clazz clazz, TypeAnnotation typeAnnotation, TypeParameterBoundTargetInfo typeParameterBoundTargetInfo) { println("Target (type = 0x" + Integer.toHexString(typeParameterBoundTargetInfo.u1targetType) + "): parameter #" + typeParameterBoundTargetInfo.u1typeParameterIndex + ", bound #" + typeParameterBoundTargetInfo.u1boundIndex); } public void visitEmptyTargetInfo(Clazz clazz, Member member, TypeAnnotation typeAnnotation, EmptyTargetInfo emptyTargetInfo) { println("Target (type = 0x" + Integer.toHexString(emptyTargetInfo.u1targetType) + ")"); } public void visitFormalParameterTargetInfo(Clazz clazz, Method method, TypeAnnotation typeAnnotation, FormalParameterTargetInfo formalParameterTargetInfo) { println("Target (type = 0x" + Integer.toHexString(formalParameterTargetInfo.u1targetType) + "): formal parameter #" + formalParameterTargetInfo.u1formalParameterIndex); } public void visitThrowsTargetInfo(Clazz clazz, Method method, TypeAnnotation typeAnnotation, ThrowsTargetInfo throwsTargetInfo) { println("Target (type = 0x" + Integer.toHexString(throwsTargetInfo.u1targetType) + "): throws #" + throwsTargetInfo.u2throwsTypeIndex); } public void visitLocalVariableTargetInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, LocalVariableTargetInfo localVariableTargetInfo) { println("Target (type = 0x" + Integer.toHexString(localVariableTargetInfo.u1targetType) + "): local variables (count = " + localVariableTargetInfo.u2tableLength + ")"); indent(); localVariableTargetInfo.targetElementsAccept(clazz, method, codeAttribute, typeAnnotation, this); outdent(); } public void visitCatchTargetInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, CatchTargetInfo catchTargetInfo) { println("Target (type = 0x" + Integer.toHexString(catchTargetInfo.u1targetType) + "): catch #" + catchTargetInfo.u2exceptionTableIndex); } public void visitOffsetTargetInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, OffsetTargetInfo offsetTargetInfo) { println("Target (type = 0x" + Integer.toHexString(offsetTargetInfo.u1targetType) + "): offset " + offsetTargetInfo.u2offset); } public void visitTypeArgumentTargetInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, TypeArgumentTargetInfo typeArgumentTargetInfo) { println("Target (type = 0x" + Integer.toHexString(typeArgumentTargetInfo.u1targetType) + "): offset " + typeArgumentTargetInfo.u2offset + ", type argument " + typeArgumentTargetInfo.u1typeArgumentIndex); } // Implementations for TypePathInfoVisitor. public void visitTypePathInfo(Clazz clazz, TypeAnnotation typeAnnotation, TypePathInfo typePathInfo) { println("kind = " + typePathInfo.u1typePathKind + ", argument index = " + typePathInfo.u1typeArgumentIndex); } // Implementations for LocalVariableTargetElementVisitor. public void visitLocalVariableTargetElement(Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, LocalVariableTargetInfo localVariableTargetInfo, LocalVariableTargetElement localVariableTargetElement) { println("v" + localVariableTargetElement.u2index + ": " + localVariableTargetElement.u2startPC + " -> " + (localVariableTargetElement.u2startPC + localVariableTargetElement.u2length)); } // Implementations for ElementValueVisitor. public void visitConstantElementValue(Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue) { println(processingInfo(constantElementValue) + " Constant element value [" + (constantElementValue.u2elementNameIndex == 0 ? "(default)" : constantElementValue.getMethodName(clazz)) + " '" + constantElementValue.u1tag + "']"); indent(); clazz.constantPoolEntryAccept(constantElementValue.u2constantValueIndex, this); outdent(); } public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue) { println(processingInfo(enumConstantElementValue) + " Enum constant element value [" + (enumConstantElementValue.u2elementNameIndex == 0 ? "(default)" : enumConstantElementValue.getMethodName(clazz)) + ", " + enumConstantElementValue.getTypeName(clazz) + ", " + enumConstantElementValue.getConstantName(clazz) + "]"); } public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue) { println(processingInfo(classElementValue) + " Class element value [" + (classElementValue.u2elementNameIndex == 0 ? "(default)" : classElementValue.getMethodName(clazz)) + ", " + classElementValue.getClassName(clazz) + "]"); } public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue) { println(processingInfo(annotationElementValue) + " Annotation element value [" + (annotationElementValue.u2elementNameIndex == 0 ? "(default)" : annotationElementValue.getMethodName(clazz)) + "]:"); indent(); annotationElementValue.annotationAccept(clazz, this); outdent(); } public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue) { println(processingInfo(arrayElementValue) + " Array element value [" + (arrayElementValue.u2elementNameIndex == 0 ? "(default)" : arrayElementValue.getMethodName(clazz)) + "]:"); indent(); arrayElementValue.elementValuesAccept(clazz, annotation, this); outdent(); } // Small utility methods. private void indent() { indentation++; } private void outdent() { indentation--; } private void println(String string) { print(string); println(); } private void print(String string) { for (int index = 0; index < indentation; index++) { pw.print(INDENTATION); } pw.print(string); } private void println() { pw.println(); } private String processingInfo(Processable processable) { return processable.getProcessingInfo() == null ? "-" : "+"; } }
36.299376
239
0.658801
1786cdb0870126e673c89a2c65a1e90213dc1098
12,741
/** * Copyright 2016 Twitter. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.graphjet.hashing; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import com.google.common.collect.Lists; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public final class IntToIntPairMapConcurrentTestHelper { private IntToIntPairMapConcurrentTestHelper() { // Utility class } /** * Helper class to allow reading from a {@link IntToIntPairHashMap} in a controlled manner. */ public static class IntToIntPairHashMapReader implements Runnable { private final IntToIntPairHashMap intToIntPairHashMap; private final CountDownLatch startSignal; private final CountDownLatch doneSignal; private final int key; private final int sleepTimeInMilliseconds; private AtomicLong bothValues = new AtomicLong(0); public IntToIntPairHashMapReader( IntToIntPairHashMap intToIntPairHashMap, CountDownLatch startSignal, CountDownLatch doneSignal, int key, int sleepTimeInMilliseconds) { this.intToIntPairHashMap = intToIntPairHashMap; this.startSignal = startSignal; this.doneSignal = doneSignal; this.key = key; this.sleepTimeInMilliseconds = sleepTimeInMilliseconds; } @Override public void run() { try { startSignal.await(); Thread.sleep(sleepTimeInMilliseconds); } catch (InterruptedException e) { throw new RuntimeException("Unable to start waiting: ", e); } bothValues.set(intToIntPairHashMap.getBothValues(key)); doneSignal.countDown(); } public long getBothValues() { return bothValues.get(); } } /** * Helper class to allow writing to a {@link IntToIntPairHashMap} in a controlled manner. */ public static class IntToIntPairHashMapWriter implements Runnable { private final IntToIntPairHashMap intToIntPairHashMap; private final MapWriterInfo mapWriterInfo; public IntToIntPairHashMapWriter( IntToIntPairHashMap intToIntPairHashMap, MapWriterInfo mapWriterInfo) { this.intToIntPairHashMap = intToIntPairHashMap; this.mapWriterInfo = mapWriterInfo; } @Override public void run() { for (int i = 0; i < mapWriterInfo.keysAndValues.length / 3; i++) { try { mapWriterInfo.startSignal.await(); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while waiting: ", e); } intToIntPairHashMap.put( mapWriterInfo.keysAndValues[i * 3], mapWriterInfo.keysAndValues[i * 3 + 1], mapWriterInfo.keysAndValues[i * 3 + 2] ); mapWriterInfo.doneSignal.countDown(); } } } /** * This class encapsulates information needed by a writer to add to a map. */ public static class MapWriterInfo { private final int[] keysAndValues; private final CountDownLatch startSignal; private final CountDownLatch doneSignal; public MapWriterInfo( int[] keysAndValues, CountDownLatch startSignal, CountDownLatch doneSignal) { this.keysAndValues = keysAndValues; this.startSignal = startSignal; this.doneSignal = doneSignal; } } /** * This helper method sets up a concurrent read-write situation with a single writer and multiple * readers that access the same underlying map, and tests for correct recovery of entries after * every single entry insertion, via the use of latches. This helps test write flushing after * every entry insertion. * * @param map is the underlying {@link IntToIntPairHashMap} * @param keyTestInfo contains all the keysAndValues to add to the map */ public static void testConcurrentReadWrites( IntToIntPairHashMap map, IntToIntPairMapTestHelper.KeyTestInfo keyTestInfo) { // start reading after first edge is written int numReaders = keyTestInfo.keysAndValues.length / 3; ExecutorService executor = Executors.newFixedThreadPool(numReaders + 1); // single writer List<CountDownLatch> readerStartLatches = Lists.newArrayListWithCapacity(numReaders); List<CountDownLatch> readerDoneLatches = Lists.newArrayListWithCapacity(numReaders); List<IntToIntPairHashMapReader> readers = Lists.newArrayListWithCapacity(numReaders); for (int i = 0; i < numReaders; i++) { CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch doneLatch = new CountDownLatch(1); // Each time, get edges for the node added in the previous step IntToIntPairHashMapReader mapReader = new IntToIntPairHashMapReader( map, startLatch, doneLatch, keyTestInfo.keysAndValues[i * 3], 0); readers.add(mapReader); executor.submit(mapReader); readerStartLatches.add(startLatch); readerDoneLatches.add(doneLatch); } /** * The start/done latches achieve the following execution order: writer, then reader 1, then * writer, then reader 2, and so on. As a concrete example, suppose we have two readers and a * writer, then the start/done latches are used as follows: * Initial latches state: * s1 = 1, d1 = 1 * s2 = 1, d2 = 1 * Execution steps: * - writer writes edge 1, sets s1 = 0 and waits on d1 * - reader 1 reads since s1 == 0 and sets d1 = 0 * - writer writes edge 2, sets s2 = 0 and waits on d2 * - reader 2 reads since s2 == 0 and sets d2 = 0 */ for (int i = 0; i < numReaders; i++) { // Start writing immediately at first, but then write an edge once the reader finishes reading // the previous edge CountDownLatch startLatch = (i > 0) ? readerDoneLatches.get(i - 1) : new CountDownLatch(0); // Release the next reader CountDownLatch doneLatch = readerStartLatches.get(i); int[] keyList = new int[] { keyTestInfo.keysAndValues[i * 3], keyTestInfo.keysAndValues[i * 3 + 1], keyTestInfo.keysAndValues[i * 3] + 2 }; executor.submit( new IntToIntPairHashMapWriter(map, new MapWriterInfo(keyList, startLatch, doneLatch))); } // Wait for all the processes to finish and then confirm that they did what they worked as // expected try { readerDoneLatches.get(numReaders - 1).await(); } catch (InterruptedException e) { throw new RuntimeException("Execution for last reader was interrupted: ", e); } // Check that all readers' read info is consistent with the map for (IntToIntPairHashMapReader reader : readers) { long value = map.getBothValues(reader.key); assertTrue(reader.getBothValues() == value); } } /** * This helper method sets up a concurrent read-write situation with a single writer and multiple * readers that access the same underlying intToIntPairHashMap, and tests for correct entry access * during simultaneous entry reads. This helps test read consistency during arbitrary points of * inserting entries. Note that the exact read-write sequence here is non-deterministic and would * vary depending on the machine, but the hope is that given the large number of readers the reads * would be done at many different points of edge insertion. The test itself checks only for * partial correctness (it could have false positives) so this should only be used as a supplement * to other testing. * * @param intToIntPairHashMap is the underlying {@link IntToIntPairHashMap} * @param defaultValue is the default bothValues returned by the map for a non-entry * @param numReaders is the number of reader threads to use * @param numKeysToInsert is the number of keysAndValues to insert in the map * @param random is the random number generator to use for generating the * keysAndValues */ public static void testRandomConcurrentReadWriteThreads( IntToIntPairHashMap intToIntPairHashMap, int defaultValue, int numReaders, int numKeysToInsert, Random random) { int maxWaitingTimeForThreads = 20; // in milliseconds CountDownLatch readersDoneLatch = new CountDownLatch(numReaders); // First, construct a random set of edges to insert in the graph IntToIntPairMapTestHelper.KeyTestInfo keyTestInfo = IntToIntPairMapTestHelper.generateRandomKeys(random, numKeysToInsert); int[] keysAndValues = keyTestInfo.keysAndValues; List<IntToIntPairHashMapReader> readers = Lists.newArrayListWithCapacity(numReaders); // Create a bunch of readers that'll read from the map at random for (int i = 0; i < numReaders; i++) { readers.add(new IntToIntPairHashMapReader( intToIntPairHashMap, new CountDownLatch(0), readersDoneLatch, keysAndValues[i * 3], random.nextInt(maxWaitingTimeForThreads))); } // Create a single writer that will insert these edges in random order List<Integer> keyIndices = Lists.newArrayListWithCapacity(numKeysToInsert); for (int i = 0; i < numKeysToInsert; i++) { keyIndices.add(i); } Collections.shuffle(keyIndices, random); int[] shuffledKeysAndValues = new int[numKeysToInsert * 3]; for (int i = 0; i < numKeysToInsert; i++) { int index = keyIndices.get(i); shuffledKeysAndValues[i * 3] = keysAndValues[index * 3]; shuffledKeysAndValues[i * 3 + 1] = keysAndValues[index * 3 + 1]; shuffledKeysAndValues[i * 3 + 2] = keysAndValues[index * 3 + 2]; } CountDownLatch writerDoneLatch = new CountDownLatch(keyIndices.size()); MapWriterInfo mapWriterInfo = new MapWriterInfo(shuffledKeysAndValues, new CountDownLatch(0), writerDoneLatch); ExecutorService executor = Executors.newFixedThreadPool(numReaders + 1); // single writer List<Callable<Integer>> allThreads = Lists.newArrayListWithCapacity(numReaders + 1); // First, we add the writer allThreads.add(Executors.callable( new IntToIntPairHashMapWriter(intToIntPairHashMap, mapWriterInfo), 1)); // then the readers for (int i = 0; i < numReaders; i++) { allThreads.add(Executors.callable(readers.get(i), 1)); } // these will execute in some non-deterministic order Collections.shuffle(allThreads, random); // Wait for all the processes to finish try { List<Future<Integer>> results = executor.invokeAll(allThreads, 10, TimeUnit.SECONDS); for (Future<Integer> result : results) { assertTrue(result.isDone()); assertEquals(1, result.get().intValue()); } } catch (InterruptedException e) { throw new RuntimeException("Execution for a thread was interrupted: ", e); } catch (ExecutionException e) { throw new RuntimeException("Execution issue in an executor thread: ", e.fillInStackTrace()); } // confirm that these worked as expected try { readersDoneLatch.await(); writerDoneLatch.await(); } catch (InterruptedException e) { throw new RuntimeException("Execution for last reader was interrupted: ", e); } // Check that all readers' read info is consistent with the map for (IntToIntPairHashMapReader reader : readers) { long expectedValue = intToIntPairHashMap.getBothValues(reader.key); // either the entry was not written at the time it was read or we get the right bothValues assertTrue( "Expected either " + defaultValue + " or " + expectedValue + ", but found " + reader.getBothValues() + " for key " + reader.key, (reader.getBothValues() == defaultValue) || (reader.getBothValues() == expectedValue) ); } } }
40.576433
100
0.693509
548d352a21ffeb881afb98e56bdc5f8a840c6f26
1,773
/* Copyright 2013 The jeo project. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jeo.data; import java.io.IOException; import io.jeo.Pending; import io.jeo.vector.Feature; import io.jeo.filter.Filter; import io.jeo.filter.cql.CQL; import io.jeo.filter.cql.ParseException; import io.jeo.vector.VectorQuery; import io.jeo.vector.VectorDataset; @Pending public class VectorDataView { VectorDataset data; public VectorDataView(VectorDataset data) { this.data = data; } public long count() throws IOException { return data.count(new VectorQuery()); } public Feature first() throws IOException { return find(new VectorQuery()); } public Feature find(String cql) throws IOException, ParseException { return find(CQL.parse(cql)); } public Feature find(Filter filter) throws IOException { return find(new VectorQuery().filter(filter)); } public Feature find(VectorQuery query) throws IOException { Cursor<Feature> c = data.read(query.limit(1)); try { if (c.hasNext()) { return c.next(); } } finally { c.close(); } return null; } }
27.276923
75
0.668923
b37da8e80c67fd537402b24d1e466b24ea9ae69e
1,159
package com.crossoverjie.algorithm; import java.util.TreeMap; public class Array_215FindKthLargest { public static void main(String[] args) { System.out.println(findKthLargest(AlgorithUtil.c, 2)); } public static int findKthLargest(int[] nums, int n) { TreeMap<Integer, Integer> treeMap = new TreeMap<>(); for (int i = 0; i < nums.length; i++) { Integer count = treeMap.get(nums[i]); if (null != count) { treeMap.put(nums[i], ++count); } else { treeMap.put(nums[i], 1); } } for (int c = treeMap.get(treeMap.lastKey()); c < n; c += treeMap.get(treeMap.lastKey())) { treeMap.remove(treeMap.lastKey()); } return treeMap.lastKey(); } public static int findKthLargest2(int[] nums, int n) { int l = -1;//左侧的元素小于K [0-l] int r = nums.length;//右侧的元素小于K [0-l] for (int i = 0; i < n; i++) { } return 0; } private static void swap(int[] nums, int i, int k) { int temp = nums[i]; nums[i] = nums[k]; nums[k] = temp; } }
26.340909
98
0.522865
19c962ac3ce73b1fc08ff7586d137a0d006d1152
1,293
package org.joder.stock.core.service.strategy.turtle; import org.joder.stock.core.domain.StockData; import org.joder.stock.core.domain.StockProcess; import org.joder.stock.core.service.strategy.StockStrategyProcess; import java.util.function.ToDoubleBiFunction; /** * @author Joder 2020/8/15 15:01 */ public abstract class AbstractTurtleStockStrategyProcess implements StockStrategyProcess { /** * 最近的最低点 * * @param process 条件 * @param dayNum 天数 * @return dayNum日最低点 */ protected double findMin(StockProcess process, int index, int dayNum) { return find(process, index, dayNum, Double.MAX_VALUE, Math::min); } protected double finMax(StockProcess process, int index, int dayNum) { return find(process, index, dayNum, Double.MIN_VALUE, Math::max); } private double find(StockProcess process, int index, int dayNum, double defultValue, ToDoubleBiFunction<Double, Double> func) { double ret = defultValue; for (int i = 0; i < dayNum; i++) { StockData stock = process.getStock(index - i); if (stock == null) { return ret; } else { ret = func.applyAsDouble(ret, stock.getClose()); } } return ret; } }
29.386364
131
0.645785
1811edeb7e46639c10c1cfa5f3a7e702dde07f5a
2,562
package com.neopixl.pushpixl; import android.content.Context; import com.neopixl.pushpixl.exception.IncorrectConfigurationException; import com.neopixl.pushpixl.listener.UserPreferencesListener; import com.neopixl.pushpixl.model.PushConfiguration; import com.neopixl.pushpixl.model.UserPreferences; import com.neopixl.pushpixl.testtools.MockedContext; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Created by Florian ALONSO on 5/2/18. * For Neopixl */ public class PushpixlManagerTest { PushConfiguration configuration; Context context; @Before public void setUp() throws Exception { configuration = new PushConfiguration( "50465c62-a3e5-4bfb-9aa6-528395d3800e", "208b23a5-3aed-49fe-b999-f2ece02656dc" , "neopixl") .debug(true) .autoRefresh(true) .askBatteryOptimization(true); context = new MockedContext(); } @Test public void publicMethods() throws Exception { // Catch-all test to find API-breaking changes. assertNotNull(PushpixlManager.class.getDeclaredMethod("getInstance")); assertNotNull(PushpixlManager.class.getDeclaredMethod("getConfiguration")); assertNotNull(PushpixlManager.class.getDeclaredConstructor(Context.class, PushConfiguration.class)); assertNotNull(PushpixlManager.class.getDeclaredMethod("install", Context.class, PushConfiguration.class)); assertNotNull(PushpixlManager.class.getDeclaredMethod("updateUserPreferences", UserPreferences.class, UserPreferencesListener.class)); assertNotNull(PushpixlManager.class.getDeclaredMethod("updateUserPreferences", UserPreferences.class)); assertNotNull(PushpixlManager.class.getDeclaredMethod("reloadUserPreferences", UserPreferencesListener.class)); assertNotNull(PushpixlManager.class.getDeclaredMethod("reloadUserPreferences")); } @Test public void installCreateAnInstance() throws Exception { PushpixlManager manager = PushpixlManager.install(context, configuration); assertEquals("The instance should be the same", manager, PushpixlManager.getInstance()); String alias = "user123"; } @Test(expected = IncorrectConfigurationException.class) public void configurationInstallIsMandatory() throws Exception { PushpixlManager.getInstance(); } }
37.130435
108
0.720921
fb52d651414958905ffcbdc9562eead9ec996cd1
2,152
package info.bitrich.xchangestream.okcoin.dto.marketdata; import com.fasterxml.jackson.annotation.JsonProperty; import java.math.BigDecimal; public class FutureTicker { private Long contractId; // 合约ID private Integer unitAmount; // 合约价值 private BigDecimal holdAmount; // 当前持仓量 private BigDecimal limitHigh; // 最高买入限制价格 private BigDecimal limitLow; // 最低卖出限制价格 private BigDecimal buy; // 买一价格 private BigDecimal sell; // 卖一价格 private BigDecimal last; // 最新成交价 private BigDecimal high; // 24小时最高价格 private BigDecimal low; // 24小时最低价格 private BigDecimal vol; // 24小时成交量 public FutureTicker( @JsonProperty("contractId") final Long contractId, @JsonProperty("unitAmount") final Integer unitAmount, @JsonProperty("hold_amount") final BigDecimal holdAmount, @JsonProperty("limitHigh") final BigDecimal limitHigh, @JsonProperty("limitLow") final BigDecimal limitLow, @JsonProperty("buy") final BigDecimal buy, @JsonProperty("sell") final BigDecimal sell, @JsonProperty("last") final BigDecimal last, @JsonProperty("high") final BigDecimal high, @JsonProperty("low") final BigDecimal low, @JsonProperty("vol") final BigDecimal vol) { this.contractId = contractId; this.unitAmount = unitAmount; this.holdAmount = holdAmount; this.limitHigh = limitHigh; this.limitLow = limitLow; this.buy = buy; this.sell = sell; this.last = last; this.high = high; this.low = low; this.vol = vol; } public Long getContractId() { return contractId; } public Integer getUnitAmount() { return unitAmount; } public BigDecimal getHoldAmount() { return holdAmount; } public BigDecimal getLimitHigh() { return limitHigh; } public BigDecimal getLimitLow() { return limitLow; } public BigDecimal getBuy() { return buy; } public BigDecimal getSell() { return sell; } public BigDecimal getLast() { return last; } public BigDecimal getHigh() { return high; } public BigDecimal getLow() { return low; } public BigDecimal getVol() { return vol; } }
23.391304
63
0.687732
4cea802f75dcfcb3366641e369ed3be2abfe5e2d
3,060
/* * TypeMatcher.java * * This source file is part of the FoundationDB open source project * * Copyright 2015-2018 Apple Inc. and the FoundationDB project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apple.foundationdb.record.query.plan.temp.matchers; import com.apple.foundationdb.annotation.API; import javax.annotation.Nonnull; import java.util.stream.Stream; /** * A <code>BindingMatcher</code> matches a data structure while binding variables to parts of the data structure. * * <p> * Extreme care should be taken when implementing <code>BindingMatcher</code>s, since it can be very delicate. * In particular, matchers may (or may not) be reused between successive rule calls and should be stateless. * Additionally, implementors of <code>TypedMatcher</code> must use the (default) reference equals. * </p> * @param <T> the bindable type that this matcher binds to */ @API(API.Status.EXPERIMENTAL) public class TypedMatcher<T> implements BindingMatcher<T> { @Nonnull private final Class<T> bindableClass; public TypedMatcher(@Nonnull final Class<T> bindableClass) { this.bindableClass = bindableClass; } @Nonnull @Override public Class<T> getRootClass() { return bindableClass; } /** * Attempt to match this matcher against the given expression reference. * Note that implementations of {@code matchWith()} should only attempt to match the given root with this planner * expression or attempt to access the members of the given reference. * * @param outerBindings preexisting bindings to be used by the matcher * @param in the bindable we attempt to match * @return a stream of {@link PlannerBindings} containing the matched bindings, or an empty stream is no match was found */ @Nonnull @Override public Stream<PlannerBindings> bindMatchesSafely(@Nonnull PlannerBindings outerBindings, @Nonnull T in) { return Stream.of(PlannerBindings.from(this, in)); } @Override public String explainMatcher(@Nonnull final Class<?> atLeastType, @Nonnull final String boundId, @Nonnull final String indentation) { if (getRootClass().isAssignableFrom(atLeastType)) { return "case _ => success "; } else { return "case _: " + getRootClass().getSimpleName() + " => success "; } } @Nonnull public static <T> TypedMatcher<T> typed(@Nonnull final Class<T> bindableClass) { return new TypedMatcher<>(bindableClass); } }
37.317073
137
0.712092
ca3e3e7bbd8e8f2d091878adb31d0ba6f17db192
5,292
package com.yilian.luckypurchase.adapter; import android.content.ComponentName; import android.content.Intent; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.jakewharton.rxbinding2.view.RxView; import com.orhanobut.logger.Logger; import com.yilian.luckypurchase.R; import com.yilian.luckypurchase.activity.LuckyRecordActivity; import com.yilian.luckypurchase.activity.LuckyUnboxingActivity; import com.yilian.luckypurchase.utils.DateUtils; import com.yilian.mylibrary.Constants; import com.yilian.mylibrary.GlideUtil; import com.yilian.mylibrary.PreferenceUtils; import com.yilian.networkingmodule.entity.SnatchShowListEntity; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.TimeUnit; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; /** * @author Created by LYQ on 2017/10/28. */ public class SnatchShowListAdapter extends BaseQuickAdapter<SnatchShowListEntity.SnatchInfoBean, BaseViewHolder> { private int posX, posY, curPosX, curPosY; public SnatchShowListAdapter(int layoutId) { super(layoutId); } @Override protected void convert(BaseViewHolder helper, final SnatchShowListEntity.SnatchInfoBean item) { ImageView iv = helper.getView(R.id.iv); GlideUtil.showCirImage(mContext, item.photo, iv); RxView.clicks(iv) .throttleFirst(1, TimeUnit.SECONDS) .subscribe(new Consumer<Object>() { @Override public void accept(@NonNull Object o) throws Exception { if (PreferenceUtils.readBoolConfig(Constants.SPKEY_STATE, mContext, false)) { Intent intent = new Intent(mContext, LuckyRecordActivity.class); intent.putExtra("userId", item.userId); mContext.startActivity(intent); } else { Intent intent = new Intent(); intent.setComponent(new ComponentName(mContext, "com.yilian.loginmodule.LeFenPhoneLoginActivity")); mContext.startActivity(intent); } } }); helper.setText(R.id.tv_name, TextUtils.isEmpty(item.userName) ? "暂无昵称" : item.userName); helper.setText(R.id.tv_number, item.snatchIssue + "期"); helper.setText(R.id.tv_date, DateUtils.luckyTimeNoYearNoSecond(item.time)); TextView tvSku = helper.getView(R.id.tv_goods_sku); tvSku.setText(Html.fromHtml("<font color=\"#999999\">商品信息: </font><font color=\"#333333\">" + item.snatchName + "</font>")); TextView tvContent = helper.getView(R.id.tv_remark); if (TextUtils.isEmpty(item.commentContent)) { tvContent.setVisibility(View.GONE); } else { tvContent.setVisibility(View.VISIBLE); tvContent.setText(item.commentContent); } RecyclerView imageRecycle = helper.getView(R.id.horizontal_recycleView); imageRecycle.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: posX = (int) event.getRawX(); posY = (int) event.getRawY(); break; case MotionEvent.ACTION_MOVE: curPosX = (int) event.getRawX(); curPosY = (int) event.getRawY(); break; case MotionEvent.ACTION_UP: int x = Math.abs(curPosX - posX); int y = Math.abs(curPosY - posY); Logger.i("2017年11月10日 11:14:56-" + x); Logger.i("2017年11月10日 11:14:56-" + y); if (x < 10 && y < 10) { Intent intent = new Intent(mContext, LuckyUnboxingActivity.class); intent.putExtra("activity_id", item.commentIndex); mContext.startActivity(intent); } else { return false; } break; default: break; } return false; } }); String[] imageUrls = item.commentImages.split(","); Logger.i("imageUerls " + imageUrls.length); LinearLayoutManager layoutManager = new LinearLayoutManager(mContext); layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); imageRecycle.setLayoutManager(layoutManager); imageRecycle.setAdapter(new ImageAdapter(R.layout.lucky_item_show_image, item.commentIndex, new ArrayList<String>(Arrays.asList(imageUrls)))); } }
43.377049
150
0.610166
2b3e65a6819c726180b32607feba1a4bec60d988
1,412
package simpleinvoke.helloworld; import java.io.Serializable; import java.lang.Long; import java.lang.String; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * Generated by Nam. * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SayGoodbyeResponse", propOrder = { "id", "reply" }) @XmlRootElement(name = "sayGoodbyeResponse") public class SayGoodbyeResponse implements Serializable { public static final long serialVersionUID = 1; @XmlAttribute(name = "id") private Long id; @XmlAttribute(name = "reply") private String reply; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getReply() { return reply; } public void setReply(String reply) { this.reply = reply; } public boolean equals(Object object) { if (object == null) return false; if (!object.getClass().isAssignableFrom(this.getClass())) return false; SayGoodbyeResponse other = (SayGoodbyeResponse) object; if (this.getId() == null || other.getId() == null) return this == other; if (this.getId().equals(other.getId())) return false; return true; } public int hashCode() { if (getId() != null) return getId().hashCode(); return 0; } }
21.074627
59
0.713173
997536f80eadc893a5838c8c9fcdc6f8b1ee3d88
6,941
/* * Copyright 2015 Torridity. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tor.tribes.util.js; import de.tor.tribes.types.Attack; import de.tor.tribes.util.ServerSettings; import java.awt.Color; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * @author Charon */ public class AttackScriptWriter { private static Logger logger = LogManager.getLogger("AttackScriptWriter"); public static boolean writeAttackScript(List<Attack> pAttacks, boolean pDrawAttacks, int pLineWidth, boolean pStraightLine, Color pStartColor, Color pEndColor, boolean pShowAttacksInVillageInfo, boolean pShowAttacksOnConfirmPage, boolean pShowAttacksOnCommandPage, boolean pShowAttacksInOverview) { logger.debug("Start writing attack script"); String tmpl = ""; try { logger.debug(" - reading template"); BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream("./templates/scriptShow.tmpl"))); String line = ""; while ((line = r.readLine()) != null) { tmpl += line + "\n"; } r.close(); } catch (Exception e) { logger.error("Failed to read template", e); return false; } logger.debug(" - building data array"); String data = "win.attacks = new Array("; for (Attack a : pAttacks) { //set type String block = "{\n"; switch (a.getType()) { case Attack.NO_TYPE: //block += ","; break; case Attack.CLEAN_TYPE: block += "'type':'axe.png',\n"; break; case Attack.FAKE_TYPE: block += "'type':'fake.png',\n"; break; case Attack.FAKE_DEFF_TYPE: block += "'type':'def_fake.png',\n"; break; case Attack.SNOB_TYPE: block += "'type':'snob.png',\n"; break; case Attack.SUPPORT_TYPE: block += "'type':'def.png',\n"; break; } //set source and target block += "'sourceName':'" + toUnicode(a.getSource().toString()) + "',\n"; block += "'source':" + a.getSource().getId() + ",\n"; block += "'xs':" + a.getSource().getX() + ",\n"; block += "'ys':" + a.getSource().getY() + ",\n"; block += "'target':" + a.getTarget().getId() + ",\n"; block += "'xt':" + a.getTarget().getX() + ",\n"; block += "'yt':" + a.getTarget().getY() + ",\n"; block += "'targetName':'" + toUnicode(a.getTarget().toString()) + "',\n"; //unit block += "'unit':'" + a.getUnit().getPlainName() + ".png',\n"; //times SimpleDateFormat df = null; if (ServerSettings.getSingleton().isMillisArrival()) { df = new SimpleDateFormat("dd.MM.yy HH:mm:ss.SSS"); } else { df = new SimpleDateFormat("dd.MM.yy HH:mm:ss"); } block += "'send':'" + df.format(a.getSendTime()) + "',\n"; block += "'arrive':'" + df.format(a.getArriveTime()) + "',\n"; block += "'expired':" + (long) Math.floor(a.getSendTime().getTime() / 1000.0) + "\n"; block += "},\n"; data += block; } //remove last comma data = data.substring(0, data.length() - 2); data += ");\n"; String param = ""; param += "win.showAttacksInVillageInfo = " + ((pShowAttacksInVillageInfo) ? 1 : 0) + ";\n"; param += "win.showAttacksOnConfirmPage = " + ((pShowAttacksOnConfirmPage) ? 1 : 0) + ";\n"; param += "win.showAttackOnCommandPage = " + ((pShowAttacksOnCommandPage) ? 1 : 0) + ";\n"; param += "win.showAttacksInOverview = " + ((pShowAttacksInOverview) ? 1 : 0) + ";\n"; tmpl = tmpl.replaceAll("\\$\\$DATA_LOCATION", data); tmpl = tmpl.replaceAll("\\$\\$PARAMETER_LOCATION", param); try { logger.debug(" - writing data to 'zz_attack_info.user.js'"); FileWriter f = new FileWriter("./zz_attack_info.user.js"); f.write(tmpl); f.flush(); f.close(); } catch (Exception e) { logger.error("Failed to write script to target file 'attack_info.user.js'", e); return false; } logger.info("Script written successfully"); return true; /*var attacks = new Array({ 'type':0, 'source':111217, 'target':123456, 'unit':0, 'send':'02:00:00', 'arrive':'27.09.2009 12:00:00', 'finished':1255168681 }, { 'type':0, 'source':111217, 'target':123456, 'unit':0, 'send':'27.09.2009 02:00:00', 'arrive':'27.09.2009 12:00:00', 'finished':1255168681 }, { 'type':2, 'source':104232, 'target':123456, 'unit':0, 'send':'27.09.2009 02:00:00', 'arrive':'27.09.2009 12:00:00', 'finished':1255168681 } );*/ } public static String char2Unicode(char c) { StringBuilder sb = new StringBuilder(Integer.toHexString(c)); int len = sb.length(); switch (len) { case 0: sb.insert(0, "\\u0000"); break; case 1: sb.insert(0, "\\u000"); break; case 2: sb.insert(0, "\\u00"); break; case 3: sb.insert(0, "\\u0"); break; case 4: sb.insert(0, "\\u"); } return sb.toString(); } private static String toUnicode(String pString) { String res = ""; for (char c : pString.toCharArray()) { res += "\\" + char2Unicode(c); } return res; } }
34.532338
125
0.508428
e59ab0b4650c0ed4f792575e15d93bd77efe2c9f
5,615
package controller; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import model.GameMode.GameType; import model.MainModel; import utilities.SceneManager; /** * GameSelectorController acts as the controller for the GameSelectorView which * the allows the user to choose the game module they wish to play in: New Zealand, * International, or Practice. * */ public class GameSelectorController { @FXML private Button buttonInfo; @FXML private Button buttonSettings; @FXML private Label labelName; @FXML private Label labelWinnings; @FXML private HBox userDetails; @FXML private ImageView imageLock; @FXML private Button buttonReturn; @FXML private Button buttonNewZealand; @FXML private Button buttonInternational; @FXML private Button buttonPractice; @FXML private Label labelUnlock; @FXML private Button buttonReturnToMain; @FXML private HBox hBox; private MainModel model; /** * Initialize the controller and populate the name, winnings and functions of * user details within the menu as well as the remaining categories to be completed * before unlocking the international section. */ public void initialize() { this.model = MainModel.getMainModel(); if (this.model.getName().getValue() != null) { this.labelName.textProperty().bind(this.model.getName()); if (this.model.getCurrentGameType().equals(GameType.GAMESMODULE)) { this.labelWinnings.textProperty().bind(this.model.getGameWinnings().asString()); } else if (this.model.getCurrentGameType().equals(GameType.INTERNATIONALMODULE)) { this.labelWinnings.textProperty().bind(this.model.getInternationalWinnings().asString()); } else { this.labelWinnings.textProperty().bind(this.model.getPracticeWinnings().asString()); } this.userDetails.setVisible(true); } else { this.userDetails.setVisible(false); } if (this.model.getInternationalUnlocked()) { this.imageLock.setVisible(false); this.buttonInternational.setDisable(false); } // set label to prompt the user to unlock international section if (!this.model.getInternationalUnlocked()) { labelUnlock.setText("COMPLETE " + (2 - this.model.getCompletedCategories()) + " MORE CATEGORIES FROM THE NEW ZEALAND MODULE TO UNLOCK INTERNATIONAL MODULE"); } else { // TODO Some reason this isn't working, user workaround hBox.getChildren().remove(labelUnlock); labelUnlock.setVisible(false); labelUnlock.setPrefWidth(0); labelUnlock.setPrefHeight(0); } } /** * Open the info pop-up window. * * @param e Event that triggered this function */ @FXML private void onClickButtonInfo(Event e) { SceneManager.addStage(getClass().getResource("/view/InfoView.fxml"), e); } /** * Open the game settings pop-up window. * * @param e Event that triggered this function */ @FXML private void onClickButtonSettings(Event e) { SceneManager.addStage(getClass().getResource("/view/SettingsView.fxml"), e); } /** * Navigate to the screen to prompt the user to enter a user name. * * @param e Event that triggered this function */ @FXML private void onClickLabelName(Event e) { SceneManager.changeScene(getClass().getResource("/view/NameView.fxml"), e); } /** * Return to the previous screen which is the main menu. * * @param e Event that triggered this function */ @FXML private void onClickButtonReturn(Event e) { SceneManager.changeScene(getClass().getResource("/view/MainMenuView.fxml"), e); } /** * Navigates to the New Zealand mode of the game. If completed, then the end view is shown * instead. * * @param e Event that triggered this function */ @FXML private void onClickButtonNewZealand(Event e) { this.model.setCurrentGameType(GameType.GAMESMODULE); if (this.model.getAllCompletedGame()) { SceneManager.changeScene(getClass().getResource("/view/EndView.fxml"), e); } else { SceneManager.changeScene(getClass().getResource("/view/PointsPlayView.fxml"), e); } } /** * Navigates to the International mode of the game. If completed, then the end view is shown * instead. * * @param e Event that triggered this function */ @FXML private void onClickButtonInternational(Event e) { this.model.setCurrentGameType(GameType.INTERNATIONALMODULE); if (this.model.getAllCompletedInternational()) { SceneManager.changeScene(getClass().getResource("/view/EndView.fxml"), e); } else { SceneManager.changeScene(getClass().getResource("/view/PointsPlayView.fxml"), e); } } /** * Navigate to PointsPracticeView. If the user has completed all the questions * within the practice game then navigate to the EndView screen instead. * * @param e Event that triggered this function */ @FXML private void onClickButtonPractice(Event e) { this.model.setCurrentGameType(GameType.PRACTICEMODULE); if (this.model.getAllCompletedPractice()) { SceneManager.changeScene(getClass().getResource("/view/EndView.fxml"), e); } else if (this.model.getPracticeQuestions().size() != 0) { SceneManager.changeScene(getClass().getResource("/view/PointsPracticeView.fxml"), e); } else { SceneManager.changeScene(getClass().getResource("/view/CategoryView.fxml"), e); } } /** * Return to the main menu screen. * * @param e Event that triggered this function */ @FXML private void onClickButtonReturnToMain(Event e) { SceneManager.changeScene(getClass().getResource("/view/MainMenuView.fxml"), e); } }
27.660099
94
0.729831
1392656f8e4762e844ee716e77b73fc0f3dfac11
792
package com.chylee.fxiaoke.xjl.event; import com.chylee.fxiaoke.common.event.ResponseEvent; import com.chylee.fxiaoke.xjl.event.data.object.OrderPaymentObj; import com.chylee.fxiaoke.xjl.event.data.object.PaymentObj; import java.util.List; public class HuikuanRespEvent extends ResponseEvent { private PaymentObj paymentObj; private List<OrderPaymentObj> orderPaymentObjs; public PaymentObj getPaymentObj() { return paymentObj; } public void setPaymentObj(PaymentObj paymentObj) { this.paymentObj = paymentObj; } public List<OrderPaymentObj> getOrderPaymentObjs() { return orderPaymentObjs; } public void setOrderPaymentObjs(List<OrderPaymentObj> orderPaymentObjs) { this.orderPaymentObjs = orderPaymentObjs; } }
27.310345
77
0.75
c46061d838225461727708b57f733a40cdf550ee
272
package com.sic.service; import com.sic.entity.ChItemRecord; import com.sic.entity.ChTaskRecord; import java.util.List; public interface ChItemRecordService { List<ChItemRecord> select(ChTaskRecord chTaskRecord); int insert(List<ChItemRecord> chItemRecordList); }
20.923077
55
0.805147
0dd18862a9e65a1a24d6e7fb38d3c2ed61b53c90
1,912
package app.exception.interceptors; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.ejb.SessionContext; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; public class LoggingInterceptor { @Resource private SessionContext sessionContext; @AroundInvoke public Object additionalInvokeForMethod(InvocationContext invocation) throws Exception { StringBuilder sb = new StringBuilder("Wywołanie metody biznesowej " + invocation.getTarget().getClass().getName() + "." + invocation.getMethod().getName()); sb.append("z tożsamością: " + sessionContext.getCallerPrincipal().getName()); try { Object[] parameters = invocation.getParameters(); if (null != parameters) { for (Object param : parameters) { if (param != null) { sb.append(" z parametrem " + param.getClass().getName() + "=" + param.toString()); } else { sb.append(" z parametrem null"); } } } long startTime = System.currentTimeMillis(); Object result = invocation.proceed(); long duration = System.currentTimeMillis() - startTime; sb.append(" czas wykonania " + duration + " ms"); if (result != null) { sb.append(" zwrócono " + result.getClass().getName() + "=" + result.toString()); } else { sb.append(" zwrócono wartość null"); } return result; } catch (Exception ex) { sb.append(" wystapil wyjatek " + ex); throw ex; //ponowne zgloszenie wyjatku } finally { Logger.getGlobal().log(Level.INFO, sb.toString()); } } }
36.769231
106
0.567992
14155cf171c9a07a34315a7d44b11fe15166956f
3,133
/* * Copyright © 2016 Cask Data, 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 co.cask.cdap.logging.gateway.handlers; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.PatternLayout; import co.cask.cdap.api.common.Bytes; import co.cask.cdap.api.dataset.lib.CloseableIterator; import co.cask.cdap.logging.read.LogEvent; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import org.apache.commons.lang.StringEscapeUtils; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * LogReader BodyProducer to encode log events, as text. */ class TextChunkedLogProducer extends AbstractChunkedLogProducer { private final PatternLayout patternLayout; private final boolean escape; private final ChannelBuffer channelBuffer; TextChunkedLogProducer(CloseableIterator<LogEvent> logEventIter, String logPattern, boolean escape) { super(logEventIter); this.escape = escape; ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); LoggerContext loggerContext = rootLogger.getLoggerContext(); patternLayout = new PatternLayout(); patternLayout.setContext(loggerContext); patternLayout.setPattern(logPattern); patternLayout.start(); channelBuffer = ChannelBuffers.dynamicBuffer(BUFFER_BYTES); } @Override public Multimap<String, String> getResponseHeaders() { return ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=utf-8"); } @Override protected ChannelBuffer writeLogEvents(CloseableIterator<LogEvent> logEventIter) throws IOException { channelBuffer.clear(); while (logEventIter.hasNext() && channelBuffer.readableBytes() < BUFFER_BYTES) { LogEvent logEvent = logEventIter.next(); String logLine = patternLayout.doLayout(logEvent.getLoggingEvent()); logLine = escape ? StringEscapeUtils.escapeHtml(logLine) : logLine; channelBuffer.writeBytes(Bytes.toBytes(logLine)); } return channelBuffer; } @Override protected ChannelBuffer onWriteStart() throws IOException { return ChannelBuffers.EMPTY_BUFFER; } @Override protected ChannelBuffer onWriteFinish() throws IOException { return ChannelBuffers.EMPTY_BUFFER; } @Override public void close() { try { patternLayout.stop(); } finally { super.close(); } } }
32.978947
103
0.760613
8e10b04dd47980e393e8458183e4cddd4fc901f1
5,752
package com.boluozhai.snowflake.h2o.command.sf.repo; import java.io.IOException; import java.net.URI; import com.boluozhai.snowflake.cli.AbstractCLICommandHandler; import com.boluozhai.snowflake.cli.CLIUtils; import com.boluozhai.snowflake.cli.client.CLIClient; import com.boluozhai.snowflake.cli.util.ParamReader; import com.boluozhai.snowflake.cli.util.ParamReader.Builder; import com.boluozhai.snowflake.cli.util.ParamSet; import com.boluozhai.snowflake.context.SnowflakeContext; import com.boluozhai.snowflake.core.SnowflakeException; import com.boluozhai.snowflake.mvc.model.ComponentContext; import com.boluozhai.snowflake.vfs.VFS; import com.boluozhai.snowflake.vfs.VFile; import com.boluozhai.snowflake.xgit.XGit; import com.boluozhai.snowflake.xgit.XGitContext; import com.boluozhai.snowflake.xgit.config.Config; import com.boluozhai.snowflake.xgit.repository.Repository; import com.boluozhai.snowflake.xgit.repository.RepositoryManager; import com.boluozhai.snowflake.xgit.site.RepositoryType; import com.boluozhai.snowflake.xgit.site.SiteRepository; import com.boluozhai.snowflake.xgit.site.SystemRepository; import com.boluozhai.snowflake.xgit.site.XGitSite; import com.boluozhai.snowflake.xgit.utils.CurrentLocation; public class CmdInit extends AbstractCLICommandHandler { private static class ConfigBuilder { private final Config conf; public ConfigBuilder(Config config) { this.conf = config; } public void set_enable() { String key = Config.xgit.enable; String value = String.valueOf(true); conf.setProperty(key, value); } public void set_hash_algorithm(String value) { String key = Config.xgit.hashalgorithm; conf.setProperty(key, value); } public void set_hash_path_pattern(String value) { String key = Config.xgit.hashpathpattern; conf.setProperty(key, value); } public void set_type(String type) { String key = Config.xgit.siterepositorytype; conf.setProperty(key, type); } } private static class Inner { private final SnowflakeContext context; public String repo_name; public boolean bare; private String type = RepositoryType.normal; private String hash_path_pattern; private String hash_algorithm; public Inner(SnowflakeContext context) { this.context = context; } public void set_as_site_repo() { // location of the repo CurrentLocation cur_loc = CurrentLocation.Factory.get(context); URI loc = cur_loc.getLocation(context); VFS vfs = VFS.Factory.getVFS(context); VFile file = vfs.newFile(loc); file = file.child(this.repo_name); loc = file.toURI(); // open repo RepositoryManager rm = XGit.getRepositoryManager(context); Repository repo = rm.open(context, loc, null); Config config = repo.context().getBean( XGitContext.component.config, Config.class); // set config ConfigBuilder cb = new ConfigBuilder(config); cb.set_enable(); cb.set_type(this.type); cb.set_hash_path_pattern(this.hash_path_pattern); cb.set_hash_algorithm(this.hash_algorithm); try { config.save(); } catch (IOException e) { throw new SnowflakeException(e); } } public void run_git_init() { String bare = this.bare ? "--bare" : ""; String name = this.repo_name; String command = String.format("git init %s %s", bare, name); CLIClient client = CLIUtils.getClient(context); client.execute(context, command); } public void load_param() { Builder builder = ParamReader.newBuilder(); builder.option("--bare"); builder.option("--type", "value"); ParamReader reader = builder.create(context); ParamSet ps = ParamSet.create(reader); this.bare = ps.hasOption("--bare"); this.type = ps.getRequiredOption("--type"); this.repo_name = ps.getRequiredArgument(0); this.check_type(); this.check_repo_name(); } private void check_repo_name() { String value = this.repo_name; char[] bad_ch = { '\\', '/', ' ' }; for (char ch : bad_ch) { if (value.indexOf(ch) < 0) { continue; } else { String msg = "the repo name [%s] contain forbidden char: %d"; String.format(msg, value, ch); throw new SnowflakeException(msg); } } } private void check_type() { String[] accept = { SiteRepository.TYPE.user, SiteRepository.TYPE.data, }; String value = this.type; for (String reg : accept) { if (reg.equals(value)) { return; } } String msg = "the repo type [%s] is not accepted."; msg = String.format(msg, value); throw new SnowflakeException(msg); } public void load_site_system_repo() { XGitSite site = XGitSite.Agent.getSite(context); SystemRepository sys_repo = site.getSystemRepository(); ComponentContext cc = sys_repo.getComponentContext(); Config conf = (Config) cc .getAttribute(XGitContext.component.config); String path_pattern = conf.getProperty(Config.xgit.hashpathpattern); String hash_algorithm = conf.getProperty(Config.xgit.hashalgorithm); String repo_type = conf.getProperty(Config.xgit.siterepositorytype); String enable = conf.getProperty(Config.xgit.enable); this.check_text(enable, "true"); this.check_text(repo_type, SiteRepository.TYPE.system); this.hash_path_pattern = path_pattern; this.hash_algorithm = hash_algorithm; } private void check_text(String todo, String reg) { if (!reg.equals(todo)) { String msg = "the value [%s] not match regular [%s]."; msg = String.format(msg, todo, reg); throw new SnowflakeException(msg); } } } @Override public void process(SnowflakeContext context, String command) { Inner inner = new Inner(context); inner.load_param(); inner.load_site_system_repo(); inner.run_git_init(); inner.set_as_site_repo(); } }
27.78744
71
0.723748
826935a9b34489247dc73c11a44062fa21b9bf93
410
package mooc.vandy.java4android.calculator.logic; import mooc.vandy.java4android.calculator.ui.ActivityInterface; public abstract class Operations { private ActivityInterface mOut; public Operations(){} public Operations(ActivityInterface out){ mOut = out; } abstract void operate(); protected void print(String output){ mOut.print(output); } }
22.777778
64
0.680488
6bc24c51ba04c2e5769cc1cae5630bdb6ea20d5e
3,187
package msifeed.mc.extensions.environment; import cpw.mods.fml.common.FMLCommonHandler; import msifeed.mc.sys.cmd.ExtCommand; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.WorldServer; public class EnvironmentCommand extends ExtCommand { @Override public String getCommandName() { return "aenv"; } @Override public String getCommandUsage(ICommandSender sender) { return "/aenv"; } @Override public boolean canCommandSenderUseCommand(ICommandSender sender) { return isGm(sender); } @Override public void processCommand(ICommandSender sender, String[] args) { if (!(sender instanceof EntityPlayer)) { final WorldServer[] worlds = FMLCommonHandler.instance().getMinecraftServerInstance().worldServers; for (WorldServer w : worlds) { info(sender, "- " + w.provider.getDimensionName() + ", dim: " + w.provider.dimensionId); } return; } final EntityPlayer player = (EntityPlayer) sender; if (args.length < 1) { printHelp(sender); return; } final int dim = player.worldObj.provider.dimensionId; final WorldEnv worldEnv = EnvironmentManager.getEnv(dim); switch (args[0].toLowerCase()) { case "rain": final WorldEnv.Rain r = worldEnv.rain; title(sender, "Rain info"); info(sender, " acc: %d +%d/-%d", r.accumulated, r.income, r.outcome); info(sender, " min/max: %d/%d", r.minThreshold, r.maxThreshold); info(sender, " thunder: %d", r.thunderThreshold); info(sender, " dice: %d", r.rainfallDice); break; case "add": final int mod = parseInt(sender, args[1]); worldEnv.rain.accumulated += mod; info(sender, "Added %d to the rain acc (current: %d)", mod, worldEnv.rain.accumulated); break; // case "snow": // worldEnv.snow = !worldEnv.snow; // sender.addChatMessage(new ChatComponentText("snow: " + worldEnv.snow)); // break; // case "melt": // worldEnv.meltSnow = !worldEnv.meltSnow; // sender.addChatMessage(new ChatComponentText("meltSnow: " + worldEnv.meltSnow)); // break; // case "stacksnow": // worldEnv.stackSnow = !worldEnv.stackSnow; // sender.addChatMessage(new ChatComponentText("stackSnow: " + worldEnv.stackSnow)); // break; } } private void printHelp(ICommandSender sender) { title(sender, "AEnv help"); info(sender, "current dim: %d", sender.getEntityWorld().provider.dimensionId); info(sender, " rain - show rain info"); info(sender, " add - modify rain accumulator"); // info(sender, " snow - toggle drop random snow"); // info(sender, " melt - toggle melt random snow"); // info(sender, " stacksnow - toggle snow stack"); } }
38.39759
111
0.581111
4298b25e59a5ae84159ad341718856339210e56c
2,991
package de.ianus.ingest.core.xml; import java.util.List; import de.ianus.ingest.core.Services; import de.ianus.ingest.core.bo.WorkflowIP; import de.ianus.ingest.core.bo.files.AgentEventLink; import de.ianus.ingest.core.bo.files.Event; import de.ianus.ingest.core.bo.files.ObjectEventLink; import de.ianus.ingest.core.mets.bo.DmdSec; import de.ianus.ingest.core.mets.bo.FileSec; import de.ianus.ingest.core.mets.bo.MetsFrame; import de.ianus.ingest.core.mets.bo.MetsHdr; import de.ianus.ingest.core.mets.bo.StructMap; import de.ianus.ingest.core.premis.bo.Premis; import de.ianus.ingest.core.premis.bo.PremisAgent; import de.ianus.ingest.core.premis.bo.PremisEvent; import de.ianus.ingest.core.premis.bo.PremisObject; import de.ianus.metadata.bo.DataCollection; import de.ianus.metadata.xml.XMLObject; public class XMLService { private WorkflowIP ip = null; private DataCollection dc = null; public XMLService(WorkflowIP wip) throws Exception { this.ip = wip; this.dc = Services.getInstance().getMDService().getDataCollection(this.ip.getMetadataId()); } // constructor for easier testing (injection of a mocked DataCollection) public XMLService(WorkflowIP wfip, DataCollection dc) { this.ip = wfip; this.dc = dc; } public void createMETS() throws Exception { // ianus.xml will be referenced in DmdSection as descriptive metadata XMLObject dc = this.dc.toXMLObject(); dc.toFile(this.ip.getMetadataFolder() + "/ianus.xml"); XMLObject mets = new MetsFrame(this.dc); XMLObject metsHdr = new MetsHdr(this.dc); XMLObject fileSec = new FileSec(this.ip); XMLObject dmd = new DmdSec(this.dc); XMLObject structMap = new StructMap(this.ip, this.dc, "physical"); XMLObject logicalMap = new StructMap(this.ip, this.dc, "logical"); mets.addDescendant(metsHdr); mets.addDescendant(fileSec); mets.addDescendant(dmd); mets.addDescendant(structMap); mets.addDescendant(logicalMap); mets.toFile(this.ip.getMetadataFolder() + "/mets.xml"); } public void createPREMIS() throws Exception { Premis premis = new Premis(); List<Event> events = Services.getInstance().getDaoService().getEventList(this.ip); if(events != null) for(Event event : events) { PremisEvent premisEvent = premis.addEvent(event); List<ObjectEventLink> objectEventList = Services.getInstance().getDaoService().getObjectEventLinkList(event); if(objectEventList != null) for(ObjectEventLink link : objectEventList) { PremisObject premisObject = premis.addObject(link); premisObject.linkEvent(event); premisEvent.linkObject(link); } List<AgentEventLink> agentEventList = Services.getInstance().getDaoService().getAgentEventLinkList(event); if(agentEventList != null) for(AgentEventLink link : agentEventList) { PremisAgent premisAgent = premis.addAgent(link); premisAgent.linkEvent(event); premisEvent.linkAgent(link); } } premis.toFile(this.ip.getMetadataFolder() + "/premis.xml"); } }
33.233333
112
0.746239
be7994d9cce49e35d2a7aa7b37a922327e5dc7d0
6,774
package net.bytebuddy.dynamic.scaffold; import net.bytebuddy.description.annotation.AnnotationDescription; import net.bytebuddy.description.annotation.AnnotationList; import net.bytebuddy.description.field.FieldDescription; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.method.MethodList; import net.bytebuddy.description.type.RecordComponentDescription; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.implementation.attribute.AnnotationValueFilter; import net.bytebuddy.implementation.attribute.RecordComponentAttributeAppender; import net.bytebuddy.test.utility.MockitoRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.mockito.Mock; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.RecordComponentVisitor; import java.lang.annotation.RetentionPolicy; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.*; public class TypeWriterRecordComponentPoolRecordTest { private static final String FOO = "foo", BAR = "bar", QUX = "qux", BAZ = "baz"; @Rule public TestRule mockitoRule = new MockitoRule(this); @Mock private RecordComponentAttributeAppender recordComponentAttributeAppender; @Mock private AnnotationValueFilter valueFilter; @Mock private AnnotationValueFilter.Factory annotationValueFilterFactory; @Mock private ClassVisitor classVisitor; @Mock private RecordComponentVisitor recordComponentVisitor; @Mock private AnnotationVisitor annotationVisitor; @Mock private RecordComponentDescription recordComponentDescription; @Mock private AnnotationDescription annotationDescription; @Mock private TypeDescription annotationType; @Before @SuppressWarnings("unchecked") public void setUp() throws Exception { when(recordComponentDescription.getActualName()).thenReturn(FOO); when(recordComponentDescription.getDescriptor()).thenReturn(BAR); when(recordComponentDescription.getGenericSignature()).thenReturn(QUX); when(recordComponentDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Explicit(annotationDescription)); when(recordComponentDescription.getType()).thenReturn(TypeDescription.Generic.OBJECT); when(classVisitor.visitRecordComponent(FOO, BAR, QUX)).thenReturn(recordComponentVisitor); when(classVisitor.visitRecordComponent(FOO, BAR, QUX)).thenReturn(recordComponentVisitor); when(annotationValueFilterFactory.on(recordComponentDescription)).thenReturn(valueFilter); when(recordComponentVisitor.visitAnnotation(any(String.class), anyBoolean())).thenReturn(annotationVisitor); when(annotationDescription.getAnnotationType()).thenReturn(annotationType); when(annotationType.getDescriptor()).thenReturn(BAZ); when(annotationType.getDeclaredMethods()).thenReturn(new MethodList.Empty<MethodDescription.InDefinedShape>()); when(annotationDescription.getRetention()).thenReturn(RetentionPolicy.RUNTIME); } @Test public void testExplicitRecordComponentEntryProperties() throws Exception { TypeWriter.RecordComponentPool.Record record = new TypeWriter.RecordComponentPool.Record.ForExplicitRecordComponent(recordComponentAttributeAppender, recordComponentDescription); assertThat(record.getRecordComponentAppender(), is(recordComponentAttributeAppender)); assertThat(record.isImplicit(), is(false)); } @Test public void testExplicitRecordComponentEntryWritesRecordComponent() throws Exception { TypeWriter.RecordComponentPool.Record record = new TypeWriter.RecordComponentPool.Record.ForExplicitRecordComponent(recordComponentAttributeAppender, recordComponentDescription); record.apply(classVisitor, annotationValueFilterFactory); verify(classVisitor).visitRecordComponent(FOO, BAR, QUX); verifyNoMoreInteractions(classVisitor); verify(recordComponentAttributeAppender).apply(recordComponentVisitor, recordComponentDescription, valueFilter); verifyNoMoreInteractions(recordComponentAttributeAppender); verify(recordComponentVisitor).visitEnd(); verifyNoMoreInteractions(recordComponentVisitor); } @Test public void testExplicitRecordComponentEntryWritesRecordComponentPartialApplication() throws Exception { TypeWriter.RecordComponentPool.Record record = new TypeWriter.RecordComponentPool.Record.ForExplicitRecordComponent(recordComponentAttributeAppender, recordComponentDescription); record.apply(recordComponentVisitor, annotationValueFilterFactory); verify(recordComponentAttributeAppender).apply(recordComponentVisitor, recordComponentDescription, valueFilter); verifyNoMoreInteractions(recordComponentAttributeAppender); verifyZeroInteractions(recordComponentVisitor); } @Test public void testImplicitRecordComponentEntryProperties() throws Exception { TypeWriter.RecordComponentPool.Record record = new TypeWriter.RecordComponentPool.Record.ForImplicitRecordComponent(recordComponentDescription); assertThat(record.isImplicit(), is(true)); } @Test public void testImplicitRecordComponentEntryWritesRecordComponent() throws Exception { TypeWriter.RecordComponentPool.Record record = new TypeWriter.RecordComponentPool.Record.ForImplicitRecordComponent(recordComponentDescription); record.apply(classVisitor, annotationValueFilterFactory); verify(classVisitor).visitRecordComponent(FOO, BAR, QUX); verifyNoMoreInteractions(classVisitor); verify(recordComponentVisitor).visitAnnotation(BAZ, true); verify(recordComponentVisitor).visitEnd(); verifyNoMoreInteractions(recordComponentVisitor); verify(annotationVisitor).visitEnd(); verifyNoMoreInteractions(annotationVisitor); } @Test(expected = IllegalStateException.class) public void testImplicitRecordComponentWritesRecordComponentPartialApplication() throws Exception { new TypeWriter.RecordComponentPool.Record.ForImplicitRecordComponent(recordComponentDescription).apply(recordComponentVisitor, annotationValueFilterFactory); } @Test(expected = IllegalStateException.class) public void testImplicitRecordComponentEntryAppliedToRecordComponent() throws Exception { new TypeWriter.RecordComponentPool.Record.ForImplicitRecordComponent(recordComponentDescription).apply(recordComponentVisitor, annotationValueFilterFactory); } }
49.086957
186
0.801299
e6116522d3528dfb82ec507e3deaf35533da94a3
392
package com.squadio.accountstatements.repositories; import com.squadio.accountstatements.entities.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByUserNameIgnoreCase(String username); }
26.133333
67
0.836735
c8c2ee8a069eaf7b1b6b1ababe92f2109546a090
876
package com.village.things; import com.queatz.earth.EarthStore; import com.queatz.earth.EarthThing; import com.queatz.snappy.as.EarthAs; import com.queatz.snappy.shared.Config; import javax.servlet.http.HttpServletRequest; /** * Created by jacob on 6/4/17. */ public class FormItemInterface extends CommonLinkInterface { @Override public EarthThing create(EarthAs as, EarthThing source, EarthThing target, String status, String role) { EarthStore earthStore = as.s(EarthStore.class); String form = extract(as.getParameters().get(Config.PARAM_IN)); String type = extract(as.getParameters().get(Config.PARAM_TYPE)); return as.s(FormItemEditor.class).newFormItem(earthStore.get(form), type); } @Override protected EarthThing edit(EarthAs as, EarthThing link, HttpServletRequest request) { return null; } }
29.2
108
0.730594