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
|
|---|---|---|---|---|---|
2d61391de25f79658b29f0789ea616618794737e
| 11,308
|
package org.derive4j.hkt.processor;
import org.derive4j.hkt.HktConfig;
import org.derive4j.hkt.TypeEq;
import org.derive4j.hkt.processor.DataTypes.*;
import javax.annotation.processing.Filer;
import javax.lang.model.element.*;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static org.derive4j.hkt.processor.DataTypes.Unit.unit;
@SuppressWarnings("OptionalGetWithoutIsPresent")
final class GenCode {
private enum HktEffectiveVisibility {
Public {
@Override
String prefix() {
return "public ";
}
}, Package {
@Override
String prefix() {
return "";
}
};
abstract String prefix();
}
private static final String CLASS_TEMPLATE = "package {0};\n" +
"\n" +
"import org.derive4j.hkt.*;\n" +
"{3}\n"+
"\n" +
"{1}final class {2} '{'\n" +
" private {2}() '{'}\n" +
"\n" +
"{4}\n" +
"}";
private static final String METHODS_TEMPLATE = " {0}static {2} {1} " +
"{4}({3} hkt) '{'\n" +
" return ({1}) hkt;\n" +
" }\n" +
"\n" +
" @SuppressWarnings(\"unchecked\")\n" +
" {0}static {2} TypeEq<{3}, {1}> {5}()'{'\n" +
" return (TypeEq) TypeEq.refl();\n" +
" }";
private static final String TYPE_PARAMS_TEMPLATE = "<{0}>";
private final Elements Elts;
private final Types Types;
private final Filer Filer;
private final TypeElement __Elt;
private final TypeElement TypeEqElt;
GenCode(Elements elts, Types types, Filer filer, TypeElement elt) {
Elts = elts;
Types = types;
Filer = filer;
__Elt = elt;
TypeEqElt = Elts.getTypeElement(TypeEq.class.getName());
}
IO<Unit> run(String genClassName, List<HktDecl> hktDecls) {
Set<TypeElement> newTypeElements = hktDecls.stream().map(_HktDecl::getTypeConstructor).collect(Collectors.toSet());
List<P2<TypeElement, P2<HktEffectiveVisibility, String>>> existingCoerceMethods = readGenClass(genClassName).map(
existingGenClasl -> ElementFilter.methodsIn(existingGenClasl.getEnclosedElements())
.stream()
.map(this::parseExistingCoerceMethod)
.flatMap(Opt::asStream)
.filter(p -> !newTypeElements.contains(p._1())))
.orElseGet(Stream::empty)
.collect(toList());
List<TypeElement> allTypeElements = Stream.concat(existingCoerceMethods.stream().map(P2::_1), hktDecls.stream().map
(_HktDecl::getTypeConstructor)).collect(toList());
Stream<P2<HktEffectiveVisibility, String>> newCoerceMethods = hktDecls.stream().map(this::genCoerceMethod).flatMap(Opt::asStream);
List<P2<HktEffectiveVisibility, String>> allMethods = Stream.concat(existingCoerceMethods.stream().map(P2::_2), newCoerceMethods)
.collect(Collectors.toList());
return allMethods.isEmpty()
? IO.unit(unit)
: generateClass(genClassName, allTypeElements, allMethods);
}
String genClassName(HktDecl hktDecl) {
return hktDecl.match((typeConstructor, hktInterface, conf) ->
_HktConf.getClassName(conf).contains(".")
? _HktConf.getClassName(conf)
: Elts.getPackageOf(typeConstructor).getQualifiedName() + "." + _HktConf.getClassName(conf));
}
private IO<Unit> generateClass(String genClassName, List<TypeElement> allTypeElements, List<P2<HktEffectiveVisibility, String>> allMethods) {
PackageElement packageELement = Elts.getPackageElement(genClassName.substring(0, genClassName.lastIndexOf(".")));
HktEffectiveVisibility classVisibility = allMethods.stream()
.map(P2::_1)
.filter(HktEffectiveVisibility.Public::equals)
.findAny()
.orElse(HktEffectiveVisibility.Package);
String genSimpleClassName = genClassName.substring(packageELement.getQualifiedName().toString().length() + 1,
genClassName.length());
String explicitImports = allTypeElements.stream()
.map(this::packageRelativeTypeElement)
.filter(te -> !Elts.getPackageOf(te).equals(packageELement))
.map(te -> "import " + te.toString() + ";")
.collect(joining("\n"));
String methods = allMethods.stream().map(P2::_2).collect(joining("\n\n"));
String classContent = MessageFormat.format(CLASS_TEMPLATE, packageELement.getQualifiedName().toString(),
classVisibility.prefix(), genSimpleClassName, explicitImports, methods);
return IO.effect(() -> {
try (Writer classWriter = new OutputStreamWriter(
Filer.createSourceFile(genClassName).openOutputStream(), UTF_8)) {
classWriter.append(classContent);
classWriter.flush();
}
});
}
private Optional<P2<TypeElement, P2<HktEffectiveVisibility, String>>> parseExistingCoerceMethod(ExecutableElement coerceMethod) {
return coerceMethod.getParameters().size() != 1
? Optional.empty()
: Visitors.asDeclaredType.visit(coerceMethod.getReturnType())
.flatMap(declaredType -> allSuperTypes(declaredType).filter(dt -> dt.asElement().equals(__Elt))
.findFirst()
.flatMap(hktInterface -> Visitors.asTypeElement.visit(declaredType.asElement())
.flatMap(typeElement -> ElementFilter.methodsIn(coerceMethod.getEnclosingElement().getEnclosedElements())
.stream()
.filter(e -> e.getParameters().isEmpty())
.filter(e -> e.getReturnType().toString().equals(
Types.getDeclaredType(TypeEqElt, hktInterface, typeElement.asType()).toString()))
.findAny()
.map(typeEqMethod -> _P2.of(typeElement, genCoerceMethod(typeElement, hktInterface,
coerceMethod.getSimpleName().toString(), typeEqMethod.getSimpleName().toString(),
coerceMethod.getModifiers().contains(Modifier.PUBLIC)
? HktEffectiveVisibility.Public
: HktEffectiveVisibility.Package))))));
}
private Optional<P2<HktEffectiveVisibility, String>> genCoerceMethod(HktDecl hktDecl) {
return hktDecl.match((typeConstructor, hktInterface, conf) -> {
HktConfig.Visibility visibility = _HktConf.getVisibility(conf);
if (visibility == HktConfig.Visibility.Disabled) {
return Optional.empty();
}
final String coerceMethodName =
_HktConf.getCoerceMethodTemplate(conf)
.replace("{ClassName}", typeConstructor.getSimpleName())
.replace("{className}", uncapitalize(typeConstructor.getSimpleName()));
final String typeEqMethodName =
_HktConf.getTypeEqMethodTemplate(conf)
.replace("{ClassName}", typeConstructor.getSimpleName())
.replace("{className}", uncapitalize(typeConstructor.getSimpleName()));
DeclaredType rootHktInterface = allSuperTypes(hktInterface).filter(dt -> dt.asElement().equals(__Elt))
.findAny()
.orElse(hktInterface);
HktEffectiveVisibility effectiveVisibility = visibility == HktConfig.Visibility.Same && typeConstructor.getModifiers()
.contains(Modifier.PUBLIC) ? HktEffectiveVisibility.Public: HktEffectiveVisibility.Package;
return Optional.of(genCoerceMethod(typeConstructor, rootHktInterface, coerceMethodName,
typeEqMethodName, effectiveVisibility));
});
}
private P2<HktEffectiveVisibility, String> genCoerceMethod(TypeElement typeConstructor,
DeclaredType hktInterface, String coerceMethodName, String typeEqMethodName, HktEffectiveVisibility visibility) {
String packageNamePrefix = Elts.getPackageOf(typeConstructor).getQualifiedName().toString() + ".";
String typeAsString = typeConstructor.asType()
.toString()
.substring(packageNamePrefix.length(), typeConstructor.asType().toString().length());
TypeElement packageRelativeTypeElement = packageRelativeTypeElement(typeConstructor);
CharSequence typeParams = MessageFormat.format(TYPE_PARAMS_TEMPLATE, showTypeParams(typeConstructor));
String hktInterfaceAsString = hktInterface.toString()
.replace(Visitors.asTypeElement.visit(hktInterface.asElement()).get().getQualifiedName(), hktInterface
.asElement().getSimpleName())
.replace(packageRelativeTypeElement.getQualifiedName(), packageRelativeTypeElement.getSimpleName());
return _P2.of(visibility,
MessageFormat.format(METHODS_TEMPLATE, visibility.prefix(), typeAsString, typeParams,
hktInterfaceAsString, coerceMethodName, typeEqMethodName));
}
private TypeElement packageRelativeTypeElement(TypeElement typeElement) {
return typeElement.getEnclosingElement().getKind() == ElementKind.PACKAGE ? typeElement : packageRelativeTypeElement(
(TypeElement) typeElement.getEnclosingElement());
}
private Optional<TypeElement> readGenClass(String genClassName) {
return Opt.unNull(Elts.getTypeElement(genClassName));
}
private Stream<DeclaredType> allSuperTypes(DeclaredType typeMirror) {
return Visitors.allSuperTypes(Types, typeMirror);
}
private static String showTypeParams(TypeElement te) {
return te
.getTypeParameters()
.stream()
.map(GenCode::showTypeParam)
.collect(joining(", "));
}
private static String showTypeParam(TypeParameterElement tpe) {
final String bounds = tpe.getBounds()
.stream()
.map(TypeMirror::toString)
.filter(s -> !s.contentEquals("java.lang.Object"))
.collect(joining(", "));
return tpe.asType().toString() + (bounds.isEmpty() ? "" : " extends " + bounds);
}
private static String uncapitalize(final CharSequence s) {
return (s.length() >= 2) && Character.isHighSurrogate(s.charAt(0)) && Character.isLowSurrogate(s.charAt(1))
? s.toString().substring(0, 2).toLowerCase(Locale.US) + s.toString().substring(2)
: s.toString().substring(0, 1).toLowerCase(Locale.US) + s.toString().substring(1);
}
}
| 42.671698
| 145
| 0.638663
|
f731f29459696e3e84b5280db4c432cdad967a64
| 2,268
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
package com.amazonaws.capstone.devopsguru_eks_test;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
@Component
public class CpuStressBackgroundComponent {
@Autowired
JedisPool redisPool;
private ExecutorService executorService;
private AtomicBoolean stressTestRunning = new AtomicBoolean(false);
private static double loadTestPercentage = 0.95;
private static double baselineLoadPercentage = 0.3;
@PostConstruct
public void init() {
BasicThreadFactory factory = new BasicThreadFactory.Builder()
.namingPattern("cpu-stress-%d").build();
executorService = Executors.newSingleThreadExecutor(factory);
executorService.execute(() -> {
while (true) {
if (System.currentTimeMillis() % 1000 == 0) {
try {
double loadPercentage = stressTestRunning.get() ? loadTestPercentage : baselineLoadPercentage;
Thread.sleep((long) Math.floor((1 - loadPercentage) * 1000));
} catch (InterruptedException e) {
}
}
}
});
}
@Scheduled(fixedRate = 30000)
public void checkCpuStressRequest() {
boolean stressTestEnabled;
try (Jedis client = redisPool.getResource()) {
stressTestEnabled = Optional.ofNullable(client.get("cpustresstest"))
.orElse("false").equals("true");
}
stressTestRunning.set(stressTestEnabled);
}
@PreDestroy
public void shutdown() {
if (executorService != null) {
executorService.shutdownNow();
}
}
}
| 34.363636
| 118
| 0.671076
|
eedefaac485eae4abfe53141f3ca02bd6955982a
| 2,032
|
/**
* CardExpiry_Deser.java
*
* This file was auto-generated from WSDL
* by the IBM Web services WSDL2Java emitter.
* cf230904.14 v13009114817
*/
package PayMeLibrary;
public class CardExpiry_Deser extends com.ibm.ws.webservices.engine.encoding.ser.BeanDeserializer {
/**
* Constructor
*/
public CardExpiry_Deser(
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType,
com.ibm.ws.webservices.engine.description.TypeDesc _typeDesc) {
super(_javaType, _xmlType, _typeDesc);
}
/**
* Create instance of java bean
*/
public void createValue() {
value = new PayMeLibrary.CardExpiry();
}
protected boolean tryElementSetFromString(javax.xml.namespace.QName qName, java.lang.String strValue) {
if (qName==QName_0_29) {
((CardExpiry)value).setMonth(com.ibm.ws.webservices.engine.encoding.ser.SimpleDeserializer.parseInteger(strValue));
return true;}
else if (qName==QName_0_30) {
((CardExpiry)value).setYear(com.ibm.ws.webservices.engine.encoding.ser.SimpleDeserializer.parseInteger(strValue));
return true;}
return false;
}
protected boolean tryAttributeSetFromString(javax.xml.namespace.QName qName, java.lang.String strValue) {
return false;
}
protected boolean tryElementSetFromObject(javax.xml.namespace.QName qName, java.lang.Object objValue) {
return false;
}
protected boolean tryElementSetFromList(javax.xml.namespace.QName qName, java.util.List listValue) {
return false;
}
private final static javax.xml.namespace.QName QName_0_30 =
com.ibm.ws.webservices.engine.utils.QNameTable.createQName(
"",
"year");
private final static javax.xml.namespace.QName QName_0_29 =
com.ibm.ws.webservices.engine.utils.QNameTable.createQName(
"",
"month");
}
| 37.62963
| 126
| 0.647146
|
7f58dd109bd6c0f0269bd3afe8626bdb59554e9f
| 1,148
|
package gms.dataacquisition.stationreceiver.cd11.dataprovider;
import gms.dataacquisition.stationreceiver.cd11.dataprovider.configuration.Cd11DataProviderConfig;
import gms.dataacquisition.stationreceiver.cd11.dataprovider.configuration.Cd11DataProviderConfigurationLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Runs the Data Provider socket service.
*/
public class Application {
private static Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
try {
// Start up the Data Provider thread.
Cd11DataProviderConfig config = Cd11DataProviderConfigurationLoader.load();
Cd11DataProvider dataProvider = new Cd11DataProvider(config);
dataProvider.start();
// Wait until the thread stops.
dataProvider.waitUntilThreadStops();
// Check for an error message.
if (dataProvider.hasErrorMessage()) {
logger.error(dataProvider.getErrorMessage());
System.exit(1);
}
} catch (Exception e) {
logger.error("Data Provider threw an exception in main(): ", e);
System.exit(1);
}
}
}
| 31.027027
| 111
| 0.729965
|
6e251e85e3a574632661cffb4b86678ce606eab8
| 1,026
|
package tree.BinaryTreeInorderTraversal;
import java.util.ArrayList;
import java.util.List;
import tree.BinaryTreeInorderTraversal.Solution.TreeNode;
public class MorrisMethod {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
TreeNode curr = root;
TreeNode pre;
while (curr != null) {
if (curr.left == null) {
res.add(curr.val);
curr = curr.right; // move to next right node
} else { // has a left subtree
pre = curr.left;
while (pre.right != null) { // find rightmost
pre = pre.right;
}
pre.right = curr; // put cur after the pre node
TreeNode temp = curr; // store cur node
curr = curr.left; // move cur to the top of the new tree
temp.left = null; // original cur left be null, avoid infinite loops
}
}
return res;
}
}
| 34.2
| 84
| 0.539961
|
41a8471e4ce9a820968a823d982d6f6df93e8467
| 3,337
|
package psn.filechief.util;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
*
* 1. Generate Initialization Vector (use SecureRandom)
* 2. IV convert to gcmSpec
* 3. make SecretKey from password and IV
* 4. init cipher with secretKey and gcmSpec
* 5. use the cipher: encode message
*/
public class PBECrypt8 {
private static final String KEY_FUNCTION = "PBKDF2WithHmacSHA256";
private static final String ALG_CRYPT = "AES";
private static final String ALG_IV_GEN = "SHA1PRNG";
private static final String TRANSFORM = "AES/GCM/NoPadding";
private static final int ITERATIONS = 1000;
private static final int KEY_BITS = 128;
public static final int IV_BITS = 128;
public static final int AUTH_TAG_BITS = 128;
public static final int IV_BYTES = IV_BITS / 8;
public static final int AUTH_TAG_BYTES = AUTH_TAG_BITS / 8;
/**
* Generates an Initialization Vector.
* @throws GeneralSecurityException
*/
private static byte[] generateIV() throws GeneralSecurityException {
SecureRandom random = SecureRandom.getInstance(ALG_IV_GEN);
byte[] iv = new byte[IV_BYTES];
random.nextBytes(iv);
return iv;
}
private static SecretKey deriveKey(char[] password, byte[] salt) throws GeneralSecurityException {
PBEKeySpec pbeKeySpec = new PBEKeySpec(password, salt, ITERATIONS, KEY_BITS);
SecretKey pbeKey = null;
byte[] keyBytes = null;
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_FUNCTION);
pbeKey = factory.generateSecret(pbeKeySpec);
keyBytes = pbeKey.getEncoded();
return new SecretKeySpec(keyBytes, ALG_CRYPT);
}
finally {
pbeKeySpec.clearPassword();
if (keyBytes != null)
Arrays.fill(keyBytes, (byte) 0);
}
}
private static Cipher initCipher(int mode, char[] password, byte[] iv) throws GeneralSecurityException
{
GCMParameterSpec gcmSpec = new GCMParameterSpec(AUTH_TAG_BITS, iv);
SecretKey key = deriveKey(password, iv);
Cipher cipher = Cipher.getInstance(TRANSFORM);
cipher.init(mode, key, gcmSpec);
return cipher;
}
private static byte[] doFinal(int mode, char[] password, byte[] iv, byte[] message) throws GeneralSecurityException
{
Cipher cipher = initCipher(mode, password, iv);
return cipher.doFinal(message);
}
public static byte[] encrypt(byte[] message, char[] password) throws GeneralSecurityException
{
byte[] iv = generateIV();
byte[] ciphertext = doFinal(Cipher.ENCRYPT_MODE, password, iv, message);
byte[] result = new byte[iv.length + ciphertext.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(ciphertext, 0, result, iv.length, ciphertext.length);
return result;
}
public static byte[] decrypt(byte[] encrypted, char[] password) throws GeneralSecurityException {
byte[] iv = Arrays.copyOfRange(encrypted, 0, IV_BYTES);
byte[] ciphertext = Arrays.copyOfRange(encrypted, IV_BYTES, encrypted.length);
return doFinal(Cipher.DECRYPT_MODE, password, iv, ciphertext);
}
}
| 34.05102
| 117
| 0.724903
|
fa39f61575c6e31ca31d938c46406fa02a1672db
| 2,371
|
package org.apache.geode.addon.function;
import java.util.Properties;
import java.util.Set;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.Declarable;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.internal.cache.BucketRegion;
import org.apache.geode.internal.cache.PartitionedRegion;
/**
* ClearFunction clears the specified region. Geode does not permit clearing
* partitioned regions. Furthermore, clients can only clear local regions such
* that they cannot clear replicated regions. This function allows clearing
* both partitioned and replicated regions.
* <p>
* <b>Arguments:</b>
* <ul><li><b>fullPath</b> String Region full path </li></ul>
*
* @author dpark
*
*/
@SuppressWarnings({ "rawtypes"})
public class ClearFunction implements Function, Declarable {
private static final long serialVersionUID = 1L;
public final static String ID = "addon.ClearFunction";
private Cache cache;
public enum ClearStatus { SUCCESS, ERROR_REGION_PATH_UNDEFINED, ERROR_REGION_PATH_NOT_FOUND };
@SuppressWarnings("unchecked")
@Override
public void execute(FunctionContext context) {
String fullPath = (String)context.getArguments();
if (fullPath == null || fullPath.length() == 0) {
context.getResultSender().lastResult(ClearStatus.ERROR_REGION_PATH_UNDEFINED);
return;
}
Region region = cache.getRegion(fullPath);
if (region == null) {
context.getResultSender().lastResult(ClearStatus.ERROR_REGION_PATH_NOT_FOUND);
return;
}
// TODO: ExecutorService to use a thread pool for concurrent
// removes.
if (region instanceof PartitionedRegion) {
PartitionedRegion pr = (PartitionedRegion) region;
Set<BucketRegion> set = pr.getDataStore().getAllLocalPrimaryBucketRegions();
for (BucketRegion bucketRegion : set) {
final BucketRegion br = bucketRegion;
Set keySet = br.keySet();
for (Object key : keySet) {
br.remove(key);
}
}
} else {
region.clear();
}
context.getResultSender().lastResult(ClearStatus.SUCCESS);
}
@Override
public void initialize(Cache cache, Properties properties) {
this.cache = cache;
}
@Override
public String getId() {
return ID;
}
}
| 30.792208
| 96
| 0.719528
|
6481f71072ca2686b40bcb1088333d408e0c1ab7
| 259
|
package com.diasemi.bleremote.ui.main.input;
public class StreamControlEvent {
private byte[] mPacket;
public StreamControlEvent(final byte[] packet) {
mPacket = packet;
}
public byte[] getPacket() {
return mPacket;
}
}
| 18.5
| 52
| 0.648649
|
dbdbf1170a75235d8e17c5ab645a6e028c555387
| 200
|
package cn.iocoder.mall.pay.biz;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"cn.iocoder.mall.pay"})
public class Application {
}
| 25
| 68
| 0.815
|
3edc9040d9bd8e5ab5001d98f745d484e531ff48
| 18,530
|
/*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.swt.widgets.Display;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourceAttributes;
import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBuffer;
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.filebuffers.LocationKind;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.text.edits.UndoEdit;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.ISynchronizable;
import org.eclipse.jface.text.RewriteSessionEditProcessor;
import org.eclipse.jdt.core.BufferChangedEvent;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.IBufferChangedListener;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.IBuffer.ITextEditCapability;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Adapts <code>IDocument</code> to <code>IBuffer</code>. Uses the
* same algorithm as the text widget to determine the buffer's line delimiter.
* All text inserted into the buffer is converted to this line delimiter.
* This class is <code>public</code> for test purposes only.
*/
public class DocumentAdapter implements IBuffer, IDocumentListener, ITextEditCapability {
/**
* Internal implementation of a NULL instanceof IBuffer.
*/
private static class NullBuffer implements IBuffer {
@Override
public void addBufferChangedListener(IBufferChangedListener listener) {
}
@Override
public void append(char[] text) {
}
@Override
public void append(String text) {
}
@Override
public void close() {
}
@Override
public char getChar(int position) {
return 0;
}
@Override
public char[] getCharacters() {
return null;
}
@Override
public String getContents() {
return null;
}
@Override
public int getLength() {
return 0;
}
@Override
public IOpenable getOwner() {
return null;
}
@Override
public String getText(int offset, int length) {
return null;
}
@Override
public IResource getUnderlyingResource() {
return null;
}
@Override
public boolean hasUnsavedChanges() {
return false;
}
@Override
public boolean isClosed() {
return false;
}
@Override
public boolean isReadOnly() {
return true;
}
@Override
public void removeBufferChangedListener(IBufferChangedListener listener) {
}
@Override
public void replace(int position, int length, char[] text) {
}
@Override
public void replace(int position, int length, String text) {
}
@Override
public void save(IProgressMonitor progress, boolean force) throws JavaModelException {
}
@Override
public void setContents(char[] contents) {
}
@Override
public void setContents(String contents) {
}
}
/** NULL implementing <code>IBuffer</code> */
public static final IBuffer NULL = new NullBuffer();
/**
* Run the given runnable in the UI thread.
*
* @param runnable the runnable
* @since 3.3
*/
private static final void run(Runnable runnable) {
Display currentDisplay = Display.getCurrent();
if (currentDisplay != null)
runnable.run();
else
Display.getDefault().syncExec(runnable);
}
/**
* Executes a document set content call in the UI thread.
*/
protected class DocumentSetCommand implements Runnable {
private String fContents;
@Override
public void run() {
if (!isClosed())
fDocument.set(fContents);
}
public void set(String contents) {
fContents = contents;
DocumentAdapter.run(this);
}
}
/**
* Executes a document replace call in the UI thread.
*/
protected class DocumentReplaceCommand implements Runnable {
private int fOffset;
private int fLength;
private String fText;
@Override
public void run() {
try {
if (!isClosed())
fDocument.replace(fOffset, fLength, fText);
} catch (BadLocationException x) {
}
}
public void replace(int offset, int length, String text) {
fOffset = offset;
fLength = length;
fText = text;
DocumentAdapter.run(this);
}
}
/**
* Executes a document replace call in the UI thread.
*
* @since 3.4
*/
protected class ApplyTextEditCommand implements Runnable {
private TextEdit fEdit;
private UndoEdit fUndoEdit;
@Override
public void run() {
try {
if (!isClosed()) {
fUndoEdit = new RewriteSessionEditProcessor(fDocument, fEdit, TextEdit.UPDATE_REGIONS | TextEdit.CREATE_UNDO).performEdits();
}
} catch (BadLocationException x) {
}
}
public UndoEdit applyTextEdit(TextEdit edit) {
fEdit = edit;
fUndoEdit = null;
DocumentAdapter.run(this);
return fUndoEdit;
}
}
private static final boolean DEBUG_LINE_DELIMITERS = true;
private IOpenable fOwner;
private IFile fFile;
private ITextFileBuffer fTextFileBuffer;
private IDocument fDocument;
private boolean fIsClosed = true;
private DocumentSetCommand fSetCmd = new DocumentSetCommand();
private DocumentReplaceCommand fReplaceCmd = new DocumentReplaceCommand();
private ApplyTextEditCommand fTextEditCmd = new ApplyTextEditCommand();
private Set<String> fLegalLineDelimiters;
private List<IBufferChangedListener> fBufferListeners = new ArrayList(3);
/** @since 3.2 */
private IPath fPath;
/** @since 3.3 */
private LocationKind fLocationKind;
/** @since 3.6 */
private IFileStore fFileStore;
/**
* Constructs a new document adapter.
*
* @param owner the owner of this buffer
* @param path the path of the file that backs the buffer
* @since 3.2
*/
public DocumentAdapter(IOpenable owner, IPath path) {
Assert.isLegal(path != null);
fOwner = owner;
fPath = path;
fLocationKind = LocationKind.NORMALIZE;
initialize();
}
/**
* Constructs a new document adapter.
*
* @param owner the owner of this buffer
* @param fileStore the file store of the file that backs the buffer
* @param path the path of the file that backs the buffer
* @since 3.6
*/
public DocumentAdapter(IOpenable owner, IFileStore fileStore, IPath path) {
Assert.isLegal(fileStore != null);
Assert.isLegal(path != null);
fOwner = owner;
fFileStore = fileStore;
fPath = path;
fLocationKind = LocationKind.NORMALIZE;
initialize();
}
/**
* Constructs a new document adapter.
*
* @param owner the owner of this buffer
* @param file the <code>IFile</code> that backs the buffer
*/
public DocumentAdapter(IOpenable owner, IFile file) {
fOwner = owner;
fFile = file;
fPath = fFile.getFullPath();
fLocationKind = LocationKind.IFILE;
initialize();
}
private void initialize() {
ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager();
try {
if (fFileStore != null) {
manager.connectFileStore(fFileStore, new NullProgressMonitor());
fTextFileBuffer = manager.getFileStoreTextFileBuffer(fFileStore);
} else {
manager.connect(fPath, fLocationKind, new NullProgressMonitor());
fTextFileBuffer = manager.getTextFileBuffer(fPath, fLocationKind);
}
fDocument = fTextFileBuffer.getDocument();
} catch (CoreException x) {
fDocument = manager.createEmptyDocument(fPath, fLocationKind);
if (fDocument instanceof ISynchronizable)
((ISynchronizable) fDocument).setLockObject(new Object());
}
fDocument.addDocumentListener(this);
fIsClosed = false;
}
/**
* Returns the adapted document.
*
* @return the adapted document
*/
public IDocument getDocument() {
return fDocument;
}
/*
* @see IBuffer#addBufferChangedListener(IBufferChangedListener)
*/
@Override
public void addBufferChangedListener(IBufferChangedListener listener) {
Assert.isNotNull(listener);
if (!fBufferListeners.contains(listener))
fBufferListeners.add(listener);
}
/*
* @see IBuffer#removeBufferChangedListener(IBufferChangedListener)
*/
@Override
public void removeBufferChangedListener(IBufferChangedListener listener) {
Assert.isNotNull(listener);
fBufferListeners.remove(listener);
}
/*
* @see IBuffer#append(char[])
*/
@Override
public void append(char[] text) {
append(new String(text));
}
/*
* @see IBuffer#append(String)
*/
@Override
public void append(String text) {
if (DEBUG_LINE_DELIMITERS) {
validateLineDelimiters(text);
}
fReplaceCmd.replace(fDocument.getLength(), 0, text);
}
/*
* @see IBuffer#close()
*/
@Override
public void close() {
if (isClosed())
return;
IDocument d = fDocument;
fDocument = new Document();
fIsClosed = true;
d.removeDocumentListener(this);
if (fTextFileBuffer != null) {
ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager();
try {
if (fFileStore != null)
manager.disconnectFileStore(fFileStore, new NullProgressMonitor());
else
manager.disconnect(fPath, fLocationKind, new NullProgressMonitor());
} catch (CoreException x) {
}
fTextFileBuffer = null;
}
fireBufferChanged(new BufferChangedEvent(this, 0, 0, null));
fBufferListeners.clear();
}
/*
* @see IBuffer#getChar(int)
*/
@Override
public char getChar(int position) {
try {
return fDocument.getChar(position);
} catch (BadLocationException x) {
throw new ArrayIndexOutOfBoundsException();
}
}
/*
* @see IBuffer#getCharacters()
*/
@Override
public char[] getCharacters() {
String content = getContents();
return content == null ? null : content.toCharArray();
}
/*
* @see IBuffer#getContents()
*/
@Override
public String getContents() {
return fDocument.get();
}
/*
* @see IBuffer#getLength()
*/
@Override
public int getLength() {
return fDocument.getLength();
}
/*
* @see IBuffer#getOwner()
*/
@Override
public IOpenable getOwner() {
return fOwner;
}
/*
* @see IBuffer#getText(int, int)
*/
@Override
public String getText(int offset, int length) {
try {
return fDocument.get(offset, length);
} catch (BadLocationException x) {
throw new ArrayIndexOutOfBoundsException();
}
}
/*
* @see IBuffer#getUnderlyingResource()
*/
@Override
public IResource getUnderlyingResource() {
return fFile;
}
/*
* @see IBuffer#hasUnsavedChanges()
*/
@Override
public boolean hasUnsavedChanges() {
return fTextFileBuffer != null ? fTextFileBuffer.isDirty() : false;
}
/*
* @see IBuffer#isClosed()
*/
@Override
public boolean isClosed() {
return fIsClosed;
}
/*
* @see IBuffer#isReadOnly()
*/
@Override
public boolean isReadOnly() {
if (fTextFileBuffer != null)
return !fTextFileBuffer.isCommitable();
IResource resource = getUnderlyingResource();
if (resource == null)
return true;
final ResourceAttributes attributes = resource.getResourceAttributes();
return attributes == null ? false : attributes.isReadOnly();
}
/*
* @see IBuffer#replace(int, int, char[])
*/
@Override
public void replace(int position, int length, char[] text) {
replace(position, length, new String(text));
}
/*
* @see IBuffer#replace(int, int, String)
*/
@Override
public void replace(int position, int length, String text) {
if (DEBUG_LINE_DELIMITERS) {
validateLineDelimiters(text);
}
fReplaceCmd.replace(position, length, text);
}
/*
* @see IBuffer#save(IProgressMonitor, boolean)
*/
@Override
public void save(IProgressMonitor progress, boolean force) throws JavaModelException {
try {
if (fTextFileBuffer != null)
fTextFileBuffer.commit(progress, force);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
/*
* @see IBuffer#setContents(char[])
*/
@Override
public void setContents(char[] contents) {
setContents(new String(contents));
}
/*
* @see IBuffer#setContents(String)
*/
@Override
public void setContents(String contents) {
int oldLength = fDocument.getLength();
if (contents == null) {
if (oldLength != 0)
//$NON-NLS-1$
fSetCmd.set(//$NON-NLS-1$
"");
} else {
// set only if different
if (DEBUG_LINE_DELIMITERS) {
validateLineDelimiters(contents);
}
if (!contents.equals(fDocument.get()))
fSetCmd.set(contents);
}
}
private void validateLineDelimiters(String contents) {
if (fLegalLineDelimiters == null) {
// collect all line delimiters in the document
HashSet<String> existingDelimiters = new HashSet();
for (int i = fDocument.getNumberOfLines() - 1; i >= 0; i--) {
try {
String curr = fDocument.getLineDelimiter(i);
if (curr != null) {
existingDelimiters.add(curr);
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
if (existingDelimiters.isEmpty()) {
// first insertion of a line delimiter: no test
return;
}
fLegalLineDelimiters = existingDelimiters;
}
DefaultLineTracker tracker = new DefaultLineTracker();
tracker.set(contents);
int lines = tracker.getNumberOfLines();
if (lines <= 1)
return;
for (int i = 0; i < lines; i++) {
try {
String curr = tracker.getLineDelimiter(i);
if (curr != null && !fLegalLineDelimiters.contains(curr)) {
StringBuffer buf = new StringBuffer("WARNING: javaeditor.DocumentAdapter added new line delimiter to code: ");
for (int k = 0; k < curr.length(); k++) {
if (k > 0)
buf.append(' ');
buf.append((int) curr.charAt(k));
}
IStatus status = new Status(IStatus.WARNING, JavaUI.ID_PLUGIN, IStatus.OK, buf.toString(), new Throwable());
JavaPlugin.log(status);
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
}
/*
* @see IDocumentListener#documentAboutToBeChanged(DocumentEvent)
*/
@Override
public void documentAboutToBeChanged(DocumentEvent event) {
// there is nothing to do here
}
/*
* @see IDocumentListener#documentChanged(DocumentEvent)
*/
@Override
public void documentChanged(DocumentEvent event) {
fireBufferChanged(new BufferChangedEvent(this, event.getOffset(), event.getLength(), event.getText()));
}
private void fireBufferChanged(BufferChangedEvent event) {
if (fBufferListeners != null && fBufferListeners.size() > 0) {
Iterator<IBufferChangedListener> e = new ArrayList(fBufferListeners).iterator();
while (e.hasNext()) e.next().bufferChanged(event);
}
}
/**
* {@inheritDoc}
* <p>
* <strong>Note:</strong> This implementation applies the edits in a rewrite session.
*
* @since 3.4
*/
@Override
public UndoEdit applyTextEdit(TextEdit edit, IProgressMonitor monitor) throws JavaModelException {
return fTextEditCmd.applyTextEdit(edit);
}
}
| 28.246951
| 145
| 0.601187
|
fbeee6c3fa82f4b77ee0c267946d45aa8e8e516f
| 1,722
|
/*
* (C) Janne Jalkanen 2005
*
*/
package com.ecyrd.jspwiki.ui;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class RedirectCommandTest extends TestCase
{
protected void tearDown() throws Exception
{
}
public void testStaticCommand()
{
Command a = RedirectCommand.REDIRECT;
assertEquals( "", a.getRequestContext() );
assertEquals( "", a.getJSP() );
assertEquals( "%u%n", a.getURLPattern() );
assertNull( a.getContentTemplate() );
assertNull( a.getTarget() );
assertEquals( a, RedirectCommand.REDIRECT );
}
public void testTargetedCommand()
{
Command a = RedirectCommand.REDIRECT;
// Test with local JSP
Command b = a.targetedCommand( "%uTestPage.jsp" );
assertEquals( "", b.getRequestContext() );
assertEquals( "TestPage.jsp", b.getJSP() );
assertEquals( "%uTestPage.jsp", b.getURLPattern() );
assertNull( b.getContentTemplate() );
assertEquals( "%uTestPage.jsp", b.getTarget() );
assertNotSame( RedirectCommand.REDIRECT, b );
// Test with non-local URL
b = a.targetedCommand( "http://www.yahoo.com" );
assertEquals( "", b.getRequestContext() );
assertEquals( "http://www.yahoo.com", b.getJSP() );
assertEquals( "http://www.yahoo.com", b.getURLPattern() );
assertNull( b.getContentTemplate() );
assertEquals( "http://www.yahoo.com", b.getTarget() );
assertNotSame( RedirectCommand.REDIRECT, b );
}
public static Test suite()
{
return new TestSuite( RedirectCommandTest.class );
}
}
| 30.75
| 66
| 0.61324
|
68d3e4f1881e4b119032f0f1a7d9af57af1c3749
| 1,362
|
import java.util.HashMap;
class Solution {
public int maxPoints(int[][] points) {
if (points == null || points.length <= 0) {
return 0;
}
int maxCount = 0;
for (int i = 0; i < points.length; i++) {
HashMap<Double, Integer> map = new HashMap<>();
int[] refPoint = points[i];
int same = 0;
for (int j = 0; j < points.length; j++) {
if (i != j) {
if (points[j][0] == refPoint[0] && points[j][1] == refPoint[1]) {
same = same + 1;
maxCount = Math.max(maxCount, same);
continue;
} else {
Double slope = Double.MAX_VALUE;
if (points[j][0] != refPoint[0]) {
slope = (((double) points[j][1] - refPoint[1]) / ((double) points[j][0] - refPoint[0]));
}
System.out.println(i + "," + j + "," + slope);
int currentSlopeCount = map.getOrDefault(slope, 0);
map.put(slope, currentSlopeCount + 1);
maxCount = Math.max(maxCount, currentSlopeCount + 1 + same);
}
}
}
}
return maxCount + 1;
}
}
| 40.058824
| 116
| 0.400147
|
e4dba5c49b8ba6df081b8d2d6312e3df80790ad7
| 3,107
|
package com.pertamina.tbbm.rewulu.ecodriving.helpers;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.widget.LinearLayout;
public class GraphHelper {
private XYSeries xySeries;
private GraphicalView chartView;
private XYMultipleSeriesDataset dataset;
private XYMultipleSeriesRenderer renderer;
int graphMax = 10;
int graphStart = 0;
public GraphHelper(Context context, LinearLayout container) {
// TODO Auto-generated constructor stub
xySeries = new XYSeries("s/km");
// Now we add our series
dataset = new XYMultipleSeriesDataset();
xySeries.add(0, 0);
dataset.addSeries(xySeries);
// addSeries(0.2);
XYSeriesRenderer xySeriesRenderer = new XYSeriesRenderer();
xySeriesRenderer.setLineWidth(5);
xySeriesRenderer.setColor(Color.BLUE);
// Include low and max value
xySeriesRenderer.setDisplayBoundingPoints(true);
// we add point markers
xySeriesRenderer.setPointStyle(PointStyle.POINT);
xySeriesRenderer.setPointStrokeWidth(7);
// Finaly we create the multiple series renderer to control the graph
renderer = new XYMultipleSeriesRenderer();
renderer.addSeriesRenderer(xySeriesRenderer);
// We want to avoid black border
renderer.setMarginsColor(Color.argb(0x00, 0xff, 0x00, 0x00)); // transparent
// Disable Pan on two axis
renderer.setPanEnabled(true, false);
renderer.setXTitle("jarak (km)");
renderer.setYTitle("waktu (detik)");
renderer.setXAxisMin(0);
renderer.setXAxisMax(5);
renderer.setXLabels(6);
renderer.setXRoundedLabels(true);
renderer.setYAxisMin(0);
renderer.setYAxisMax(200);
renderer.setYLabels(5);
renderer.setShowGrid(true);
renderer.setGridColor(Color.WHITE);
renderer.setInScroll(true);
renderer.setAxesColor(Color.BLACK);
renderer.setLabelsColor(Color.BLACK);
renderer.setXLabelsColor(Color.RED);
renderer.setYLabelsColor(0, Color.RED);
renderer.setFitLegend(true);
renderer.setLabelsTextSize(18);
renderer.setAxisTitleTextSize(24);
renderer.setLegendTextSize(24);
renderer.setMargins(new int[] { 20, 48, 16, 16 });
renderer.setYLabelsAlign(Align.LEFT);
chartView = ChartFactory.getLineChartView(context, dataset, renderer);
container.addView(chartView);
}
public void addSeriesChart(double x, double y) {
// TODO Auto-generated method stub
int maxX = (int) xySeries.getMaxX();
dataset.clear();
xySeries.add(x, y);
dataset.addSeries(xySeries);
if (maxX + 0.5d > renderer.getXAxisMax()) {
// renderer.setXLabels(7);
renderer.setXAxisMin(maxX - 1);
renderer.setXAxisMax(maxX + 4);
}
int maxY = (int) xySeries.getMaxY();
if (maxY > renderer.getYAxisMax()) {
renderer.setYAxisMin(0);
renderer.setYAxisMax(maxY + 10);
}
chartView.repaint();
}
}
| 31.07
| 78
| 0.761828
|
1d4479e7b1cba96fbea2723612db35236b743ecc
| 4,173
|
package fr.eni.maximot;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Maximot {
public final static Scanner SCAN = new Scanner(System.in);
public static void main(String[] args) {
final String PATH = "dictionnaire.txt";
String word = "";
String setOfLetters = "";
String input = "";
word = getRandomWord(PATH);
try {
setOfLetters = shuffleLettersIn(word);
input = askForInput(setOfLetters);
printResult(input, setOfLetters, word, PATH);
} catch (Exception e ) {
System.err.println(e.getMessage());
}
SCAN.close();
}
private static void printResult(String input, String mixedWord, String word, String path) {
boolean found = false;
if(input.compareTo(word) == 0) {
System.out.println("Félicitations! " + input + " est bien le plus long que vous puissiez former avec les lettres : " + mixedWord);
} else {
try(FileInputStream dictionnary = new FileInputStream(path)) {
Scanner reader = new Scanner(dictionnary);
while(reader.hasNextLine() && !found) {
found = (input.compareTo(reader.nextLine().toUpperCase()) == 0);
}
System.out.println(found ? "Le mot " + input + " n'était pas le mot le plus long, mais il existe tout de même! Bravo!" : "Désolé! " + input + " n'est pas dans le dico!");
} catch(FileNotFoundException e) {
System.err.println("Impossible de vérifier l'existence du mot : le fichier " + path + " n'a pas été trouvé.");
} catch(IOException e) {
System.err.println("Impossible de vérifier l'existence du mot : le fichier " + path + " n'a pas pu être lu.");
}
}
}
private static String askForInput(String setOfLetters) {
String input = "";
System.out.println("Formez le mot le plus long possible avec le tirage de lettres suivant :");
System.out.println(setOfLetters);
System.out.println();
System.out.println("-> À vous de jouer ! ");
System.out.println();
do {
System.out.println("Écrivez un mot uniquement avec les lettres que vous avez tirées :");
input = SCAN.nextLine();
} while(!foundInSet(setOfLetters,input));
return input.toUpperCase();
}
private static boolean foundInSet(String setOfLetters, String input) {
boolean found = false;
int i = 0;
do {
found = (setOfLetters.indexOf(input.toUpperCase().charAt(i)) >= 0);
i++;
} while(found && i<input.length());
return found;
}
private static String shuffleLettersIn(String word) throws Exception {
if(word.isBlank()) throw new Exception("Erreur: le mot généré à partir du dictionnaire est vide. Impossible de lancer le jeu.");
else {
char letters[] = word.toCharArray();
char temp;
Random rand = new Random();
for(int i = 0, j = 0; i<letters.length; i++) {
j = rand.nextInt(letters.length);
temp = letters[i];
letters[i] = letters[j];
letters[j] = temp;
}
return String.valueOf(letters);
}
}
private static String getRandomWord(String path) {
String word = "";
try(FileInputStream dictionnary = new FileInputStream(path)) {
Scanner reader = new Scanner(dictionnary);
int rand = new Random().nextInt(countLinesIn(path));
for(int i = 0; i<rand; i++)
reader.nextLine();
word = reader.nextLine().toUpperCase();
} catch(FileNotFoundException e) {
System.err.println("Impossible de générer le mot demandé : le fichier " + path + " n'a pas été trouvé.");
} catch(IOException e) {
System.err.println("Impossible de générer le mot demandé : le fichier " + path + " n'a pas pu être lu.");
}
return word;
}
private static int countLinesIn(String path) {
int counter = 0;
try(FileInputStream dictionnary = new FileInputStream(path)) {
Scanner reader = new Scanner(dictionnary);
while(reader.hasNextLine()) {
reader.nextLine();
counter++;
}
} catch(FileNotFoundException e) {
System.err.println("Impossible de générer le mot demandé : le fichier " + path + " n'a pas été trouvé.");
} catch(IOException e) {
System.err.println("Impossible de générer le mot demandé : le fichier " + path + " n'a pas pu être lu.");
}
return counter;
}
}
| 34.487603
| 174
| 0.67745
|
f8015577ffaa2735695a6c659f62b6c74fa45f91
| 3,635
|
package mods.railcraft.advancements;
import com.google.gson.JsonObject;
import mods.railcraft.Railcraft;
import mods.railcraft.util.JsonTools;
import mods.railcraft.util.LevelUtil;
import net.minecraft.advancements.critereon.AbstractCriterionTriggerInstance;
import net.minecraft.advancements.critereon.DeserializationContext;
import net.minecraft.advancements.critereon.EntityPredicate;
import net.minecraft.advancements.critereon.ItemPredicate;
import net.minecraft.advancements.critereon.LocationPredicate;
import net.minecraft.advancements.critereon.NbtPredicate;
import net.minecraft.advancements.critereon.SerializationContext;
import net.minecraft.advancements.critereon.SimpleCriterionTrigger;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
public class SpikeMaulUseTrigger extends SimpleCriterionTrigger<SpikeMaulUseTrigger.Instance> {
private static final ResourceLocation ID = new ResourceLocation(Railcraft.ID, "spike_maul_use");
@Override
public ResourceLocation getId() {
return ID;
}
@Override
public SpikeMaulUseTrigger.Instance createInstance(JsonObject json,
EntityPredicate.Composite entityPredicate, DeserializationContext parser) {
NbtPredicate nbt =
JsonTools.whenPresent(json, "nbt", NbtPredicate::fromJson, NbtPredicate.ANY);
ItemPredicate tool =
JsonTools.whenPresent(json, "tool", ItemPredicate::fromJson, ItemPredicate.ANY);
LocationPredicate locationPredicate = JsonTools.whenPresent(json, "location",
LocationPredicate::fromJson, LocationPredicate.ANY);
return new SpikeMaulUseTrigger.Instance(entityPredicate, nbt, tool, locationPredicate);
}
/**
* Invoked when the user successfully uses a spike maul.
*/
public void trigger(ServerPlayer playerEntity, ItemStack item,
ServerLevel world, BlockPos pos) {
this.trigger(playerEntity, (criterionInstance) -> criterionInstance.matches(item, world, pos));
}
public static class Instance extends AbstractCriterionTriggerInstance {
private final NbtPredicate nbt;
private final ItemPredicate tool;
private final LocationPredicate location;
private Instance(EntityPredicate.Composite entityPredicate, NbtPredicate nbt,
ItemPredicate tool, LocationPredicate predicate) {
super(SpikeMaulUseTrigger.ID, entityPredicate);
this.nbt = nbt;
this.tool = tool;
this.location = predicate;
}
public static SpikeMaulUseTrigger.Instance hasUsedSpikeMaul() {
return new SpikeMaulUseTrigger.Instance(EntityPredicate.Composite.ANY,
NbtPredicate.ANY, ItemPredicate.ANY, LocationPredicate.ANY);
}
public boolean matches(ItemStack item, ServerLevel level, BlockPos pos) {
return LevelUtil
.getBlockEntity(level, pos)
.map(blockEntity -> blockEntity.save(new CompoundTag()))
.map(this.nbt::matches)
.orElse(false)
&& this.tool.matches(item)
&& this.location.matches(level, pos.getX(), pos.getY(), pos.getZ());
}
@Override
public ResourceLocation getCriterion() {
return ID;
}
@Override
public JsonObject serializeToJson(SerializationContext serializer) {
JsonObject json = new JsonObject();
json.add("nbt", this.nbt.serializeToJson());
json.add("tool", this.tool.serializeToJson());
json.add("location", this.location.serializeToJson());
return json;
}
}
}
| 38.263158
| 99
| 0.756259
|
830a1256132d8e330c3cce74f3221f8c8e7109d9
| 14,032
|
package io.github.yangxlei.bjnetwork.websocket;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import io.github.yangxlei.bjnetwork.BJNetworkClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.ws.WebSocket;
import okhttp3.ws.WebSocketCall;
import okhttp3.ws.WebSocketListener;
import okio.Buffer;
/**
* Created by yanglei on 16/6/28.
*/
public class BJWebSocketClient {
public enum State {
Offline, Connecting, Connected
}
public enum LogLevel {
None, Info, Body
}
public static int ERROR_CODE_CLOSE_BY_USER = 3998;
public static int ERROR_CODE_CLIENT_EXCEPTION = 3999;
public static int MESSAGE_SEND_RETRY_COUNT = 5;
private BJNetworkClient mNetworkClient;
private WebSocketCall mWebSocketCall;
private WebSocket mWebSocket;
private BJWebSocketListener mListener;
private WSListener mWSListener;
private SendMessageThread mSendMessageThread;
private State mState = State.Offline;
private String address;
private String mClientName;
private LogLevel mLogLevel = LogLevel.Info;
public BJWebSocketClient(String name) {
this(name, null);
}
public BJWebSocketClient(String name, BJNetworkClient networkClient) {
if (networkClient == null) {
mNetworkClient = new BJNetworkClient.Builder()
.setReadTimeoutAtSeconds(600)
.build();
} else {
mNetworkClient = networkClient;
}
mSendMessageThread = new SendMessageThread();
mClientName = name;
}
private ReconnectSignalHandler mReconnectSignalHandler;
private static class ReconnectSignalHandler extends Handler {
private WeakReference<BJWebSocketClient> mWebSocketClient ;
private HandlerThread mHandlerThread;
private ReconnectSignalHandler(BJWebSocketClient client, HandlerThread handlerThread) {
super(handlerThread.getLooper());
mWebSocketClient = new WeakReference<>(client);
mHandlerThread = handlerThread;
}
private void sendReconnectSignal() {
if (! mHandlerThread.isAlive()) return;
Message message = new Message();
message.what = 0;
sendMessageDelayed(message, 500);
}
private void quitReconnect() {
removeMessages(0);
mHandlerThread.quit();
}
@Override
public void handleMessage(Message msg) {
if (mWebSocketClient.get() == null) return;
BJWebSocketClient client = mWebSocketClient.get();
client.connect();
}
}
public void setClientName(String clientName) {
mClientName = clientName;
}
public String getClientName() {
if (mClientName == null) {
mClientName = "BJWebSocketClient";
}
return mClientName;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public void setListener(BJWebSocketListener listener) {
mListener = listener;
}
public State getState() {
return mState;
}
public List<BJMessageBody> getRequestQueue() {
return new ArrayList<>(mSendMessageThread.mMessageQueue);
}
public void setLogLevel(LogLevel logLevel) {
assert (logLevel != null);
mLogLevel = logLevel;
}
private void setAndNotifyStateChanged(State state) {
if (mState == state) return;
mState = state;
if (mListener != null) {
mListener.onStateChanged(this, mState);
}
}
public void connect() {
logInfo("connect() while environment is " +
"(state="+mState+", address="+address+", " +
"SendMsgQueueSize="+mSendMessageThread.mMessageQueue.size()+")");
if (mState != State.Offline) return;
if (TextUtils.isEmpty(address)) {
throw new NullPointerException("address is empty!");
}
if (mReconnectSignalHandler == null) {
HandlerThread handlerThread = new HandlerThread("ReconnectSignalHandlerThread");
handlerThread.start();
mReconnectSignalHandler = new ReconnectSignalHandler(this, handlerThread);
}
setAndNotifyStateChanged(State.Connecting);
Request request = new Request.Builder().url(getAddress())
.build();
mWebSocketCall = WebSocketCall.create(mNetworkClient.getOkHttpClient(),
request);
mWSListener = new WSListener();
mWebSocketCall.enqueue(mWSListener);
if (mSendMessageThread.getState() != Thread.State.NEW) {
mSendMessageThread = mSendMessageThread.clone();
}
}
public void disconnect() {
disconnect(ERROR_CODE_CLOSE_BY_USER, "user close ws client.");
}
private synchronized void disconnect(int code, String reason) {
logInfo(" disconnect("+code+", "+reason+") " +
"while environment is (state="+mState+", address="+address+", " +
"SendMsgQueueSize="+mSendMessageThread.mMessageQueue.size()+")");
if (mSendMessageThread != null) {
mSendMessageThread.interrupt();
}
if (code == ERROR_CODE_CLOSE_BY_USER) {
if (mReconnectSignalHandler != null) {
mReconnectSignalHandler.quitReconnect();
}
mReconnectSignalHandler = null;
}
if (mState == State.Offline) return;
setAndNotifyStateChanged(State.Offline);
try {
if (mWebSocket != null) {
mWebSocket.close(code, reason);
} else {
if (mWebSocketCall != null) {
mWebSocketCall.cancel();
mWebSocketCall = null;
}
if (code != ERROR_CODE_CLOSE_BY_USER) {
// 非用户主动退出
if (mListener != null) {
mListener.onReconnect(this);
}
// connect();
if (mReconnectSignalHandler != null) {
mReconnectSignalHandler.sendReconnectSignal();
}
}
}
} catch (Exception e) {
e.printStackTrace();
if (mWebSocketCall != null) {
mWebSocketCall.cancel();
mWebSocketCall = null;
}
if (code != ERROR_CODE_CLOSE_BY_USER) {
// 非用户主动退出
if (mListener != null) {
mListener.onReconnect(this);
}
// connect();
if (mReconnectSignalHandler != null) {
mReconnectSignalHandler.sendReconnectSignal();
}
}
}
}
public void sendMessage(String messag) {
sendMessage(messag, MESSAGE_SEND_RETRY_COUNT);
}
public void sendMessage(String message, int retryCount) {
assert (message != null);
assert (retryCount >= 0);
mSendMessageThread.add(message, retryCount);
}
private class WSListener implements WebSocketListener {
@Override
public void onOpen(WebSocket webSocket, Response response) {
logInfo(" onOpen() while environment is " +
"(state="+mState+", address="+address+", " +
"SendMsgQueueSize="+mSendMessageThread.mMessageQueue.size()+")");
setAndNotifyStateChanged(State.Connected);
mWebSocket = webSocket;
mSendMessageThread.start();
}
@Override
public void onFailure(IOException e, Response response) {
logException(e, " onFailure() while environment is " +
"(state="+mState+", address="+address+", " +
"SendMsgQueueSize="+mSendMessageThread.mMessageQueue.size()+")");
e.printStackTrace();
disconnect(ERROR_CODE_CLIENT_EXCEPTION, e.getMessage());
}
@Override
public void onMessage(ResponseBody message) throws IOException {
logInfo(" onMessage("+message+") while environment is " +
"(state="+mState+", address="+address+", " +
"SendMsgQueueSize="+mSendMessageThread.mMessageQueue.size()+")");
try {
if (mListener != null) {
if (message.contentType() == WebSocket.TEXT) {
String result = message.string();
logData("onMessage() recv TEXT: " + result);
mListener.onMessage(BJWebSocketClient.this, result);
} else {
mListener.onMessage(BJWebSocketClient.this, message.byteStream());
}
}
message.close();
} catch (IOException e) {
e.printStackTrace();
logException(e, "onMessage()");
}
}
@Override
public void onPong(Buffer payload) {
}
@Override
public void onClose(int code, String reason) {
logInfo(" onClose("+code+", "+reason+") while environment is " +
"(state="+mState+", address="+address+", " +
"SendMsgQueueSize="+mSendMessageThread.mMessageQueue.size()+")");
if (mWebSocketCall != null) {
mWebSocketCall.cancel();
mWebSocketCall = null;
}
setAndNotifyStateChanged(State.Offline);
if (code != ERROR_CODE_CLOSE_BY_USER) {
// 非用户主动退出
if (mListener != null) {
mListener.onReconnect(BJWebSocketClient.this);
}
if (code != ERROR_CODE_CLIENT_EXCEPTION) {
disconnect(code, reason);
}
// connect();
if (mReconnectSignalHandler != null) {
mReconnectSignalHandler.sendReconnectSignal();
}
} else {
if (mListener != null) {
if(mSendMessageThread.mMessageQueue.size() > 0) {
BJMessageBody body = mSendMessageThread.mMessageQueue.poll();
while (body != null) {
mListener.onSentMessageFailure(BJWebSocketClient.this, body);
body = mSendMessageThread.mMessageQueue.poll();
}
}
mListener.onClose(BJWebSocketClient.this);
}
}
}
}
private void logInfo(String log) {
if (mLogLevel == LogLevel.Info || mLogLevel == LogLevel.Body) {
Log.i(getClientName(), log);
}
}
private void logData(String data) {
if (mLogLevel == LogLevel.Body) {
Log.i(getClientName(), data);
}
}
private void logException(Exception e, String ext) {
String message = e.getMessage();
if (message == null && e.getCause() != null) {
message = e.getCause().getMessage();
}
if (message == null) {
message = e.toString();
}
Log.e(getClientName(), ext + " " + message);
}
private class SendMessageThread extends Thread implements Cloneable {
private LinkedBlockingQueue<BJMessageBody> mMessageQueue = new LinkedBlockingQueue<>();
private SendMessageThread() {
super("SendMessageThread");
setDaemon(true);
}
public void add(String message, int retryCount) {
BJMessageBody messageBody = new BJMessageBody(message, retryCount);
messageBody.retryCount = retryCount;
mMessageQueue.add(messageBody);
}
@Override
public void run() {
BJMessageBody message = null;
while (! interrupted()) {
if (message != null) {
try {
RequestBody body = RequestBody.create(WebSocket.TEXT, message.getContent());
mWebSocket.sendMessage(body);
if (mLogLevel == LogLevel.Info) {
logInfo("sendMessage() BJMessageBody(" + message.hashCode() + ", " + (message.originRetryCount - message.retryCount) +" retry)");
} else {
logData("sendMessage() BJMessageBody(" + message + ")");
}
} catch (IOException e) {
e.printStackTrace();
if (message.retryCount >= 0) {
// 发送失败继续重试
message.retryCount -- ;
mMessageQueue.add(message);
} else {
if (mListener != null) {
mListener.onSentMessageFailure(BJWebSocketClient.this, message);
}
}
}
}
try {
message = mMessageQueue.take();
} catch (InterruptedException ignore) {
break;
}
}
}
@Override
protected SendMessageThread clone() {
SendMessageThread thread = new SendMessageThread();
thread.mMessageQueue = new LinkedBlockingQueue<>(mMessageQueue);
return thread;
}
}
}
| 31.890909
| 158
| 0.546893
|
1d59633d0f7ce648d038d19ba4809d45443b5e89
| 2,328
|
package com.coymaple.spring.config;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
@ComponentScan(basePackages = {"com.coymaple"},excludeFilters= {@Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class)})
@PropertySource(value= {"classpath:jdbc.properties"},ignoreResourceNotFound=true)
//@PropertySource(value= {"jdbc.properties"},ignoreResourceNotFound=true)
@EnableTransactionManagement
public class AppConfig {
@Resource
private Environment environment;
@Resource
private DataSource driverManagerDataSource;
@Bean(name= {"driverManagerDataSource"})
public DriverManagerDataSource driverManagerDataSource() {
DriverManagerDataSource dmds = new DriverManagerDataSource();
dmds.setDriverClassName(environment.getProperty("jdbc.className"));
dmds.setUrl(environment.getProperty("jdbc.url"));
dmds.setUsername(environment.getProperty("jdbc.userName"));
dmds.setPassword(environment.getProperty("jdbc.password"));
return dmds;
}
@Bean
public DruidDataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
@Bean()
public DataSourceTransactionManager txManager() {
DataSourceTransactionManager dstm = new DataSourceTransactionManager(driverManagerDataSource);
return dstm;
}
@Bean()
public JdbcTemplate jdbcTemplate() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);
return jdbcTemplate;
}
}
| 35.815385
| 127
| 0.802835
|
4def11f7cfc21d7a85f6004717116f0a6b16e1d0
| 5,425
|
/*
* @(#)LoadFileAction.java
*
* Copyright (c) 1996-2010 by the original authors of JHotDraw
* and all its contributors.
* All rights reserved.
*
* The copyright of this software is owned by the authors and
* contributors of the JHotDraw project ("the copyright holders").
* You may not use, copy or modify this software, except in
* accordance with the license agreement you entered into with
* the copyright holders. For details see accompanying license terms.
*/
package org.jhotdraw.app.action.file;
import java.awt.Component;
import java.awt.Window;
import org.jhotdraw.util.*;
import org.jhotdraw.gui.*;
import org.jhotdraw.gui.event.*;
import javax.swing.*;
import java.io.*;
import java.net.URI;
import org.jhotdraw.app.Application;
import org.jhotdraw.app.View;
import org.jhotdraw.app.action.AbstractSaveUnsavedChangesAction;
import org.jhotdraw.gui.URIChooser;
import org.jhotdraw.io.ExtensionFileFilter;
import org.jhotdraw.net.URIUtil;
/**
* Lets the user save unsaved changes of the active view, then presents
* an {@code URIChooser} and loads the selected URI into the active view.
* <p>
* This action is called when the user selects the Load item in the File
* menu. The menu item is automatically created by the application.
* A Recent Files sub-menu is also automatically generated.
* <p>
* If you want this behavior in your application, you have to create it
* and put it in your {@code ApplicationModel} in method
* {@link org.jhotdraw.app.ApplicationModel#initApplication}.
* <p>
* This action is designed for applications which do not automatically
* create a new view for each opened file. This action goes together with
* {@link ClearFileAction}, {@link NewWindowAction}, {@link LoadFileAction},
* {@link LoadDirectoryAction} and {@link CloseFileAction}.
* This action should not be used together with {@link OpenFileAction}.
*
* @author Werner Randelshofer
* @version $Id: LoadFileAction.java 604 2010-01-09 12:00:29Z rawcoder $
*/
public class LoadFileAction extends AbstractSaveUnsavedChangesAction {
public final static String ID = "file.load";
/** Creates a new instance. */
public LoadFileAction(Application app, View view) {
super(app, view);
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
labels.configureAction(this, ID);
}
protected URIChooser getChooser(View view) {
URIChooser chsr = (URIChooser) (view.getComponent()).getClientProperty("loadChooser");
if (chsr == null) {
chsr = getApplication().getModel().createSaveChooser(getApplication(), view);
view.getComponent().putClientProperty("loadChooser", chsr);
}
return chsr;
}
public void doIt(final View view) {
URIChooser fileChooser = getChooser(view);
Window wAncestor = SwingUtilities.getWindowAncestor(view.getComponent());
final Component oldFocusOwner = (wAncestor == null) ? null : wAncestor.getFocusOwner();
JSheet.showOpenSheet(fileChooser, view.getComponent(), new SheetListener() {
public void optionSelected(final SheetEvent evt) {
if (evt.getOption() == JFileChooser.APPROVE_OPTION) {
final URI uri;
if ((evt.getChooser() instanceof JFileURIChooser) && evt.getFileChooser().getFileFilter() instanceof ExtensionFileFilter) {
uri = ((ExtensionFileFilter) evt.getFileChooser().getFileFilter()).makeAcceptable(evt.getFileChooser().getSelectedFile()).toURI();
} else {
uri = evt.getChooser().getSelectedURI();
}
loadViewFromURI(view, uri, evt.getChooser());
} else {
view.setEnabled(true);
if (oldFocusOwner != null) {
oldFocusOwner.requestFocus();
}
}
}
});
}
public void loadViewFromURI(final View view, final URI uri, final URIChooser chooser) {
view.setEnabled(false);
// Open the file
view.execute(new Worker() {
protected Object construct() throws IOException {
view.read(uri, chooser);
return null;
}
@Override
protected void done(Object value) {
view.setURI(uri);
view.setEnabled(true);
getApplication().addRecentURI(uri);
}
@Override
protected void failed(Throwable value) {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
JSheet.showMessageSheet(view.getComponent(),
"<html>" + UIManager.getString("OptionPane.css") +
"<b>" + labels.getFormatted("file.load.couldntLoad.message", URIUtil.getName(uri)) + "</b><p>" +
((value == null) ? "" : value),
JOptionPane.ERROR_MESSAGE, new SheetListener() {
public void optionSelected(SheetEvent evt) {
view.clear();
view.setEnabled(true);
}
});
}
});
}
}
| 40.185185
| 158
| 0.61659
|
82ceec52441ca20d5d0f2402e4cb8441ebcee94e
| 511
|
package com.lchng.ripple.sampleyelpapp.home.model;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public class RestaurantResponse implements Serializable{
@SerializedName("businesses")
private List<Restaurant> restaurants;
private Map<String,Object> region;
public List<Restaurant> getRestaurants() {
return restaurants;
}
public Map<String, Object> getRegion() {
return region;
}
}
| 22.217391
| 56
| 0.731898
|
32f4d52f58072f3669f520e553a6122e21d50103
| 284
|
package hu.elte.tancify.repository;
import hu.elte.tancify.model.Lesson;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface LessonRepository extends CrudRepository<Lesson, Long> {}
| 35.5
| 73
| 0.838028
|
2fa19de72b5d1eab35f390fdca450b5aefefbd9f
| 5,155
|
package android.support.v7.p015b;
/* renamed from: android.support.v7.b.d */
public final class C0235d {
public static final int abc_background_cache_hint_selector_material_dark = 2131427389;
public static final int abc_background_cache_hint_selector_material_light = 2131427390;
public static final int abc_color_highlight_material = 2131427391;
public static final int abc_input_method_navigation_guard = 2131427328;
public static final int abc_primary_text_disable_only_material_dark = 2131427392;
public static final int abc_primary_text_disable_only_material_light = 2131427393;
public static final int abc_primary_text_material_dark = 2131427394;
public static final int abc_primary_text_material_light = 2131427395;
public static final int abc_search_url_text = 2131427396;
public static final int abc_search_url_text_normal = 2131427329;
public static final int abc_search_url_text_pressed = 2131427330;
public static final int abc_search_url_text_selected = 2131427331;
public static final int abc_secondary_text_material_dark = 2131427397;
public static final int abc_secondary_text_material_light = 2131427398;
public static final int accent_material_dark = 2131427332;
public static final int accent_material_light = 2131427333;
public static final int background_floating_material_dark = 2131427334;
public static final int background_floating_material_light = 2131427335;
public static final int background_material_dark = 2131427336;
public static final int background_material_light = 2131427337;
public static final int bright_foreground_disabled_material_dark = 2131427338;
public static final int bright_foreground_disabled_material_light = 2131427339;
public static final int bright_foreground_inverse_material_dark = 2131427340;
public static final int bright_foreground_inverse_material_light = 2131427341;
public static final int bright_foreground_material_dark = 2131427342;
public static final int bright_foreground_material_light = 2131427343;
public static final int button_material_dark = 2131427344;
public static final int button_material_light = 2131427345;
public static final int dim_foreground_disabled_material_dark = 2131427349;
public static final int dim_foreground_disabled_material_light = 2131427350;
public static final int dim_foreground_material_dark = 2131427351;
public static final int dim_foreground_material_light = 2131427352;
public static final int foreground_material_dark = 2131427353;
public static final int foreground_material_light = 2131427354;
public static final int highlighted_text_material_dark = 2131427355;
public static final int highlighted_text_material_light = 2131427356;
public static final int hint_foreground_material_dark = 2131427357;
public static final int hint_foreground_material_light = 2131427358;
public static final int material_blue_grey_800 = 2131427359;
public static final int material_blue_grey_900 = 2131427360;
public static final int material_blue_grey_950 = 2131427361;
public static final int material_deep_teal_200 = 2131427362;
public static final int material_deep_teal_500 = 2131427363;
public static final int material_grey_100 = 2131427364;
public static final int material_grey_300 = 2131427365;
public static final int material_grey_50 = 2131427366;
public static final int material_grey_600 = 2131427367;
public static final int material_grey_800 = 2131427368;
public static final int material_grey_850 = 2131427369;
public static final int material_grey_900 = 2131427370;
public static final int primary_dark_material_dark = 2131427371;
public static final int primary_dark_material_light = 2131427372;
public static final int primary_material_dark = 2131427373;
public static final int primary_material_light = 2131427374;
public static final int primary_text_default_material_dark = 2131427375;
public static final int primary_text_default_material_light = 2131427376;
public static final int primary_text_disabled_material_dark = 2131427377;
public static final int primary_text_disabled_material_light = 2131427378;
public static final int ripple_material_dark = 2131427379;
public static final int ripple_material_light = 2131427380;
public static final int secondary_text_default_material_dark = 2131427381;
public static final int secondary_text_default_material_light = 2131427382;
public static final int secondary_text_disabled_material_dark = 2131427383;
public static final int secondary_text_disabled_material_light = 2131427384;
public static final int switch_thumb_disabled_material_dark = 2131427385;
public static final int switch_thumb_disabled_material_light = 2131427386;
public static final int switch_thumb_material_dark = 2131427399;
public static final int switch_thumb_material_light = 2131427400;
public static final int switch_thumb_normal_material_dark = 2131427387;
public static final int switch_thumb_normal_material_light = 2131427388;
}
| 67.828947
| 91
| 0.817847
|
027eb2369e6cdee55975c088622d832d4447945f
| 346
|
/**
*
*/
package nl.andredewaal.home.juluspace.events.complex;
import nl.andredewaal.home.juluspace.events.SpaceEvent;
import nl.andredewaal.home.juluspace.events.SpaceEventType;
/**
* @author awaal
*
*/
public class LaunchEvent extends SpaceEvent {
public LaunchEvent()
{
this.type=SpaceEventType.LAUNCH;
}
}
| 16.47619
| 60
| 0.696532
|
645bfa7a0dd1a39145bf821583b0b3fd428cdbdd
| 351
|
package ru.andreibelkin.pochtarossii.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import ru.andreibelkin.pochtarossii.entity.Receiver;
import ru.andreibelkin.pochtarossii.entity.Shipment;
@Data
@AllArgsConstructor
public class ShipmentCreationInputDTO {
private Shipment.ShipmentType shipmentType;
private Receiver receiver;
}
| 25.071429
| 52
| 0.834758
|
6743cf2f09f351540fc64183f4fa287b193badcb
| 236
|
package com.reactnativemonthpicker.wheelFunctions;
import com.reactnativemonthpicker.wheels.Wheel;
public class Refresh implements WheelFunction {
@Override
public void apply(Wheel wheel) {
wheel.refresh();
}
}
| 16.857143
| 50
| 0.737288
|
1dce0df561d2b71317cba0a19e74381f7ce54d04
| 6,529
|
/**
*
* MIT License
*
* Copyright (c) 2021 Maxim Gansert, Mindscan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package de.mindscan.brightflux.ingest.parser;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import de.mindscan.brightflux.dataframes.DataFrameColumn;
import de.mindscan.brightflux.ingest.DataToken;
import de.mindscan.brightflux.ingest.columns.DataTokenColumn;
import de.mindscan.brightflux.ingest.token.ColumnHeaderToken;
import de.mindscan.brightflux.ingest.token.ColumnSeparatorToken;
import de.mindscan.brightflux.ingest.token.EmptyToken;
import de.mindscan.brightflux.ingest.token.IdentifierToken;
import de.mindscan.brightflux.ingest.token.LineSeparatorToken;
import de.mindscan.brightflux.ingest.token.NumberToken;
import de.mindscan.brightflux.ingest.token.TextToken;
/**
* The DataFrame Parser will create a list of DataFrameColumn (in future probably a DataFrame),
* which reensemble an abstract data frame, which is not yet translated into effective primitive
* data types.
*
* The DataFrameColumns will contain a list of DataTokens, which may or may not be annotated.
*
*/
public class DataFrameParserImpl implements DataFrameParser {
/**
* {@inheritDoc}
*/
@Override
public List<DataFrameColumn<DataToken>> parse( Iterator<DataToken> tokenStream ) {
List<DataFrameColumn<DataToken>> parseResult = new ArrayList<>();
// always start with an empty column
DataFrameColumn<DataToken> currentColumn = prepareNewColumn( parseResult );
int currentRow = 0;
Iterator<DataFrameColumn<DataToken>> columnIterator = null;
DataToken lastToken = null;
while (tokenStream.hasNext()) {
DataToken dataToken = tokenStream.next();
// I don't like the instanceof thing for the tokens / i would prefer an enum, but also keep it extensible.
if (dataToken instanceof LineSeparatorToken) {
// TODO: test if this is the last column, otherwise we must fill the remaining columns with N/A values
currentRow++;
// if something is ColumnSeparatorToken LineSeparatorToken, then append an NA token
// this will fill the last selected column right before the Lineseparator was found,
// but this might not be the last column expected.
if (lastToken instanceof ColumnSeparatorToken) {
currentColumn.appendNA();
}
// also reset the current row...
columnIterator = parseResult.iterator();
currentColumn = columnIterator.next();
}
// I don't like the instanceof thing for the tokens / i would prefer an enum, but also keep it extensible.
if (dataToken instanceof ColumnSeparatorToken) {
if (currentRow == 0) {
currentColumn = prepareNewColumn( parseResult );
}
else {
if (lastToken instanceof ColumnSeparatorToken || lastToken instanceof LineSeparatorToken) {
currentColumn.appendNA();
}
try {
// select the current row
currentColumn = columnIterator.next();
}
catch (Exception e) {
// That means that the current row has more columns than built by the first lines
// we should report an error for the current row.
System.out.println( "[READERROR] Too many Columns/Columnseparators found for row: " + currentRow );
// TODO: InputDataFormatException, with the collected errors.
// Also set a kind of format exception which should be thrown at the end of processing
// nothing is more worse, than processing a dataset finding one issue, processing it
// the next time and then find the next issue.
}
}
}
if (dataToken instanceof IdentifierToken) {
currentColumn.append( dataToken );
}
if (dataToken instanceof TextToken) {
currentColumn.append( dataToken );
}
if (dataToken instanceof NumberToken) {
currentColumn.append( dataToken );
}
if (dataToken instanceof EmptyToken) {
currentColumn.appendNA();
}
if (dataToken instanceof ColumnHeaderToken) {
currentColumn.append( dataToken );
}
lastToken = dataToken;
// System.out.println( "tokentype: " + lastToken.getClass().toString() + " value: " + lastToken.getValue() );
}
return parseResult;
}
/**
* @param parseResult
* @return
*/
private DataTokenColumn prepareNewColumn( List<DataFrameColumn<DataToken>> parseResult ) {
int size = parseResult.size();
DataTokenColumn dataTokenColumn = new DataTokenColumn();
dataTokenColumn.setColumnName( Integer.toString( size ) );
parseResult.add( dataTokenColumn );
return dataTokenColumn;
}
}
| 42.122581
| 124
| 0.625823
|
d0dea1afd420dd22ee1217df161f79bff694f7ed
| 8,271
|
package io.dockstore.tooltester.client.cli;
import java.io.File;
import com.beust.jcommander.ParameterException;
import io.dockstore.tooltester.helper.JenkinsHelper;
import io.dockstore.tooltester.helper.PipelineTester;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ExpectedSystemExit;
import org.junit.contrib.java.lang.system.SystemOutRule;
import static io.dockstore.tooltester.client.cli.Client.main;
import static io.dockstore.tooltester.helper.ExceptionHandler.COMMAND_ERROR;
public class ClientTest {
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
private Client client;
@Before
public void initialize() {
this.client = new Client();
this.client.setupClientEnvironment();
Assert.assertNotNull("client API could not start", client.getContainersApi());
}
@Test
public void setupEnvironment() {
client = new Client();
client.setupClientEnvironment();
Assert.assertNotNull("client API could not start", client.getContainersApi());
}
/**
* Tests if Jenkins server is set up
*/
@Test
public void setupTesters() {
client.setupTesters();
PipelineTester pipelineTester = client.getPipelineTester();
Assert.assertNotNull("Jenkins server can not be reached", pipelineTester.getJenkins());
}
/**
* Test with unknown command
*/
@Test
public void unknownCommand() {
String[] argv = { "mmmrrrggglll" };
exit.expectSystemExitWithStatus(COMMAND_ERROR);
main(argv);
}
/**
* Test enqueue which should run all jobs
*/
@Test
public void enqueue() {
String[] argv = { "enqueue" };
main(argv);
Assert.assertTrue(systemOutRule.getLog().isEmpty());
}
/**
* Test enqueue with option --help which should display enqueue help
*/
@Test
public void enqueueHelp() {
String[] argv = { "enqueue", "--help" };
main(argv);
Assert.assertTrue(systemOutRule.getLog().contains("Test verified tools on Jenkins."));
}
/**
* Test enqueue with a specific tool
*/
@Test
public void enqueueTool() {
String[] argv = { "enqueue", "--tool", "quay.io/pancancer/pcawg_delly_workflow" };
main(argv);
Assert.assertTrue(systemOutRule.getLog().isEmpty());
}
/**
* Test enqueue with specific verified source
*/
@Test
public void enqueueToolSource() {
String[] argv = { "enqueue", "--source", "Docktesters group" };
main(argv);
Assert.assertTrue(systemOutRule.getLog().isEmpty());
}
/**
* This tests the Jenkins pipeline creation
*/
@Test
public void createJenkinsTests() {
String[] argv = { "sync" };
main(argv);
Assert.assertTrue(systemOutRule.getLog().isEmpty());
}
/**
* Test sync with option --help which should display sync help
*/
@Test
public void syncHelp() {
String[] argv = { "sync", "--help" };
main(argv);
Assert.assertTrue(systemOutRule.getLog().contains("Synchronizes with Jenkins to create tests for verified tools."));
}
/**
* This tests the Jenkins pipeline creation
*/
@Test
public void createJenkinsTestsSource() {
String[] argv = { "sync", "--source", "Docktesters group"};
main(argv);
Assert.assertTrue(systemOutRule.getLog().isEmpty());
}
/**
* This tests the Jenkins pipeline creation
*/
@Test
public void createUnverifiedJenkinsTests() {
String[] argv = { "sync", "--source", "Docktesters group", "--tools", "quay.io/ucsc_cgl/dockstore_tool_adtex" };
main(argv);
Assert.assertTrue(systemOutRule.getLog().isEmpty());
}
/**
* This tests the client with no parameters
*/
@Test
public void empty() {
String[] argv = { "" };
main(argv);
Assert.assertTrue(systemOutRule.getLog().contains("Usage: autotool [options] [command] [command options]"));
}
/**
* This prints the usage for report
*/
@Test
public void report() {
String[] argv = { "report" };
main(argv);
assertReport();
}
/**
* This reports on a specific tool
*/
@Test
public void reportTool() {
String[] argv = new String[] { "report", "--tool", "quay.io/briandoconnor/dockstore-tool-md5sum" };
main(argv);
assertReport();
}
/**
* This reports on specific tools
*/
@Test
public void reportTools() {
String[] argv = new String[] { "report", "--tool", "quay.io/pancancer/pcawg-bwa-mem-workflow",
"quay.io/briandoconnor/dockstore-tool-md5sum" };
main(argv);
assertReport();
}
private void assertReport() {
Assert.assertTrue(systemOutRule.getLog().contains("Tool/Workflow ID"));
Assert.assertTrue(systemOutRule.getLog().contains("DATE"));
Assert.assertTrue(systemOutRule.getLog().contains("Version"));
Assert.assertTrue(systemOutRule.getLog().contains("Engine"));
Assert.assertTrue(systemOutRule.getLog().contains("Action Performed"));
Assert.assertTrue(systemOutRule.getLog().contains("Runtime"));
Assert.assertTrue(systemOutRule.getLog().contains("Status of Test Files"));
Assert.assertFalse(new File("tooltester/Report.csv").exists());
}
private void assertFileReport() {
Assert.assertTrue(systemOutRule.getLog().contains("Build ID"));
Assert.assertTrue(systemOutRule.getLog().contains("Tag"));
Assert.assertTrue(systemOutRule.getLog().contains("File Name"));
Assert.assertTrue(systemOutRule.getLog().contains("CWL ID"));
Assert.assertTrue(systemOutRule.getLog().contains("md5sum"));
Assert.assertTrue(systemOutRule.getLog().contains("File Size"));
Assert.assertFalse(new File("tooltester/FileReport.csv").exists());
}
@Test
public void reportInvalidTool() {
String[] argv = new String[] { "report", "--tool", "quay.io/pancancer/pcawg-bwa" };
main(argv);
assertReport();
}
@Test
public void testCleanSuffix() {
final String testSuffix1 = "quay.io/pancancer/pcawg-bwa";
final String testSuffix2 = "#workflow/pancancer/pcawg-bwa";
Assert.assertEquals("quay.io-pancancer-pcawg-bwa", JenkinsHelper.cleanSuffx(testSuffix1));
Assert.assertEquals("-workflow-pancancer-pcawg-bwa", JenkinsHelper.cleanSuffx(testSuffix2));
}
/**
* This tests file-report with no --tool option
*/
@Test(expected = ParameterException.class)
public void fileReport() {
String[] argv = new String[] { "file-report" };
main(argv);
}
/**
* This tests file-report with no --tool option
*/
@Test
public void fileReportTool() {
String[] argv = new String[] { "file-report", "--tool", "quay.io/briandoconnor/dockstore-tool-md5sum" };
main(argv);
assertFileReport();
}
/**
* This tests the help message for the file-report command
*/
@Test
public void fileReportHelp() {
String[] argv = new String[] { "file-report", "--help" };
main(argv);
Assert.assertTrue(
systemOutRule.getLog().contains("Reports the file sizes and checksum of a verified tool across all tested versions."));
}
/**
* This displays the help menu for the report command
*/
@Test
public void reportHelp() {
String[] argv = { "report", "--help" };
main(argv);
Assert.assertTrue(systemOutRule.getLog().contains("Report status of verified tools tested."));
}
/**
* This displays the help menu for the main command
*/
@Test
public void mainHelp() {
String[] argv = { "--help" };
main(argv);
Assert.assertTrue(systemOutRule.getLog().contains("Usage: autotool [options] [command] [command options]"));
}
}
| 30.747212
| 135
| 0.619998
|
1be9ab49da9f2b3b112e36d5cf9f5197bc8265e5
| 2,836
|
package com.codepath.apps.restclienttemplate;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.codepath.apps.restclienttemplate.fragments.HomeTimelineFragment;
import com.codepath.apps.restclienttemplate.fragments.TweetsPagerAdapter;
import com.codepath.apps.restclienttemplate.models.Tweet;
import org.parceler.Parcels;
public class TimelineActivity extends AppCompatActivity {
private SwipeRefreshLayout swipeContainer;
TweetsPagerAdapter pagerAdapter;
private ViewPager viewPager;
// private HomeTimelineFragment homeTimelineFragment;
// private MentionsTimelineFragment mentionsTimelineFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.logo_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
//removed swipe refresh layout
viewPager = (ViewPager) findViewById(R.id.viewpager);
pagerAdapter = new TweetsPagerAdapter(getSupportFragmentManager(), this);
viewPager.setAdapter(pagerAdapter);
//vpPager.setAdapter(new TweetsPagerAdapter(getSupportFragmentManager(), this));
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
}
private final int REQUEST = 20;
public void onComposeAction(MenuItem mi) {
// handle click here
Intent intent = new Intent(this, ComposeActivity.class);
startActivityForResult(intent, REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == resultCode) {
Tweet tweet = (Tweet) Parcels.unwrap(data.getParcelableExtra("tweet"));
((HomeTimelineFragment) pagerAdapter.getItem(viewPager.getCurrentItem())).addTweet(tweet);
//tweets.add(0, tweet);
//tweetAdapter.notifyItemInserted(0);
//rvTweets.scrollToPosition(0);
}
// REQUEST_CODE is defined above
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return true;
}
public void onProfileView(MenuItem item) {
Intent intent = new Intent(this, ProfileActivity.class);
//intent.putExtra("screen_name", );
startActivity(intent);
}
//removed fetch timeline async
}
| 32.976744
| 102
| 0.726375
|
f8a9daec2ed4252f68ad12f06aa6328eba93418d
| 200
|
package com.alvis.exam.viewmodel.student.user;
import com.alvis.exam.base.BasePage;
import lombok.Data;
@Data
public class MessageRequestVM extends BasePage {
private Integer receiveUserId;
}
| 16.666667
| 48
| 0.79
|
3393afad271fc88c5d7fecd4a79dc085b2e0f5a0
| 471
|
package com.steelkiwi.cropiwa.sample.util;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
/**
* Created by yarolegovich https://github.com/yarolegovich
* on 22.03.2017.
*/
public class Permissions {
public static boolean isGranted(Activity activity, String permission) {
return ActivityCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED;
}
}
| 24.789474
| 109
| 0.770701
|
9c4adc18273bc7107abb5192f96d6e8d7316c05b
| 327
|
package org.charles.learning.rpc.server;
public class RpcServerMain {
public static void main(String[] args) {
Service service = new ServiceImpl();
RpcProxyServer rpcProxyServer = new RpcProxyServer();
rpcProxyServer.send(service, 8090);
System.out.println(service.send("charles"));
}
}
| 32.7
| 61
| 0.685015
|
60c6ed692401e4d378dd04c9a8362e5a7696f079
| 1,684
|
package tr.com.infumia.infumialib.kubernetes;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
/**
* a class that represents server registries
*/
public final class ServerRegistry {
/**
* the registered default servers.
*/
private static final Set<DiscoveredService> REGISTERED_DEFAULT_SERVERS = new HashSet<>();
/**
* the registered servers.
*/
private static final Set<DiscoveredService> REGISTERED_SERVERS = new HashSet<>();
/**
* ctor.
*/
private ServerRegistry() {
}
/**
* registers the server.
*
* @param server the server to register.
*/
public static void register(@NotNull final DiscoveredService server) {
ServerRegistry.REGISTERED_SERVERS.add(server);
if (server.isDefault()) {
ServerRegistry.REGISTERED_DEFAULT_SERVERS.add(server);
}
}
/**
* obtains the registered default servers.
*
* @return default servers.
*/
@NotNull
public static Set<DiscoveredService> registeredDefaultServices() {
return Collections.unmodifiableSet(ServerRegistry.REGISTERED_DEFAULT_SERVERS);
}
/**
* obtains the registered servers.
*
* @return registered servers.
*/
@NotNull
public static Set<DiscoveredService> registeredServices() {
return Collections.unmodifiableSet(ServerRegistry.REGISTERED_SERVERS);
}
/**
* unregisters the server.
*
* @param server the server to unregister.
*/
public static void unregister(@NotNull final DiscoveredService server) {
ServerRegistry.REGISTERED_SERVERS.remove(server);
ServerRegistry.REGISTERED_DEFAULT_SERVERS.remove(server);
}
}
| 23.71831
| 91
| 0.712589
|
654c5899315c8bfecbcca090ada260211ea992f4
| 8,609
|
package com.skidsdev.fyrestone.item;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
import com.skidsdev.fyrestone.FyrestoneCreativeTabs;
import com.skidsdev.fyrestone.item.swordeffect.ISwordEffect;
import com.skidsdev.fyrestone.item.swordeffect.ISwordEffectOnHit;
import com.skidsdev.fyrestone.item.swordeffect.ISwordEffectOnSwing;
import com.skidsdev.fyrestone.item.swordeffect.ISwordEffectOnTickInHand;
import com.skidsdev.fyrestone.item.swordeffect.ISwordEffectOnUse;
import com.skidsdev.fyrestone.item.swordeffect.SwordEffectFire;
import com.skidsdev.fyrestone.item.swordeffect.SwordEffectFireball;
import com.skidsdev.fyrestone.item.swordeffect.SwordEffectPotion;
import com.skidsdev.fyrestone.item.swordeffect.SwordEffectWaterstone;
import com.skidsdev.fyrestone.utils.Helper;
import com.skidsdev.fyrestone.utils.ItemNBTHelper;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.IItemPropertyGetter;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.potion.Potion;
import net.minecraft.util.DamageSource;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class ItemBaseSword extends ItemSword
{
public ItemBaseSword(ToolMaterial material, String regName)
{
super(material);
this.setRegistryName(regName);
this.setUnlocalizedName(this.getRegistryName().toString());
this.setCreativeTab(FyrestoneCreativeTabs.tabFyrestone);
this.addPropertyOverride(new ResourceLocation("sword"), new IItemPropertyGetter()
{
@SideOnly(Side.CLIENT)
public float apply(ItemStack stack, @Nullable World worldIn, @Nullable EntityLivingBase entityIn)
{
return ItemNBTHelper.getInt(stack, "sword_type", 0);
}
});
}
@Override
public int getMaxDamage(ItemStack stack)
{
EnumSwordType type = EnumSwordType.values()[ItemNBTHelper.getInt(stack, "sword_type", 0)];
return type.getDurability();
}
@Override
public boolean onEntitySwing(EntityLivingBase entity, ItemStack stack)
{
if (entity instanceof EntityPlayer)
{
applyEffectOnSwing(stack, (EntityPlayer)entity);
}
return false;
}
@Override
public boolean onLeftClickEntity(ItemStack stack, EntityPlayer player, Entity entity)
{
boolean flag = false;
if (entity instanceof EntityLivingBase)
{
EnumSwordType type = EnumSwordType.values()[ItemNBTHelper.getInt(stack, "sword_type", 0)];
float attackDamage = type.getAttackDamage();
boolean isCrit = (player.fallDistance > 0.2F);
if (isCrit) attackDamage *= 1.2;
flag = entity.attackEntityFrom(DamageSource.causePlayerDamage(player), attackDamage);
applyEffectOnHit(stack, (EntityLivingBase)entity, player);
if (flag) stack.damageItem(1, player);
if (stack.stackSize < 1) player.inventory.setInventorySlotContents(player.inventory.currentItem, null);
}
return flag;
}
@Override
public String getUnlocalizedName(ItemStack stack)
{
EnumSwordType type = EnumSwordType.values()[ItemNBTHelper.getInt(stack, "sword_type", 0)];
return super.getUnlocalizedName() + "_" + type.getName();
}
@Override
public void addInformation(ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced)
{
EnumSwordType type = EnumSwordType.values()[ItemNBTHelper.getInt(stack, "sword_type", 0)];
List<String> swordTooltip = type.getTooltip();
for(String line : swordTooltip)
{
tooltip.add(line);
}
}
@SideOnly(Side.CLIENT)
public void getSubItems(Item itemIn, CreativeTabs tab, List subItems)
{
for(EnumSwordType type : EnumSwordType.values())
{
ItemStack stack = new ItemStack(itemIn);
ItemNBTHelper.setInt(stack, "sword_type", type.ordinal());
subItems.add(stack);
}
}
private void applyEffectOnHit(ItemStack stack, EntityLivingBase entity, EntityPlayer player)
{
EnumSwordType type = EnumSwordType.values()[ItemNBTHelper.getInt(stack, "sword_type", 0)];
List<ISwordEffect> effects = type.getEffects();
for(ISwordEffectOnHit effect : getEffectsOnHit(effects))
{
effect.ApplyEffect(stack, entity, player);
}
}
private void applyEffectOnTickInHand(ItemStack stack, EntityLivingBase entity)
{
EnumSwordType type = EnumSwordType.values()[ItemNBTHelper.getInt(stack, "sword_type", 0)];
List<ISwordEffect> effects = type.getEffects();
for(ISwordEffectOnTickInHand effect : getEffectsOnTickInHand(effects))
{
effect.ApplyEffect(stack, entity);
}
}
private void applyEffectOnUse(ItemStack stack, EntityLivingBase entity)
{
EnumSwordType type = EnumSwordType.values()[ItemNBTHelper.getInt(stack, "sword_type", 0)];
List<ISwordEffect> effects = type.getEffects();
for(ISwordEffectOnUse effect : getEffectsOnUse(effects))
{
effect.ApplyEffect(stack, entity);
}
}
private void applyEffectOnSwing(ItemStack stack, EntityPlayer player)
{
EnumSwordType type = EnumSwordType.values()[ItemNBTHelper.getInt(stack, "sword_type", 0)];
List<ISwordEffect> effects = type.getEffects();
for(ISwordEffectOnSwing effect : getEffectsOnSwing(effects))
{
effect.ApplyEffect(stack, player);
}
}
private List<ISwordEffectOnHit> getEffectsOnHit(List<ISwordEffect> effects)
{
return getEffectsOfType(effects, ISwordEffectOnHit.class);
}
private List<ISwordEffectOnTickInHand> getEffectsOnTickInHand(List<ISwordEffect> effects)
{
return getEffectsOfType(effects, ISwordEffectOnTickInHand.class);
}
private List<ISwordEffectOnUse> getEffectsOnUse(List<ISwordEffect> effects)
{
return getEffectsOfType(effects, ISwordEffectOnUse.class);
}
private List<ISwordEffectOnSwing> getEffectsOnSwing(List<ISwordEffect> effects)
{
return getEffectsOfType(effects, ISwordEffectOnSwing.class);
}
private <T extends ISwordEffect> List<T> getEffectsOfType(List<ISwordEffect> effects, Class<T> type)
{
ArrayList<T> list = new ArrayList<T>();
for(ISwordEffect effect : effects)
{
if (type.isInstance(effect)) list.add((T)effect);
}
return list;
}
public static ItemStack getSwordStack(EnumSwordType type)
{
ItemStack stack = new ItemStack(ItemRegister.itemSword);
ItemNBTHelper.setInt(stack, "sword_type", type.ordinal());
return stack;
}
public enum EnumSwordType implements IStringSerializable
{
FYRESTONE_SWORD
(
"fyrestone", 1.6f, 6.0f, 500,
Helper.formatTooltip(""),
new SwordEffectFire(5)
),
EARTHSTONE_SWORD
(
"earthstone", 1.0f, 7.0f, 1000,
Helper.formatTooltip(""),
new SwordEffectPotion(Potion.getPotionById(2), 80, 2)
),
PLAGUEBLADE
(
"plagueblade", 1.6f, 7.0f, 1000,
Helper.formatTooltip(""),
new SwordEffectPotion(Potion.getPotionById(19), 50, 1)
),
FLAMEVENOM
(
"flamevenom", 1.6f, 6.0f, 500,
Helper.formatTooltip(""),
new SwordEffectFire(3),
new SwordEffectPotion(Potion.getPotionById(19), 40, 1)
),
WATERSTONE_SWORD
(
"waterstone", 1.6f, 6.0f, 250,
Helper.formatTooltip(""),
new SwordEffectWaterstone(12)
),
BRIMSTONE_SWORD
(
"brimstone", 1.6f, 10.0f, 1500,
Helper.formatTooltip(""),
new SwordEffectFireball(),
new SwordEffectFire(1)
),
AIRSTONE_SWORD
(
"airstone", 1.6f, 150.0f, 10,
Helper.formatTooltip("")
);
private List<ISwordEffect> effects;
private List<String> tooltip;
private float attackSpeed;
private float attackDamage;
private int durability;
private String name;
private EnumSwordType(String name, float atkSpeed, float atkDamage, int durability, List<String> tooltip, ISwordEffect... effects)
{
this.name = name;
this.attackSpeed = atkSpeed;
this.attackDamage = atkDamage;
this.durability = durability;
this.tooltip = tooltip;
this.effects = Arrays.asList(effects);
}
public List<ISwordEffect> getEffects()
{
return (List)new ArrayList<ISwordEffect>(effects);
}
public List<String> getTooltip()
{
return (List)new ArrayList<String>(tooltip);
}
public float getAttackSpeed()
{
return attackSpeed;
}
public float getAttackDamage()
{
return attackDamage;
}
public int getDurability()
{
return durability;
}
public String getName()
{
return name;
}
public String toString()
{
return name;
}
}
}
| 27.592949
| 132
| 0.74515
|
c0be4b1df7b848f549e783f84d9600067b37f457
| 1,815
|
package com.aqif.hackernews.screens.topstories.activity.dagger;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import com.aqif.hackernews.restapi.hackernews.manager.IHackerNewsApiManager;
import com.aqif.hackernews.screens.topstories.activity.ITopStoriesActivityViewModel;
import com.aqif.hackernews.screens.topstories.activity.TopStoriesActivityViewModel;
import com.aqif.hackernews.screens.topstories.activity.dagger.scope.TopStoriesActivityScope;
import com.aqif.hackernews.screens.topstories.recycler.viewmodel.ITopStoriesRecyclerViewModel;
import com.aqif.hackernews.screens.topstories.refresh.viewmodel.ITopStoriesRefreshViewModel;
import dagger.Module;
import dagger.Provides;
/**
* Created by aqifhamid.
*/
@Module
public class TopStoriesViewModelModule
{
@Provides
@TopStoriesActivityScope
public ITopStoriesActivityViewModel provideTopStoriesActivityViewModel(AppCompatActivity activity,
Toolbar toolbar,
TextView textView,
ITopStoriesRecyclerViewModel topStoriesRecyclerViewModel,
ITopStoriesRefreshViewModel topStoriesRefreshViewModel,
IHackerNewsApiManager hackerNewsApiManager)
{
return new TopStoriesActivityViewModel(activity,
toolbar,
textView,
topStoriesRecyclerViewModel,
topStoriesRefreshViewModel,
hackerNewsApiManager);
}
}
| 41.25
| 132
| 0.639669
|
ae4efea09279f184eb65324f3287295c41cc1617
| 1,129
|
package groovy;
import groovy.lang.GroovyClassLoader;
/**
* @author:YangLiu
* @date:2018年5月18日 上午10:17:27
* @describe:使用Groovy或 Jruby动态语言脚本作为规则引擎解决方案将会越来越普及.
*/
public class InvokeGroovy {
public static void main(String[] args) {
ClassLoader cl = new InvokeGroovy().getClass().getClassLoader();
GroovyClassLoader groovyCl = new GroovyClassLoader(cl);
try {
// 从文件中读取
// Class groovyClass = groovyCl.parseClass(new
// File("D:/project/openjweb/src/java/org/openjweb/groovy/Foo.groovy"));
// 直接使用Groovy字符串,也可以获得正确结果
// Class groovyClass =
// groovyCl.parseClass("package org.openjweb.groovy; /r/n import org.openjweb.core.groovy.test.IFoo;/r/n class Foo implements IFoo {public Object run(Object foo) {return 23}}");
Class groovyClass = groovyCl
.parseClass("package org.intsmaze.groovy;"
+ " class Foo implements IFoo {"
+ "public Object run(Object obj) "
+ "{return obj.toString()+\"1111111111\"}"
+ "}");
IFoo foo = (IFoo) groovyClass.newInstance();
System.out.println(foo.run(new Integer(2)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 32.257143
| 180
| 0.687334
|
6c0755ffe6b2b0efcae067beaea22bb5069db898
| 748
|
package com.twu.biblioteca.model;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class UserTest {
private User user = new User("1","Jinnew Chyi","123","13389773421","gabralia@gmail.com");
@Test
public void getId(){
assertThat(user.getId(),is("1"));
}
@Test
public void getName(){
assertThat(user.getName(),is("Jinnew Chyi"));
}
@Test
public void getPassword(){
assertThat(user.getPassword(),is("123"));
}
@Test
public void getPhone(){
assertThat(user.getPhone(),is("13389773421"));
}
@Test
public void getEmail(){
assertThat(user.getEmail(),is("gabralia@gmail.com"));
}
}
| 20.777778
| 93
| 0.620321
|
6d755de092e0a6bc497fe9aa9468111db197d8fe
| 327
|
package com.bestaone.himall.core.service;
import com.bestaone.himall.common.entity.BaseEntity;
import java.io.Serializable;
import java.util.List;
public interface BaseService<T extends BaseEntity, PK extends Serializable> {
T save(T entity);
void delete(PK id);
T findById(PK id);
List<T> findAll();
}
| 17.210526
| 77
| 0.727829
|
2b08c3ec8273fba1a1f45bf1b001bccd1d741ac9
| 4,116
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.grupoad3.flexfx.db.services;
import com.grupoad3.flexfx.db.AbstractDaoService;
import com.grupoad3.flexfx.db.model.ItemStatus;
import com.grupoad3.flexfx.db.model.Rss;
import com.grupoad3.flexfx.db.model.RssItems;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import java.io.IOException;
import java.util.List;
/**
*
* @author daniel_serna
*/
@SuppressWarnings("unchecked")
public class RssItemService extends AbstractDaoService<RssItems> {
public RssItemService() {
super(RssItems.class);
}
/*public List<RssItems> getLastItems(long limit, long offset, boolean withDeleted) throws IOException {
// return all with deleted
if (withDeleted) {
return super.getAll(limit, offset);
} else {
try {
QueryBuilder builder = dao.queryBuilder();
if (limit != -1l) {
builder.limit(limit);
}
if (offset != -1l) {
builder.offset(offset);
}
builder.where().eq(RssItems.DELETED_FIELD_NAME, false);
builder.orderBy(RssItems.DATE_PUB_FIELD_NAME, false);
return builder.query();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}*/
// getLastRssNotDeleted
/*public List<RssItems> getLastItemsDownloadedByRss(Rss rss) {
try {
QueryBuilder builder = dao.queryBuilder();
builder.limit(50l);
builder.offset(0l);
builder.where()
.eq(RssItems.STATUS_FIELD_NAME, ItemStatus.DOWNLOADED)
.and()
.eq(RssItems.DELETED_FIELD_NAME, false)
.and()
.eq(RssItems.ID_RSS_FIELD_NAME, rss.getId());
builder.orderBy(RssItems.DATE_PUB_FIELD_NAME, false);
return builder.query();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}*/
public List<RssItems> getAllItemsByFilter(Rss rss, RssItems itemFilter) {
try {
QueryBuilder builder = dao.queryBuilder();
builder.limit(50l);
builder.offset(0l);
Where where = builder.where();
where.eq(RssItems.DELETED_FIELD_NAME, false)
.and()
.eq(RssItems.ID_RSS_FIELD_NAME, rss.getId());
if (itemFilter.getTitle() != null && itemFilter.getTitle().isEmpty() == false) {
where.and().like(RssItems.TITLE_FIELD_NAME, "%" + itemFilter.getTitle().trim() + "%");
}
if (itemFilter.getStatus() != null && itemFilter.getStatus().equals(ItemStatus.DOWNLOADED.toString())) {
where.and().eq(RssItems.STATUS_FIELD_NAME, ItemStatus.DOWNLOADED);
}
builder.orderBy(RssItems.DATE_PUB_FIELD_NAME, false);
return builder.query();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List<RssItems> getLastAlltemsByRss(Rss rss, long limit, long offset, boolean withDeleted) {
try {
QueryBuilder builder = dao.queryBuilder();
if (limit != -1l) {
builder.limit(limit);
}
if (offset != -1l) {
builder.offset(offset);
}
builder.where()
.eq(RssItems.DELETED_FIELD_NAME, withDeleted)
.and()
.eq(RssItems.ID_RSS_FIELD_NAME, rss.getId());
builder.orderBy(RssItems.DATE_PUB_FIELD_NAME, false);
return builder.query();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| 28.783217
| 116
| 0.553693
|
bbe83a739e8b6a0335365014e8e6900843628494
| 2,474
|
package eu.razniewski.mineduino.entitybraincontroller.data;
import com.github.ysl3000.bukkit.pathfinding.entity.Insentient;
import java.io.Serializable;
import java.util.Objects;
public class EntityInformationData implements Serializable {
private EntityLocation location;
private int id;
private String entityType;
private boolean isMoving;
public EntityInformationData(EntityLocation location, int id, String entityType) {
this.location = location;
this.id = id;
this.entityType = entityType;
}
public EntityInformationData() {
}
public EntityLocation getLocation() {
return location;
}
public void setLocation(EntityLocation location) {
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEntityType() {
return entityType;
}
public void setEntityType(String entityType) {
this.entityType = entityType;
}
public boolean isMoving() {
return isMoving;
}
public void setMoving(boolean moving) {
isMoving = moving;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EntityInformationData that = (EntityInformationData) o;
return id == that.id &&
isMoving == that.isMoving &&
Objects.equals(location, that.location) &&
Objects.equals(entityType, that.entityType);
}
@Override
public int hashCode() {
return Objects.hash(location, id, entityType, isMoving);
}
@Override
public String toString() {
return "EntityInformationData{" +
"location=" + location +
", id=" + id +
", entityType='" + entityType + '\'' +
", isMoving=" + isMoving +
'}';
}
public static EntityInformationData from(Insentient insentient) {
EntityInformationData data = new EntityInformationData();
data.setEntityType(insentient.getBukkitEntity().getType().name());
data.setId(insentient.getBukkitEntity().getEntityId());
data.setMoving(!insentient.getNavigation().isDoneNavigating());
data.setLocation(EntityLocation.from(insentient.getBukkitEntity().getLocation()));
return data;
}
}
| 27.186813
| 90
| 0.621665
|
9b21b55285c3e1ea016dff6570d5a7bf5273eac8
| 591
|
package cn.ts.rpc.upms.api;
import cn.ts.core.mybatis.BaseService;
import cn.ts.rpc.upms.model.UpmsUserPermission;
import cn.ts.rpc.upms.model.UpmsUserPermissionExample;
import com.alibaba.fastjson.JSONArray;
import java.math.BigDecimal;
/**
* UpmsUserPermissionService接口
*
* @author Created by YL on 2017/4/27.
*/
public interface UpmsUserPermissionService extends BaseService<UpmsUserPermission, UpmsUserPermissionExample> {
/**
* 用户权限
*
* @param datas 权限
* @param userId 用户ID
* @return
*/
int permission(JSONArray datas, BigDecimal userId);
}
| 24.625
| 111
| 0.729272
|
5fc685e52a54ca6fdf14693f381247225e4d304c
| 2,113
|
package gameengine.actors.properties;
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Consumer;
import gamedata.composition.ActorDamageableData;
import gameengine.actors.propertygen.IActProperty;
import gameengine.grid.interfaces.ActorGrid.ReadAndDamageGrid;
import types.BasicActorType;
/**
* Class implementing the IActProperty interface that allows for an actor to be
* damaged within a certain radius called a "hitbox". This "hitbox" accepts
* damage from all enemy actors within a certain radius, removing them and
* damaging itself.
*
* @author Moses Wayne
*
* @param <G>
*/
public class ActorDamageableProperty<G extends ReadAndDamageGrid> implements IActProperty<G> {
private Collection<BasicActorType> myTypes;
private double hitBox;
public ActorDamageableProperty(ActorDamageableData data) {
hitBox = data.getMyHitRadius();
myTypes = new ArrayList<>();
for (BasicActorType t : data.getMyEnemyTypes()) {
myTypes.add(t);
}
}
/**
* Action to damage enemy units inside hitbox and to take the remaining
* damage
*
* @see IActProperty#action(gameengine.grid.interfaces.ActorGrid.ReadableGrid,
* Integer)
*/
public void action(G grid, Integer actorID) {
myTypes.stream()
.forEach(type -> grid
.getActorDamagablesInRadius(grid.getLocationOf(actorID).getX(),
grid.getLocationOf(actorID).getY(), hitBox, type)
.forEach((damage, health) -> damageActor(grid, actorID, damage, health)));
}
/**
* Helper method to determine the action taken for each given target
*
* @param grid
* generic grid used to interface with the game engine
* @param actorID
* unique integer identification of its actor
* @param damage
* the consumer used to damage the target
* @param health
* the remaining health of the target
*/
protected void damageActor(G grid, Integer actorID, Consumer<Double> damage, Double health) {
grid.getMyDamageable(actorID).accept(health);
damage.accept(health);
}
@Override
public boolean isOn() {
return true;
}
}
| 29.760563
| 94
| 0.723142
|
38d507200402912df7e917c103809f29db003fdf
| 136
|
package dacer.utils;
import android.app.admin.DeviceAdminReceiver;
public class AdminReceiver extends DeviceAdminReceiver {
}
| 17
| 57
| 0.786765
|
a282a0fa68a85b62e3a53ba1532ca832f6c9c42f
| 5,469
|
/*
* Copyright (c) 2020 Dzikoysk
*
* 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.panda_lang.utilities.commons.function;
import org.jetbrains.annotations.Nullable;
import org.panda_lang.utilities.commons.ObjectUtils;
import org.panda_lang.utilities.commons.iterable.SingletonIterator;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class Option<T> implements Iterable<T>, Serializable {
private static final Option<?> NONE = new Option<>(null);
private final @Nullable T value;
private Option(@Nullable T value) {
this.value = value;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
@Override
public boolean equals(@Nullable Object to) {
if (!(to instanceof Option)) {
return false;
}
return Objects.equals(value, ((Option<?>) to).value);
}
@Override
public Iterator<T> iterator() {
return isDefined() ? new SingletonIterator<>(value) : Collections.emptyIterator();
}
public Option<T> filter(Predicate<T> predicate) {
return (isDefined() && predicate.test(value)) ? this : Option.none();
}
public Option<T> filterNot(Predicate<T> predicate) {
return filter(value -> !predicate.test(value));
}
public <R> Option<R> map(Function<T, R> function) {
return isDefined() ? Option.of(function.apply(value)) : Option.none();
}
public <R> Option<R> flatMap(Function<T, Option<R>> function) {
return isDefined() ? function.apply(value) : Option.none();
}
@SafeVarargs
public final <R> Option<R> match(Case<T, R>... cases) {
if (isEmpty()) {
return Option.none();
}
for (Case<T, R> currentCase : cases) {
if (currentCase.getCondition().test(value)) {
return Option.of(currentCase.getValue().apply(value));
}
}
return Option.none();
}
public Option<T> peek(Consumer<T> consumer) {
if (isDefined()) {
consumer.accept(value);
}
return this;
}
public Option<T> onEmpty(Runnable runnable) {
if (isEmpty()) {
runnable.run();
}
return this;
}
public Option<T> orElse(T value) {
return isDefined() ? this : of(value);
}
public Option<T> orElse(Option<T> value) {
return isDefined() ? this : value;
}
public Option<T> orElse(Supplier<Option<T>> supplier) {
return isDefined() ? this : supplier.get();
}
public <E extends Throwable> T orThrow(Supplier<E> exceptionSupplier) throws E {
if (isEmpty()) {
throw exceptionSupplier.get();
}
return value;
}
public T orElseGet(T elseValue) {
return isDefined() ? value : elseValue;
}
public T orElseGet(Supplier<T> supplier) {
return isDefined() ? value : supplier.get();
}
public @Nullable T getOrNull() {
return value;
}
public T get() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("Value is not defined");
}
return value;
}
public boolean isPresent() {
return isDefined();
}
public boolean isDefined() {
return value != null;
}
public boolean isEmpty() {
return value == null;
}
public PandaStream<T> toStream() {
return PandaStream.of(toJavaStream());
}
public Stream<T> toJavaStream() {
return isDefined() ? Stream.of(value) : Stream.empty();
}
public Optional<T> toOptional() {
return Optional.ofNullable(value);
}
public static <T> Option<T> none() {
return ObjectUtils.cast(NONE);
}
public static <T> Option<T> of(@Nullable T value) {
return value != null? new Option<>(value) : none();
}
@SuppressWarnings({ "OptionalUsedAsFieldOrParameterType" })
public static <T> Option<T> ofOptional(Optional<T> optional) {
return of(optional.orElse(null));
}
public static <T> Option<T> when(boolean flag, @Nullable T value) {
return flag ? of(value) : Option.none();
}
public static <T, E extends Exception> Option<T> attempt(Class<E> exceptionType, ThrowingSupplier<T, E> supplier) {
try {
return of(supplier.get());
} catch (Exception e) {
if (exceptionType.isAssignableFrom(e.getClass())) {
return Option.none();
}
throw new RuntimeException("Unsupported exception", e);
}
}
}
| 26.678049
| 119
| 0.61748
|
06d40acc8ae55ddae5aee5a6972ff573404b98cb
| 375
|
package com.jaffa.rpc.lib.security;
import lombok.ToString;
import lombok.Setter;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import java.io.Serializable;
@ToString
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class SecurityTicket implements Serializable {
private String user;
private String token;
}
| 18.75
| 53
| 0.813333
|
3da86e9ff22193ea4168ce949c76fef10e964c06
| 11,888
|
package com.hazeluff.discord.nhlbot.nhl;
import java.net.URISyntaxException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.http.client.utils.URIBuilder;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hazeluff.discord.nhlbot.utils.DateUtils;
import com.hazeluff.discord.nhlbot.utils.HttpUtils;
public class Game {
private static final Logger LOGGER = LoggerFactory.getLogger(Game.class);
private final ZonedDateTime date;
private final int gamePk;
private final Team awayTeam;
private final Team homeTeam;
private int awayScore;
private int homeScore;
private GameStatus status;
private final List<GameEvent> events = new ArrayList<>();
private final List<GameEvent> newEvents = new ArrayList<>();
private final List<GameEvent> updatedEvents = new ArrayList<>();
private final List<GameEvent> removedEvents = new ArrayList<>();
Game(ZonedDateTime date, int gamePk, Team awayTeam, Team homeTeam, int awayScore, int homeScore,
GameStatus status, List<GameEvent> events, List<GameEvent> newEvents, List<GameEvent> updatedEvents,
List<GameEvent> removedEvents) {
this.date = date;
this.gamePk = gamePk;
this.awayTeam = awayTeam;
this.homeTeam = homeTeam;
this.awayScore = awayScore;
this.homeScore = homeScore;
this.status = status;
this.events.addAll(events);
this.newEvents.addAll(newEvents);
this.updatedEvents.addAll(updatedEvents);
this.removedEvents.addAll(removedEvents);
}
public Game (JSONObject jsonGame) {
date = DateUtils.parseNHLDate(jsonGame.getString("gameDate"));
gamePk = jsonGame.getInt("gamePk");
awayTeam = Team
.parse(jsonGame.getJSONObject("teams").getJSONObject("away").getJSONObject("team").getInt("id"));
homeTeam = Team
.parse(jsonGame.getJSONObject("teams").getJSONObject("home").getJSONObject("team").getInt("id"));
updateInfo(jsonGame);
updateEvents(jsonGame);
newEvents.clear();
updatedEvents.clear();
}
public ZonedDateTime getDate() {
return date;
}
/**
* Gets the date in the format "YY-MM-DD"
*
* @param zone
* time zone to convert the time to
* @return the date in the format "YY-MM-DD"
*/
public String getShortDate(ZoneId zone) {
return date.withZoneSameInstant(zone)
.format(DateTimeFormatter.ofPattern("yy-MM-dd"));
}
/**
* Gets the date in the format "EEEE dd MMM yyyy"
*
* @param zone
* time zone to convert the time to
* @return the date in the format "EEEE dd MMM yyyy"
*/
public String getNiceDate(ZoneId zone) {
return date.withZoneSameInstant(zone)
.format(DateTimeFormatter.ofPattern("EEEE d/MMM/yyyy"));
}
/**
* Gets the time in the format "HH:mm aaa"
*
* @param zone
* time zone to convert the time to
* @return the time in the format "HH:mm aaa"
*/
public String getTime(ZoneId zone) {
return date.withZoneSameInstant(zone)
.format(DateTimeFormatter.ofPattern("H:mm z"));
}
public int getGamePk() {
return gamePk;
}
public Team getAwayTeam() {
return awayTeam;
}
public Team getHomeTeam() {
return homeTeam;
}
/**
* Gets both home and aways teams as a list
*
* @return list containing both home and away teams
*/
public List<Team> getTeams() {
return Arrays.asList(homeTeam, awayTeam);
}
/**
* Determines if the given team is participating in this game
*
* @param team
* @return true, if team is a participant<br>
* false, otherwise
*/
public boolean isContain(Team team) {
return homeTeam == team || awayTeam == team;
}
public boolean containsTeam(Team team) {
return awayTeam == team || homeTeam == team;
}
public int getAwayScore() {
return awayScore;
}
public int getHomeScore() {
return homeScore;
}
/**
* Gets the name that a channel in Discord related to this game would have.
*
* @return channel name in format: "AAA_vs_BBB-yy-MM-DD". <br>
* AAA is the 3 letter code of home team<br>
* BBB is the 3 letter code of away team<br>
* yy-MM-DD is a date format
*/
public String getChannelName() {
String channelName = String.format("%.3s_vs_%.3s_%s",
homeTeam.getCode(),
awayTeam.getCode(),
getShortDate(ZoneId.of("America/New_York")));
return channelName.toString();
}
/**
* Gets the message that NHLBot will respond with when queried about this game
*
* @param timeZone
* the time zone to localize to
*
* @return message in the format: "The next game is:\n<br>
* **Home Team** vs **Away Team** at HH:mm aaa on EEEE dd MMM yyyy"
*/
public String getDetailsMessage(ZoneId timeZone) {
String message = String.format("**%s** vs **%s** at **%s** on **%s**",
homeTeam.getFullName(),
awayTeam.getFullName(),
getTime(timeZone),
getNiceDate(timeZone));
return message.toString();
}
/**
* Gets the message that NHLBot will respond with when queried about the
* score of this game
*
* @return message in the format : "Home Team **homeScore** - **awayScore**
* Away Team"
*/
public String getScoreMessage() {
return String.format("%s **%s** - **%s** %s", homeTeam.getName(), homeScore, awayScore,
awayTeam.getName());
}
public GameStatus getStatus() {
return status;
}
public List<GameEvent> getEvents() {
List<GameEvent> value = new ArrayList<>(events);
return value;
}
public List<GameEvent> getNewEvents() {
return new ArrayList<>(newEvents);
}
public List<GameEvent> getUpdatedEvents() {
return new ArrayList<>(updatedEvents);
}
List<GameEvent> getRemovedEvents() {
return new ArrayList<>(removedEvents);
}
@Override
public String toString() {
return "NHLGame [date=" + date + ", gamePk=" + gamePk + ", awayTeam=" + awayTeam + ", homeTeam=" + homeTeam
+ ", awayScore=" + awayScore + ", homeScore=" + homeScore + ", status=" + status + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + awayScore;
result = prime * result + ((awayTeam == null) ? 0 : awayTeam.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + gamePk;
result = prime * result + homeScore;
result = prime * result + ((homeTeam == null) ? 0 : homeTeam.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Game other = (Game) obj;
if (awayScore != other.awayScore)
return false;
if (awayTeam != other.awayTeam)
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (gamePk != other.gamePk)
return false;
if (homeScore != other.homeScore)
return false;
if (homeTeam != other.homeTeam)
return false;
if (status != other.status)
return false;
return true;
}
public boolean equals(Game other) {
return gamePk == other.gamePk;
}
public static Comparator<Game> getDateComparator() {
return new Comparator<Game>() {
public int compare(Game g1, Game g2) {
return (g1.getDate().compareTo(g2.getDate()));
}
};
}
/**
* Calls the NHL API and gets the current information of the game and
* updates all the update-able members in this class
*/
public void update() {
LOGGER.trace("Updating. [" + gamePk + "]");
URIBuilder uriBuilder = null;
String strJSONSchedule = "";
try {
uriBuilder = new URIBuilder("https://statsapi.web.nhl.com/api/v1/schedule");
uriBuilder.addParameter("gamePk", Integer.toString(gamePk));
uriBuilder.addParameter("expand", "schedule.scoringplays");
strJSONSchedule = HttpUtils.get(uriBuilder.build());
JSONObject jsonSchedule = new JSONObject(strJSONSchedule);
JSONObject jsonGame = jsonSchedule.getJSONArray("dates").getJSONObject(0).getJSONArray("games")
.getJSONObject(0);
updateInfo(jsonGame);
updateEvents(jsonGame);
} catch (URISyntaxException e) {
LOGGER.error("Error building URI", e);
}
}
/**
* Updates information about the game.
* <UL>
* <LI>Scores</LI>
* <LI>Status</LI>
* </UL>
*
* @param jsonGame
*/
void updateInfo(JSONObject jsonGame) {
awayScore = jsonGame.getJSONObject("teams").getJSONObject("away").getInt("score");
homeScore = jsonGame.getJSONObject("teams").getJSONObject("home").getInt("score");
status = GameStatus.parse(Integer.parseInt(jsonGame.getJSONObject("status").getString("statusCode")));
}
/**
* Updates about events in the game
*/
void updateEvents(JSONObject jsonGame) {
newEvents.clear();
updatedEvents.clear();
removedEvents.clear();
JSONArray jsonScoringPlays = jsonGame.getJSONArray("scoringPlays");
List<GameEvent> actualEvents = new ArrayList<>();
for(int i=0; i<jsonScoringPlays.length(); i++){
actualEvents.add(new GameEvent(jsonScoringPlays.getJSONObject(i)));
}
actualEvents.forEach(actualEvent -> {
if (!actualEvent.getPlayers().isEmpty() && !events.stream().anyMatch(event -> event.equals(actualEvent))) {
if (events.removeIf(event -> event.getId() == actualEvent.getId())) {
// Updated events
LOGGER.debug("Updated event: [" + actualEvent + "]");
updatedEvents.add(actualEvent);
} else {
// New events
LOGGER.debug("New event: [" + actualEvent + "]");
newEvents.add(actualEvent);
}
events.add(actualEvent);
}
});
// Deleted events
events.removeIf(event -> {
if (!actualEvents.contains(event)) {
LOGGER.debug("Removed event: [" + event + "]");
removedEvents.add(event);
return true;
}
return false;
});
}
public String getGoalsMessage() {
List<GameEvent> goals = events;
StringBuilder response = new StringBuilder();
response.append("```\n");
for (int i = 1; i <= 3; i++) {
switch (i) {
case 1:
response.append("1st Period:");
break;
case 2:
response.append("\n\n2nd Period:");
break;
case 3:
response.append("\n\n3rd Period:");
break;
}
int period = i;
Predicate<GameEvent> isPeriod = gameEvent -> gameEvent.getPeriod().getPeriodNum() == period;
if (goals.stream().anyMatch(isPeriod)) {
for (GameEvent gameEvent : goals.stream().filter(isPeriod)
.collect(Collectors.toList())) {
response.append("\n").append(gameEvent.getDetails());
}
} else {
response.append("\nNone");
}
}
Predicate<GameEvent> isOtherPeriod = gameEvent -> gameEvent.getPeriod().getPeriodNum() > 3;
if (goals.stream().anyMatch(isOtherPeriod)) {
GameEvent gameEvent = goals.stream().filter(isOtherPeriod).findFirst().get();
GamePeriod period = gameEvent.getPeriod();
response.append("\n\n").append(period.getDisplayValue()).append(":");
goals.stream().filter(isOtherPeriod).forEach(event -> response.append("\n").append(event.getDetails()));
}
response.append("\n```");
return response.toString();
}
/**
* Determines if game is ended.
*
* @return true, if game has ended<br>
* false, otherwise
*/
public boolean isEnded() {
return status == GameStatus.FINAL;
}
}
| 29.425743
| 111
| 0.650488
|
f2daa813b4a5ba93f75c175941250745386ad355
| 3,824
|
package com.lambdaschool.restaurants.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lambdaschool.restaurants.model.Menu;
import com.lambdaschool.restaurants.model.Restaurant;
import com.lambdaschool.restaurants.model.RestaurantPayments;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;
import java.util.ArrayList;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.number.OrderingComparison.lessThan;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RestaurantControllerIntegrationTest
{
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void initialiseRestAssuredMockMvcWebApplicationContext()
{
RestAssuredMockMvc.webAppContextSetup(webApplicationContext);
}
// GET /restaurants/restaurants
@Test
public void whenMeasuredReponseTime()
{
given().when().get("/restaurants/restaurants").then().time(lessThan(5000L));
}
// POST /restaurants/restaurant
@Test
public void givenPostARestaurant() throws Exception
{
ArrayList<RestaurantPayments> thisPay = new ArrayList<>();
String rest3Name = "Number 1 Test Eats";
Restaurant r3 = new Restaurant(rest3Name, "565 Side Test Avenue", "Village", "ST", "555-123-1555", thisPay);
r3.getMenus().add(new Menu("Pizza", 15.15, r3));
ObjectMapper mapper = new ObjectMapper();
String stringR3 = mapper.writeValueAsString(r3);
given().contentType("application/json").body(stringR3).when().post("/restaurants/restaurant").then().statusCode(201);
}
// GET /restaurants/restaurant/{restaurantId}
@Test
public void givenFoundRestaurantId() throws Exception
{
long aRestaurant = 10L;
given().when().get("/restaurants/restaurant/" + aRestaurant).then().statusCode(200).and().body(containsString("Bird"));
}
// GET /restaurants/restaurant/name/{name}
@Test
public void givenFoundRestaurantName() throws Exception
{
String aRestaurant = "Apple";
given().when().get("/restaurants/restaurant/name/" + aRestaurant).then().statusCode(200).and().body(containsString("Apple"));
}
// GET /restaurants/restaurants
@Test
public void givenFindAllRestaurants()
{
given().when().get("/restaurants/restaurants").then().statusCode(200).and().body(containsString("Apple"));
}
// PUT /restaurants/restaurant/{restaurantid}
@Test
public void givenUpdateARestaurant() throws Exception
{
ArrayList<RestaurantPayments> thisPay = new ArrayList<>();
Restaurant r1 = new Restaurant(null,
null,
null, "ZZ", null,
thisPay);
r1.setRestaurantid(10);
ObjectMapper mapper = new ObjectMapper();
String stringR1 = mapper.writeValueAsString(r1);
given().contentType("application/json").body(stringR1).when().put("/restaurants/restaurant/10").then().statusCode(200);
}
// DELETE /restaurants/restaurant/{restaurantid}
// at the end so I can use restaurant 10 in examples!
@Test
public void givenDeleteARestaurant()
{
long aRestaurant = 10L;
given().when().delete("/restaurants/restaurant/" + aRestaurant).then().statusCode(200);
}
}
| 33.54386
| 133
| 0.70319
|
d7a92066295d49d79cde3b6d98368767c7bd2a9b
| 7,613
|
package edu.sdu.sensumbosted.data;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import edu.sdu.sensumbosted.AuditAction;
import edu.sdu.sensumbosted.SystemContext;
import edu.sdu.sensumbosted.entity.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.postgresql.util.PGobject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.lang.NonNull;
import org.springframework.jdbc.core.RowMapper;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
public class DataService {
final JdbcTemplate jdbc;
private final DepartmentLoader departmentLoader;
private static final Logger log = LoggerFactory.getLogger(DataService.class);
SystemContext systemContext = null;
public DataService() {
HikariConfig conf = new HikariConfig("database.properties");
conf.validate();
log.info("Database config passed validation");
conf.setMaximumPoolSize(2);
jdbc = new JdbcTemplate(new HikariDataSource(conf));
departmentLoader = new DepartmentLoader(this);
}
public HashMap<UUID, Department> loadDepartments(SystemContext systemContext) {
this.systemContext = systemContext;
return departmentLoader.loadDepartments();
}
public void create(Department department) {
jdbc.update("INSERT INTO departments VALUES(?, ?);", varargs(
department.getId(),
department.getName()
));
}
public void create(Manager manager) {
jdbc.update("INSERT INTO managers VALUES(?, ?, ?, ?);", varargs(
manager.getId(),
manager.getDepartment().getId(),
manager.getName(),
manager.getAuth().toString()
));
}
public void create(Patient patient) {
jdbc.update("INSERT INTO patients VALUES(?, ?, ?, ?, ?, ?);", varargs(
patient.getId(),
patient.getDepartment().getId(),
patient.getName(),
patient.isEnrolled(),
patient.getDiaryJson(),
patient.getCalendarJson()
));
}
public void create(Practitioner practitioner) {
jdbc.update("INSERT INTO practitioners VALUES(?, ?, ?);", varargs(
practitioner.getId(),
practitioner.getDepartment().getId(),
practitioner.getName()
));
}
public void update(Department department) {
jdbc.update("UPDATE departments SET name = ? WHERE id = ?;", varargs(
department.getName(),
department.getId()
));
}
public void update(Manager manager) {
jdbc.update("UPDATE managers SET department = ?, name = ?, auth = ? WHERE id = ?;", varargs(
manager.getDepartment().getId(),
manager.getName(),
manager.getAuth().toString(),
manager.getId()
));
}
public void update(Patient patient) {
jdbc.update("UPDATE patients SET department = ?, name = ?, enrolled = ?, diary = ?, calendar = ? WHERE id = ?;", varargs(
patient.getDepartment().getId(),
patient.getName(),
patient.isEnrolled(),
patient.getDiaryJson(),
patient.getCalendarJson(),
patient.getId()
));
}
public void update(Practitioner practitioner) {
jdbc.update("UPDATE practitioners SET department = ?, name = ? WHERE id = ?;", varargs(
practitioner.getDepartment().getId(),
practitioner.getName(),
practitioner.getId()
));
}
/**
* Create a new relation between a practitioner and a patient
*/
public void associate(Practitioner practitioner, Patient patient) {
jdbc.update("INSERT INTO practitionerpatientrelation VALUES (?, ?);", varargs(
practitioner.getId(),
patient.getId()
));
}
public void disassociate(Practitioner practitioner, Patient patient) {
jdbc.update("DELETE FROM practitionerpatientrelation WHERE practitioner = ? AND patient = ?;", varargs(
practitioner.getId(),
patient.getId()
));
}
/**
* @param entity the entity to delete
* @return true if deleted
*/
public boolean delete(DataEntity entity) {
return delete(entity.getId(), entity.getSqlTable());
}
/**
* @param id the UUID of the entity to delete
* @param table the table to delete from
* @return true if deleted
*/
public boolean delete(UUID id, SqlTable table) {
@SuppressWarnings("SqlResolve")
int changed = jdbc.update("DELETE FROM " + table.getTableName() + " WHERE id = ?;", varargs(id));
return changed > 0;
}
public List<Object> getRawUserRow(UUID id) {
RowMapper<List<Object>> rowMapper = (rs, rowNum) -> {
int i = 1;
ArrayList<Object> list = new ArrayList<>();
while (i < 100) {
try {
list.add(rs.getObject(i++));
} catch (SQLException e) {
break;
}
}
return list;
};
List<List<Object>> row = jdbc.query("SELECT * FROM managers WHERE id = ?;", varargs(id), rowMapper);
if (!row.isEmpty()) return row.get(0);
row = jdbc.query("SELECT * FROM practitioners WHERE id = ?;", varargs(id), rowMapper);
if (!row.isEmpty()) return row.get(0);
row = jdbc.query("SELECT * FROM patients WHERE id = ?;", varargs(id), rowMapper);
if (!row.isEmpty()) return row.get(0);
return null;
}
public void log(Context ctx, AuditAction action) {
log(ctx, action, "");
}
public void log(@NonNull Context ctx, @NonNull AuditAction action, @NonNull String description) {
log.info("{} {} {}", ctx.getUser(), action, description);
UUID userId = null;
User user = ctx.getUser();
if (user != null) userId = user.getId();
jdbc.update("INSERT INTO audit (time, actor, action, description) VALUES(?, ?, ?, ?);", varargs(
Instant.now(), userId, action.toString(), description
));
}
/**
* Convenience class to preserve my sanity.
* <p>
* This is at the cost of strong typing.
*/
class VarargSetter implements PreparedStatementSetter {
private Object[] args;
VarargSetter(Object... args) {
this.args = args;
}
@Override
public void setValues(PreparedStatement ps) throws SQLException {
int i = 1;
for (Object o : args) {
if (o instanceof Instant) o = Timestamp.from((Instant) o);
else if (o instanceof JSONObject || o instanceof JSONArray) {
PGobject pgo = new PGobject();
pgo.setType("json");
pgo.setValue(o.toString());
o = pgo;
}
ps.setObject(i++, o);
}
}
}
/**
* Convenience function
*/
@SuppressWarnings("WeakerAccess")
VarargSetter varargs(Object... args) {
return new VarargSetter(args);
}
}
| 33.1
| 129
| 0.584132
|
09ed6468e7378a37c5c1cc654b438a990c7bb481
| 1,148
|
/*
* Java
*
* Copyright 2014 IS2T. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be found at http://www.is2t.com/open-source-bsd-license/.
*/
package com.is2t.demo.showroom.widgets;
import com.is2t.demo.utilities.mosaic.BackgroundImageHelper;
import com.is2t.demo.utilities.mosaic.RatioMosaic;
import ej.microui.io.Display;
import ej.microui.io.GraphicsContext;
import ej.mwt.Panel;
import ej.mwt.Renderable;
import ej.mwt.rendering.Look;
import ej.mwt.rendering.Renderer;
public class PanelRenderer extends Renderer {
private final BackgroundImageHelper backgroundImageHelper;
public PanelRenderer(Display display) {
this.backgroundImageHelper = new BackgroundImageHelper(display, new RatioMosaic(
new float[] { 0, -0.66f, -0.33f }), "background", "background_tile");
}
@Override
public Class<?> getManagedType() {
return Panel.class;
}
@Override
public void render(GraphicsContext g, Renderable renderable) {
this.backgroundImageHelper.drawBackground(g, renderable.getWidth(), renderable.getHeight(), getLook()
.getProperty(Look.GET_BACKGROUND_COLOR_DEFAULT));
}
}
| 28.7
| 128
| 0.769164
|
7563aaa8d4d14ad408596e38c3e4893e5b91a37e
| 8,845
|
/*
* Copyright 2015-2016 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.hal.client.configuration.subsystem.logging;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest;
import org.jboss.hal.ballroom.form.Form;
import org.jboss.hal.core.ComplexAttributeOperations;
import org.jboss.hal.core.CrudOperations;
import org.jboss.hal.core.finder.Finder;
import org.jboss.hal.core.finder.FinderPath;
import org.jboss.hal.core.finder.FinderPathFactory;
import org.jboss.hal.core.mbui.MbuiPresenter;
import org.jboss.hal.core.mbui.MbuiView;
import org.jboss.hal.core.mvp.SupportsExpertMode;
import org.jboss.hal.dmr.ModelNode;
import org.jboss.hal.dmr.NamedNode;
import org.jboss.hal.dmr.ResourceAddress;
import org.jboss.hal.meta.AddressTemplate;
import org.jboss.hal.meta.Metadata;
import org.jboss.hal.meta.SelectionAwareStatementContext;
import org.jboss.hal.meta.StatementContext;
import org.jboss.hal.meta.token.NameTokens;
import org.jboss.hal.resources.Ids;
import org.jboss.hal.resources.Names;
import org.jboss.hal.spi.Requires;
import static org.jboss.hal.client.configuration.subsystem.logging.AddressTemplates.*;
import static org.jboss.hal.dmr.ModelDescriptionConstants.FORMATTER;
import static org.jboss.hal.dmr.ModelDescriptionConstants.LOGGING;
import static org.jboss.hal.dmr.ModelDescriptionConstants.NAME;
import static org.jboss.hal.dmr.ModelNodeHelper.asNamedNodes;
import static org.jboss.hal.dmr.ModelNodeHelper.failSafePropertyList;
import static org.jboss.hal.resources.Ids.ADD;
import static org.jboss.hal.resources.Ids.asId;
public class LoggingProfilePresenter
extends MbuiPresenter<LoggingProfilePresenter.MyView, LoggingProfilePresenter.MyProxy>
implements SupportsExpertMode {
private final CrudOperations crud;
private final FinderPathFactory finderPathFactory;
private final StatementContext statementContext;
private final ComplexAttributeOperations ca;
private String loggingProfile;
@Inject
public LoggingProfilePresenter(EventBus eventBus,
MyView view,
MyProxy myProxy,
Finder finder,
CrudOperations crud,
FinderPathFactory finderPathFactory,
StatementContext statementContext,
ComplexAttributeOperations ca) {
super(eventBus, view, myProxy, finder);
this.crud = crud;
this.finderPathFactory = finderPathFactory;
this.statementContext = new SelectionAwareStatementContext(statementContext, () -> loggingProfile);
this.ca = ca;
}
@Override
protected void onBind() {
super.onBind();
getView().setPresenter(this);
}
@Override
public void prepareFromRequest(PlaceRequest request) {
super.prepareFromRequest(request);
loggingProfile = request.getParameter(NAME, null);
}
@Override
public ResourceAddress resourceAddress() {
return SELECTED_LOGGING_PROFILE_TEMPLATE.resolve(statementContext);
}
String getLoggingProfile() {
return loggingProfile;
}
@Override
public FinderPath finderPath() {
return finderPathFactory.configurationSubsystemPath(LOGGING)
.append(Ids.LOGGING_CONFIG_AND_PROFILES, Ids.asId(Names.LOGGING_PROFILES),
Names.LOGGING, Names.LOGGING_PROFILES)
.append(Ids.LOGGING_PROFILE, Ids.loggingProfile(loggingProfile),
Names.LOGGING_PROFILE, loggingProfile);
}
@Override
protected void reload() {
ResourceAddress address = SELECTED_LOGGING_PROFILE_TEMPLATE.resolve(statementContext);
crud.read(address, 2, result -> {
// @formatter:off
if (result.hasDefined(ROOT_LOGGER_TEMPLATE.lastName())) {
getView().updateRootLogger(result.get(ROOT_LOGGER_TEMPLATE.lastName()).get(ROOT_LOGGER_TEMPLATE.lastValue()));
} else {
getView().noRootLogger();
}
getView().updateLogger(asNamedNodes(failSafePropertyList(result, LOGGER_TEMPLATE.lastName())));
getView().updateAsyncHandler(asNamedNodes(failSafePropertyList(result, ASYNC_HANDLER_TEMPLATE.lastName())));
getView().updateConsoleHandler(asNamedNodes(failSafePropertyList(result, CONSOLE_HANDLER_TEMPLATE.lastName())));
getView().updateCustomHandler(asNamedNodes(failSafePropertyList(result, CUSTOM_HANDLER_TEMPLATE.lastName())));
getView().updateFileHandler(asNamedNodes(failSafePropertyList(result, FILE_HANDLER_TEMPLATE.lastName())));
getView().updatePeriodicHandler(asNamedNodes(failSafePropertyList(result, PERIODIC_ROTATING_FILE_HANDLER_TEMPLATE.lastName())));
getView().updatePeriodicSizeHandler(asNamedNodes(failSafePropertyList(result, PERIODIC_SIZE_ROTATING_FILE_HANDLER_TEMPLATE.lastName())));
getView().updateSizeHandler(asNamedNodes(failSafePropertyList(result, SIZE_ROTATING_FILE_HANDLER_TEMPLATE.lastName())));
getView().updateSocketHandler(asNamedNodes(failSafePropertyList(result, SOCKET_HANDLER_TEMPLATE.lastName())));
getView().updateSyslogHandler(asNamedNodes(failSafePropertyList(result, SYSLOG_HANDLER_TEMPLATE.lastName())));
getView().updateCustomFormatter(asNamedNodes(failSafePropertyList(result, CUSTOM_FORMATTER_TEMPLATE.lastName())));
getView().updatePatternFormatter(asNamedNodes(failSafePropertyList(result, PATTERN_FORMATTER_TEMPLATE.lastName())));
getView().updateJsonFormatter(asNamedNodes(failSafePropertyList(result, JSON_FORMATTER_TEMPLATE.lastName())));
getView().updateXmlFormatter(asNamedNodes(failSafePropertyList(result, XML_FORMATTER_TEMPLATE.lastName())));
// @formatter:on
});
}
void saveComplexObject(String type, String name, String complexAttribute, AddressTemplate template,
Map<String, Object> changedValues) {
ca.save(name, complexAttribute, type, template, changedValues, this::reload);
}
void resetComplexObject(String type, String name, String complexAttribute, AddressTemplate template,
Metadata metadata, Form<ModelNode> form) {
ca.reset(name, complexAttribute, type, template, metadata, form, this::reload);
}
void removeComplexObject(String type, String name, String complexAttribute, AddressTemplate template) {
ca.remove(name, complexAttribute, type, template, this::reload);
}
void addComplexObject(String type, String name, String complexAttribute, AddressTemplate template) {
ca.add(Ids.build(LOGGING, FORMATTER, asId(type), ADD), name, complexAttribute, type, template, this::reload);
}
public StatementContext getStatementContext() {
return statementContext;
}
// @formatter:off
@ProxyCodeSplit
@NameToken(NameTokens.LOGGING_PROFILE)
@Requires(LOGGING_PROFILE_ADDRESS)
public interface MyProxy extends ProxyPlace<LoggingProfilePresenter> {
}
public interface MyView extends MbuiView<LoggingProfilePresenter> {
void updateRootLogger(ModelNode modelNode);
void noRootLogger();
void updateLogger(List<NamedNode> items);
void updateAsyncHandler(List<NamedNode> items);
void updateConsoleHandler(List<NamedNode> items);
void updateCustomHandler(List<NamedNode> items);
void updateFileHandler(List<NamedNode> items);
void updatePeriodicHandler(List<NamedNode> items);
void updatePeriodicSizeHandler(List<NamedNode> items);
void updateSizeHandler(List<NamedNode> items);
void updateSocketHandler(List<NamedNode> items);
void updateSyslogHandler(List<NamedNode> items);
void updateCustomFormatter(List<NamedNode> items);
void updatePatternFormatter(List<NamedNode> items);
void updateJsonFormatter(List<NamedNode> items);
void updateXmlFormatter(List<NamedNode> items); }
// @formatter:on
}
| 45.358974
| 149
| 0.738949
|
e5456e7c2c4ce9b6f501f31758ca487cd85df494
| 463
|
package com.supervisor.domain;
import java.io.IOException;
import com.supervisor.sdk.metadata.Field;
import com.supervisor.sdk.metadata.Recordable;
@Recordable(
name="value_expression_arg",
label="Argument valeur d'une expression",
comodel=ExpressionArg.class
)
public interface ValueArg extends ExpressionArg {
@Field(label="Valeur")
String value() throws IOException;
@Field(label="Type de valeur")
DataFieldType valueType() throws IOException;
}
| 22.047619
| 49
| 0.786177
|
87f3d14b778dc41a6d5e0b626100641416e8c8f3
| 1,963
|
package com.interview.codechef.ccdsapfoundation_1.strings;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
public class LAPIN {
public static void main( String[] args ) {
try {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-- > 0) {
char[] str = scanner.next().toCharArray();
int halfPoint;
if (str.length % 2 == 0) {
halfPoint = str.length / 2;
} else {
halfPoint = str.length / 2 + 1;
}
HashMap<Character, Integer> map = new HashMap<>();
HashMap<Character, Integer> map1 = new HashMap<>();
for (int i = 0; i < str.length / 2; i++) {
if (map.containsKey(str[i])) {
map.put(str[i], map.get(str[i]) + 1);
} else {
map.put(str[i], 1);
}
}
for (int i = halfPoint; i < str.length; i++) {
if (map1.containsKey(str[i])) {
map1.put(str[i], map1.get(str[i]) + 1);
} else {
map1.put(str[i], 1);
}
}
boolean isFalse = true;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (!map1.containsKey(entry.getKey())
|| !Objects.equals(map1.get(entry.getKey()), map.get(entry.getKey()))) {
System.out.println("NO");
isFalse = false;
break;
}
}
if (isFalse)
System.out.println("YES");
}
} catch (Exception e) {
return;
}
}
}
| 30.671875
| 100
| 0.403464
|
c381ae1b9d07cf39b9f44f12b6c9da5d4154a2b9
| 1,206
|
package org.ohdsi.webapi.check.checker.estimation.helper;
import static org.ohdsi.webapi.check.checker.estimation.helper.EstimationAnalysisSpecificationHelper.*;
import org.ohdsi.analysis.estimation.comparativecohortanalysis.design.ComparativeCohortAnalysis;
import org.ohdsi.analysis.estimation.design.EstimationAnalysisSettings;
import org.ohdsi.webapi.check.builder.NotNullNotEmptyValidatorBuilder;
import org.ohdsi.webapi.check.builder.ValidatorGroupBuilder;
public class EstimationSettingsHelper {
public static ValidatorGroupBuilder<EstimationAnalysisSettings, ComparativeCohortAnalysis> prepareAnalysisSpecificationBuilder() {
ValidatorGroupBuilder<EstimationAnalysisSettings, ComparativeCohortAnalysis> builder = new ValidatorGroupBuilder<EstimationAnalysisSettings, ComparativeCohortAnalysis>()
.valueGetter(EstimationAnalysisSettings::getAnalysisSpecification)
.validators(
new NotNullNotEmptyValidatorBuilder<>()
)
.groups(
prepareTargetComparatorBuilder(),
prepareAnalysisSettingsBuilder()
);
return builder;
}
}
| 46.384615
| 177
| 0.746269
|
7c69c3e7a7ea70f64f54bf75cf22654efa50f06d
| 1,848
|
package com.gmail.willramanand.RamMMO.player;
import com.gmail.willramanand.RamMMO.RamMMO;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class PlayerManager {
private final RamMMO plugin;
private final ConcurrentHashMap<UUID, MMOPlayer> playerData;
public PlayerManager(RamMMO plugin) {
this.plugin = plugin;
this.playerData = new ConcurrentHashMap<>();
startAutoSave();
}
@Nullable
public MMOPlayer getPlayerData(Player player) {
return playerData.get(player.getUniqueId());
}
@Nullable
public MMOPlayer getPlayerData(UUID id) {
return this.playerData.get(id);
}
public void addPlayerData(@NotNull MMOPlayer mmoPlayer) {
this.playerData.put(mmoPlayer.getUuid(), mmoPlayer);
}
public void removePlayerData(UUID id) {
this.playerData.remove(id);
}
public boolean hasPlayerData(Player player) {
return playerData.containsKey(player.getUniqueId());
}
public ConcurrentHashMap<UUID, MMOPlayer> getPlayerDataMap() {
return playerData;
}
public void startAutoSave() {
new BukkitRunnable() {
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
MMOPlayer mmoPlayer = plugin.getPlayerManager().getPlayerData(player);
if (mmoPlayer != null && !mmoPlayer.isSaving()) {
plugin.getConfigManager().save(mmoPlayer.getPlayer(), false);
}
}
}
}.runTaskTimer(plugin, 6000L, 6000L);
}
}
| 28.430769
| 90
| 0.649351
|
6c46379a25a2d6ef5481200e06af917c05f0c4bb
| 3,750
|
package com.obsidiandynamics.indigo;
import java.util.concurrent.*;
import org.junit.*;
import com.obsidiandynamics.indigo.ActorSystemConfig.*;
import com.obsidiandynamics.indigo.benchmark.*;
import com.obsidiandynamics.indigo.util.*;
import com.obsidiandynamics.threads.*;
public final class ThroughputBenchmark implements TestSupport {
abstract static class Config implements Spec {
ExecutorChoice executorChoice = null;
long n;
int threads;
int actors;
int bias;
float warmupFrac;
LogConfig log;
/* Derived fields. */
long warmup;
@Override
public void init() {
warmup = (long) (n * warmupFrac);
}
@Override
public LogConfig getLog() {
return log;
}
@Override
public String describe() {
return String.format("%d threads, %,d receive actors, %,d messages/actor, %.0f%% warmup fraction",
threads, actors, n, warmupFrac * 100);
}
@Override
public Summary run() {
return new ThroughputBenchmark().test(this);
}
}
@Test
public void test() throws Exception {
new Config() {{
threads = Runtime.getRuntime().availableProcessors();
actors = 4;
bias = 1_000;
n = 1_000;
warmupFrac = .05f;
log = new LogConfig() {{
summary = stages = LOG;
}};
}}.test();
}
private Summary test(Config c) {
final String SINK = "sink";
final CountDownLatch latch = new CountDownLatch(c.actors);
final long n = c.n;
final ActorSystem system = new TestActorSystemConfig() {{
if (c.executorChoice != null) {
executor = c.executorChoice;
}
parallelism = c.threads;
reaperPeriodMillis = 0;
defaultActorConfig = new ActorConfig() {{
bias = c.bias;
backlogThrottleCapacity = Integer.MAX_VALUE;
backlogThrottleTries = 10;
}};
}}
.createActorSystem()
.on(SINK).cue(IntegerState::new, (a, m, s) -> {
if (++s.value == n) {
latch.countDown();
}
});
final ActorRef[] refs = new ActorRef[c.actors];
for (int i = 0; i < c.actors; i++) {
refs[i] = ActorRef.of(SINK, String.valueOf(i));
system.tell(refs[i]);
}
if (c.warmup != 0) {
if (c.log.stages) c.log.out.format("Warming up...\n");
Parallel.blocking(c.actors, i -> {
final ActorRef to = refs[i];
final Message m = Message.builder().to(to).build();
for (int j = 0; j < c.warmup; j++) {
system.send(m);
}
}).run();
try {
system.drain(0);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (c.log.stages) c.log.out.format("Starting timed run...\n");
final long o = n - c.warmup;
final long took = TestSupport.took(
Parallel.blocking(c.actors, i -> {
final ActorRef to = refs[i];
final Message m = Message.builder().to(to).build();
for (int j = 0; j < o; j++) {
system.send(m);
}
TestSupport.await(latch);
})
);
system.shutdownSilently();
final Summary summary = new Summary();
summary.timedOps = o * c.actors;
summary.avgTime = took;
return summary;
}
public static void main(String[] args) throws Exception {
new Config() {{
executorChoice = ActorSystemConfig.ExecutorChoice.FIXED_THREAD_POOL;
threads = Runtime.getRuntime().availableProcessors() * 1;
actors = threads * 1;
n = 10_000_000;
warmupFrac = .05f;
bias = 10_000;
log = new LogConfig() {{
summary = true;
}};
}}.testPercentile(9, 21, 50, Summary::byThroughput);
}
}
| 26.041667
| 105
| 0.578133
|
e534e47e678a14136bb1a7081d5479310c0d82b1
| 182
|
package com.pf.base;
/**
* 封装API的错误码
* Created by on 2019/4/19.
*/
public interface BaseErrCode {
Integer getCode();
String getMessage();
String getCodeToStr();
}
| 13
| 30
| 0.642857
|
4215ce46ce1932c35a4ea6f55d3b2389f6153923
| 24,695
|
package com.ts.FetcherHander.InHospital.dayReprot;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.hitzd.DBUtils.JDBCQueryImpl;
import com.hitzd.DBUtils.TCommonRecord;
import com.hitzd.Factory.DBQueryFactory;
import com.hitzd.Transaction.TransaCallback;
import com.hitzd.Transaction.TransactionTemp;
import com.hitzd.Utils.StringUtils;
import com.hitzd.his.DDD.DDDUtils;
import com.hitzd.his.ReportBuilder.Interfaces.IReportBuilder;
import com.hitzd.his.Utils.Config;
import com.hitzd.his.Utils.DateUtils;
import com.hitzd.his.Utils.DictCache;
import com.hitzd.his.Utils.DrugUtils;
import com.hitzd.his.casehistory.helper.CaseHistoryFactory;
import com.hitzd.his.casehistory.helper.CaseHistoryFunction;
import com.hitzd.his.casehistory.helper.CaseHistoryHelperUtils;
import com.hitzd.his.casehistory.helper.CaseHistoryUtils;
import com.hitzd.his.casehistory.helper.ICaseHistoryHelper;
import com.hitzd.his.task.Task;
import com.ts.util.LoggerFileSaveUtil;
import com.ts.util.UuidUtil;
/**
* 适用于307医院,304医院,北京军区总院,上海长征医院
*
* @author
*
*/
public class DrDeptDoctDrugEx implements IReportBuilder
{
private Logger logger = Logger.getLogger("DrDeptDoctDrugEx");
private List<TCommonRecord> resultSet = new ArrayList<TCommonRecord>();
private List<TCommonRecord> supplier = new ArrayList<TCommonRecord>();
public String BuildReportWithCR(String ADate, TCommonRecord crPatInfo,
Task AOwner)
{
JDBCQueryImpl query = DBQueryFactory.getQuery("HIS");
logger.info("处理药品数据附加信息:" + ADate + "日报数据");
for (TCommonRecord cr : this.resultSet)
{
if (supplier == null || supplier.size() == 0)
{
supplier = StringUtils.getSupplier();
}
StringUtils.execCF(supplier, cr);
// 是否抗菌药
if (DrugUtils.isKJDrug(cr.get("item_code")))
{
cr.set("is_anti", "1");
}
// 国家药物基本目录
cr.set("is_basedrug", "0");
if (DrugUtils.isCountryBase(cr.get("item_code"),
cr.get("item_spec")))
{
cr.set("is_basedrug", "1");
}
setDoctor(query, cr);
}
return "";
}
public void setDoctor(JDBCQueryImpl query, TCommonRecord cr)
{
ICaseHistoryHelper chhr = CaseHistoryFactory.getCaseHistoryHelper();
if ("".equals(cr.get("doctor_name")))
{
List<TCommonRecord> list = null;
String strFields = "DOCTOR_IN_CHARGE";
List<TCommonRecord> lsWheres1 = new ArrayList<TCommonRecord>();
TCommonRecord where1 = CaseHistoryHelperUtils.genWhereCR(
"patient_id", cr.get("patient_id"), "Char", "", "", "");
lsWheres1.add(where1);
where1 = CaseHistoryHelperUtils.genWhereCR("visit_id",
cr.get("visit_id"), "Char", "", "", "");
lsWheres1.add(where1);
try
{
list = chhr.fetchPatVisit2CR(strFields, lsWheres1, null, null,
null);
}
catch (Exception e)
{
e.printStackTrace();
}
String doctor = "";
if ((list != null) && (list.size() > 0))
{
if (!"".equals(
((TCommonRecord) list.get(0)).get("DOCTOR_IN_CHARGE")))
doctor = ((TCommonRecord) list.get(0))
.get("DOCTOR_IN_CHARGE");
}
if ("".equals(doctor))
{
try
{
list = chhr.fetchOrders2CR(cr.get("patient_id"),
cr.get("visit_id"), null).subList(0, 1);
}
catch (Exception e)
{
e.printStackTrace();
}
if ((list != null) && (list.size() > 0))
doctor = ((TCommonRecord) list.get(0)).get("doctor");
}
cr.set("doctor_Name", doctor);
chhr = null;
}
}
public String BuildReport(String ADate, Task AOwner)
{
buildBegin(ADate, AOwner);
logger.info("正在汇总" + ADate + "的账单记录!药品统计");
JDBCQueryImpl queryHIS = DBQueryFactory.getQuery("HIS");
getResultSetByMiddleWare(ADate, queryHIS);
String ErrorInfo = "";
if ((this.resultSet != null) && (this.resultSet.size() > 0))
{
logger.info(ADate + "共有" + this.resultSet.size() + "条汇总记录!药品统计");
ErrorInfo = BuildReportWithCR(ADate, null, AOwner);
buildOver(ADate, AOwner);
}
queryHIS = null;
if (ErrorInfo.length() == 0)
{
return "构建日报结束";
}
return ErrorInfo;
}
private void getResultSetByMiddleWare(String ADate, JDBCQueryImpl hisQuery)
{
ICaseHistoryHelper chhr = CaseHistoryFactory.getCaseHistoryHelper();
DictCache dc = DictCache.getNewInstance();
// 2013-12-11 为青岛添加FIRM_ID查询字段,在已经在field_config中添加映射字段,军卫的HIS请直接设置为''
List<TCommonRecord> lsWheres = new ArrayList<TCommonRecord>();
String fields = CaseHistoryFunction.genSum("inpbill.inp_bill_detail",
"costs", "costs")
+ ","
+ CaseHistoryFunction.genSum("inpbill.inp_bill_detail",
"charges", "charges")
+ ","
+ CaseHistoryFunction.genSum("inpbill.inp_bill_detail",
"amount", "amount")
+ ","
+ "ordered_by,item_name,item_code,item_spec,units,patient_id,visit_id,firm_id";
TCommonRecord where = CaseHistoryHelperUtils.genWhereCR("item_class",
Config.getParamValue("Drug_In_Order"), "Char", "", "", "");
lsWheres.add(where);
where = CaseHistoryHelperUtils.genWhereCR(
CaseHistoryFunction.genToChar("inpbill.inp_bill_detail",
"billing_date_time", "yyyy-MM-dd", ""),
ADate, "Char", ">=", "", "");
lsWheres.add(where);
where = CaseHistoryHelperUtils.genWhereCR(
CaseHistoryFunction.genToChar("inpbill.inp_bill_detail",
"billing_date_time", "yyyy-MM-dd", ""),
DateUtils.getDateAdded(1, ADate), "Char", "<", "", "");
lsWheres.add(where);
List<TCommonRecord> lsGroups = new ArrayList<TCommonRecord>();
TCommonRecord group = CaseHistoryHelperUtils.genGroupCR("ordered_by");
lsGroups.add(group);
group = CaseHistoryHelperUtils.genGroupCR("item_name");
lsGroups.add(group);
group = CaseHistoryHelperUtils.genGroupCR("item_code");
lsGroups.add(group);
group = CaseHistoryHelperUtils.genGroupCR("item_spec");
lsGroups.add(group);
group = CaseHistoryHelperUtils.genGroupCR("patient_id");
lsGroups.add(group);
group = CaseHistoryHelperUtils.genGroupCR("visit_id");
lsGroups.add(group);
group = CaseHistoryHelperUtils.genGroupCR("units");
lsGroups.add(group);
group = CaseHistoryHelperUtils.genGroupCR("firm_id");
lsGroups.add(group);
try
{
this.resultSet = chhr.fetchInpBillDetail2CR(fields, lsWheres,
lsGroups, null, null);
}
catch (Exception e)
{
e.printStackTrace();
}
// 填入部门信息
for (TCommonRecord data : resultSet)
{
data.set("dept_code", data.get("ordered_by"));
data.set("dept_name", dc.getDeptName(data.get("ordered_by")));
}
String strFields = "";
// SQLServer 关键字
if ("SQLServer".equals(CaseHistoryUtils
.getTableConfig("MedRec.pat_visit").get("DB_NAME")))
{
strFields = "'identity',charge_type,attending_doctor";
}
else
{
strFields = "identity,charge_type,attending_doctor";
}
List<TCommonRecord> lsWheres1 = new ArrayList<TCommonRecord>();
List<TCommonRecord> patVisitList = null;
// 填入身份、医生、费别信息
for (TCommonRecord data : resultSet)
{
TCommonRecord where1 = CaseHistoryHelperUtils.genWhereCR(
"patient_id", data.get("patient_id"), "Char", "", "", "");
lsWheres1.add(where1);
where1 = CaseHistoryHelperUtils.genWhereCR("visit_id",
data.get("visit_id"), "Char", "", "", "");
lsWheres1.add(where1);
try
{
patVisitList = chhr.fetchPatVisit2CR(strFields, lsWheres1, null,
null, null);
}
catch (Exception e)
{
e.printStackTrace();
}
data.set("doctor_name",
getDoctorInCharge(data.get("patient_id"),
data.get("visit_id"), data.get("ordered_by"))
.get("DOCTOR_IN_CHARGE"));
if (patVisitList.size() > 0)
{
data.set("identity", patVisitList.get(0).get("identity"));
data.set("charge_type", patVisitList.get(0).get("charge_type"));
if ("".equals(data.get("doctor_name")))
{
data.set("doctor_name",
patVisitList.get(0).get("attending_doctor"));
}
}
lsWheres1.clear();
}
// 填入药品信息
for (TCommonRecord data : resultSet)
{
data.set("drug_form",
dc.getDrugDictInfo(data.get("item_code")).get("drug_form"));
}
}
public TCommonRecord getDoctorInCharge(String p_id, String v_id,
String deptCode)
{
ICaseHistoryHelper chhr = CaseHistoryFactory.getCaseHistoryHelper();
List<TCommonRecord> list = new ArrayList<TCommonRecord>();
try
{
String strFields = "*";
List<TCommonRecord> lsWheres = new ArrayList<TCommonRecord>();
TCommonRecord where = CaseHistoryHelperUtils
.genWhereCR("PATIENT_ID", p_id, "Char", "", "", "");
lsWheres.add(where);
where = CaseHistoryHelperUtils.genWhereCR("VISIT_ID", v_id, "Char",
"", "", "");
lsWheres.add(where);
where = CaseHistoryHelperUtils.genWhereCR("DEPT_STAYED", deptCode,
"Char", "", "", "");
lsWheres.add(where);
list = chhr.fetchTransfer2CR(strFields, lsWheres, null, null, null);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
chhr = null;
}
return (list == null || list.size() == 0) ? new TCommonRecord()
: list.get(0);
}
public void saveDeptDrug(JDBCQueryImpl queryIAS)
{
logger.info("保存部门药品使用统计日报");
String sql = " insert into dr_Dept_Drug (is_basedrug ,CHARGES, Rpt_Date, Dept_Code, Dept_Name, Drug_Code, Drug_Name, costs, Amount, Drug_Units, DRUG_SPEC ,IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form) select is_basedrug ,sum(CHARGES)CHARGES, Rpt_Date, Dept_Code, Dept_Name, Drug_Code, Drug_Name, sum(costs)costs, sum(Amount)amount, Drug_Units, DRUG_SPEC ,IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form from DR_DRUG_SUMMARY_OUT t group by Rpt_Date, Dept_Code, Dept_Name, Drug_Code, Drug_Name, Drug_Units, DRUG_SPEC ,IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form ,is_basedrug";
queryIAS.update(sql);
sql = " insert into dr_Dept_Drug_anti (is_basedrug ,CHARGES, Rpt_Date, Dept_Code, Dept_Name, Drug_Code, Drug_Name, costs, Amount, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form) select is_basedrug ,sum(CHARGES)CHARGES, Rpt_Date, Dept_Code, Dept_Name, Drug_Code, Drug_Name, sum(costs)costs, sum(Amount)amount, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form from DR_DRUG_SUMMARY_OUT t where is_anti=1 group by Rpt_Date, Dept_Code, Dept_Name, Drug_Code, Drug_Name,Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form ,is_basedrug";
queryIAS.update(sql);
sql = null;
}
public void saveDeptDoctDrug(JDBCQueryImpl queryIAS)
{
logger.info("保存部门医生药品使用统计日报");
String sql = "insert into dr_Dept_doctor_Drug (is_basedrug ,CHARGES, Rpt_Date, doctor_code, doctor_Name, Dept_Code, Dept_Name, Drug_Code, Drug_Name, costs, Amount, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form) select is_basedrug ,sum(CHARGES)CHARGES, Rpt_Date, doctor_code, doctor_Name, Dept_Code, Dept_Name, Drug_Code, Drug_Name, sum(costs)costs, sum(Amount)amount, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID , drug_form from DR_DRUG_SUMMARY_OUT group by Rpt_Date, doctor_code, doctor_Name, Dept_Code, Dept_Name, Drug_Code, Drug_Name, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form ,is_basedrug";
queryIAS.update(sql);
sql = "insert into dr_Dept_doctor_Drug_anti (is_basedrug ,CHARGES, Rpt_Date, doctor_code, doctor_Name, Dept_Code, Dept_Name, Drug_Code, Drug_Name, costs, Amount, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form) select is_basedrug ,sum(CHARGES)CHARGES, Rpt_Date, doctor_code, doctor_Name, Dept_Code, Dept_Name, Drug_Code, Drug_Name, sum(costs)costs, sum(Amount)amount, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form from DR_DRUG_SUMMARY_OUT where is_anti=1 group by Rpt_Date, doctor_code, doctor_Name, Dept_Code, Dept_Name, Drug_Code, Drug_Name, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form ,is_basedrug";
queryIAS.update(sql);
sql = null;
}
public void saveDrug(JDBCQueryImpl queryIAS)
{
logger.info("保存药品使用统计日报");
String sql = "insert into dr_Drug (is_basedrug ,CHARGES, Rpt_Date, Drug_Code, Drug_Name, costs, Amount, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form) select is_basedrug ,sum(CHARGES)CHARGES, Rpt_Date, Drug_Code, Drug_Name, sum(costs)costs, sum(Amount)amount, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form from DR_DRUG_SUMMARY_OUT group by Rpt_Date, Drug_Code, Drug_Name, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form ,is_basedrug";
queryIAS.update(sql);
sql = "insert into dr_Drug_anti (is_basedrug ,CHARGES, Rpt_Date, Drug_Code, Drug_Name, costs, Amount, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form) select is_basedrug ,sum(CHARGES)CHARGES, Rpt_Date, Drug_Code, Drug_Name, sum(costs)costs, sum(Amount)amount, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form from DR_DRUG_SUMMARY_OUT where is_anti = 1 group by Rpt_Date, Drug_Code, Drug_Name, Drug_Units, DRUG_SPEC, IDENTITY,CHARGE_TYPE, FIRM_ID, drug_form ,is_basedrug";
queryIAS.update(sql);
sql = null;
}
public void saveAllCosts(JDBCQueryImpl queryIAS)
{
logger.info("保存金额总计");
String sql = "insert into DR_ALL_COSTS (CHARGES,COSTS, Rpt_Date) select sum(CHARGES)CHARGES, sum(COSTS)COSTS, Rpt_Date from DR_DRUG_SUMMARY_OUT group by Rpt_Date";
queryIAS.update(sql);
sql = null;
}
public void saveDr_Drug_Summary(JDBCQueryImpl queryIAS)
{
logger.info("保存患者每天用药信息");
String sql = " insert into dr_drug_summary(FIRM_ID, drug_code, DRUG_FORM, drug_name, patient_id, visit_id, costs, drug_units, amount, rpt_date, doctor_code, doctor_name, dept_code, dept_name, drug_spec, charges, identity, charge_type, is_basedrug ,is_anti,ddd_value)"
+ "select FIRM_ID, drug_code, DRUG_FORM, drug_name, patient_id, visit_id, costs, drug_units, amount, rpt_date, doctor_code, doctor_name, dept_code, dept_name, drug_spec, charges, identity, charge_type, is_basedrug ,is_anti ,ddd_value from dr_drug_summary_out";
queryIAS.update(sql);
sql = null;
}
public void deleteDR_DRUG_SUMMARY_OUT(JDBCQueryImpl queryIAS)
{
queryIAS.update("delete DR_DRUG_SUMMARY_OUT");
}
public void deleteDR(JDBCQueryImpl query, String Adate)
{
logger.info("删除旧数据");
String where = "where rpt_date = to_date('" + Adate + "','yyyy-mm-dd')";
// query.update("delete dr_Drug " + where);
// query.update("delete dr_Drug_anti " + where);
query.update("delete dr_drug_summary " + where);
// query.update("delete dr_Dept_doctor_Drug " + where);
// query.update("delete dr_Dept_doctor_Drug_anti " + where);
// query.update("delete dr_Dept_Drug_anti " + where);
// query.update("delete dr_Dept_Drug " + where);
// query.update("delete DR_ALL_COSTS " + where);
where = null;
}
public String getLogFileName()
{
return null;
}
public void buildBegin(String ADate, Task AOwner)
{
LoggerFileSaveUtil.LogFileSave(logger,
"APPLOG\\dr\\DR_" + ADate + ".log");
}
private void saveResultSet(String ADate)
{
// 保存过程 修改。
TCommonRecord tc = new TCommonRecord();
tc.set("ADate", ADate);
TransactionTemp tt = new TransactionTemp("ph");
tt.execute(new TransaCallback(tc) {
public void ExceuteSqlRecord()
{
JDBCQueryImpl Jquery = DBQueryFactory.getQuery("ph");
DrDeptDoctDrugEx.this.deleteDR(Jquery,getTranParm().get("ADate"));
int i = 1;
for (TCommonRecord cr : DrDeptDoctDrugEx.this.resultSet)
{
logger.info("第-----" + i + "-----共-----"
+ DrDeptDoctDrugEx.this.resultSet.size() + "药品统计");
List<Object> sqlParams = new ArrayList<Object>();
String sql = " insert into dr_drug_summary(drug_code, FIRM_ID, DRUG_FORM, drug_name, patient_id, visit_id, costs, drug_units, amount, rpt_date, doctor_code, doctor_name, dept_code, dept_name, drug_spec, charges, identity, charge_type, is_basedrug ,is_anti,DDD_VALUE,"
+ " is_exhilarant,is_injection,is_oral,anti_level,is_impregnant,IS_NOCHINESEDRUG,is_external,is_chinesedrug,is_allergy,is_patentdrug,is_tumor,is_poison,is_psychotic,is_habitforming,is_radiation,is_precious,is_danger,is_assist,is_albumin,id ) "
+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// to_date('" + getTranParm().get("ADate") + "','yyyy-mm-dd')
sqlParams.add(cr.get("item_code"));
sqlParams.add(cr.get("FIRM_ID"));
sqlParams.add(cr.get("drug_FORM"));
sqlParams.add(cr.get("item_name"));
sqlParams.add(cr.get("patient_id"));
sqlParams.add(cr.get("visit_id"));
sqlParams.add(cr.getDouble("costs"));
sqlParams.add(cr.get("units"));
sqlParams.add(cr.getDouble("amount"));
Timestamp dateTime = new Timestamp(DateUtils.getDateFromString(getTranParm().get("ADate")).getTime());
sqlParams.add(dateTime);
sqlParams.add(cr.get("doctor_code"));
sqlParams.add(cr.get("doctor_name"));
sqlParams.add(cr.get("dept_code"));
sqlParams.add(cr.get("dept_name"));
sqlParams.add(cr.get("item_spec"));
sqlParams.add(cr.getDouble("charges"));
sqlParams.add(cr.get("identity"));
sqlParams.add(cr.get("charge_type"));
sqlParams.add(cr.get("is_basedrug"));
sqlParams.add(cr.getInt("is_anti"));
double dddValue = 0d;
if (cr.getInt("is_anti") == 1)
{
dddValue = DDDUtils.CalcDDD(
cr.get("item_code"),
cr.get("item_spec"), cr.get("units"),
cr.get("Firm_ID"), cr.get("amount"),
cr.get("COSTS"));
logger.info("存在抗菌药" + cr.get("item_code") + "●●●" + cr.get("item_spec") + "●●●" + dddValue);
}
// 计算出ddd值
sqlParams.add(dddValue);
sqlParams.add(getflag(DrugUtils.isExhilarantDrug(cr.get("item_code")))); // is_exhilarant '兴奋剂标识,0是非兴奋剂,1是兴奋剂';
sqlParams.add(getflag(DrugUtils.isZSDrug(cr.get("item_code")))); // is_injection '注射剂标识,0是非注射剂,1是注射剂';
sqlParams.add(getflag(DrugUtils.IsOralDrug(cr.get("item_code")))); // is_oral '口服制剂标识,0是非口服,1是口服';
sqlParams.add(DrugUtils.getDrugAntiByLevel(cr.get("item_code"))); // anti_level'抗菌药级别,1是非限制用药,2是限制用药,3是特殊用药';
sqlParams.add(getflag(DrugUtils.isImpregnant(cr.get("item_code"))) ); // is_impregnant '溶剂标识,0是非溶剂,1是溶剂';
sqlParams.add(getflag(!DrugUtils.isChineseDrug(cr.get("item_code"))) ); // IS_NOCHINESEDRUG '药理分类, 0 饮片 1 非饮片 ';
sqlParams.add(getflag(DrugUtils.isExternalDrug(cr.get("item_code"))) ); // is_external '外用标识,0是非外用,1是外用';
sqlParams.add(getflag(DrugUtils.isChineseDrug(cr.get("item_code"))) ); // is_chinesedrug '中药标识,0是非中药,1是中药';
sqlParams.add(getflag(DrugUtils.isAntiAllergyDrug(cr.get("item_code"))) ); // is_allergy '抗过敏标识,0是非抗过敏药物,1是抗过敏药物';
sqlParams.add(getflag(DrugUtils.isPatentDrug(cr.get("item_code"))) ); // is_patentdrug '中成药标识,0是非中成药,1是中成药';
sqlParams.add(getflag(DrugUtils.isTumor(cr.get("item_code"))) ); // is_tumor '抗肿瘤标识,0是非抗肿瘤药,1是抗肿瘤药';
sqlParams.add(getflag(DrugUtils.isDDrug(cr.get("item_code"))) ); // is_poison '毒药标识,0是非毒药,1是毒药';
sqlParams.add(getflag(DrugUtils.isJSDrug(cr.get("item_code"))) ); // is_psychotic'精神药标识,0是非精神药,1是精神药,';
sqlParams.add(getflag(DrugUtils.isMDrug(cr.get("item_code"))) ); // is_habitforming '麻药标识,0是非麻药,1是麻药';
sqlParams.add(getflag(DrugUtils.isFSDrug(cr.get("item_code"))) ); // is_radiation '放射标识,0是非放射药,1是放射药';
sqlParams.add(getflag(DrugUtils.isGZDrug(cr.get("item_code"))) ); // is_precious '贵重药标识,0是非贵重药,1是贵重药';
sqlParams.add(getflag(DrugUtils.isDanger(cr.get("item_code"))) ); // is_danger '危险级别: 0-不是 1-是危险药品;
sqlParams.add(getflag(DrugUtils.IsAssist(cr.get("item_code"))) ); // is_assist '辅助用药 0 否 1 是';
sqlParams.add(getflag(DrugUtils.isAlbumin(cr.get("item_code"))) ); // is_albumin '白蛋白 0 否 1 是';
sqlParams.add(UuidUtil.get32UUID() );// 表主键id
Jquery.update(sql, sqlParams.toArray());
i++;
}
// 注释不必要处理
// DrDeptDoctDrugEx.this.saveDeptDrug(Jquery);
//
// DrDeptDoctDrugEx.this.saveDeptDoctDrug(Jquery);
//
// DrDeptDoctDrugEx.this.saveDrug(Jquery);
//
// DrDeptDoctDrugEx.this.saveAllCosts(Jquery);
// DrDeptDoctDrugEx.this.saveDr_Drug_Summary(Jquery);
// DrDeptDoctDrugEx.this.deleteDR_DRUG_SUMMARY_OUT(Jquery);
Jquery = null;
}
});
}
private String getflag(boolean rs)
{
return rs ? "1":"0";
}
public void buildOver(String ADate, Task AOwner)
{
logger.info("开始保存日报");
saveResultSet(ADate);
logger.info("结束保存日报");
}
}
| 50.295316
| 666
| 0.576797
|
c67cf12966a5f5734b1e9cc048bc429a36f0e516
| 25,990
|
/*
* Copyright 2018 Nextworks s.r.l.
*
* 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 it.nextworks.nfvmano.timeo.vnfm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.core.task.TaskExecutor;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import it.nextworks.nfvmano.libs.catalogues.interfaces.elements.PnfdInfo;
import it.nextworks.nfvmano.libs.common.elements.Filter;
import it.nextworks.nfvmano.libs.common.enums.InstantiationState;
import it.nextworks.nfvmano.libs.common.enums.OperationStatus;
import it.nextworks.nfvmano.libs.common.exceptions.AlreadyExistingEntityException;
import it.nextworks.nfvmano.libs.common.exceptions.FailedOperationException;
import it.nextworks.nfvmano.libs.common.exceptions.MalformattedElementException;
import it.nextworks.nfvmano.libs.common.exceptions.MethodNotImplementedException;
import it.nextworks.nfvmano.libs.common.exceptions.NotExistingEntityException;
import it.nextworks.nfvmano.libs.common.messages.GeneralizedQueryRequest;
import it.nextworks.nfvmano.libs.common.messages.SubscribeRequest;
import it.nextworks.nfvmano.libs.descriptors.onboardedvnfpackage.OnboardedVnfPkgInfo;
import it.nextworks.nfvmano.libs.descriptors.vnfd.Vnfd;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.VnfLcmConsumerInterface;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.ChangeExternalVnfConnectivityRequest;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.ChangeVnfFlavourRequest;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.CreateVnfIdentifierRequest;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.HealVnfRequest;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.InstantiateVnfRequest;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.ModifyVnfInformationRequest;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.OperateVnfRequest;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.QueryVnfResponse;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.ScaleVnfRequest;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.ScaleVnfToLevelRequest;
import it.nextworks.nfvmano.libs.orvnfm.vnflcm.interfaces.messages.TerminateVnfRequest;
import it.nextworks.nfvmano.libs.records.nsinfo.PnfInfo;
import it.nextworks.nfvmano.libs.records.vnfinfo.VnfInfo;
import it.nextworks.nfvmano.libs.vnfconfig.interfaces.VnfConfigurationConsumerInterface;
import it.nextworks.nfvmano.libs.vnfconfig.interfaces.messages.SetConfigurationRequest;
import it.nextworks.nfvmano.timeo.catalogue.nsdmanagement.NsdManagementService;
import it.nextworks.nfvmano.timeo.catalogue.pnfmanagement.PnfManagementService;
import it.nextworks.nfvmano.timeo.catalogue.pnfmanagement.elements.PnfInstance;
import it.nextworks.nfvmano.timeo.catalogue.vnfpackagemanagement.VnfPackageManagementService;
import it.nextworks.nfvmano.timeo.common.NfvoConstants;
import it.nextworks.nfvmano.timeo.common.Utilities;
import it.nextworks.nfvmano.timeo.nso.repository.NsDbWrapper;
import it.nextworks.nfvmano.timeo.ro.VimResourcePollingManager;
import it.nextworks.nfvmano.timeo.sbdriver.SbDriversManager;
import it.nextworks.nfvmano.timeo.vnfm.pnfm.CreatePnfIdentifierRequest;
import it.nextworks.nfvmano.timeo.vnfm.pnfm.QueryPnfResponse;
import it.nextworks.nfvmano.timeo.vnfm.repository.VnfDbWrapper;
import it.nextworks.nfvmano.timeo.vnfm.repository.VnfmInternalOperation;
import it.nextworks.nfvmano.timeo.vnfm.sdkimpl.PnfLifecycleManager;
import it.nextworks.nfvmano.timeo.vnfm.sdkimpl.VnfLifecycleManager;
import it.nextworks.nfvmano.timeo.vnfm.sdkimpl.messages.ConfigureVnfRequestMessage;
import it.nextworks.nfvmano.timeo.vnfm.sdkimpl.messages.InstantiateVnfRequestMessage;
import it.nextworks.nfvmano.timeo.vnfm.sdkimpl.messages.TerminateVnfRequestMessage;
public class SdkVnfm extends Vnfm {
private static final Logger log = LoggerFactory.getLogger(SdkVnfm.class);
private VnfDbWrapper vnfDbWrapper;
private NsDbWrapper nsDbWrapper;
private NsdManagementService nsdManagement;
private VnfPackageManagementService vnfPackageManagementService;
private PnfManagementService pnfManagementService;
private VimResourcePollingManager vimResourcePollingManager;
private SbDriversManager sbDriversManager;
private String rabbitHost;
private RabbitTemplate rabbitTemplate;
private RestTemplate restTemplate = new RestTemplate();
private TaskExecutor taskExecutor;
TopicExchange messageExchange;
//Key: vnf instance ID; Value: VNFD
private Map<String, Vnfd> vnfds = new HashMap<>();
//Key: VNF instance ID; Value: VNF lifecycle manager
private Map<String, VnfLifecycleManager> vnfLifecycleManagers = new HashMap<>();
//Key: PNF ID; Value: PNF lifecycle manager
//The PNF identifier is an internal ID generated by the system
private Map<String, PnfLifecycleManager> pnfLifecycleManagers = new HashMap<>();
public SdkVnfm(VnfmInfo vnfmInfo,
VnfDbWrapper vnfDbWrapper,
NsDbWrapper nsDbWrapper,
NsdManagementService nsdManagement,
VnfPackageManagementService vnfPackageManagementService,
PnfManagementService pnfManagementService,
VimResourcePollingManager vimResourcePollingManager,
SbDriversManager sbDriversManager,
String rabbitHost,
RabbitTemplate rabbitTemplate,
TopicExchange messageExchange,
TaskExecutor taskExecutor) {
super(VnfmType.SDK, vnfmInfo);
this.vnfDbWrapper = vnfDbWrapper;
this.nsDbWrapper = nsDbWrapper;
this.nsdManagement = nsdManagement;
this.vnfPackageManagementService = vnfPackageManagementService;
this.pnfManagementService = pnfManagementService;
this.vimResourcePollingManager = vimResourcePollingManager;
this.sbDriversManager = sbDriversManager;
this.rabbitHost = rabbitHost;
this.rabbitTemplate = rabbitTemplate;
this.messageExchange = messageExchange;
this.taskExecutor = taskExecutor;
}
@Override
public String createVnfIdentifier(CreateVnfIdentifierRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
String vnfdId = request.getVnfdId();
String vnfInstanceName = request.getVnfInstanceName();
String vnfInstanceDescription = request.getVnfInstanceDescription();
log.debug("Received request to create a new VNF identifier for VNF " + vnfInstanceName + " with VNFD " + vnfdId);
OnboardedVnfPkgInfo pkg = vnfPackageManagementService.getOnboardedVnfPkgInfoFromVnfd(vnfdId);
log.debug("Found VNF package.");
String vnfInstanceId = vnfDbWrapper.createVnfInfo(vnfInstanceName, vnfInstanceDescription, vnfdId, pkg.getVnfProvider(),
pkg.getVnfProductName(), pkg.getVnfSoftwareVersion(), pkg.getVnfdVersion(), pkg.getOnboardedVnfPkgInfoId(), null, null);
log.debug("VNF info created");
Vnfd vnfd = pkg.getVnfd();
vnfds.put(vnfInstanceId, vnfd);
VnfLifecycleManager vnfLifecycleManager = new VnfLifecycleManager(vnfInstanceId,
vnfd,
rabbitTemplate,
messageExchange,
vnfDbWrapper,
vimResourcePollingManager,
sbDriversManager,
restTemplate,
taskExecutor);
createQueue(vnfInstanceId, vnfLifecycleManager);
vnfLifecycleManagers.put(vnfInstanceId, vnfLifecycleManager);
return vnfInstanceId;
}
@Override
public String instantiateVnf(InstantiateVnfRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
String vnfInstanceId = request.getVnfInstanceId();
log.debug("Received VNF instantiation request for VNF instance " + vnfInstanceId);
if (!(vnfLifecycleManagers.containsKey(vnfInstanceId))) throw new NotExistingEntityException("VNF lifecycle manager not found for VNF instance " + vnfInstanceId);
String operationId = generateNewOperation(vnfInstanceId, "VNF instantiation");
String topic = "vnflifecycle.instantiate." + vnfInstanceId;
InstantiateVnfRequestMessage msg = new InstantiateVnfRequestMessage(vnfInstanceId, operationId, request);
ObjectMapper mapper = Utilities.buildObjectMapper();
try {
String json = mapper.writeValueAsString(msg);
rabbitTemplate.convertAndSend(messageExchange.getName(), topic, json);
log.debug("Sent internal message with request to instantiate VNF " + vnfInstanceId);
return operationId;
} catch (JsonProcessingException e) {
log.error("Error while translating internal instantiation message in Json format.");
vnfDbWrapper.updateVnfmInternalOperation(operationId, OperationStatus.FAILED, "Error while translating internal instantiation message in Json format.");
return operationId;
}
}
@Override
public String scaleVnf(ScaleVnfRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
throw new MethodNotImplementedException();
//TODO:
}
@Override
public String scaleVnfToLevel(ScaleVnfToLevelRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
throw new MethodNotImplementedException();
//TODO:
}
@Override
public String changeVnfFlavour(ChangeVnfFlavourRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
throw new MethodNotImplementedException();
//TODO:
}
@Override
public String terminateVnf(TerminateVnfRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
String vnfInstanceId = request.getVnfInstanceId();
log.debug("Received VNF termination request for VNF instance " + vnfInstanceId);
if (!(vnfLifecycleManagers.containsKey(vnfInstanceId))) throw new NotExistingEntityException("VNF lifecycle manager not found for VNF instance " + vnfInstanceId);
String operationId = generateNewOperation(vnfInstanceId, "VNF termination");
String topic = "vnflifecycle.terminate." + vnfInstanceId;
TerminateVnfRequestMessage msg = new TerminateVnfRequestMessage(vnfInstanceId, operationId, request);
ObjectMapper mapper = Utilities.buildObjectMapper();
try {
String json = mapper.writeValueAsString(msg);
rabbitTemplate.convertAndSend(messageExchange.getName(), topic, json);
log.debug("Sent internal message with request to terminate VNF " + vnfInstanceId);
return operationId;
} catch (JsonProcessingException e) {
log.error("Error while translating internal termination message in Json format.");
vnfDbWrapper.updateVnfmInternalOperation(operationId, OperationStatus.FAILED, "Error while translating internal termination message in Json format.");
return operationId;
}
}
@Override
public void deleteVnfIdentifier(String vnfInstanceId)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
log.debug("Received request to delete VNF ID " + vnfInstanceId);
VnfInfo vnfInfo = vnfDbWrapper.getVnfInfo(vnfInstanceId);
if (vnfInfo.getInstantiationState() == InstantiationState.NOT_INSTANTIATED) {
log.debug("VNF " + vnfInstanceId + " is in not instantiated state and it can be removed.");
vnfDbWrapper.deleteVnfInfo(vnfInstanceId);
} else {
log.debug("VNF " + vnfInstanceId + " is in instantiated state and it cannot be removed.");
throw new FailedOperationException("VNF " + vnfInstanceId + " is in instantiated state and it cannot be removed.");
}
}
@Override
public QueryVnfResponse queryVnf(GeneralizedQueryRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
log.debug("Received query for a VNF.");
//At the moment the only filter accepted is:
//1. VNF Instance ID
//No attribute selector is supported at the moment
Filter filter = request.getFilter();
List<String> attributeSelector = request.getAttributeSelector();
if ((attributeSelector == null) || (attributeSelector.isEmpty())) {
Map<String,String> fp = filter.getParameters();
if ((fp == null) || (fp.isEmpty())) {
log.debug("Query with empty filter. Returning all the elements");
List<VnfInfo> vnfInfos = vnfDbWrapper.getAllVnfInfo();
return new QueryVnfResponse(vnfInfos);
} else if (fp.size()==1 && fp.containsKey("VNF_INSTANCE_ID")) {
String vnfInstanceId = fp.get("VNF_INSTANCE_ID");
log.debug("Received query for VNF instance " + vnfInstanceId);
VnfInfo vnfInfo = vnfDbWrapper.getVnfInfo(vnfInstanceId);
List<VnfInfo> vnfInfos = new ArrayList<>();
vnfInfos.add(vnfInfo);
return new QueryVnfResponse(vnfInfos);
}
} else {
log.error("Received query VNF info with attribute selector. Not supported at the moment.");
throw new FailedOperationException("Received query VNF info with attribute selector. Not supported at the moment.");
}
throw new MethodNotImplementedException();
}
@Override
public String healVnf(HealVnfRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
throw new MethodNotImplementedException();
//TODO:
}
@Override
public String operateVnf(OperateVnfRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
throw new MethodNotImplementedException();
//TODO:
}
@Override
public String modifyVnfInformation(ModifyVnfInformationRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
String vnfInstanceId = request.getVnfInstanceId();
log.debug("Received VNF modification request for VNF instance " + vnfInstanceId);
if (!(vnfLifecycleManagers.containsKey(vnfInstanceId))) throw new NotExistingEntityException("VNF lifecycle manager not found for VNF instance " + vnfInstanceId);
String operationId = generateNewOperation(vnfInstanceId, "VNF configuration");
String topic = "vnflifecycle.configure." + vnfInstanceId;
ConfigureVnfRequestMessage msg = new ConfigureVnfRequestMessage(vnfInstanceId, operationId, request);
ObjectMapper mapper = Utilities.buildObjectMapper();
try {
String json = mapper.writeValueAsString(msg);
rabbitTemplate.convertAndSend(messageExchange.getName(), topic, json);
log.debug("Sent internal message with request to configure VNF " + vnfInstanceId);
return operationId;
} catch (JsonProcessingException e) {
log.error("Error while translating internal configuration message in Json format.");
vnfDbWrapper.updateVnfmInternalOperation(operationId, OperationStatus.FAILED, "Error while translating internal configuration message in Json format.");
return operationId;
}
}
@Override
public OperationStatus getOperationStatus(String operationId)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
log.debug("Getting operation status for operation " + operationId);
VnfmInternalOperation operation = vnfDbWrapper.readVnfmInternalOperation(operationId);
return operation.getStatus();
}
@Override
public String subscribe(SubscribeRequest request, VnfLcmConsumerInterface consumer)
throws MethodNotImplementedException, MalformattedElementException, FailedOperationException {
throw new MethodNotImplementedException();
//TODO:
}
@Override
public void unsubscribe(String subscriptionId)
throws MethodNotImplementedException, MalformattedElementException, NotExistingEntityException, FailedOperationException {
throw new MethodNotImplementedException();
//TODO:
}
@Override
public void queryNsSubscription(GeneralizedQueryRequest request)
throws MethodNotImplementedException, NotExistingEntityException, FailedOperationException, MalformattedElementException {
throw new MethodNotImplementedException();
//TODO:
}
@Override
public String changeExternalVnfConnectivity(ChangeExternalVnfConnectivityRequest request)
throws MethodNotImplementedException, NotExistingEntityException, FailedOperationException, MalformattedElementException {
throw new MethodNotImplementedException();
//TODO:
}
//PNFM methods
@Override
public String createPnfIdentifier(CreatePnfIdentifierRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
String pnfdId = request.getPnfdId();
String pnfName = request.getName();
String pnfInstanceId = request.getPnfInstanceId();
String pnfdVersion = request.getPnfdVersion();
log.debug("Received request to create a new PNF identifier for PNF " + pnfName + " with PNFD " + pnfdId + " mapped to PNF instance " + pnfInstanceId);
List<PnfdInfo> pnfdInfo = nsdManagement.queryPnfd(new GeneralizedQueryRequest(Utilities.buildPnfdFilter(pnfdId, pnfdVersion), null)).getQueryResult();
if (pnfdInfo.isEmpty()) {
log.error("PNFD with ID " + pnfdId + " and version " + pnfdVersion + " not found in DB.");
throw new NotExistingEntityException("Impossible to create PNF Identifier: " + "PNFD with ID " + pnfdId + " and version " + pnfdVersion + " not found in DB.");
}
PnfdInfo pnfd = pnfdInfo.get(0);
PnfInstance pnfInstance = pnfManagementService.getPnfInstance(pnfInstanceId);
String pnfInfoId = nsDbWrapper.createPnfInfo(request.getNsInstanceId(), pnfd, pnfInstance, pnfName, request.getPnfProfileId());
log.debug("PNF info created with ID " + pnfInfoId);
String pnfMgtAddress = pnfInstance.getManagementIpAddress();
PnfLifecycleManager pnfLcm = new PnfLifecycleManager(
pnfInfoId,
pnfd.getPnfd(),
rabbitTemplate,
messageExchange,
vnfDbWrapper,
nsDbWrapper,
restTemplate,
taskExecutor,
pnfMgtAddress);
createQueue(pnfInfoId, pnfLcm);
pnfLifecycleManagers.put(pnfInfoId, pnfLcm);
return pnfInfoId;
}
@Override
public void deletePnfIdentifier(String pnfId)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
log.debug("Received request to delete PNF ID " + pnfId);
nsDbWrapper.deletePnfInfo(pnfId);
log.debug("PNF info removed from DB");
pnfLifecycleManagers.remove(pnfId);
log.debug("PNF info removed from VNFM");
}
@Override
public QueryPnfResponse queryPnf(GeneralizedQueryRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
log.debug("Received query for a PNF.");
//At the moment the only filter accepted is:
//1. PNF ID
//No attribute selector is supported at the moment
Filter filter = request.getFilter();
List<String> attributeSelector = request.getAttributeSelector();
if ((attributeSelector == null) || (attributeSelector.isEmpty())) {
Map<String,String> fp = filter.getParameters();
if ((fp == null) || (fp.isEmpty())) {
log.debug("Query with empty filter. Returning all the elements");
List<PnfInfo> pnfInfos = nsDbWrapper.getAllPnfInfo();
return new QueryPnfResponse(pnfInfos);
} else if (fp.size()==1 && fp.containsKey("PNF_ID")) {
String pnfId = fp.get("PNF_ID");
log.debug("Received query for PNF " + pnfId);
PnfInfo pnfInfo = nsDbWrapper.getPnfInfo(pnfId);
List<PnfInfo> pnfInfos = new ArrayList<>();
pnfInfos.add(pnfInfo);
return new QueryPnfResponse(pnfInfos);
}
} else {
log.error("Received query PNF info with attribute selector. Not supported at the moment.");
throw new FailedOperationException("Received query PNF info with attribute selector. Not supported at the moment.");
}
throw new MethodNotImplementedException();
}
@Override
public String operatePnf(OperateVnfRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
throw new MethodNotImplementedException();
//TODO:
}
@Override
public String modifyPnfInformation(ModifyVnfInformationRequest request)
throws MethodNotImplementedException, FailedOperationException, NotExistingEntityException, MalformattedElementException {
String pnfId = request.getVnfInstanceId();
log.debug("Received PNF modification request for PNF " + pnfId);
if (!(pnfLifecycleManagers.containsKey(pnfId))) throw new NotExistingEntityException("PNF lifecycle manager not found for PNF " + pnfId);
String operationId = generateNewOperation(pnfId, "PNF configuration");
String topic = "pnflifecycle.configure." + pnfId;
ConfigureVnfRequestMessage msg = new ConfigureVnfRequestMessage(pnfId, operationId, request);
ObjectMapper mapper = Utilities.buildObjectMapper();
try {
String json = mapper.writeValueAsString(msg);
rabbitTemplate.convertAndSend(messageExchange.getName(), topic, json);
log.debug("Sent internal message with request to configure PNF " + pnfId);
return operationId;
} catch (JsonProcessingException e) {
log.error("Error while translating internal configuration message in Json format.");
vnfDbWrapper.updateVnfmInternalOperation(operationId, OperationStatus.FAILED, "Error while translating internal configuration message in Json format.");
return operationId;
}
}
//End of PNFM methods
private String generateNewOperation(String vnfInstanceId, String description) {
String operationId = null;
boolean operationIdFound = false;
while (!operationIdFound) {
try {
operationId = UUID.randomUUID().toString();
vnfDbWrapper.createNewVnfmInternalOperation(operationId, vnfInstanceId, description);
operationIdFound = true;
} catch (AlreadyExistingEntityException e) {
log.debug("Already existing operation ID. Trying with a new one.");
}
}
return operationId;
}
private void createQueue(String vnfInstanceId, VnfLifecycleManager vnfLifecycleManager) {
String queueName = NfvoConstants.vnfmQueueNamePrefix + vnfInstanceId;
log.debug("Creating new Queue " + queueName + " in rabbit host " + rabbitHost);
CachingConnectionFactory cf = new CachingConnectionFactory();
cf.setAddresses(rabbitHost);
cf.setConnectionTimeout(5);
RabbitAdmin rabbitAdmin = new RabbitAdmin(cf);
Queue queue = new Queue(queueName, false, false, true);
rabbitAdmin.declareQueue(queue);
rabbitAdmin.declareExchange(messageExchange);
rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(messageExchange).with("vnflifecycle.*." + vnfInstanceId));
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cf);
MessageListenerAdapter adapter = new MessageListenerAdapter(vnfLifecycleManager, "receiveMessage");
container.setMessageListener(adapter);
container.setQueueNames(queueName);
container.start();
log.debug("Queue created");
}
void createQueue(String pnfId, PnfLifecycleManager pnfLifecycleManager) {
String queueName = NfvoConstants.pnfmQueueNamePrefix + pnfId;
log.debug("Creating new Queue " + queueName + " in rabbit host " + rabbitHost);
CachingConnectionFactory cf = new CachingConnectionFactory();
cf.setAddresses(rabbitHost);
cf.setConnectionTimeout(5);
RabbitAdmin rabbitAdmin = new RabbitAdmin(cf);
Queue queue = new Queue(queueName, false, false, true);
rabbitAdmin.declareQueue(queue);
rabbitAdmin.declareExchange(messageExchange);
rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(messageExchange).with("pnflifecycle.*." + pnfId));
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cf);
MessageListenerAdapter adapter = new MessageListenerAdapter(pnfLifecycleManager, "receiveMessage");
container.setMessageListener(adapter);
container.setQueueNames(queueName);
container.start();
log.debug("Queue created");
}
/**
* Registers a new NFVO for the asynchronous interactions
* needed for a given VNF instance
*
* @param vnfId ID of the VNF instance
* @param nfvo NFVO to be contacted for the given VNF instance
*/
@Override
public void registerNfvo(String vnfId, OrVnfmNfvoAccess nfvo) {
nfvos.put(vnfId, nfvo);
vnfLifecycleManagers.get(vnfId).setOrVnfmNfvoAccess(nfvo);
log.debug("Registered NFVO for VNF " + vnfId);
}
/***************VnfConfigurationManagementProviderInterface methods************/
@Override
public void setConfiguration(SetConfigurationRequest request, VnfConfigurationConsumerInterface consumer)
throws MethodNotImplementedException, FailedOperationException, MalformattedElementException {
throw new MethodNotImplementedException();
//TODO:
}
}
| 46.16341
| 164
| 0.797884
|
4288e0c24417be549eac01365f0d9971f9cbeb2f
| 11,139
|
/**
* 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.metron.solr.writer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.metron.common.Constants;
import org.apache.metron.common.configuration.IndexingConfigurations;
import org.apache.metron.common.configuration.writer.IndexingWriterConfiguration;
import org.apache.metron.common.writer.BulkMessage;
import org.apache.metron.enrichment.integration.utils.SampleUtil;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.common.SolrInputDocument;
import org.json.simple.JSONObject;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;
public class SolrWriterTest {
static class CollectionRequestMatcher implements ArgumentMatcher<QueryRequest> {
private String name;
public CollectionRequestMatcher(String name) {
this.name = name;
}
@Override
public boolean matches(QueryRequest queryRequest) {
return name.equals(queryRequest.getParams().get("action"));
}
@Override
public String toString() {
return name;
}
}
static class SolrInputDocumentMatcher implements ArgumentMatcher<List<SolrInputDocument>> {
List<Map<String, Object>> expectedDocs;
public SolrInputDocumentMatcher(List<Map<String, Object>> expectedDocs) {
this.expectedDocs = expectedDocs;
}
@Override
public boolean matches(List<SolrInputDocument> docs) {
int size = docs.size();
if(size != expectedDocs.size()) {
return false;
}
for(int i = 0; i < size;++i) {
SolrInputDocument doc = docs.get(i);
Map<String, Object> expectedDoc = expectedDocs.get(i);
for(Map.Entry<String, Object> expectedKv : expectedDoc.entrySet()) {
if(!expectedKv.getValue().equals(doc.get(expectedKv.getKey()).getValue())) {
return false;
}
}
}
return true;
}
@Override
public String toString() {
return expectedDocs.toString();
}
}
@Test
public void testWriter() throws Exception {
IndexingConfigurations configurations = SampleUtil.getSampleIndexingConfigs();
JSONObject message1 = new JSONObject();
message1.put(Constants.GUID, "guid-1");
message1.put(Constants.SENSOR_TYPE, "test");
message1.put("intField", 100);
message1.put("doubleField", 100.0);
JSONObject message2 = new JSONObject();
message2.put(Constants.GUID, "guid-2");
message2.put(Constants.SENSOR_TYPE, "test");
message2.put("intField", 200);
message2.put("doubleField", 200.0);
List<BulkMessage<JSONObject>> messages = new ArrayList<>();
messages.add(new BulkMessage<>("message1", message1));
messages.add(new BulkMessage<>("message2", message2));
String collection = "metron";
MetronSolrClient solr = Mockito.mock(MetronSolrClient.class);
SolrWriter writer = new SolrWriter().withMetronSolrClient(solr);
writer.init(null,new IndexingWriterConfiguration("solr", configurations));
verify(solr, times(1)).setDefaultCollection(collection);
collection = "metron2";
Map<String, Object> globalConfig = configurations.getGlobalConfig();
globalConfig.put("solr.collection", collection);
configurations.updateGlobalConfig(globalConfig);
writer = new SolrWriter().withMetronSolrClient(solr);
writer.init(null, new IndexingWriterConfiguration("solr", configurations));
verify(solr, times(1)).setDefaultCollection(collection);
writer.write("test", new IndexingWriterConfiguration("solr", configurations), messages);
verify(solr, times(1)).add(eq("yaf"), argThat(new SolrInputDocumentMatcher(ImmutableList.of(message1, message2))));
verify(solr, times(1)).commit("yaf"
, (boolean)SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.defaultValue.get()
, (boolean)SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.defaultValue.get()
, (boolean)SolrWriter.SolrProperties.COMMIT_SOFT.defaultValue.get()
);
}
@Test
public void configTest_zookeeperQuorumSpecified() {
String expected = "test";
assertEquals(expected,
SolrWriter.SolrProperties.ZOOKEEPER_QUORUM.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.ZOOKEEPER_QUORUM.name, expected)
, String.class));
}
@Test
public void configTest_zookeeperQuorumUnpecified() {
assertThrows(
IllegalArgumentException.class,
() ->
SolrWriter.SolrProperties.ZOOKEEPER_QUORUM.coerceOrDefaultOrExcept(
new HashMap<>(), String.class));
}
@Test
public void configTest_commitPerBatchSpecified() {
Object expected = false;
assertEquals(expected,
SolrWriter.SolrProperties.COMMIT_PER_BATCH.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_PER_BATCH.name, false)
, Boolean.class));
}
@Test
public void configTest_commitPerBatchUnpecified() {
assertEquals(SolrWriter.SolrProperties.COMMIT_PER_BATCH.defaultValue.get(),
SolrWriter.SolrProperties.COMMIT_PER_BATCH.coerceOrDefaultOrExcept(
new HashMap<>()
, Boolean.class));
assertEquals(SolrWriter.SolrProperties.COMMIT_PER_BATCH.defaultValue.get(),
SolrWriter.SolrProperties.COMMIT_PER_BATCH.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_PER_BATCH.name, new DummyClass())
, Boolean.class));
}
@Test
public void configTest_commitSoftSpecified() {
Object expected = true;
assertEquals(expected,
SolrWriter.SolrProperties.COMMIT_SOFT.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_SOFT.name, expected)
, Boolean.class));
}
@Test
public void configTest_commitSoftUnpecified() {
assertEquals(SolrWriter.SolrProperties.COMMIT_SOFT.defaultValue.get(),
SolrWriter.SolrProperties.COMMIT_SOFT.coerceOrDefaultOrExcept(
new HashMap<>()
, Boolean.class));
assertEquals(SolrWriter.SolrProperties.COMMIT_SOFT.defaultValue.get(),
SolrWriter.SolrProperties.COMMIT_SOFT.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_SOFT.name, new DummyClass())
, Boolean.class));
}
@Test
public void configTest_commitWaitFlushSpecified() {
Object expected = false;
assertEquals(expected,
SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.name, expected)
, Boolean.class));
}
@Test
public void configTest_commitWaitFlushUnspecified() {
assertEquals(SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.defaultValue.get(),
SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.coerceOrDefaultOrExcept(
new HashMap<>()
, Boolean.class));
assertEquals(SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.defaultValue.get(),
SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_WAIT_FLUSH.name, new DummyClass())
, Boolean.class));
}
@Test
public void configTest_commitWaitSearcherSpecified() {
Object expected = false;
assertEquals(expected,
SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.name, expected)
, Boolean.class));
}
@Test
public void configTest_commitWaitSearcherUnspecified() {
assertEquals(SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.defaultValue.get(),
SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.coerceOrDefaultOrExcept(
new HashMap<>()
, Boolean.class));
assertEquals(SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.defaultValue.get(),
SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.COMMIT_WAIT_SEARCHER.name, new DummyClass())
, Boolean.class));
}
@Test
public void configTest_defaultCollectionSpecified() {
Object expected = "mycollection";
assertEquals(expected,
SolrWriter.SolrProperties.DEFAULT_COLLECTION.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.DEFAULT_COLLECTION.name, expected)
, String.class));
}
@Test
public void configTest_defaultCollectionUnspecified() {
assertEquals(SolrWriter.SolrProperties.DEFAULT_COLLECTION.defaultValue.get(),
SolrWriter.SolrProperties.DEFAULT_COLLECTION.coerceOrDefaultOrExcept(
new HashMap<>()
, String.class));
}
@Test
public void configTest_httpConfigSpecified() {
Object expected = new HashMap<String, Object>() {{
put("name", "metron");
}};
assertEquals(expected,
SolrWriter.SolrProperties.HTTP_CONFIG.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.HTTP_CONFIG.name, expected)
, Map.class));
}
@Test
public void configTest_httpConfigUnspecified() {
assertEquals(SolrWriter.SolrProperties.HTTP_CONFIG.defaultValue.get(),
SolrWriter.SolrProperties.HTTP_CONFIG.coerceOrDefaultOrExcept(
new HashMap<>()
, Map.class));
assertEquals(SolrWriter.SolrProperties.HTTP_CONFIG.defaultValue.get(),
SolrWriter.SolrProperties.HTTP_CONFIG.coerceOrDefaultOrExcept(
ImmutableMap.of( SolrWriter.SolrProperties.HTTP_CONFIG.name, new DummyClass())
, Map.class));
}
public static class DummyClass {}
}
| 39.221831
| 119
| 0.698088
|
9dd0b28fbb178d30485c6db278df80a43a9994e7
| 3,276
|
package com.toluhta.immersify;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.view.View;
import android.view.WindowManager;
public class ImmersiveMode extends CordovaPlugin {
public static final String ACTION_ENABLE_IMMERSIVE = "enableImmersive";
public static final String ACTION_ENABLE_IMMERSIVE_STICKY = "enableSticky";
public static final String ACTION_IMMERSIVE_DISABLE = "disable";
public boolean execute(final String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
if (action.equals(ACTION_ENABLE_IMMERSIVE)
|| action.equals(ACTION_ENABLE_IMMERSIVE_STICKY)) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// Override Cordova's own full screen setting
cordova.getActivity()
.getWindow()
.clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Non-Sticky immersion
cordova.getActivity()
.getWindow()
.getDecorView()
.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE);
if (action.equals(ACTION_ENABLE_IMMERSIVE_STICKY)) {
cordova.getActivity()
.getWindow()
.getDecorView()
.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
});
callbackContext.success();
return true;
}else if (action.equals(ACTION_IMMERSIVE_DISABLE)) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
cordova.getActivity().getWindow().getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
});
callbackContext.success();
return true;
} else {
callbackContext.error("Invalid action");
return false;
}
}
}
| 44.27027
| 90
| 0.511905
|
9fd13384160f66b0a69207a978007e32232281c7
| 1,734
|
package bla.tm.pages.site.products_and_docs;
import bla.tm.pages.AncestorPage;
import net.serenitybdd.core.annotations.findby.FindBy;
import net.serenitybdd.core.pages.WebElementFacade;
import net.thucydides.core.annotations.DefaultUrl;
import java.util.HashMap;
import java.util.Map;
@DefaultUrl("/products-and-docs/tutorials/widgets/")
public class PD_Tutorials_WidgetsPage extends AncestorPage {
public final String pageHeader = "WIDGETS TUTORIALS";
@FindBy(xpath = "//div[@class='announcement']/a[text()='Learn more']")
private WebElementFacade addingEventDiscoveryWidgetButton;
@FindBy(xpath = "//div[@class='announcement']/h3/a[text()='Adding Event Discovery widget to your website']")
private WebElementFacade addingEventDiscoveryWidgetHeaderLink;
@FindBy(xpath = "//div[@class='tutorials-article']/a/img[@alt='Adding Event Discovery widget to your website']")
private WebElementFacade addingEventDiscoveryWidgetImageLink;
@FindBy(xpath = ".//button[@id='js_feedback_btn_alert_ok']")
private WebElementFacade successfulSentEmailNotificationOKButton;
public Map<String, WebElementFacade> getClickableElements() {
Map<String, WebElementFacade> elements = new HashMap<String, WebElementFacade>();
elements.put("Adding Event Discovery Widget Button", addingEventDiscoveryWidgetButton);
elements.put("Adding Event Discovery Widget Header Link", addingEventDiscoveryWidgetHeaderLink);
elements.put("Adding Event Discovery Widget Image Link", addingEventDiscoveryWidgetImageLink);
return elements;
}
public WebElementFacade getSuccessfulSentEmailNotificationOKButton() {
return successfulSentEmailNotificationOKButton;
}
}
| 42.292683
| 116
| 0.770473
|
e0b6152bdc43955c194191425ec54e3d869584f2
| 3,471
|
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.dataprepper.expression;
import com.amazon.dataprepper.model.event.Event;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedConstruction;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mockConstruction;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class ParseTreeEvaluatorTest {
@Mock
private Event event;
@Mock
private OperatorProvider operatorProvider;
@Mock
private ParseTree parseTree;
@Mock
private ParseTreeWalker parseTreeWalker;
@Mock
private ParseTreeCoercionService coercionService;
private ParseTreeEvaluator objectUnderTest;
@BeforeEach
void setUp() {
objectUnderTest = new ParseTreeEvaluator(operatorProvider, parseTreeWalker, coercionService);
}
@Test
void testEvaluateSuccess() throws ExpressionCoercionException {
when(coercionService.coerce(any(), any())).thenAnswer(invocation -> {
final Object res = invocation.getArgument(0);
final Class<Boolean> clazz = invocation.getArgument(1);
return clazz.cast(res);
});
try (final MockedConstruction<ParseTreeEvaluatorListener> ignored =
mockConstruction(ParseTreeEvaluatorListener.class, (mock, context) -> when(mock.getResult()).thenReturn(true))) {
assertThat(objectUnderTest.evaluate(parseTree, event), is(true));
}
}
@Test
void testEvaluateFailureInWalk() {
doThrow(new RuntimeException()).when(parseTreeWalker).walk(
any(ParseTreeEvaluatorListener.class), any(ParseTree.class));
try (final MockedConstruction<ParseTreeEvaluatorListener> ignored =
mockConstruction(ParseTreeEvaluatorListener.class)) {
assertThrows(ExpressionEvaluationException.class, () -> objectUnderTest.evaluate(parseTree, event));
}
}
@Test
void testEvaluateFailureInGetResult() {
try (final MockedConstruction<ParseTreeEvaluatorListener> ignored =
mockConstruction(ParseTreeEvaluatorListener.class,
(mock, context) -> when(mock.getResult()).thenThrow(new RuntimeException()))) {
assertThrows(ExpressionEvaluationException.class, () -> objectUnderTest.evaluate(parseTree, event));
}
}
@Test
void testEvaluateFailureInCoerce() throws ExpressionCoercionException {
when(coercionService.coerce(any(), any())).thenThrow(new ExpressionCoercionException("test message"));
try (final MockedConstruction<ParseTreeEvaluatorListener> ignored =
mockConstruction(ParseTreeEvaluatorListener.class, (mock, context) -> when(mock.getResult()).thenReturn(true))) {
assertThrows(ExpressionEvaluationException.class, () -> objectUnderTest.evaluate(parseTree, event));
}
}
}
| 38.142857
| 134
| 0.717661
|
b503df98360855b96f813a551e856339c1fa6594
| 4,362
|
package musictheory.xinweitech.cn.musictheory.ui.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v7.widget.TintTypedArray;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import musictheory.xinweitech.cn.musictheory.R;
public class CustomToolbar extends Toolbar {
private LayoutInflater mInflater;
private View mView;
private TextView mTextTitle;
private Button mRightButton;
public CustomToolbar(Context context) {
this(context, null);
}
public CustomToolbar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
setContentInsetsRelative(10, 10);
if (attrs != null) {
final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs,
R.styleable.CustomToolbar, defStyleAttr, 0);
final Drawable rightIcon = a.getDrawable(R.styleable.CustomToolbar_rightButtonIcon);
if (rightIcon != null) {
//setNavigationIcon(navIcon);
setRightButtonIcon(rightIcon);
}
CharSequence rightButtonText = a.getText(R.styleable.CustomToolbar_rightButtonText);
if (rightButtonText != null) {
setRightButtonText(rightButtonText);
}
a.recycle();
}
}
private void initView() {
if (mView == null) {
mInflater = LayoutInflater.from(getContext());
mView = mInflater.inflate(R.layout.toolbar, null);
mTextTitle = (TextView) mView.findViewById(R.id.toolbar_title);
mRightButton = (Button) mView.findViewById(R.id.toolbar_rightButton);
LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
addView(mView, lp);
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void setRightButtonIcon(Drawable icon) {
if (mRightButton != null) {
mRightButton.setBackground(icon);
mRightButton.setVisibility(VISIBLE);
}
}
public void setRightButtonIcon(int icon) {
setRightButtonIcon(getResources().getDrawable(icon));
}
/* public void setTextColor(int viewId, String color) {
TextView textView = getView(viewId);
textView.setTextColor(Color.parseColor(color));
}*/
public void setRightButtonOnClickListener(OnClickListener li) {
mRightButton.setOnClickListener(li);
}
public void setRightButtonText(CharSequence text) {
mRightButton.setText(text);
mRightButton.setVisibility(VISIBLE);
}
public void setRightButtonText(int id) {
setRightButtonText(getResources().getString(id));
}
public Button getRightButton() {
return this.mRightButton;
}
@Override
public void setTitle(int resId) {
setTitle(getContext().getText(resId));
}
@Override
public void setTitle(CharSequence title) {
initView();
if (mTextTitle != null) {
mTextTitle.setText(title);
showTitleView();
}
}
public void showTitleView() {
if (mTextTitle != null)
mTextTitle.setVisibility(VISIBLE);
}
public void hideTitleView() {
if (mTextTitle != null)
mTextTitle.setVisibility(GONE);
}
//
// private void ensureRightButtonView() {
// if (mRightImageButton == null) {
// mRightImageButton = new ImageButton(getContext(), null,
// android.support.v7.appcompat.R.attr.toolbarNavigationButtonStyle);
// final LayoutParams lp = generateDefaultLayoutParams();
// lp.gravity = GravityCompat.START | (Gravity.VERTICAL_GRAVITY_MASK);
// mRightImageButton.setLayoutParams(lp);
// }
// }
}
| 24.784091
| 148
| 0.649473
|
260e56c9d35953a51d18220b694801c4b31c17d0
| 8,145
|
/*
* (C) Copyright 2017-2020 OpenVidu (https://openvidu.io)
*
* 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.openvidu.java.client;
import io.openvidu.java.client.Recording.OutputMode;
/**
* See
* {@link io.openvidu.java.client.OpenVidu#startRecording(String, RecordingProperties)}
*/
public class RecordingProperties {
private String name;
private Recording.OutputMode outputMode;
private RecordingLayout recordingLayout;
private String customLayout;
private String resolution;
private boolean hasAudio;
private boolean hasVideo;
/**
* Builder for {@link io.openvidu.java.client.RecordingProperties}
*/
public static class Builder {
private String name = "";
private Recording.OutputMode outputMode = Recording.OutputMode.COMPOSED;
private RecordingLayout recordingLayout;
private String customLayout;
private String resolution;
private boolean hasAudio = true;
private boolean hasVideo = true;
/**
* Builder for {@link io.openvidu.java.client.RecordingProperties}
*/
public RecordingProperties build() {
if (OutputMode.COMPOSED.equals(this.outputMode)) {
this.recordingLayout = this.recordingLayout != null ? this.recordingLayout : RecordingLayout.BEST_FIT;
this.resolution = this.resolution != null ? this.resolution : "1920x1080";
if (RecordingLayout.CUSTOM.equals(this.recordingLayout)) {
this.customLayout = this.customLayout != null ? this.customLayout : "";
}
}
return new RecordingProperties(this.name, this.outputMode, this.recordingLayout, this.customLayout,
this.resolution, this.hasAudio, this.hasVideo);
}
/**
* Call this method to set the name of the video file. You can access this same
* value in your clients on recording events (<code>recordingStarted</code>,
* <code>recordingStopped</code>)
*/
public RecordingProperties.Builder name(String name) {
this.name = name;
return this;
}
/**
* Call this method to set the mode of recording: COMPOSED for a single archive
* in a grid layout or INDIVIDUAL for one archive for each stream
*/
public RecordingProperties.Builder outputMode(Recording.OutputMode outputMode) {
this.outputMode = outputMode;
return this;
}
/**
* Call this method to set the layout to be used in the recording. Will only
* have effect if
* {@link io.openvidu.java.client.RecordingProperties.Builder#outputMode(Recording.OutputMode)}
* has been called with value
* {@link io.openvidu.java.client.Recording.OutputMode#COMPOSED}
*/
public RecordingProperties.Builder recordingLayout(RecordingLayout layout) {
this.recordingLayout = layout;
return this;
}
/**
* If setting
* {@link io.openvidu.java.client.RecordingProperties.Builder#recordingLayout(RecordingLayout)}
* to {@link io.openvidu.java.client.RecordingLayout#CUSTOM} you can call this
* method to set the relative path to the specific custom layout you want to
* use.<br>
* Will only have effect if
* {@link io.openvidu.java.client.RecordingProperties.Builder#outputMode(Recording.OutputMode)}
* has been called with value
* {@link io.openvidu.java.client.Recording.OutputMode#COMPOSED}.<br>
* See <a href=
* "https://docs.openvidu.io/en/stable/advanced-features/recording#custom-recording-layouts"
* target="_blank">Custom recording layouts</a> to learn more
*/
public RecordingProperties.Builder customLayout(String path) {
this.customLayout = path;
return this;
}
/**
* Call this method to specify the recording resolution. Must be a string with
* format "WIDTHxHEIGHT", being both WIDTH and HEIGHT the number of pixels
* between 100 and 1999.<br>
* Will only have effect if
* {@link io.openvidu.java.client.RecordingProperties.Builder#outputMode(Recording.OutputMode)}
* has been called with value
* {@link io.openvidu.java.client.Recording.OutputMode#COMPOSED}. For
* {@link io.openvidu.java.client.Recording.OutputMode#INDIVIDUAL} all
* individual video files will have the native resolution of the published
* stream
*/
public RecordingProperties.Builder resolution(String resolution) {
this.resolution = resolution;
return this;
}
/**
* Call this method to specify whether to record audio or not. Cannot be set to
* false at the same time as {@link hasVideo(boolean)}
*/
public RecordingProperties.Builder hasAudio(boolean hasAudio) {
this.hasAudio = hasAudio;
return this;
}
/**
* Call this method to specify whether to record video or not. Cannot be set to
* false at the same time as {@link hasAudio(boolean)}
*/
public RecordingProperties.Builder hasVideo(boolean hasVideo) {
this.hasVideo = hasVideo;
return this;
}
}
protected RecordingProperties(String name, Recording.OutputMode outputMode, RecordingLayout layout,
String customLayout, String resolution, boolean hasAudio, boolean hasVideo) {
this.name = name;
this.outputMode = outputMode;
this.recordingLayout = layout;
this.customLayout = customLayout;
this.resolution = resolution;
this.hasAudio = hasAudio;
this.hasVideo = hasVideo;
}
/**
* Defines the name you want to give to the video file. You can access this same
* value in your clients on recording events (<code>recordingStarted</code>,
* <code>recordingStopped</code>)
*/
public String name() {
return this.name;
}
/**
* Defines the mode of recording: {@link Recording.OutputMode#COMPOSED} for a
* single archive in a grid layout or {@link Recording.OutputMode#INDIVIDUAL}
* for one archive for each stream.<br>
* <br>
*
* Default to {@link Recording.OutputMode#COMPOSED}
*/
public Recording.OutputMode outputMode() {
return this.outputMode;
}
/**
* Defines the layout to be used in the recording.<br>
* Will only have effect if
* {@link io.openvidu.java.client.RecordingProperties.Builder#outputMode(Recording.OutputMode)}
* has been called with value {@link Recording.OutputMode#COMPOSED}.<br>
* <br>
*
* Default to {@link RecordingLayout#BEST_FIT}
*/
public RecordingLayout recordingLayout() {
return this.recordingLayout;
}
/**
* If {@link io.openvidu.java.client.RecordingProperties#recordingLayout()} is
* set to {@link io.openvidu.java.client.RecordingLayout#CUSTOM}, this property
* defines the relative path to the specific custom layout you want to use.<br>
* See <a href=
* "https://docs.openvidu.io/en/stable/advanced-features/recording#custom-recording-layouts"
* target="_blank">Custom recording layouts</a> to learn more
*/
public String customLayout() {
return this.customLayout;
}
/**
* Defines the resolution of the recorded video.<br>
* Will only have effect if
* {@link io.openvidu.java.client.RecordingProperties.Builder#outputMode(Recording.OutputMode)}
* has been called with value
* {@link io.openvidu.java.client.Recording.OutputMode#COMPOSED}. For
* {@link io.openvidu.java.client.Recording.OutputMode#INDIVIDUAL} all
* individual video files will have the native resolution of the published
* stream.<br>
* <br>
*
* Default to "1920x1080"
*/
public String resolution() {
return this.resolution;
}
/**
* Defines whether to record audio or not. Cannot be set to false at the same
* time as {@link hasVideo()}.<br>
* <br>
*
* Default to true
*/
public boolean hasAudio() {
return this.hasAudio;
}
/**
* Defines whether to record video or not. Cannot be set to false at the same
* time as {@link hasAudio()}.<br>
* <br>
*
* Default to true
*/
public boolean hasVideo() {
return this.hasVideo;
}
}
| 32.842742
| 106
| 0.723511
|
de05e7d0d9ec85e1715821e862243de7c32bd884
| 2,819
|
package com.ad.zakatrizki.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ad.zakatrizki.R;
import com.ad.zakatrizki.Zakat;
import com.ad.zakatrizki.fragment.LaporanDonasiDetailFragment;
import com.ad.zakatrizki.utils.Prefs;
public class LaporanDonasiDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content_detail);
if (savedInstanceState == null) {
String mustahiqId;
Intent intent = getIntent();
Uri data = intent.getData();
if (data == null) {
// Not loading from deep link
mustahiqId = getIntent().getStringExtra(Zakat.DONASI_ID);
loadLaporanDonasiDetailsOf(mustahiqId);
} else {
// Loading from deep link
String[] parts = data.toString().split("/");
mustahiqId = parts[parts.length - 1];
switch (mustahiqId) {
// Load LaporanDonasi Lists
case "movie":
loadLaporanDonasiOfType(0);
break;
case "top-rated":
loadLaporanDonasiOfType(1);
break;
case "faq":
loadLaporanDonasiOfType(2);
break;
case "now-playing":
loadLaporanDonasiOfType(3);
break;
// Load details of a particular movie
default:
int dashPosition = mustahiqId.indexOf("-");
if (dashPosition != -1) {
mustahiqId = mustahiqId.substring(0, dashPosition);
}
loadLaporanDonasiDetailsOf(mustahiqId);
break;
}
}
}
}
private void loadLaporanDonasiDetailsOf(String mustahiqId) {
LaporanDonasiDetailFragment fragment = new LaporanDonasiDetailFragment();
Bundle args = new Bundle();
args.putString(Zakat.DONASI_ID, mustahiqId);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.content_detail_container, fragment).commit();
}
@SuppressLint("CommitPrefEdits")
private void loadLaporanDonasiOfType(int viewType) {
Prefs.putLastSelected(this, Zakat.VIEW_TYPE_LAPORAN_DONASI);
startActivity(new Intent(this, DrawerActivity.class));
finish();
}
}
| 37.092105
| 113
| 0.566513
|
06de39de419844ec49115ddb0a3422459c05d0fc
| 2,527
|
package spaceInvaders;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;
public class Network {
public int port = 7575;
java.util.ArrayList<Player> players = Game.netPlayers;
public Network() {
try {
DatagramSocket socket = new DatagramSocket(port);
EndPoint peer = Recieve(socket);
String[] msg = peer.msg.split(":"); // ID:REQUEST
int id = Integer.parseInt(msg[0]);
if (msg[1] == "LOGGEDUSR") {
for (int i=0; i<players.size(); i++) {
Player p = players.get(i);
if (p == null) {
p = new Player(100, 100, Sprite.playerAnimO, Game.playerAnim); // Change X,Y to the exact coordinates.
}
}
}
else if (msg[1] == "LOGGEDOUTUSR") {
}
} catch(Exception e) { e.printStackTrace(); }
}
public void sendMessage(DatagramSocket socket, String msg, EndPoint toEp) {
try {
byte[] buffer = msg.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, toEp.addr, toEp.port);
socket.send(packet);
} catch(Exception e) { e.printStackTrace(); }
}
public void sendEndPoint(DatagramSocket socket, EndPoint toEp, EndPoint contentEp) {
try {
String msg = contentEp.hAddr + ":" + contentEp.port;
byte[] buffer = msg.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, toEp.addr, toEp.port);
socket.send(packet);
} catch(Exception e) { e.printStackTrace(); }
}
public EndPoint Recieve(DatagramSocket socket) {
try {
byte[] buffer = new byte[10];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
String msg = new String(buffer);
return new EndPoint(packet.getAddress(), packet.getPort(), msg);
} catch(Exception e) { e.printStackTrace(); }
return null;
}
}
/*
class PlayerAI extends Player {
public PlayerAI(int x, int y, Sprite sprite, Sprite[] animSprite) {
super(x, y, sprite, animSprite);
}
public boolean tick() {
super.tick();
return false;
}
public void draw(Bitmap bitmap) {
super.draw(bitmap);
}
}*/
class EndPoint {
public InetAddress addr;
public String hAddr, msg;
public int port;
public EndPoint(InetAddress addr, int port, String msg) {
this.addr = addr;
this.port = port;
this.msg = msg;
}
public EndPoint(String addr, int port, String msg) {
this.hAddr = addr;
this.port = port;
this.msg = msg;
}
}
| 23.183486
| 109
| 0.627622
|
5b37faf48ebbb00f032592f8b57510ee82286786
| 2,286
|
package com.jborchardt.imagefeed.presentation.presenter.details;
import android.support.annotation.NonNull;
import com.jborchardt.imagefeed.domain.details.DetailsInteractor;
import com.jborchardt.imagefeed.domain.details.DetailsModel;
import com.jborchardt.imagefeed.presentation.presenter.common.Presenter;
import com.jborchardt.imagefeed.presentation.view.common.BaseObserver;
public class DetailsPresenter implements Presenter {
private final DetailsInteractor mInteractor;
private final DetailsView mView;
private final String mImageId;
private boolean mMetadataVisible;
public DetailsPresenter(@NonNull final DetailsInteractor interactor, @NonNull DetailsView view, @NonNull String imageId) {
mInteractor = interactor;
mView = view;
mImageId = imageId;
}
@Override
public void register() {
showLoading();
fetchDetails();
}
@Override
public void unregister() {
}
@Override
public void destroy() {
mInteractor.dispose();
}
public void retry() {
fetchDetails();
}
private void fetchDetails() {
final DetailsObserver observer = new DetailsObserver();
mInteractor.fetchDetails(observer, observer, mImageId);
}
private void showDetails(final DetailsModel details) {
mView.renderDetails(details);
}
private void showLoading() {
mView.showLoading();
}
private void hideLoading() {
mView.hideLoading();
}
private void showError(final boolean showRetry) {
mView.showError(showRetry);
}
public void toggleMetadata() {
if (mMetadataVisible) {
mView.hideMetadata();
mMetadataVisible = false;
} else {
mView.showMetadata();
mMetadataVisible = true;
}
}
private class DetailsObserver extends BaseObserver<DetailsModel> {
@Override
public void onNext(final DetailsModel details) {
showDetails(details);
}
@Override
public void onComplete() {
hideLoading();
}
@Override
public void onError(final Throwable e) {
hideLoading();
showError(shouldRetry(e));
}
}
}
| 24.847826
| 126
| 0.646982
|
46ef581d89284c3e4b64b2207f32a53cf08d8544
| 3,709
|
package org.aravind.oss.kafka.connect.lib;
import org.apache.kafka.common.config.AbstractConfig;
import org.apache.kafka.connect.source.SourceTask;
import org.apache.kafka.connect.util.ConnectorUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* This class encapsulates the following common behavior of building task configurations
* <p>
* <ul>
* <li>Group all the work into multiple smaller work groups.</li>
* <li>For each smaller work group, creates a <i>task config</i> that will be handed over to a single {@link SourceTask}</li>
* <li>Each task config is encoded as a comma separated string. This is the simpler convention followed by few other connectors as well. The {@link SourceTask} is expected to split this String with comma delimiter.</li>
* <li>Adds the connector specific configuration to <i>task config</i> so that it can be forwarded to {@link SourceTask}</li>
* </ul>
*
* @author Aravind R Yarram
* @since 0.5.0
*/
public class TaskConfigBuilder<T> {
private final int maxTasks;
private final AbstractConfig connectorCfg;
private final TaskConfigExtractor<T> taskCfgExtractor;
private final String taskCfgKey;
private static Logger logger = LoggerFactory.getLogger(TaskConfigBuilder.class);
/**
* @param maxTasks The maximum simultaneous tasks configured to be run by connector.
* @param taskConfigKey The key to be used while adding the task config.
* @param connectorCfg The reference to the custom config class you wrote extending from {@link AbstractConfig}. Null if not applicable.
* @param taskConfigExtractor The class used to extract the task configuration. This is used as the value for key <i>taskConfigKey</i>.
*/
public TaskConfigBuilder(int maxTasks, String taskConfigKey, AbstractConfig connectorCfg, TaskConfigExtractor taskConfigExtractor) {
this.maxTasks = maxTasks;
this.connectorCfg = connectorCfg;
this.taskCfgExtractor = taskConfigExtractor;
this.taskCfgKey = taskConfigKey;
}
/**
* Builds task config for each task.
*
* @param work The entire work expected to be fulfilled by this connector
* @return The task configuration for each of the tasks
*/
public List<Map<String, String>> build(List<T> work) {
//Create job groups
int workSizeCount = work.size();
int numGroups = Math.min(workSizeCount, maxTasks);
logger.debug("Total work size: {} units. maxTasks: {}. numGroups: {}.", workSizeCount, maxTasks, numGroups);
List<List<T>> workGroups = ConnectorUtils.groupPartitions(work, numGroups);
logger.debug("Number of work groups created: {}.", workGroups.size());
//Create task configs for each group
List<Map<String, String>> taskConfigs = new ArrayList<>(workGroups.size());
for (List<T> group : workGroups) {
//Forward the config from connector to SourceTask so that they have access to the configured TOPIC NAME
Map<String, String> taskProps = new HashMap<>(connectorCfg.originalsStrings());
//Concatenate all job urls that need to be handled by a single task
String commaSeparatedJobUrls = group.stream()
.map(j -> taskCfgExtractor.extract(j))
.collect(Collectors.joining(","));
taskProps.put(taskCfgKey, commaSeparatedJobUrls);
logger.trace("taskProps: {}", taskProps);
taskConfigs.add(taskProps);
}
return taskConfigs;
}
}
| 44.686747
| 219
| 0.696684
|
9fe3bdf0a43920035f6f791c8d00b802623d9199
| 6,537
|
package chav1961.bt.mnemoed.controls;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.TextAttribute;
import java.util.HashMap;
import java.util.Map;
import chav1961.bt.mnemoed.entities.BackgroundProp;
import chav1961.bt.mnemoed.entities.BasicEntityComponent;
import chav1961.bt.mnemoed.entities.BasicEntityContainer;
import chav1961.bt.mnemoed.entities.ColorProp;
import chav1961.bt.mnemoed.entities.EntityAlignment;
import chav1961.bt.mnemoed.entities.FontProp;
import chav1961.bt.mnemoed.entities.HyperlinkComponent;
import chav1961.bt.mnemoed.entities.LabelComponent;
import chav1961.bt.mnemoed.entities.LocationProp;
import chav1961.bt.mnemoed.entities.ObjectConstantValueSource;
import chav1961.bt.mnemoed.entities.PrimitiveConstantValueSource;
import chav1961.bt.mnemoed.entities.TextProp;
import chav1961.bt.mnemoed.entities.TooltipProp;
import chav1961.bt.mnemoed.entities.VisibilityProp;
import chav1961.purelib.basic.exceptions.PrintingException;
import chav1961.purelib.basic.exceptions.SyntaxException;
import chav1961.purelib.i18n.interfaces.Localizer;
import chav1961.purelib.streams.JsonStaxParser;
import chav1961.purelib.streams.JsonStaxPrinter;
import chav1961.purelib.ui.swing.useful.JBackgroundComponent;
public class Plane extends JBackgroundComponent {
private static final long serialVersionUID = -831480745460062449L;
@FunctionalInterface
private interface DrawingInterface {
void draw(Graphics2D g2d, BasicEntityComponent item);
}
private static final Map<Class<?>,DrawingInterface> MAPPER = new HashMap<>();
private static final Map<TextAttribute, Integer> UNDERLINE_FONT = new HashMap<TextAttribute, Integer>();
static {
MAPPER.put(LabelComponent.class, Plane::drawLabel);
MAPPER.put(HyperlinkComponent.class, Plane::drawHyperlink);
UNDERLINE_FONT.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
}
public Plane(final Localizer localizer) {
super(localizer);
setLayout(null);
}
protected BasicEntityComponent getRootComponent() {
final HyperlinkComponent result = new HyperlinkComponent(new HashMap<>());
result.setColor(new ColorProp(new ObjectConstantValueSource(Color.BLUE)));
result.setVisibility(new VisibilityProp(new PrimitiveConstantValueSource(true)));
result.setLocation(new LocationProp(new PrimitiveConstantValueSource(20), new PrimitiveConstantValueSource(20)));
result.setTooltip(new TooltipProp(new ObjectConstantValueSource("tooltip")));
result.setBackground(new BackgroundProp(new ObjectConstantValueSource(Color.RED)));
result.setText(new TextProp(new ObjectConstantValueSource("tooltip"), new ObjectConstantValueSource(EntityAlignment.WEST)));
result.setFont(new FontProp(new ObjectConstantValueSource("Monospace"), new PrimitiveConstantValueSource(12), new PrimitiveConstantValueSource(Font.BOLD)));
return result;
}
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
paintComponents((Graphics2D)g, getRootComponent());
}
private void paintComponents(final Graphics2D g2d, final BasicEntityComponent component) {
if (((PrimitiveConstantValueSource)component.getVisibility().getVisibility()).getBooleanValue()) {
MAPPER.get(component.getClass()).draw(g2d, component);
if (component instanceof BasicEntityContainer) {
for (BasicEntityComponent item : ((BasicEntityContainer)component)) {
paintComponents(g2d,item);
}
}
}
}
public void serialize(final JsonStaxPrinter printer) throws PrintingException {
}
public void deserialize(final JsonStaxParser printer) throws SyntaxException {
}
private static void drawLabel(final Graphics2D g2d, final BasicEntityComponent item) {
final LabelComponent lc = (LabelComponent)item;
final Color oldColor = g2d.getColor();
final Font oldFont = g2d.getFont();
final int fontSize = ((PrimitiveConstantValueSource)lc.getFont().getSize()).getIntValue();
final Font newFont = new Font(
((ObjectConstantValueSource<String>)lc.getFont().getFamily()).getObjectValue(),
((PrimitiveConstantValueSource)lc.getFont().getStyle()).getIntValue(),
fontSize
);
final String text = ((ObjectConstantValueSource<String>)lc.getText().getText()).getObjectValue();
final int x = ((PrimitiveConstantValueSource)lc.getLocation().getXLocation()).getIntValue();
final int y = ((PrimitiveConstantValueSource)lc.getLocation().getYLocation()).getIntValue();
g2d.setFont(newFont);
if (lc.getBackground().getBackground() != null) {
final FontMetrics fm = g2d.getFontMetrics(newFont);
final int width = fm.stringWidth(text), height = fm.getHeight();
g2d.setColor(((ObjectConstantValueSource<Color>)lc.getBackground().getBackground()).getObjectValue());
g2d.fillRect(x, y, width, height);
}
g2d.setColor(((ObjectConstantValueSource<Color>)lc.getColor().getColor()).getObjectValue());
g2d.drawString(text,x,y+fontSize);
g2d.setFont(oldFont);
g2d.setColor(oldColor);
}
private static void drawHyperlink(final Graphics2D g2d, final BasicEntityComponent item) {
final HyperlinkComponent lc = (HyperlinkComponent)item;
final Color oldColor = g2d.getColor();
final Font oldFont = g2d.getFont();
final int fontSize = ((PrimitiveConstantValueSource)lc.getFont().getSize()).getIntValue();
final Font newFont = new Font(
((ObjectConstantValueSource<String>)lc.getFont().getFamily()).getObjectValue(),
((PrimitiveConstantValueSource)lc.getFont().getStyle()).getIntValue(),
fontSize
).deriveFont(UNDERLINE_FONT);
final String text = ((ObjectConstantValueSource<String>)lc.getText().getText()).getObjectValue();
final int x = ((PrimitiveConstantValueSource)lc.getLocation().getXLocation()).getIntValue();
final int y = ((PrimitiveConstantValueSource)lc.getLocation().getYLocation()).getIntValue();
g2d.setFont(newFont);
if (lc.getBackground().getBackground() != null) {
final FontMetrics fm = g2d.getFontMetrics(newFont);
final int width = fm.stringWidth(text), height = fm.getHeight();
g2d.setColor(((ObjectConstantValueSource<Color>)lc.getBackground().getBackground()).getObjectValue());
g2d.fillRect(x, y, width, height);
}
g2d.setColor(((ObjectConstantValueSource<Color>)lc.getColor().getColor()).getObjectValue());
g2d.drawString(text,x,y+fontSize);
g2d.setFont(oldFont);
g2d.setColor(oldColor);
}
}
| 41.113208
| 158
| 0.766866
|
1638ee0c5e0c81d363a9246bfe1c02978af81c39
| 436
|
package com.sise.graduation.common.web.component;
import java.util.concurrent.atomic.AtomicInteger;
public class OperatingData {
private static AtomicInteger workNum = new AtomicInteger(0);
public static void addWorkNum() {
workNum.incrementAndGet();
}
public static void decWorkNum() {
workNum.decrementAndGet();
}
public static int getWorkNum(){
return workNum.intValue();
}
}
| 21.8
| 64
| 0.690367
|
de7ea6a5435b36dfac6b90c2a3af6950ec34f01a
| 4,054
|
//
// Treasure Data Bulk-Import Tool in Java
//
// Copyright (C) 2012 - 2013 Muga Nishizawa
//
// 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.treasure_data.td_import.upload;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
public class MultiThreadUploadProcessor {
static class Worker extends Thread {
private MultiThreadUploadProcessor parent;
private UploadProcessorBase proc;
AtomicBoolean isFinished = new AtomicBoolean(false);
public Worker(MultiThreadUploadProcessor parent, UploadProcessorBase proc) {
this.parent = parent;
this.proc = proc;
}
@Override
public void run() {
while (true) {
UploadTaskBase t = parent.taskQueue.poll();
if (t == null) {
continue;
} else if (t.endTask()) {
break;
}
TaskResult result = proc.execute(t);
parent.setTaskResult(result);
}
isFinished.set(true);
}
}
private static final Logger LOG = Logger.getLogger(MultiThreadUploadProcessor.class.getName());
private static BlockingQueue<UploadTaskBase> taskQueue;
static {
taskQueue = new LinkedBlockingQueue<UploadTaskBase>();
}
public static synchronized void addTask(UploadTaskBase task) {
taskQueue.add(task);
}
public static synchronized void clearTasks() {
// the method is for tests
taskQueue.clear();
}
public static synchronized void addFinishTask(UploadConfigurationBase conf) {
for (int i = 0; i < conf.getNumOfUploadThreads() * 2; i++) {
taskQueue.add(UploadTaskBase.FINISH_TASK);
}
}
private UploadConfigurationBase conf;
private List<Worker> workers;
private List<TaskResult> results;
public MultiThreadUploadProcessor(UploadConfigurationBase conf) {
this.conf = conf;
workers = new ArrayList<Worker>();
results = new ArrayList<TaskResult>();
}
protected synchronized void setTaskResult(TaskResult error) {
results.add(error);
}
public List<TaskResult> getTaskResults() {
return results;
}
public void registerWorkers() {
for (int i = 0; i < conf.getNumOfUploadThreads(); i++) {
addWorker(createWorker(conf));
}
}
protected Worker createWorker(UploadConfigurationBase conf) {
return new Worker(this, createUploadProcessor(conf));
}
protected void addWorker(Worker w) {
workers.add(w);
}
protected UploadProcessorBase createUploadProcessor(UploadConfigurationBase conf) {
return conf.createNewUploadProcessor();
}
public void startWorkers() {
for (int i = 0; i < workers.size(); i++) {
workers.get(i).start();
}
}
public void joinWorkers() {
long waitSec = 1 * 1000;
while (!workers.isEmpty()) {
Worker last = workers.get(workers.size() - 1);
if (last.isFinished.get()) {
workers.remove(workers.size() - 1);
}
try {
Thread.sleep(waitSec);
} catch (InterruptedException e) {
// ignore
}
}
}
}
| 30.02963
| 99
| 0.620375
|
ae3d12a788c3c89cf1c743f4a09f8433772407b6
| 1,972
|
package com.apigcc.core.resolver.impl;
import com.apigcc.core.common.ObjectMappers;
import com.apigcc.core.resolver.TypeResolvers;
import com.apigcc.core.resolver.Types;
import com.apigcc.core.resolver.ast.Clazz;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration;
import com.github.javaparser.resolution.declarations.ResolvedTypeParameterDeclaration;
import com.github.javaparser.resolution.types.ResolvedType;
import com.github.javaparser.utils.Pair;
import java.util.List;
public class MapResolver extends ReferenceResolver {
@Override
public boolean accept(ResolvedReferenceTypeDeclaration typeDeclaration) {
return Clazz.Maps.isAssignableBy(typeDeclaration);
}
@Override
public void resolve(Types types, ResolvedReferenceTypeDeclaration typeDeclaration,
List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> typeParametersMap) {
if (typeParametersMap != null && typeParametersMap.size() == 2) {
ObjectNode objectNode = ObjectMappers.instance().createObjectNode();
Object key = null;
Object value = null;
if (!"?".equals(typeParametersMap.get(0).b.describe())) {
Types componentType = TypeResolvers.of(typeParametersMap.get(0).b);
if (componentType.isResolved()) {
key = componentType.getValue();
}
}
if (!"?".equals(typeParametersMap.get(1).b.describe())) {
Types componentType = TypeResolvers.of(typeParametersMap.get(1).b);
if (componentType.isResolved()) {
value = componentType.getValue();
}
}
if (key != null && value != null) {
objectNode.putPOJO(String.valueOf(key), value);
types.setValue(objectNode);
}
}
}
}
| 40.244898
| 103
| 0.657201
|
a89ae7f5065ec1b2883c1d664c1e3be176635041
| 1,249
|
/*
* Copyright 2021 Christian Heina
*
* 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.christianheina.communication.javafied.signalprocessing.data;
/**
* Enum for handling supported binary formats of IQ data
*
* @author Christian Heina (developer@christianheina.com)
*/
public enum BinaryIqFormat {
/**
* 16 bit float
*/
FLOAT_16(2),
/**
* 32 bit float
*/
FLOAT_32(4),
/**
* 64 bit float
*/
FLOAT_64(8);
private int byteLength;
BinaryIqFormat(int byteLength) {
this.byteLength = byteLength;
}
/**
* Retrieve byte length
*
* @return byte length
*/
public int getByteLength() {
return byteLength;
}
}
| 23.12963
| 75
| 0.658927
|
3d073882ade2fa061c2cc1f24ad3da6ccf2bfe4c
| 527
|
package gg.projecteden.nexus.models.playerplushie;
import gg.projecteden.mongodb.annotations.PlayerClass;
import gg.projecteden.nexus.models.MongoService;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@PlayerClass(PlayerPlushieUser.class)
public class PlayerPlushieUserService extends MongoService<PlayerPlushieUser> {
private final static Map<UUID, PlayerPlushieUser> cache = new ConcurrentHashMap<>();
public Map<UUID, PlayerPlushieUser> getCache() {
return cache;
}
}
| 27.736842
| 85
| 0.815939
|
6023777f42f0a0d93ee9a843707dbfab24133f1d
| 3,461
|
/*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package tech.pegasys.poc.witnesscodeanalysis.strictfixed;
import org.apache.logging.log4j.Logger;
import org.apache.tuweni.bytes.Bytes;
import tech.pegasys.poc.witnesscodeanalysis.CodeAnalysisBase;
import tech.pegasys.poc.witnesscodeanalysis.common.PcUtils;
import tech.pegasys.poc.witnesscodeanalysis.vm.MainnetEvmRegistries;
import tech.pegasys.poc.witnesscodeanalysis.vm.Operation;
import tech.pegasys.poc.witnesscodeanalysis.vm.OperationRegistry;
import tech.pegasys.poc.witnesscodeanalysis.vm.operations.InvalidOperation;
import tech.pegasys.poc.witnesscodeanalysis.vm.operations.JumpOperation;
import java.math.BigInteger;
import java.util.ArrayList;
import static org.apache.logging.log4j.LogManager.getLogger;
public class StrictFixedSizeAnalysis extends CodeAnalysisBase {
private static final Logger LOG = getLogger();
private int chunkSize;
public static OperationRegistry registry = MainnetEvmRegistries.berlin(BigInteger.ONE);
public StrictFixedSizeAnalysis(Bytes code, int chunkSize) {
super(code);
this.chunkSize = chunkSize;
}
public ArrayList<Integer> analyse() {
int pc = 0;
int currentChunkSize = 0;
ArrayList<Integer> chunkStartOffsets = new ArrayList<>();
chunkStartOffsets.add(0);
int codeLength = this.code.size();
// True when the part of the contract being processed is definitely code.
boolean executableCodeSection = true;
LOG.trace(" Contract size: {}", codeLength);
while (pc < codeLength) {
if (executableCodeSection) {
// While processing executable code, determine the start offset of the
// the first opcode.
final Operation curOp = registry.get(code.get(pc), 0);
if (curOp == null) {
LOG.trace(" Found unknown opcode at PC: {}", PcUtils.pcStr(pc));
executableCodeSection = false;
// Move the PC to the end of the chunk.
pc += this.chunkSize - pc % this.chunkSize;
continue;
}
int opSize = curOp.getOpSize();
// Detect the end of the chunk
if(currentChunkSize + opSize >= this.chunkSize) {
currentChunkSize = currentChunkSize + opSize - this.chunkSize;
pc += opSize;
// Since the start addresses are fairly standard, we will track the offset to the first
// instruction in the chunk in this analysis.
chunkStartOffsets.add(currentChunkSize);
}
else {
currentChunkSize += opSize;
pc += opSize;
}
}
else {
// processing non-executable code
chunkStartOffsets.add(0);
pc += this.chunkSize;
}
}
LOG.trace(" StrictFixed Analysis found operation start offsets: ");
for(Integer e : chunkStartOffsets) {
LOG.trace(PcUtils.pcStr(e));
}
return chunkStartOffsets;
}
}
| 36.431579
| 118
| 0.700665
|
9faf88cfcf33c049544f22b54d1dd984aaa2d7fa
| 57,007
|
/*
* Copyright (c) 2012, 2018, 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.
*
* 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 jdk.internal.vm.compiler.word;
/**
* Lowest-level memory access of native C memory.
* <p>
* Do not use these methods to access Java objects. These methods access the raw memory without any
* null checks, read- or write barriers. Even when the VM uses compressed pointers, then readObject
* and writeObject methods access uncompressed pointers.
*
* @since 19.0
*/
public interface Pointer extends UnsignedWord, PointerBase {
/**
* Unsafe conversion of this Pointer to a Java language object. No correctness checks or type
* checks are performed. The caller must ensure that the Pointer contains a valid Java object
* that can i.e., processed by the garbage collector.
*
* @return this Pointer cast to Object.
*
* @since 19.0
*/
Object toObject();
/**
* Unsafe conversion of this Pointer to a Java language object. No correctness checks or type
* checks are performed. The caller must ensure that the Pointer contains a valid Java object
* that can i.e., processed by the garbage collector and the Pointer does not contain 0.
*
* @return this Pointer cast to non-null Object.
*
* @since 19.0
*/
Object toObjectNonNull();
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
byte readByte(WordBase offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
char readChar(WordBase offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
short readShort(WordBase offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
int readInt(WordBase offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
long readLong(WordBase offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
float readFloat(WordBase offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
double readDouble(WordBase offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
<T extends WordBase> T readWord(WordBase offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
Object readObject(WordBase offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
byte readByte(int offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
char readChar(int offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
short readShort(int offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
int readInt(int offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
long readLong(int offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
float readFloat(int offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
double readDouble(int offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
<T extends WordBase> T readWord(int offset, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the read
* @return the result of the memory access
*
* @since 19.0
*/
Object readObject(int offset, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeByte(WordBase offset, byte val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeChar(WordBase offset, char val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeShort(WordBase offset, short val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeInt(WordBase offset, int val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeLong(WordBase offset, long val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeFloat(WordBase offset, float val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeDouble(WordBase offset, double val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeWord(WordBase offset, WordBase val, LocationIdentity locationIdentity);
/**
* Initializes the memory at address {@code (this + offset)}. Both the base address and offset
* are in bytes. The memory must be uninitialized or zero prior to this operation.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void initializeLong(WordBase offset, long val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeObject(WordBase offset, Object val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeByte(int offset, byte val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeChar(int offset, char val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeShort(int offset, short val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeInt(int offset, int val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeLong(int offset, long val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeFloat(int offset, float val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeDouble(int offset, double val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeWord(int offset, WordBase val, LocationIdentity locationIdentity);
/**
* Initializes the memory at address {@code (this + offset)}. Both the base address and offset
* are in bytes. The memory must be uninitialized or zero prior to this operation.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void initializeLong(int offset, long val, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param locationIdentity the identity of the write
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeObject(int offset, Object val, LocationIdentity locationIdentity);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
byte readByte(WordBase offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
char readChar(WordBase offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
short readShort(WordBase offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
int readInt(WordBase offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
long readLong(WordBase offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
float readFloat(WordBase offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
double readDouble(WordBase offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
<T extends WordBase> T readWord(WordBase offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
Object readObject(WordBase offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
byte readByte(int offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
char readChar(int offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
short readShort(int offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
int readInt(int offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
long readLong(int offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
float readFloat(int offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
double readDouble(int offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
<T extends WordBase> T readWord(int offset);
/**
* Reads the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @return the result of the memory access
*
* @since 19.0
*/
Object readObject(int offset);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeByte(WordBase offset, byte val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeChar(WordBase offset, char val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeShort(WordBase offset, short val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeInt(WordBase offset, int val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeLong(WordBase offset, long val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeFloat(WordBase offset, float val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeDouble(WordBase offset, double val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeWord(WordBase offset, WordBase val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeObject(WordBase offset, Object val);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return The value that was read for comparison, which is {@code expectedValue} if the
* exchange was performed.
*
* @since 19.0
*/
int compareAndSwapInt(WordBase offset, int expectedValue, int newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return The value that was read for comparison, which is {@code expectedValue} if the
* exchange was performed.
*
* @since 19.0
*/
long compareAndSwapLong(WordBase offset, long expectedValue, long newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return The value that was read for comparison, which is {@code expectedValue} if the
* exchange was performed.
*
* @since 19.0
*/
<T extends WordBase> T compareAndSwapWord(WordBase offset, T expectedValue, T newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return The value that was read for comparison, which is {@code expectedValue} if the
* exchange was performed.
*
* @since 19.0
*/
Object compareAndSwapObject(WordBase offset, Object expectedValue, Object newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return {@code true} if successful. False return indicates that the actual value was not
* equal to the expected value.
*
* @since 19.0
*/
boolean logicCompareAndSwapInt(WordBase offset, int expectedValue, int newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return {@code true} if successful. False return indicates that the actual value was not
* equal to the expected value.
*
* @since 19.0
*/
boolean logicCompareAndSwapLong(WordBase offset, long expectedValue, long newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return {@code true} if successful. False return indicates that the actual value was not
* equal to the expected value.
*
* @since 19.0
*/
boolean logicCompareAndSwapWord(WordBase offset, WordBase expectedValue, WordBase newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
* <p>
* The offset is always treated as a {@link SignedWord} value. However, the static type is
* {@link WordBase} to avoid the frequent casts of {@link UnsignedWord} values (where the caller
* knows that the highest-order bit of the unsigned value is never used).
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return {@code true} if successful. False return indicates that the actual value was not
* equal to the expected value.
*
* @since 19.0
*/
boolean logicCompareAndSwapObject(WordBase offset, Object expectedValue, Object newValue, LocationIdentity locationIdentity);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeByte(int offset, byte val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeChar(int offset, char val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeShort(int offset, short val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeInt(int offset, int val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeLong(int offset, long val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeFloat(int offset, float val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeDouble(int offset, double val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeWord(int offset, WordBase val);
/**
* Writes the memory at address {@code (this + offset)}. Both the base address and offset are in
* bytes.
*
* @param offset the signed offset for the memory access
* @param val the value to be written to memory
*
* @since 19.0
*/
void writeObject(int offset, Object val);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return The value that was read for comparison, which is {@code expectedValue} if the
* exchange was performed.
*
* @since 19.0
*/
int compareAndSwapInt(int offset, int expectedValue, int newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return The value that was read for comparison, which is {@code expectedValue} if the
* exchange was performed.
*
* @since 19.0
*/
long compareAndSwapLong(int offset, long expectedValue, long newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return The value that was read for comparison, which is {@code expectedValue} if the
* exchange was performed.
*
* @since 19.0
*/
<T extends WordBase> T compareAndSwapWord(int offset, T expectedValue, T newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return The value that was read for comparison, which is {@code expectedValue} if the
* exchange was performed.
*
* @since 19.0
*/
Object compareAndSwapObject(int offset, Object expectedValue, Object newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return {@code true} if successful. False return indicates that the actual value was not
* equal to the expected value.
*
* @since 19.0
*/
boolean logicCompareAndSwapInt(int offset, int expectedValue, int newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return {@code true} if successful. False return indicates that the actual value was not
* equal to the expected value.
*
* @since 19.0
*/
boolean logicCompareAndSwapLong(int offset, long expectedValue, long newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return {@code true} if successful. False return indicates that the actual value was not
* equal to the expected value.
*
* @since 19.0
*/
boolean logicCompareAndSwapWord(int offset, WordBase expectedValue, WordBase newValue, LocationIdentity locationIdentity);
/**
* In a single atomic step, compares the memory at address {@code (this + offset)} to the
* expected value, and if equal, exchanges it for the new value. Both the base address and
* offset are in bytes.
*
* @param offset the signed offset for the memory access
* @param expectedValue the expected current value at the memory address
* @param newValue the new value for the atomic exchange
* @param locationIdentity the identity of the memory location
* @return {@code true} if successful. False return indicates that the actual value was not
* equal to the expected value.
*
* @since 19.0
*/
boolean logicCompareAndSwapObject(int offset, Object expectedValue, Object newValue, LocationIdentity locationIdentity);
// Math functions that are defined in Unsigned, but known to preserve the
// pointer-characteristics.
// It is therefore safe that they return a static type of Pointer instead of Unsigned.
/**
* Returns a Pointer whose value is {@code (this + val)}.
*
* @param val value to be added to this Pointer.
* @return {@code this + val}
*
* @since 19.0
*/
@Override
Pointer add(UnsignedWord val);
/**
* Returns a Pointer whose value is {@code (this + val)}.
*
* @param val value to be added to this Pointer.
* @return {@code this + val}
*
* @since 19.0
*/
@Override
Pointer add(int val);
/**
* Returns a Pointer whose value is {@code (this - val)}.
*
* @param val value to be subtracted from this Pointer.
* @return {@code this - val}
*
* @since 19.0
*/
@Override
Pointer subtract(UnsignedWord val);
/**
* Returns a Pointer whose value is {@code (this - val)}.
*
* @param val value to be subtracted from this Pointer.
* @return {@code this - val}
*
* @since 19.0
*/
@Override
Pointer subtract(int val);
/**
* Returns a Pointer whose value is {@code (this & val)}.
*
* @param val value to be AND'ed with this Pointer.
* @return {@code this & val}
*
* @since 19.0
*/
@Override
Pointer and(UnsignedWord val);
/**
* Returns a Pointer whose value is {@code (this & val)}.
*
* @param val value to be AND'ed with this Pointer.
* @return {@code this & val}
*
* @since 19.0
*/
@Override
Pointer and(int val);
/**
* Returns a Pointer whose value is {@code (this | val)}.
*
* @param val value to be OR'ed with this Pointer.
* @return {@code this | val}
*
* @since 19.0
*/
@Override
Pointer or(UnsignedWord val);
/**
* Returns a Pointer whose value is {@code (this | val)}.
*
* @param val value to be OR'ed with this Pointer.
* @return {@code this | val}
*
* @since 19.0
*/
@Override
Pointer or(int val);
}
| 39.153159
| 131
| 0.656814
|
fe5d75764d3cf7476197e9fa6e76d5676e72f6a6
| 14,036
|
/*
* Copyright © 2011 Everit Kft. (http://www.everit.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.everit.jetty.server.ecm.internal;
import java.util.function.Consumer;
import javax.sql.DataSource;
import org.eclipse.jetty.server.session.AbstractSessionDataStore;
import org.eclipse.jetty.server.session.DatabaseAdaptor;
import org.eclipse.jetty.server.session.FileSessionDataStore;
import org.eclipse.jetty.server.session.JDBCSessionDataStore;
import org.eclipse.jetty.server.session.JDBCSessionDataStore.SessionTableSchema;
import org.everit.jetty.server.SessionDataStoreFactory;
import org.everit.jetty.server.ecm.JDBCSessionDataStoreFactoryConstants;
import org.everit.osgi.ecm.annotation.Component;
import org.everit.osgi.ecm.annotation.ConfigurationPolicy;
import org.everit.osgi.ecm.annotation.Service;
import org.everit.osgi.ecm.annotation.ServiceRef;
import org.everit.osgi.ecm.annotation.attribute.StringAttribute;
import org.everit.osgi.ecm.extender.ExtendComponent;
/**
* Configurable component that creates a {@link FileSessionDataStore} instance.
*/
@ExtendComponent
@Component(componentId = JDBCSessionDataStoreFactoryConstants.SERVICE_FACTORY_PID,
configurationPolicy = ConfigurationPolicy.FACTORY,
label = "Everit Jetty JDBCSessionDataStore Factory")
@Service(SessionDataStoreFactory.class)
public class JDBCSessionDataStoreFactoryComponent extends AbstractSessionDataStoreFactoryComponent {
private static <T> void setIfNotNull(T value, Consumer<T> setter) {
if (value != null) {
setter.accept(value);
}
}
private String accessTimeColumn;
private String blobType;
private String contextPathColumn;
private String cookieTimeColumn;
private String createTimeColumn;
private DataSource dataSource;
private String expiryTimeColumn;
private String idColumn;
private String lastAccessTimeColumn;
private String lastNodeColumn;
private String lastSavedTimeColumn;
private String longType;
private String mapColumn;
private String maxIntervalColumn;
private String schemaName;
private String stringType;
private String tableName;
private String virtualHostColumn;
@Override
protected AbstractSessionDataStore doCreateSessionDataStore() {
JDBCSessionDataStore jdbcSessionDataStore = new JDBCSessionDataStore();
DatabaseAdaptor dbAdaptor = new DatabaseAdaptor();
dbAdaptor.setDatasource(this.dataSource);
dbAdaptor.setBlobType(this.blobType);
dbAdaptor.setLongType(this.longType);
dbAdaptor.setStringType(this.stringType);
SessionTableSchema sessionTableSchema = new SessionTableSchema();
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.schemaName,
sessionTableSchema::setSchemaName);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.tableName,
sessionTableSchema::setTableName);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.idColumn,
sessionTableSchema::setIdColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.accessTimeColumn,
sessionTableSchema::setAccessTimeColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.contextPathColumn,
sessionTableSchema::setContextPathColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.cookieTimeColumn,
sessionTableSchema::setCookieTimeColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.createTimeColumn,
sessionTableSchema::setCreateTimeColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.expiryTimeColumn,
sessionTableSchema::setExpiryTimeColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.lastAccessTimeColumn,
sessionTableSchema::setLastAccessTimeColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.lastNodeColumn,
sessionTableSchema::setLastNodeColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.lastSavedTimeColumn,
sessionTableSchema::setLastSavedTimeColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.mapColumn,
sessionTableSchema::setMapColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.maxIntervalColumn,
sessionTableSchema::setMaxIntervalColumn);
JDBCSessionDataStoreFactoryComponent.setIfNotNull(this.virtualHostColumn,
sessionTableSchema::setVirtualHostColumn);
jdbcSessionDataStore.setSessionTableSchema(sessionTableSchema);
jdbcSessionDataStore.setDatabaseAdaptor(dbAdaptor);
return jdbcSessionDataStore;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_ACCESS_TIME_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P36_ACCESS_TIME_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_ACCESS_TIME_COLUMN,
label = "Access time column",
description = "Name of the database table column where access time of the session is stored."
+ " Default: accessTime")
public void setAccessTimeColumn(String accessTimeColumn) {
this.accessTimeColumn = accessTimeColumn;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_BLOB_TYPE,
priority = JDBCSessionDataStoreFactoryConstants.P30_BLOB_TYPE,
optional = true,
label = "Blob type",
description = "Type of blob column. This is an optional field. If not set, type 'bytea'"
+ " is used for postgres, type 'blob' is used otherwise.")
public void setBlobType(String blobType) {
this.blobType = blobType;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_CONTEXT_PATH_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P37_CONTEXT_PATH_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_CONTEXT_PATH_COLUMN,
label = "Context path column",
description = "Name of the database table column where the context path of the session"
+ " is stored. Default: contextPath")
public void setContextPathColumn(String contextPathColumn) {
this.contextPathColumn = contextPathColumn;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_COOKIE_TIME_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P38_COOKIE_TIME_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_COOKIE_TIME_COLUMN,
label = "Cookie time column",
description = "Name of the database table column where the cookie time of the session"
+ " is stored. Default: cookieTime")
public void setCookieTimeColumn(String cookieTimeColumn) {
this.cookieTimeColumn = cookieTimeColumn;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_CREATE_TIME_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P39_CREATE_TIME_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_CREATE_TIME_COLUMN,
label = "Create time column",
description = "Name of the database table column where the creation time of the session"
+ " is stored. Default: createTime")
public void setCreateTimeColumn(String createTimeColumn) {
this.createTimeColumn = createTimeColumn;
}
@ServiceRef(referenceId = JDBCSessionDataStoreFactoryConstants.ATTR_DATASTORE, optional = false,
attributePriority = JDBCSessionDataStoreFactoryAttributePriority.P01_DATASTORE,
label = "DataStore (target)",
description = "The datasource that is used to access the database.")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_EXPIRY_TIME_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P40_EXPIRY_TIME_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_EXPIRY_TIME_COLUMN,
label = "Expiry time column",
description = "Name of the database table column where the expiry time of the session"
+ " is stored. Default: expiryTime")
public void setExpiryTimeColumn(String expiryTimeColumn) {
this.expiryTimeColumn = expiryTimeColumn;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_ID_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P35_ID_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_ID_COLUMN,
label = "Id column",
description = "Name of the database table column where the session id is stored."
+ " Default: sessionId")
public void setIdColumn(String idColumn) {
this.idColumn = idColumn;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_LAST_ACCESS_TIME_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P41_LAST_ACCESS_TIME_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_LAST_ACCESS_TIME_COLUMN,
label = "Last access time column",
description = "Name of the database table column where the last access time of the session"
+ " is stored. Default: lastAccessTime")
public void setLastAccessTimeColumn(String lastAccessTimeColumn) {
this.lastAccessTimeColumn = lastAccessTimeColumn;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_LAST_NODE_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P42_LAST_NODE_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_LAST_NODE_COLUMN,
label = "Last node column",
description = "Name of the database table column where the last node of the session"
+ " is stored. Default: lastNode")
public void setLastNodeColumn(String lastNodeColumn) {
this.lastNodeColumn = lastNodeColumn;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_LAST_SAVED_TIME_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P43_LAST_SAVED_TIME_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_LAST_SAVED_TIME_COLUMN,
label = "Last saved time column",
description = "Name of the database table column where the last saved time of the session"
+ " is stored. Default: lastSavedTime")
public void setLastSavedTimeColumn(String lastSavedTimeColumn) {
this.lastSavedTimeColumn = lastSavedTimeColumn;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_LONG_TYPE,
priority = JDBCSessionDataStoreFactoryConstants.P31_LONG_TYPE,
optional = true,
label = "Long type",
description = "Type of long column. This is an optional field. If not set, type 'number(20)'"
+ " is used for oracle, type 'bigint' is used otherwise.")
public void setLongType(String longType) {
this.longType = longType;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_MAP_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P44_MAP_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_MAP_COLUMN,
label = "Map column",
description = "Name of the database table column where the session attributes are stored."
+ " Default: map")
public void setMapColumn(String mapColumn) {
this.mapColumn = mapColumn;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_MAX_INTERVAL_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P45_MAX_INTERVAL_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_MAX_INTERVAL_COLUMN,
label = "Max interval column",
description = "Name of the database table column where the max interval of the session"
+ " is stored. Default: maxInterval")
public void setMaxIntervalColumn(String maxIntervalColumn) {
this.maxIntervalColumn = maxIntervalColumn;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_SCHEMA_NAME,
priority = JDBCSessionDataStoreFactoryConstants.P33_SCHEMA_NAME,
optional = true,
label = "Schema name",
description = "Name of the database schema where the tables should be.")
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_STRING_TYPE,
priority = JDBCSessionDataStoreFactoryConstants.P32_STRING_TYPE,
defaultValue = "varchar",
label = "String type",
description = "Type of string column. Default: varchar.")
public void setStringType(String stringType) {
this.stringType = stringType;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_TABLE_NAME,
priority = JDBCSessionDataStoreFactoryConstants.P34_TABLE_NAME,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_TABLE_NAME,
label = "Table name",
description = "Name of the table where the session data is stored. Default: JettySessions")
public void setTableName(String tableName) {
this.tableName = tableName;
}
@StringAttribute(attributeId = JDBCSessionDataStoreFactoryConstants.ATTR_VIRTUAL_HOST_COLUMN,
priority = JDBCSessionDataStoreFactoryConstants.P46_VIRTUAL_HOST_COLUMN,
defaultValue = JDBCSessionDataStoreFactoryConstants.DEFAULT_VIRTUAL_HOST_COLUMN,
label = "Virtual host column",
description = "Name of the database table column where the virtual host of the session"
+ " is stored. Default: virtualHost")
public void setVirtualHostColumn(String virtualHostColumn) {
this.virtualHostColumn = virtualHostColumn;
}
}
| 45.277419
| 100
| 0.781989
|
fea301b2ba413d93bb3bcd311f9d566e2c417dd4
| 569
|
package com.baiyu.securityjwt.entity;
import org.springframework.security.core.GrantedAuthority;
/**
* @author baiyu
* @data 2020-05-19 13:31
*/
public class Role implements GrantedAuthority {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getAuthority() {
return name;
}
}
| 15.805556
| 58
| 0.604569
|
66000e0e709b63b364ba9e91bd743cb880b081de
| 797
|
package file.processor.factory;
import java.util.Arrays;
public enum FileProcessorType {
SALESMAN("001"),
CUSTOMER("002"),
SALE("003");
private final String dataIdentifierPattern;
FileProcessorType(String dataIdentifierPattern) {
this.dataIdentifierPattern = dataIdentifierPattern;
}
public static FileProcessorType getFileProcessorType(String line) throws Exception {
return Arrays.stream(FileProcessorType.values())
.filter(fileProcessorType ->
line.contains(fileProcessorType.getDataIdentifierPattern()))
.findFirst()
.orElseThrow(() -> new Exception("No pattern found"));
}
public String getDataIdentifierPattern() {
return dataIdentifierPattern;
}
}
| 28.464286
| 88
| 0.667503
|
b35523c93d049504d8b941ab4038a1f1a9fbbfbc
| 5,817
|
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2021 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.postmodern.postmoderndungeon.items.potions.exotic;
import com.postmodern.postmoderndungeon.Dungeon;
import com.postmodern.postmoderndungeon.items.Item;
import com.postmodern.postmoderndungeon.items.Recipe;
import com.postmodern.postmoderndungeon.items.potions.Potion;
import com.postmodern.postmoderndungeon.items.potions.PotionOfExperience;
import com.postmodern.postmoderndungeon.items.potions.PotionOfFrost;
import com.postmodern.postmoderndungeon.items.potions.PotionOfHaste;
import com.postmodern.postmoderndungeon.items.potions.PotionOfHealing;
import com.postmodern.postmoderndungeon.items.potions.PotionOfInvisibility;
import com.postmodern.postmoderndungeon.items.potions.PotionOfLevitation;
import com.postmodern.postmoderndungeon.items.potions.PotionOfLiquidFlame;
import com.postmodern.postmoderndungeon.items.potions.PotionOfMindVision;
import com.postmodern.postmoderndungeon.items.potions.PotionOfParalyticGas;
import com.postmodern.postmoderndungeon.items.potions.PotionOfPurity;
import com.postmodern.postmoderndungeon.items.potions.PotionOfStrength;
import com.postmodern.postmoderndungeon.items.potions.PotionOfToxicGas;
import com.watabou.utils.Reflection;
import java.util.ArrayList;
import java.util.HashMap;
public class ExoticPotion extends Potion {
{
//sprite = equivalent potion sprite but one row down
}
public static final HashMap<Class<?extends Potion>, Class<?extends ExoticPotion>> regToExo = new HashMap<>();
public static final HashMap<Class<?extends ExoticPotion>, Class<?extends Potion>> exoToReg = new HashMap<>();
static{
regToExo.put(PotionOfHealing.class, PotionOfShielding.class);
exoToReg.put(PotionOfShielding.class, PotionOfHealing.class);
regToExo.put(PotionOfToxicGas.class, PotionOfCorrosiveGas.class);
exoToReg.put(PotionOfCorrosiveGas.class, PotionOfToxicGas.class);
regToExo.put(PotionOfStrength.class, PotionOfMastery.class);
exoToReg.put(PotionOfMastery.class, PotionOfStrength.class);
regToExo.put(PotionOfFrost.class, PotionOfSnapFreeze.class);
exoToReg.put(PotionOfSnapFreeze.class, PotionOfFrost.class);
regToExo.put(PotionOfHaste.class, PotionOfStamina.class);
exoToReg.put(PotionOfStamina.class, PotionOfHaste.class);
regToExo.put(PotionOfLiquidFlame.class, PotionOfDragonsBreath.class);
exoToReg.put(PotionOfDragonsBreath.class, PotionOfLiquidFlame.class);
regToExo.put(PotionOfInvisibility.class, PotionOfShroudingFog.class);
exoToReg.put(PotionOfShroudingFog.class, PotionOfInvisibility.class);
regToExo.put(PotionOfMindVision.class, PotionOfMagicalSight.class);
exoToReg.put(PotionOfMagicalSight.class, PotionOfMindVision.class);
regToExo.put(PotionOfLevitation.class, PotionOfStormClouds.class);
exoToReg.put(PotionOfStormClouds.class, PotionOfLevitation.class);
regToExo.put(PotionOfExperience.class, PotionOfDivineInspiration.class);
exoToReg.put(PotionOfDivineInspiration.class, PotionOfExperience.class);
regToExo.put(PotionOfPurity.class, PotionOfCleansing.class);
exoToReg.put(PotionOfCleansing.class, PotionOfPurity.class);
regToExo.put(PotionOfParalyticGas.class, PotionOfEarthenArmor.class);
exoToReg.put(PotionOfEarthenArmor.class, PotionOfParalyticGas.class);
}
@Override
public boolean isKnown() {
return anonymous || (handler != null && handler.isKnown( exoToReg.get(this.getClass()) ));
}
@Override
public void setKnown() {
if (!isKnown()) {
handler.know(exoToReg.get(this.getClass()));
updateQuickslot();
Potion p = Dungeon.hero.belongings.getItem(getClass());
if (p != null) p.setAction();
p = Dungeon.hero.belongings.getItem(exoToReg.get(this.getClass()));
if (p != null) p.setAction();
}
}
@Override
public void reset() {
super.reset();
if (handler != null && handler.contains(exoToReg.get(this.getClass()))) {
image = handler.image(exoToReg.get(this.getClass())) + 16;
color = handler.label(exoToReg.get(this.getClass()));
}
}
@Override
//20 gold more than its none-exotic equivalent
public int value() {
return (Reflection.newInstance(exoToReg.get(getClass())).value() + 20) * quantity;
}
@Override
//4 more energy than its none-exotic equivalent
public int energyVal() {
return (Reflection.newInstance(exoToReg.get(getClass())).energyVal() + 4) * quantity;
}
public static class PotionToExotic extends Recipe{
@Override
public boolean testIngredients(ArrayList<Item> ingredients) {
if (ingredients.size() == 1 && regToExo.containsKey(ingredients.get(0).getClass())){
return true;
}
return false;
}
@Override
public int cost(ArrayList<Item> ingredients) {
return 4;
}
@Override
public Item brew(ArrayList<Item> ingredients) {
for (Item i : ingredients){
i.quantity(i.quantity()-1);
}
return Reflection.newInstance(regToExo.get(ingredients.get(0).getClass()));
}
@Override
public Item sampleOutput(ArrayList<Item> ingredients) {
return Reflection.newInstance(regToExo.get(ingredients.get(0).getClass()));
}
}
}
| 36.35625
| 110
| 0.772735
|
a776c4e7f7cd7dbd4aea976b81961772901e9a96
| 12,182
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|tika
operator|.
name|utils
package|;
end_package
begin_import
import|import
name|java
operator|.
name|text
operator|.
name|DateFormat
import|;
end_import
begin_import
import|import
name|java
operator|.
name|text
operator|.
name|DateFormatSymbols
import|;
end_import
begin_import
import|import
name|java
operator|.
name|text
operator|.
name|SimpleDateFormat
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Calendar
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Date
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|GregorianCalendar
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Locale
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|TimeZone
import|;
end_import
begin_comment
comment|/** * Date related utility methods and constants */
end_comment
begin_class
specifier|public
class|class
name|DateUtils
block|{
comment|/** * The UTC time zone. Not sure if {@link TimeZone#getTimeZone(String)} * understands "UTC" in all environments, but it'll fall back to GMT * in such cases, which is in practice equivalent to UTC. */
specifier|public
specifier|static
specifier|final
name|TimeZone
name|UTC
init|=
name|TimeZone
operator|.
name|getTimeZone
argument_list|(
literal|"UTC"
argument_list|)
decl_stmt|;
comment|/** * Custom time zone used to interpret date values without a time * component in a way that most likely falls within the same day * regardless of in which time zone it is later interpreted. For * example, the "2012-02-17" date would map to "2012-02-17T12:00:00Z" * (instead of the default "2012-02-17T00:00:00Z"), which would still * map to "2012-02-17" if interpreted in say Pacific time (while the * default mapping would result in "2012-02-16" for UTC-8). */
specifier|public
specifier|static
specifier|final
name|TimeZone
name|MIDDAY
init|=
name|TimeZone
operator|.
name|getTimeZone
argument_list|(
literal|"GMT-12:00"
argument_list|)
decl_stmt|;
specifier|private
specifier|static
name|DateFormat
name|createDateFormat
parameter_list|(
name|String
name|format
parameter_list|,
name|TimeZone
name|timezone
parameter_list|)
block|{
specifier|final
name|SimpleDateFormat
name|sdf
init|=
operator|new
name|SimpleDateFormat
argument_list|(
name|format
argument_list|,
operator|new
name|DateFormatSymbols
argument_list|(
name|Locale
operator|.
name|US
argument_list|)
argument_list|)
decl_stmt|;
if|if
condition|(
name|timezone
operator|!=
literal|null
condition|)
block|{
name|sdf
operator|.
name|setTimeZone
argument_list|(
name|timezone
argument_list|)
expr_stmt|;
block|}
return|return
name|sdf
return|;
block|}
comment|/** * So we can return Date objects for these, this is the * list (in preference order) of the various ISO-8601 * variants that we try when processing a date based * property. */
specifier|private
specifier|final
name|List
argument_list|<
name|DateFormat
argument_list|>
name|iso8601InputFormats
init|=
name|loadDateFormats
argument_list|()
decl_stmt|;
specifier|private
name|List
argument_list|<
name|DateFormat
argument_list|>
name|loadDateFormats
parameter_list|()
block|{
name|List
argument_list|<
name|DateFormat
argument_list|>
name|dateFormats
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
comment|// yyyy-mm-ddThh...
name|dateFormats
operator|.
name|add
argument_list|(
name|createDateFormat
argument_list|(
literal|"yyyy-MM-dd'T'HH:mm:ss'Z'"
argument_list|,
name|UTC
argument_list|)
argument_list|)
expr_stmt|;
comment|// UTC/Zulu
name|dateFormats
operator|.
name|add
argument_list|(
name|createDateFormat
argument_list|(
literal|"yyyy-MM-dd'T'HH:mm:ssZ"
argument_list|,
literal|null
argument_list|)
argument_list|)
expr_stmt|;
comment|// With timezone
name|dateFormats
operator|.
name|add
argument_list|(
name|createDateFormat
argument_list|(
literal|"yyyy-MM-dd'T'HH:mm:ss"
argument_list|,
literal|null
argument_list|)
argument_list|)
expr_stmt|;
comment|// Without timezone
comment|// yyyy-mm-dd hh...
name|dateFormats
operator|.
name|add
argument_list|(
name|createDateFormat
argument_list|(
literal|"yyyy-MM-dd' 'HH:mm:ss'Z'"
argument_list|,
name|UTC
argument_list|)
argument_list|)
expr_stmt|;
comment|// UTC/Zulu
name|dateFormats
operator|.
name|add
argument_list|(
name|createDateFormat
argument_list|(
literal|"yyyy-MM-dd' 'HH:mm:ssZ"
argument_list|,
literal|null
argument_list|)
argument_list|)
expr_stmt|;
comment|// With timezone
name|dateFormats
operator|.
name|add
argument_list|(
name|createDateFormat
argument_list|(
literal|"yyyy-MM-dd' 'HH:mm:ss"
argument_list|,
literal|null
argument_list|)
argument_list|)
expr_stmt|;
comment|// Without timezone
comment|// Date without time, set to Midday UTC
name|dateFormats
operator|.
name|add
argument_list|(
name|createDateFormat
argument_list|(
literal|"yyyy-MM-dd"
argument_list|,
name|MIDDAY
argument_list|)
argument_list|)
expr_stmt|;
comment|// Normal date format
name|dateFormats
operator|.
name|add
argument_list|(
name|createDateFormat
argument_list|(
literal|"yyyy:MM:dd"
argument_list|,
name|MIDDAY
argument_list|)
argument_list|)
expr_stmt|;
comment|// Image (IPTC/EXIF) format
return|return
name|dateFormats
return|;
block|}
comment|/** * Returns a ISO 8601 representation of the given date. This method * is thread safe and non-blocking. * * @see<a href="https://issues.apache.org/jira/browse/TIKA-495">TIKA-495</a> * @param date given date * @return ISO 8601 date string, including timezone details */
specifier|public
specifier|static
name|String
name|formatDate
parameter_list|(
name|Date
name|date
parameter_list|)
block|{
name|Calendar
name|calendar
init|=
name|GregorianCalendar
operator|.
name|getInstance
argument_list|(
name|UTC
argument_list|,
name|Locale
operator|.
name|US
argument_list|)
decl_stmt|;
name|calendar
operator|.
name|setTime
argument_list|(
name|date
argument_list|)
expr_stmt|;
return|return
name|doFormatDate
argument_list|(
name|calendar
argument_list|)
return|;
block|}
comment|/** * Returns a ISO 8601 representation of the given date. This method * is thread safe and non-blocking. * * @see<a href="https://issues.apache.org/jira/browse/TIKA-495">TIKA-495</a> * @param date given date * @return ISO 8601 date string, including timezone details */
specifier|public
specifier|static
name|String
name|formatDate
parameter_list|(
name|Calendar
name|date
parameter_list|)
block|{
comment|// Explicitly switch it into UTC before formatting
name|date
operator|.
name|setTimeZone
argument_list|(
name|UTC
argument_list|)
expr_stmt|;
return|return
name|doFormatDate
argument_list|(
name|date
argument_list|)
return|;
block|}
comment|/** * Returns a ISO 8601 representation of the given date, which is * in an unknown timezone. This method is thread safe and non-blocking. * * @see<a href="https://issues.apache.org/jira/browse/TIKA-495">TIKA-495</a> * @param date given date * @return ISO 8601 date string, without timezone details */
specifier|public
specifier|static
name|String
name|formatDateUnknownTimezone
parameter_list|(
name|Date
name|date
parameter_list|)
block|{
comment|// Create the Calendar object in the system timezone
name|Calendar
name|calendar
init|=
name|GregorianCalendar
operator|.
name|getInstance
argument_list|(
name|TimeZone
operator|.
name|getDefault
argument_list|()
argument_list|,
name|Locale
operator|.
name|US
argument_list|)
decl_stmt|;
name|calendar
operator|.
name|setTime
argument_list|(
name|date
argument_list|)
expr_stmt|;
comment|// Have it formatted
name|String
name|formatted
init|=
name|formatDate
argument_list|(
name|calendar
argument_list|)
decl_stmt|;
comment|// Strip the timezone details before returning
return|return
name|formatted
operator|.
name|substring
argument_list|(
literal|0
argument_list|,
name|formatted
operator|.
name|length
argument_list|()
operator|-
literal|1
argument_list|)
return|;
block|}
specifier|private
specifier|static
name|String
name|doFormatDate
parameter_list|(
name|Calendar
name|calendar
parameter_list|)
block|{
return|return
name|String
operator|.
name|format
argument_list|(
name|Locale
operator|.
name|ROOT
argument_list|,
literal|"%04d-%02d-%02dT%02d:%02d:%02dZ"
argument_list|,
name|calendar
operator|.
name|get
argument_list|(
name|Calendar
operator|.
name|YEAR
argument_list|)
argument_list|,
name|calendar
operator|.
name|get
argument_list|(
name|Calendar
operator|.
name|MONTH
argument_list|)
operator|+
literal|1
argument_list|,
name|calendar
operator|.
name|get
argument_list|(
name|Calendar
operator|.
name|DAY_OF_MONTH
argument_list|)
argument_list|,
name|calendar
operator|.
name|get
argument_list|(
name|Calendar
operator|.
name|HOUR_OF_DAY
argument_list|)
argument_list|,
name|calendar
operator|.
name|get
argument_list|(
name|Calendar
operator|.
name|MINUTE
argument_list|)
argument_list|,
name|calendar
operator|.
name|get
argument_list|(
name|Calendar
operator|.
name|SECOND
argument_list|)
argument_list|)
return|;
block|}
comment|/** * Tries to parse the date string; returns null if no parse was possible. * * This is not thread safe! Wrap in synchronized or create new {@link DateUtils} * for each class. * * @param dateString * @return */
specifier|public
name|Date
name|tryToParse
parameter_list|(
name|String
name|dateString
parameter_list|)
block|{
comment|// Java doesn't like timezones in the form ss+hh:mm
comment|// It only likes the hhmm form, without the colon
name|int
name|n
init|=
name|dateString
operator|.
name|length
argument_list|()
decl_stmt|;
if|if
condition|(
name|dateString
operator|.
name|charAt
argument_list|(
name|n
operator|-
literal|3
argument_list|)
operator|==
literal|':'
operator|&&
operator|(
name|dateString
operator|.
name|charAt
argument_list|(
name|n
operator|-
literal|6
argument_list|)
operator|==
literal|'+'
operator|||
name|dateString
operator|.
name|charAt
argument_list|(
name|n
operator|-
literal|6
argument_list|)
operator|==
literal|'-'
operator|)
condition|)
block|{
name|dateString
operator|=
name|dateString
operator|.
name|substring
argument_list|(
literal|0
argument_list|,
name|n
operator|-
literal|3
argument_list|)
operator|+
name|dateString
operator|.
name|substring
argument_list|(
name|n
operator|-
literal|2
argument_list|)
expr_stmt|;
block|}
for|for
control|(
name|DateFormat
name|df
range|:
name|iso8601InputFormats
control|)
block|{
try|try
block|{
return|return
name|df
operator|.
name|parse
argument_list|(
name|dateString
argument_list|)
return|;
block|}
catch|catch
parameter_list|(
name|java
operator|.
name|text
operator|.
name|ParseException
name|e
parameter_list|)
block|{ }
block|}
return|return
literal|null
return|;
block|}
block|}
end_class
end_unit
| 18.263868
| 810
| 0.770481
|
dec8f199919356d3532ec714518425eccee06877
| 338
|
package edp.vap.dto.dashboardDto;
import edp.vap.model.Dashboard;
import edp.vap.model.MemDashboardWidget;
import edp.vap.model.View;
import lombok.Data;
import java.util.List;
import java.util.Set;
@Data
public class DashboardWithMem extends Dashboard {
String flag;
List<MemDashboardWidget> widgets;
Set<View> views;
}
| 17.789474
| 49
| 0.766272
|
a16039d041ba45bd353bee2ce4001b87eaa23063
| 754
|
package CalcTest;
import CalcTest.parser.util.*;
import CalcTest.parser.*;
import java.util.ArrayList;
import java.util.List;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
// Silly s=new Silly();
// System.out.println(s.silly() );
String f_xs = "(x+y)*2+(x+y)*1.2";
// final Point xo = new Point("x", new Double(2));
// final Point zo = new Point("y", new Double(1));
// final List<Point> foo = new ArrayList<Point>();
// foo.add(xo);
// foo.add(zo);
String[] ps=new String[] {"y","x"};
Double[] vs=new Double[] {3.0,3.0};
Double result = Parser.eval(f_xs,ps,vs);
System.out.println(result);
}
}
| 25.133333
| 58
| 0.545093
|
a37717f25af8ad97683d92ee30d83980b9c6e998
| 1,274
|
package eapli.base.contratoSLAmanagement.domain;
import eapli.base.catalogmanagement.domain.BriefDescription;
import eapli.framework.domain.model.ValueObject;
import eapli.framework.strings.util.StringPredicates;
import javax.persistence.Embeddable;
import java.util.Objects;
@Embeddable
public class ContratoDesignacao implements ValueObject {
private final String designacao;
protected ContratoDesignacao(){this.designacao=null;}
public ContratoDesignacao(final String designacao){
if (StringPredicates.isNullOrEmpty(designacao))
throw new IllegalArgumentException("Designation should not be null nor empty");
if (designacao.length() > 25)
throw new IllegalArgumentException("Designation max length is 25 characters");
this.designacao = designacao;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ContratoDesignacao a = (ContratoDesignacao) o;
return Objects.equals(this.designacao, a.designacao);
}
@Override
public int hashCode() {
return Objects.hash(designacao);
}
@Override
public String toString() {
return designacao;
}
}
| 28.954545
| 91
| 0.704867
|
bbd83589eac9db7c546a9d8fcc0081f170aa2927
| 399
|
package com.github.lanif.sys.modular.sms.enums;
import lombok.Getter;
/**
* 短信发送业务枚举
*
* @author
* @date 2018/5/6 12:30
*/
@Getter
public enum SmsSendSourceEnum {
/**
* APP
*/
APP(1),
/**
* PC
*/
PC(2),
/**
* OTHER
*/
OTHER(3);
private final Integer code;
SmsSendSourceEnum(Integer code) {
this.code = code;
}
}
| 11.083333
| 47
| 0.511278
|
689acd4f09dde8dcf6aebcde8e4c5f5694254be2
| 1,814
|
package test;
// A generic class containing information regarding different types of test cases.
public class TestCase {
// Contains enum value representing the type of operation to be performed.
private TestCommand testCommand;
// Time when the test case has to be executed.
private int inputTime;
// Unique integer identifier for the building.
private int buildingId;
// Total time required for constructing the entire building.
private int totalConstructionTime;
// Range of building numbers to be printed.
// endBuildingNum would be 0 in case if only one building has to be printed.
private int startBuildingNum, endBuildingNum;
public TestCase() {}
public TestCommand getTestCommand() {
return testCommand;
}
public void setTestCommand(TestCommand testCommand) {
this.testCommand = testCommand;
}
public int getInputTime() {
return inputTime;
}
public void setInputTime(int inputTime) {
this.inputTime = inputTime;
}
public int getBuildingId() {
return buildingId;
}
public void setBuildingId(int buildingId) {
this.buildingId = buildingId;
}
public int getTotalConstructionTime() {
return totalConstructionTime;
}
public void setTotalConstructionTime(int totalConstructionTime) {
this.totalConstructionTime = totalConstructionTime;
}
public int getStartBuildingNum() {
return startBuildingNum;
}
public void setStartBuildingNum(int startBuildingNum) {
this.startBuildingNum = startBuildingNum;
}
public int getEndBuildingNum() {
return endBuildingNum;
}
public void setEndBuildingNum(int endBuildingNum) {
this.endBuildingNum = endBuildingNum;
}
}
| 26.289855
| 82
| 0.690739
|
6e2809580116919312813fc9e4eb0180bbd83097
| 5,119
|
package org.sda.todolist;
/**
* This is main contains various display messages
*
* @author Imtiaz
* @version 1.0
* @since 2019-10-17
**/
public class Messages {
//A public constant field to hold code to RESET the text font color
public static final String RESET_TEXT = "\u001B[0m";
//A public constant field to hold code to change the text font color to RED
public static final String RED_TEXT = "\u001B[31m";
//A public constant field to hold code to change the text font color to GREEN
public static final String GREEN_TEXT = "\u001B[32m";
/**
* This method will display the main menu (top level menu) on standard output (terminal)
* to display all options for user selection.
* @param incompleteTaskCount takes the number of incomplete tasks (int) to show in main menu
* @param completedTaskCount takes the number of complete tasks (int) to show in main menu
*/
public static void mainMenu(int incompleteTaskCount, int completedTaskCount) {
System.out.println("\nMAIN MENU");
System.out.println("===========\n");
System.out.println("You have " + Messages.RED_TEXT
+ incompleteTaskCount + " task(s) todo "
+ Messages.RESET_TEXT + " and " + Messages.GREEN_TEXT
+ completedTaskCount + " completed task(s)\n" + Messages.RESET_TEXT);
System.out.println("Pick an option:");
System.out.println("(1) Show Task List (by date or project)");
System.out.println("(2) Add New Task");
System.out.println("(3) Edit Task (update, mark as done, remove)");
System.out.println("(4) Save and Quit\n");
System.out.print("Please enter your choice [1-4]: ");
}
/**
* This method displays the menu to standard output (terminal) to show the options to display all tasks
* for user selection
*/
public static void listAllTasksMenu() {
System.out.println("\nDisplay All Tasks");
System.out.println("===================\n");
System.out.println("Pick an option:");
System.out.println("(1) Show Task List by date" +
Messages.RED_TEXT + " [default choice, just press ENTER key]" + Messages.RESET_TEXT);
System.out.println("(2) Show Task List by project");
System.out.print("\nPlease enter your choice [1-2]: ");
}
/**
* This method will display a prompt to user for typing the task number to EDIT
*/
public static void editTaskSelection() {
System.out.println(GREEN_TEXT);
System.out.print(">>> Type a task number to EDIT and press ENTER key: ");
System.out.print(RESET_TEXT);
}
/**
* This method will display the Edit menu options on standard output (terminal)
* for user selection
*/
public static void editTaskMenu() {
System.out.println("\nTask Edit Options");
System.out.println("======================\n");
System.out.println("Pick an option:");
System.out.println("(1) Modify selected task");
System.out.println("(2) Mark selected task as COMPLETED");
System.out.println("(3) Delete selected task");
System.out.println("(4) Return to main menu "
+ Messages.RED_TEXT + " [default choice, just press ENTER]"+Messages.RESET_TEXT);
System.out.print("\nPlease enter your choice [1-4]: ");
}
/**
* This method will display the bye message while ending the program
*/
public static void byeMessage() {
System.out.println(GREEN_TEXT);
System.out.println(">>> All tasks are saved to data file");
System.out.println(">>> Good Bye");
System.out.println(RESET_TEXT);
}
/**
* This method will display the error message if a user input an option which is not
* from the choices given in main menu
*/
public static void unknownMessage() {
System.out.println(RED_TEXT);
System.out.println(">>> Incorrect choice: Please type a number from given choices ");
System.out.print(RESET_TEXT);
}
/**
* This message will display any given message in RED or GREEN text on standard output (terminal)
* @param message a text message as String
* @param warning a boolean value, true for printing warning with RED text, and false
* for printing message in GREEN text on standard output (terminal)
*/
public static void showMessage(String message, boolean warning) {
System.out.println(warning?RED_TEXT:GREEN_TEXT);
System.out.println(">>> " + message);
System.out.println(RESET_TEXT);
}
/**
* This message will print the given character on standard output (terminal) to given number of times
* @param charToPrint a character given in single quote to print, i.e., '='
* @param times an integer to repeat printing the given character
*/
public static void separator (char charToPrint, int times) {
for (int index=0; index<times; index++) System.out.print(charToPrint);
System.out.println("");
}
}
| 41.959016
| 107
| 0.63489
|
efa1e61db5ec744e3b14e839e3bc277dc28fcc32
| 10,204
|
package com.chinasoft.hospital_manager.controller.user.clinicUserWork;
import com.alibaba.fastjson.JSONObject;
import com.chinasoft.hospital_manager.domain.*;
import com.chinasoft.hospital_manager.service.admin.work.WorkUserInfoService;
import org.apache.ibatis.javassist.expr.NewExpr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by Jack on 2020/1/23 15:20
*/
@Controller
@RequestMapping("/admin/user")
public class ClinicUserWorkController {
@Autowired
private WorkUserInfoService workUserInfoService;
@ResponseBody
@RequestMapping("/deleteWorkInfoById")
public Map<String,Object> deleteWorkInfoById(HttpServletRequest request){
Map<String,Object> map= new HashMap<String, Object>();
Map<String,Object> response_map= new HashMap<String, Object>();
String id=request.getParameter("id");
map.put("id",Integer.parseInt(id));
int i = workUserInfoService.deleteWorkInfoById(map);
if (i>0){
response_map.put("type","success");
return response_map;
}else {
response_map.put("type","fail");
}
return map;
}
@RequestMapping("/editWorkInfoById")
@ResponseBody
public Map<String,Object> editWorkInfoById(HttpServletRequest request){
Map<String,Object> map= new HashMap<String, Object>();
Map<String,Object> response_map= new HashMap<String, Object>();
String id =request.getParameter("id");
String address=request.getParameter("address");
map.put("id",Integer.parseInt(id));
map.put("address",address);
int i = workUserInfoService.editWorkInfoById(map);
if (i>0){
response_map.put("type","success");
}else {
response_map.put("type","fail");
}
return map;
}
/**
* @description:这个是根据类型,查询具体的用户
* @author jack
* @date 2020/3/2 1:40
* @param null
* @return
*/
@ResponseBody
@RequestMapping("/findUsersByCategory")
public Map<String,Object> findUsersByCategory(HttpServletRequest request){
Map<String,Object> map=new HashMap<String, Object>();
String id=request.getParameter("id");
if (id!=null&&id!=""){
if (Integer.parseInt(id)==1){
List<Admin> adminsByCategory = workUserInfoService.findAdminsByCategory();
if (adminsByCategory!=null){
map.put("type","success");
map.put("admins",adminsByCategory);
return map;
}
}if (Integer.parseInt(id)==2){
List<User> usersByCategory = workUserInfoService.findUsersByCategory();
if (usersByCategory!=null){
map.put("type","success");
map.put("users",usersByCategory);
return map;
}
}
if (Integer.parseInt(id)==3){
List<Doctor> doctorsByCategory = workUserInfoService.findDoctorsByCategory();
if (doctorsByCategory!=null){
map.put("type","success");
map.put("doctors",doctorsByCategory);
return map;
}
}
}else {
map.put("type","error");
}
return map;
}
/**
* @descriptio:点击页面,查询这个类型
* @author jack
* @date 2020/3/2 1:41
* @param null
* @return
*/
@RequestMapping("/clinicUserWorkInfo")
public ModelAndView loadUserWorkInfo(HttpServletRequest request){
ModelAndView andView =new ModelAndView();
andView.setViewName("/admin/user_clinicManager/index");
Object user = request.getSession().getAttribute("user");
List<User> users = workUserInfoService.getUsers();
List<Role> allRoles = workUserInfoService.getAllRoles();
if (allRoles!=null){
andView.addObject("allRoles",allRoles);
andView.addObject("users",users);
}
return andView;
}
@RequestMapping("/addUserWorkInfo")
@ResponseBody
public Map<String,Object> addUserWorkInfo(HttpServletRequest request) throws ParseException {
Map<String,Object> map=new HashMap<String, Object>();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
String user_id = request.getParameter("user_id");
User user=new User();
user.setId(Integer.parseInt(user_id));
String morning = request.getParameter("morning");
String afternoon = request.getParameter("afternoon");
String address = request.getParameter("address");
String startime = request.getParameter("startime");
String endtime = request.getParameter("endtime");
String onday="";
Date date_start=new Date(simpleDateFormat.parse(startime).getTime());
Date date_end=new Date(simpleDateFormat.parse(endtime).getTime());
/* private Integer id;
private User user;
private String address;
private String onday;
private String morning;
private String afternoon;
private String startime;
private String endtime;*/
long time = simpleDateFormat.parse(startime).getTime();
Date date = new Date(time);
onday = getWeekOfDate(date);
// Work work=new Work(user,address,onday,morning,afternoon,date_start,date_end);
map.put("address",address);
if (onday!=""&&onday!=null){
map.put("onday",onday);
}
map.put("morning",morning);
map.put("afternoon",afternoon);
map.put("startime",date_start);
map.put("endtime",date_end);
map.put("user_id",Integer.parseInt(user_id));
int i = workUserInfoService.addUserWorkInfo(map);
if (i>0){
map.put("type","success");
}else {
map.put("type","fail");
}
return map;
}
//获得星期几
public static String getWeekOfDate(Date date) {
String[] weekOfDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar calendar = Calendar.getInstance();
if(date != null){
calendar.setTime(date);
}
int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return weekOfDays[w];
}
@RequestMapping("/requestloadUserWorkInfo")
@ResponseBody
public Map<String, Object> requestloadUserWorkInfo(HttpServletRequest request){
Map<String,Object> map=new HashMap<String, Object>();
// int id=Integer.parseInt(request.getParameter("id"));
//. Work work = workUserInfoService.requestloadUserWorkInfo(4);
/* if (work!=null){
map.put("type","success");
map.put("info",work);
}*/
return map;
}
@ResponseBody
@RequestMapping(value = "/searchUserWorkInfoById",method = RequestMethod.POST)
public Map<String,Object> searchUserWorkInfoById(HttpServletRequest request) throws ParseException {
Map<String,Object> map= new HashMap<String, Object>();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
int id =Integer.parseInt(request.getParameter("id"));
List<Work> works = workUserInfoService.requestloadUserWorkInfo(id);
if (works!=null){
map.put("type","success");
map.put("info",works);
}
return map;
}
/**
* @description:这个是根据这个用户的工作的id,查询这个具体的工作的详情信息
* @author jack
* @date 2020/3/8 17:45
* @param null
* @return
*/
@ResponseBody
@RequestMapping(value = "/findUserWorkInfoById",method = RequestMethod.GET)
public Map<String,Object> findUserWorkInfoById(HttpServletRequest request){
Map<String,Object> map=new HashMap<String, Object>();
int id=Integer.parseInt(request.getParameter("id"));
Work userWorkInfoById = workUserInfoService.findUserWorkInfoById(id);
if (userWorkInfoById!=null){
map.put("type","success");
map.put("work",userWorkInfoById);
map.put("user",userWorkInfoById.getUser());
}
return map;
}
/**
* @description:这个是根据id,查询所有的该用户的工作所有的信息
* @author jack
* @date 2020/3/8 17:48
* @param null
* @return
*/
@RequestMapping("/findUsersWorkInfo")
@ResponseBody
public Map<String,Object> findUsersWorkInfo (HttpServletRequest request){
Map<String,Object> map=new HashMap<String, Object>();
int id = Integer.parseInt(request.getParameter("id"));
if (id!=0){
List<Work> doctorsWorkInfoById = workUserInfoService.findUsersWorkInfo(id);
if (doctorsWorkInfoById!=null){
String string = JSONObject.toJSONString(doctorsWorkInfoById);
map.put("info",doctorsWorkInfoById);
}
}
return map;
}
/**
* @description:这个是挂号人员点击工作信息的时候,显示这个工作信息的页面,然后获取这个id,进行这个ajax查询的,从而显示这个工作的信息!!!
* @author jack
* @date 2020/3/7 16:26
* @param null
* @return
*/
@RequestMapping("/findUsersWorkInfoById")
public ModelAndView findUsersWorkInfoById(HttpServletRequest request){
ModelAndView andView=new ModelAndView();
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
User doctor1=null;int id=0;
if (user!=null){
doctor1=(User) user;
id=doctor1.getId();
}
andView.addObject("user",doctor1);
andView.setViewName("/admin/userInfoAndManager/usersForWork/work");
return andView;
}
}
| 34.241611
| 104
| 0.620051
|
2c573893f32432c9c8e4e5a69a97b45020c6d787
| 3,282
|
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.api.runtime.rule;
/**
* A DataSource is a source of the data processed by a given {@link RuleUnit}.
*/
public interface DataSource<T> extends Iterable<T> {
/**
* Inserts a new fact into this DataSource
*
* @param object
* the fact to be inserted
*
* @return the fact handle created for the given fact
*/
FactHandle insert( T object );
/**
* Updates the fact for which the given FactHandle was assigned with the new
* fact set as the second parameter in this method.
* It is also possible to optionally specify the set of properties that have been modified.
*
* @param handle the FactHandle for the fact to be updated.
* @param object the new value for the fact being updated.
* @param modifiedProperties the list of the names of the object's properties modified by this update.
*/
void update(FactHandle handle, T object, String... modifiedProperties);
/**
* Deletes the fact for which the given FactHandle was assigned
*
* @param handle the handle whose fact is to be retracted.
*/
void delete(FactHandle handle);
/**
* Deletes the given object from this DataSource
*
* @param object the object to be deleted.
*/
void delete(Object object);
/**
* Creates a DataSource, optionally containing some items
*
* @param items the items contained in the DataSource.
*/
static <T> DataSource<T> create(T... items) {
try {
DataSource<T> dataSource = DataSourceFactory.newInstance();
for (T item : items) {
dataSource.insert( item );
}
return dataSource;
} catch (Exception e) {
throw new RuntimeException("Unable to instance KieServices", e);
}
}
class DataSourceFactory {
private static class LazyHolder {
private static Class<?> DATA_SOURCE_DEFAULT_CLASS;
static {
try {
DATA_SOURCE_DEFAULT_CLASS = Class.forName( "org.drools.core.datasources.CursoredDataSource" );
} catch (ClassNotFoundException e) {
throw new RuntimeException( e );
}
}
}
/**
* Returns a reference to the KieServices singleton
*/
public static <T> DataSource<T> newInstance() {
try {
return (DataSource<T>) LazyHolder.DATA_SOURCE_DEFAULT_CLASS.newInstance();
} catch (Exception e) {
throw new RuntimeException( e );
}
}
}
}
| 32.176471
| 114
| 0.617916
|
52736f367c26c1e99b7a38c96abb00790662c205
| 3,296
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.mctester.api;
import com.google.common.util.concurrent.Futures;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.spongepowered.mctester.junit.Client;
import java.util.concurrent.CompletableFuture;
public class RunnerEvents {
private static CompletableFuture<Void> clientInitialized = new CompletableFuture<>();
private static CompletableFuture<Void> playerJoined = new CompletableFuture<>();
private static CompletableFuture<Void> gameClosed = new CompletableFuture<>();
private static CompletableFuture<LaunchClassLoader> launchClassLoaderFuture = new CompletableFuture<>();
public static void waitForPlayerJoin() {
Futures.getUnchecked(playerJoined);
}
public static void setPlayerJoined() {
playerJoined.complete(null);
}
public static void resetPlayerJoined() {
if (!playerJoined.isDone()) {
return;
}
playerJoined = new CompletableFuture<>();
}
public static boolean hasPlayerJoined() {
return playerJoined.isDone();
}
public static void waitForGameClosed() {
Futures.getUnchecked(gameClosed);
}
public static void setGameClosed() {
gameClosed.complete(null);
}
public static LaunchClassLoader waitForLaunchClassLoaderFuture() {
return Futures.getUnchecked(launchClassLoaderFuture);
}
public static void setLaunchClassLoaderFuture(LaunchClassLoader launchClassLoader) {
launchClassLoaderFuture.complete(launchClassLoader);
}
public static void waitForClientInit() {
Futures.getUnchecked(clientInitialized);
}
public static void setClientInit() {
clientInitialized.complete(null);
}
public static void fatalError(Throwable throwable) {
clientInitialized.completeExceptionally(throwable);
playerJoined.completeExceptionally(throwable);
gameClosed.completeExceptionally(throwable);
launchClassLoaderFuture.completeExceptionally(throwable);
}
}
| 36.21978
| 108
| 0.737561
|
1a239330996bab460acc01363c394b0c03d796e4
| 5,687
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.transform.action;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.support.master.AcknowledgedRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.xpack.core.common.validation.SourceDestValidator;
import org.elasticsearch.xpack.core.transform.TransformField;
import org.elasticsearch.xpack.core.transform.TransformMessages;
import org.elasticsearch.xpack.core.transform.transforms.TransformConfig;
import org.elasticsearch.xpack.core.transform.utils.TransformStrings;
import java.io.IOException;
import java.util.Objects;
import static org.elasticsearch.action.ValidateActions.addValidationError;
public class PutTransformAction extends ActionType<AcknowledgedResponse> {
public static final PutTransformAction INSTANCE = new PutTransformAction();
public static final String NAME = "cluster:admin/transform/put";
private static final TimeValue MIN_FREQUENCY = TimeValue.timeValueSeconds(1);
private static final TimeValue MAX_FREQUENCY = TimeValue.timeValueHours(1);
private PutTransformAction() {
super(NAME, AcknowledgedResponse::new);
}
public static class Request extends AcknowledgedRequest<Request> {
private final TransformConfig config;
private final boolean deferValidation;
public Request(TransformConfig config, boolean deferValidation) {
this.config = config;
this.deferValidation = deferValidation;
}
public Request(StreamInput in) throws IOException {
super(in);
this.config = new TransformConfig(in);
if (in.getVersion().onOrAfter(Version.V_7_4_0)) {
this.deferValidation = in.readBoolean();
} else {
this.deferValidation = false;
}
}
public static Request fromXContent(final XContentParser parser, final String id, final boolean deferValidation) {
return new Request(TransformConfig.fromXContent(parser, id, false), deferValidation);
}
/**
* More complex validations with how {@link TransformConfig#getDestination()} and
* {@link TransformConfig#getSource()} relate are done in the transport handler.
*/
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
validationException = config.validate(validationException);
validationException = SourceDestValidator.validateRequest(validationException, config.getDestination().getIndex());
if (TransformStrings.isValidId(config.getId()) == false) {
validationException = addValidationError(
TransformMessages.getMessage(TransformMessages.INVALID_ID, TransformField.ID.getPreferredName(), config.getId()),
validationException
);
}
if (TransformStrings.hasValidLengthForId(config.getId()) == false) {
validationException = addValidationError(
TransformMessages.getMessage(TransformMessages.ID_TOO_LONG, TransformStrings.ID_LENGTH_LIMIT),
validationException
);
}
TimeValue frequency = config.getFrequency();
if (frequency != null) {
if (frequency.compareTo(MIN_FREQUENCY) < 0) {
validationException = addValidationError(
"minimum permitted [" + TransformField.FREQUENCY + "] is [" + MIN_FREQUENCY.getStringRep() + "]",
validationException
);
} else if (frequency.compareTo(MAX_FREQUENCY) > 0) {
validationException = addValidationError(
"highest permitted [" + TransformField.FREQUENCY + "] is [" + MAX_FREQUENCY.getStringRep() + "]",
validationException
);
}
}
return validationException;
}
public TransformConfig getConfig() {
return config;
}
public boolean isDeferValidation() {
return deferValidation;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
this.config.writeTo(out);
if (out.getVersion().onOrAfter(Version.V_7_4_0)) {
out.writeBoolean(this.deferValidation);
}
}
@Override
public int hashCode() {
return Objects.hash(config, deferValidation);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Request other = (Request) obj;
return Objects.equals(config, other.config) && this.deferValidation == other.deferValidation;
}
}
}
| 40.049296
| 133
| 0.650255
|
2b8b6695b089ae5b888541e0e4f78e60e8f2be4d
| 983
|
package pl.com.agora.kornaja.domain;
import javax.persistence.*;
import java.util.List;
/**
* Created by kornaja.
*/
@Entity
public class UserGroup {
@Id
@GeneratedValue
private Long id;
private String name;
@ElementCollection
@Enumerated(EnumType.STRING)
private List<Permission> permissions;
@ManyToMany(mappedBy = "userGroups")
private List<User> users;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Permission> getPermissions() {
return permissions;
}
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
| 17.245614
| 62
| 0.613428
|
ce955494c0a1c956f89b61b4068e1d2899e264b7
| 15,039
|
/*
* 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 com.aliyun.emr.rss.service.deploy.master.clustermeta.ha;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import org.apache.ratis.io.MD5Hash;
import org.apache.ratis.proto.RaftProtos;
import org.apache.ratis.protocol.Message;
import org.apache.ratis.protocol.RaftClientRequest;
import org.apache.ratis.protocol.RaftGroupId;
import org.apache.ratis.server.RaftServer;
import org.apache.ratis.server.protocol.TermIndex;
import org.apache.ratis.server.raftlog.RaftLog;
import org.apache.ratis.server.storage.FileInfo;
import org.apache.ratis.server.storage.RaftStorage;
import org.apache.ratis.statemachine.SnapshotInfo;
import org.apache.ratis.statemachine.SnapshotRetentionPolicy;
import org.apache.ratis.statemachine.StateMachineStorage;
import org.apache.ratis.statemachine.TransactionContext;
import org.apache.ratis.statemachine.impl.BaseStateMachine;
import org.apache.ratis.statemachine.impl.SimpleStateMachineStorage;
import org.apache.ratis.statemachine.impl.SingleFileSnapshotInfo;
import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
import org.apache.ratis.util.ExitUtils;
import org.apache.ratis.util.FileUtils;
import org.apache.ratis.util.LifeCycle;
import org.apache.ratis.util.MD5FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aliyun.emr.rss.common.util.ThreadUtils;
import com.aliyun.emr.rss.service.deploy.master.clustermeta.ResourceProtos;
import com.aliyun.emr.rss.service.deploy.master.clustermeta.ResourceProtos.ResourceResponse;
public class StateMachine extends BaseStateMachine {
private static final Logger LOG = LoggerFactory.getLogger(StateMachine.class);
public static final Pattern MD5_REGEX = Pattern.compile("snapshot\\.(\\d+)_(\\d+)\\.md5");
private final SimpleStateMachineStorage storage = new SimpleStateMachineStorage() {
/**
* we need to delete md5 file as the same time as snapshot file deleted,
* so we override the SimpleStateMachineStorage.cleanupOldSnapshots method,
* add delete md5 file action.
*
* @param snapshotRetentionPolicy snapshot retention policy
* @throws IOException
*/
@Override
public void cleanupOldSnapshots(SnapshotRetentionPolicy snapshotRetentionPolicy)
throws IOException {
if (snapshotRetentionPolicy != null
&& snapshotRetentionPolicy.getNumSnapshotsRetained() > 0) {
List<SingleFileSnapshotInfo> allSnapshotFiles = new ArrayList<>();
List<SingleFileSnapshotInfo> allMD5Files = new ArrayList<>();
try (DirectoryStream<Path> stream =
Files.newDirectoryStream(this.getSmDir().toPath())) {
for (Path path : stream) {
if (filePatternMatches(SNAPSHOT_REGEX, allSnapshotFiles, path)) {
continue;
} else {
filePatternMatches(MD5_REGEX, allMD5Files, path);
}
}
}
// first step, cleanup old snapshot and md5 file
SingleFileSnapshotInfo snapshotInfo = cleanupOldFiles(allSnapshotFiles,
snapshotRetentionPolicy.getNumSnapshotsRetained(), false, null);
// second step, cleanup only old md5 file
cleanupOldFiles(allMD5Files, snapshotRetentionPolicy.getNumSnapshotsRetained(),
true, snapshotInfo);
}
}
private boolean filePatternMatches(Pattern pattern,
List<SingleFileSnapshotInfo> result, Path filePath) {
Matcher md5Matcher = pattern.matcher(filePath.getFileName().toString());
if (md5Matcher.matches()) {
final long endIndex = Long.parseLong(md5Matcher.group(2));
final long term = Long.parseLong(md5Matcher.group(1));
final FileInfo fileInfo = new FileInfo(filePath, null);
result.add(new SingleFileSnapshotInfo(fileInfo, term, endIndex));
return true;
}
return false;
}
private SingleFileSnapshotInfo cleanupOldFiles(List<SingleFileSnapshotInfo> inputFiles,
int retainedNum, boolean onlyCleanupMD5Files, SingleFileSnapshotInfo snapshotInfo) {
SingleFileSnapshotInfo result = null;
if (inputFiles.size() > retainedNum) {
inputFiles.sort(new RatisSnapshotFileComparator());
List<SingleFileSnapshotInfo> filesToBeCleaned =
inputFiles.subList(retainedNum, inputFiles.size());
result = filesToBeCleaned.get(0);
for (SingleFileSnapshotInfo fileInfo : filesToBeCleaned) {
if ((null != snapshotInfo && (fileInfo.getIndex() >= snapshotInfo.getIndex()) ||
(onlyCleanupMD5Files && null == snapshotInfo))) {
continue;
}
File file = fileInfo.getFile().getPath().toFile();
if (onlyCleanupMD5Files) {
LOG.info("Deleting old md5 file at {}.", file.getAbsolutePath());
FileUtils.deleteFileQuietly(file);
} else {
File md5File = new File(file.getAbsolutePath() + MD5FileUtil.MD5_SUFFIX);
LOG.info("Deleting old snapshot at {}, md5 file at {}.", file.getAbsolutePath(),
md5File.getAbsolutePath());
FileUtils.deleteFileQuietly(file);
FileUtils.deleteFileQuietly(md5File);
}
}
}
return result;
}
};
private final HARaftServer masterRatisServer;
private RaftGroupId raftGroupId;
private final ExecutorService executorService;
private RaftServer mServer;
private final MetaHandler metaHandler;
public StateMachine(HARaftServer ratisServer) {
this.masterRatisServer = ratisServer;
this.metaHandler = ratisServer.getMetaHandler();
this.executorService = ThreadUtils.newDaemonSingleThreadExecutor(
"Master-Meta-StateMachine");
}
/**
* Initializes the State Machine with the given server, group and storage.
*/
@Override
public void initialize(
RaftServer server, RaftGroupId id, RaftStorage raftStorage) throws IOException {
getLifeCycle().startAndTransition(() -> {
super.initialize(server, id, raftStorage);
this.mServer = server;
this.raftGroupId = id;
storage.init(raftStorage);
});
loadSnapshot(storage.getLatestSnapshot());
LOG.info("Initialized State Machine.");
}
@Override
public void reinitialize() throws IOException {
LOG.info("Reinitializing state machine.");
storage.loadLatestSnapshot();
loadSnapshot(storage.getLatestSnapshot());
}
private synchronized void loadSnapshot(SingleFileSnapshotInfo snapshot) throws IOException {
if (snapshot == null) {
return;
}
LOG.info("Loading Snapshot {}.", snapshot);
final File snapshotFile = snapshot.getFile().getPath().toFile();
if (!snapshotFile.exists()) {
throw new FileNotFoundException(
String.format("The snapshot file %s does not exist", snapshotFile.getPath()));
}
try {
setLastAppliedTermIndex(snapshot.getTermIndex());
install(snapshotFile);
} catch (Exception e) {
throw new IOException(String.format("Failed to load snapshot %s", snapshot), e);
}
}
private void install(File snapshotFile) {
try {
metaHandler.loadSnapShot(snapshotFile);
} catch (Exception e) {
LOG.warn("Failed to install snapshot!", e);
}
LOG.info("Successfully installed snapshot!");
}
@Override
public SnapshotInfo getLatestSnapshot() {
return storage.getLatestSnapshot();
}
@Override
public TransactionContext startTransaction(
RaftClientRequest raftClientRequest) throws IOException {
Preconditions.checkArgument(raftClientRequest.getRaftGroupId().equals(
raftGroupId));
return handleStartTransactionRequests(raftClientRequest);
}
/**
* Apply a committed log entry to the state machine.
*/
@Override
public CompletableFuture<Message> applyTransaction(TransactionContext trx) {
try {
ResourceProtos.ResourceRequest request = HAHelper.convertByteStringToRequest(
trx.getStateMachineLogEntry().getLogData());
long trxLogIndex = trx.getLogEntry().getIndex();
// In the current approach we have one single global thread executor.
// with single thread. Right now this is being done for correctness, as
// applyTransaction will be run on multiple Master we want to execute the
// transactions in the same order on all Master, otherwise there is a
// chance that Master replica can be out of sync.
// Ref: from Ozone project (OzoneManagerStateMachine)
CompletableFuture<Message> ratisFuture =
new CompletableFuture<>();
CompletableFuture<ResourceResponse> future = CompletableFuture.supplyAsync(
() -> runCommand(request, trxLogIndex), executorService);
future.thenApply(response -> {
if (!response.getSuccess()) {
LOG.warn("Failed to apply log {} for this raft group {}!",
request.getCmdType(), this.raftGroupId);
}
byte[] responseBytes = response.toByteArray();
ratisFuture.complete(Message.valueOf(ByteString.copyFrom(responseBytes)));
return ratisFuture;
});
return ratisFuture;
} catch (Exception e) {
return completeExceptionally(e);
}
}
/**
* Submits write request to MetaSystem and returns the response Message.
* @param request MasterMetaRequest
* @return response from meta system
*/
@VisibleForTesting
protected ResourceResponse runCommand(ResourceProtos.ResourceRequest request, long trxLogIndex) {
try {
return metaHandler.handleWriteRequest(request);
} catch (Throwable e) {
String errorMessage = "Request " + request + "failed with exception";
ExitUtils.terminate(1, errorMessage, e, LOG);
}
return null;
}
/**
* Query the state machine. The request must be read-only.
*/
@Override
public CompletableFuture<Message> query(Message request) {
try {
byte[] bytes = request.getContent().toByteArray();
return CompletableFuture.completedFuture(
queryCommand(ResourceProtos.ResourceRequest.parseFrom(bytes)));
} catch (IOException e) {
return completeExceptionally(e);
}
}
/**
* Submits read request to MetaSystem and returns the response Message.
* @param request MasterMetaRequest
* @return response from meta system
*/
private Message queryCommand(ResourceProtos.ResourceRequest request) {
ResourceResponse response = metaHandler.handleReadRequest(request);
return HAHelper.convertResponseToMessage(response);
}
/**
* Store the current state as an snapshot file in the stateMachineStorage.
*
* @return the index of the snapshot
*/
@Override
public long takeSnapshot() {
if (mServer.getLifeCycleState() != LifeCycle.State.RUNNING) {
LOG.warn("Skip taking snapshot because raft server is not in running state: "
+ "current state is {}.", mServer.getLifeCycleState());
return RaftLog.INVALID_LOG_INDEX;
}
TermIndex lastTermIndex = getLastAppliedTermIndex();
LOG.debug("Current Snapshot Index {}.", lastTermIndex);
File tempFile;
try {
tempFile = HAHelper.createTempSnapshotFile(storage);
metaHandler.writeToSnapShot(tempFile);
} catch (IOException e) {
LOG.warn("Failed to create temp snapshot file.", e);
return RaftLog.INVALID_LOG_INDEX;
}
LOG.debug("Taking a snapshot to file {}.", tempFile);
final File snapshotFile = storage.getSnapshotFile(
lastTermIndex.getTerm(), lastTermIndex.getIndex());
try {
final MD5Hash digest = MD5FileUtil.computeMd5ForFile(tempFile);
LOG.info("Saving digest {} for snapshot file {}.", digest, snapshotFile);
MD5FileUtil.saveMD5File(snapshotFile, digest);
LOG.info("Renaming a snapshot file {} to {}.", tempFile, snapshotFile);
if (!tempFile.renameTo(snapshotFile)) {
tempFile.delete();
LOG.warn("Failed to rename snapshot from {} to {}.", tempFile, snapshotFile);
return RaftLog.INVALID_LOG_INDEX;
}
} catch (Exception e) {
tempFile.delete();
LOG.warn("Failed to complete snapshot: {}.", snapshotFile, e);
return RaftLog.INVALID_LOG_INDEX;
}
return lastTermIndex.getIndex();
}
/**
* Notifies the state machine that the raft peer is no longer leader.
*/
@Override
public void notifyNotLeader(Collection<TransactionContext> pendingEntries) throws IOException {
masterRatisServer.updateServerRole();
}
/**
* Handle the RaftClientRequest and return TransactionContext object.
* @param raftClientRequest
* @return TransactionContext
*/
private TransactionContext handleStartTransactionRequests(RaftClientRequest raftClientRequest) {
return TransactionContext.newBuilder()
.setClientRequest(raftClientRequest)
.setStateMachine(this)
.setServerRole(RaftProtos.RaftPeerRole.LEADER)
.setLogData(raftClientRequest.getMessage().getContent())
.build();
}
@VisibleForTesting
public void setRaftGroupId(RaftGroupId raftGroupId) {
this.raftGroupId = raftGroupId;
}
private static <T> CompletableFuture<T> completeExceptionally(Exception e) {
final CompletableFuture<T> future = new CompletableFuture<>();
future.completeExceptionally(e);
return future;
}
@Override
public StateMachineStorage getStateMachineStorage() {
return this.storage;
}
}
/**
* Compare snapshot files based on transaction indexes.
* Copy from org.apache.ratis.statemachine.impl.SnapshotFileComparator
*/
class RatisSnapshotFileComparator implements Comparator<SingleFileSnapshotInfo> {
@Override
public int compare(SingleFileSnapshotInfo file1, SingleFileSnapshotInfo file2) {
return (int) (file2.getIndex() - file1.getIndex());
}
}
| 37.881612
| 99
| 0.71268
|
4f312d95449af1a7fa6a17d6797284e820a761ec
| 793
|
package xyz.iotcode.iadmin.common.validated.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import xyz.iotcode.iadmin.common.annotation.validated.IdCard;
/**
* @author 孙金川
* @since 2019年5月8日
*/
public class IdCardValidator implements ConstraintValidator<IdCard, String> {
private boolean notNull;
@Override
public void initialize(IdCard constraintAnnotation) {
this.notNull = constraintAnnotation.notNull();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (StrUtil.isNotBlank(value)) {
return Validator.isCitizenId(value);
}
if (notNull) {
return false;
}
return true;
}
}
| 21.432432
| 77
| 0.765448
|
a365e79d76b7e7e73608e50d8ded5eef000b12cc
| 13,939
|
package Presentacion;
import Negocio.Bitwise;
import javax.swing.JOptionPane;
/**
*
* @author Marcoaf
*/
public class Formulario extends javax.swing.JFrame {
/**
* Creates new form Presentacion
*/
public Bitwise a;
public Formulario() {
a = new Bitwise();
initComponents();
jLabel1.setText(a.toString());
setLocationRelativeTo(null);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated
// Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jComboBox1 = new javax.swing.JComboBox<>();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Bitwise");
jPanel1.setBackground(new java.awt.Color(102, 102, 102));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setText(" X=");
jButton1.setText("Insertar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextField1KeyTyped(evt);
}
});
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { " 1", " 0", "Valor" }));
jLabel2.setText("En la Pos:");
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel3.setText(" Manejo de Bits");
jButton3.setText("<<");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText(">>>");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jLabel6.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
jLabel6.setText("Mover Bits");
jLabel7.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
jButton2.setText(">>");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup().addGap(93, 93, 93).addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 470,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0).addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 74,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(137, 137, 137).addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 70,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel1Layout.createSequentialGroup().addComponent(jButton2).addGap(10,
10, 10)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)))
.addContainerGap(312, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup().addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap()));
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 48,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26).addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2).addComponent(jButton3).addComponent(jButton4)
.addComponent(jLabel6))
.addGap(41, 41, 41)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 42,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel7,
javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(110, 110, 110)));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
pack();
}// </editor-fold>//GEN-END:initComponents
public void bits() {
String s = "";
for (int i = 64; i >= 1; i--) {
if (a.getBit(i) > 0)
s = s + i + ",";
}
// tomamos desde la pos ini hasta la final
s = s.length() > 0 ? s.substring(0, s.length() - 1) : "";
s = "{" + s + "}";
jLabel7.setText("Posiciones de Bits 1 =" + s + " = " + a.Cant1());
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton1ActionPerformed
long x = Integer.parseInt(jTextField1.getText());
switch (jComboBox1.getSelectedIndex()) {
case 0:
a.Set1((int) x);
break;
case 1:
a.Set0((int) x);
break;
case 2:
a.setX(x);
break;
}
bits();
jLabel1.setText(a.toString());
}// GEN-LAST:event_jButton1ActionPerformed
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jTextField1KeyTyped
char c = evt.getKeyChar();
if (Character.isLetter(c)) {
getToolkit().beep();
evt.consume();
JOptionPane.showMessageDialog(rootPane, "Solo ingrese numeros");
}
}// GEN-LAST:event_jTextField1KeyTyped
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton3ActionPerformed
long z = a.getvalor();
z = z << 1;
a.setX(z);
jLabel1.setText(a.toString());
bits();
}// GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton4ActionPerformed
long z = a.getvalor();
z = z >>> 1;
a.setX(z);
jLabel1.setText(a.toString());
bits();
}// GEN-LAST:event_jButton4ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton2ActionPerformed
long z = a.getvalor();
z = z >> 1;
a.setX(z);
jLabel1.setText(a.toString());
bits();
}// GEN-LAST:event_jButton2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
// <editor-fold defaultstate="collapsed" desc=" Look and feel setting code
// (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the default
* look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
}
// </editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Formulario().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
| 48.231834
| 119
| 0.584475
|
55ca4eaaa84a1647d73c70f611a20af0cdf59c6e
| 4,521
|
package org.hisp.dhis.analytics.util;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.hisp.dhis.common.CombinationGenerator;
import org.hisp.dhis.common.DimensionalItemObject;
import org.hisp.dhis.common.DimensionalObject;
import org.hisp.dhis.common.Grid;
import org.hisp.dhis.common.GridHeader;
import org.hisp.dhis.system.grid.ListGrid;
import static org.hisp.dhis.common.DimensionalObjectUtils.getSortedKeysMap;
import static org.hisp.dhis.common.DimensionalObjectUtils.getKey;
import static org.hisp.dhis.common.DimensionalObjectUtils.getName;
/**
* @author Lars Helge Overland
*/
public class GridRenderUtils
{
/**
* Generates a grid according to the provided columns, rows and values.
*
* @param columns the columns.
* @param rows the rows.
* @param valueMap the values as a mapping between metadata key and value.
* @return a grid.
*/
public static Grid asGrid( List<? extends DimensionalObject> columns, List<? extends DimensionalObject> rows, Map<String, Object> valueMap )
{
List<List<DimensionalItemObject>> columnItems = columns.stream()
.map( DimensionalObject::getItems ).collect( Collectors.toList() );
List<List<DimensionalItemObject>> rowItems = rows.stream()
.map( DimensionalObject::getItems ).collect( Collectors.toList() );
List<List<DimensionalItemObject>> gridColumns = CombinationGenerator.newInstance( columnItems ).getCombinations();
List<List<DimensionalItemObject>> gridRows = CombinationGenerator.newInstance( rowItems ).getCombinations();
Map<String, Object> internalValueMap = getSortedKeysMap( valueMap );
Grid grid = new ListGrid();
// ---------------------------------------------------------------------
// Headers
// ---------------------------------------------------------------------
for ( DimensionalObject object : rows )
{
grid.addHeader( new GridHeader( object.getDimension(), object.getDisplayName() ) );
}
for ( List<DimensionalItemObject> column : gridColumns )
{
grid.addHeader( new GridHeader( getKey( column ), getName( column ) ) );
}
// ---------------------------------------------------------------------
// Rows
// ---------------------------------------------------------------------
for ( List<DimensionalItemObject> row : gridRows )
{
grid.addRow();
for ( DimensionalItemObject object : row )
{
grid.addValue( object.getDisplayName() );
}
for ( List<DimensionalItemObject> column : gridColumns )
{
String key = getKey( column, row );
Object value = internalValueMap.get( key );
grid.addValue( value );
}
}
return grid;
}
}
| 40.72973
| 144
| 0.651405
|
4a78735fa87f7cc562959fc221830c2e360714ea
| 116
|
package de.icongmbh.oss.maven.plugin.javassist.stubs;
public class Sub1TransformerStub extends TransformerStub {
}
| 23.2
| 58
| 0.836207
|
006964d5b8d90e376375ae15eedbdc7fad5f5f66
| 1,281
|
package io.walkers.planes.pandora.spring.bean.definition;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
/**
* Bean GC 示例,Bean 回收在关闭 Spring 容器后,由 JVM 进行垃圾回收
*
* @author planeswalker23
* @date 2021/11/18
*/
@Configuration
public class BeanGCDemo {
@Test
public void gc() throws InterruptedException {
// 创建 BeanFactory 容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
// 注册 Configuration Class(配置类)
applicationContext.register(BeanGCDemo.class);
// 启动 Spring 应用上下文
applicationContext.refresh();
// 依赖查找
BeanGCDemo bean = applicationContext.getBean(BeanGCDemo.class);
System.out.println(bean);
// 关闭 Spring 应用上下文
applicationContext.close();
System.out.println("Spring 应用上下文已关闭...");
Thread.sleep(1000L);
// 帮助垃圾收集器进行垃圾回收!!!
bean = null;
// 强制触发 GC
System.gc();
Thread.sleep(1000L);
}
// ---------- Bean 回收 ----------
@Override
protected void finalize() throws Throwable {
System.out.println("当前 BeanGCDemo 对象正在被垃圾回收");
}
}
| 29.113636
| 105
| 0.65886
|
95ab93cb8cef4f8d98922398ab812a78063a084c
| 501
|
package com.shengsiyuan.nio;
import java.nio.IntBuffer;
import java.security.SecureRandom;
public class NioTest1 {
public static void main(String[] args) {
IntBuffer buffer = IntBuffer.allocate(10);
for (int i = 0; i < buffer.capacity(); i++) {
int anInt = new SecureRandom().nextInt(20);
buffer.put(anInt);
}
buffer.flip();
while (buffer.hasRemaining()) {
System.out.println(buffer.get());
}
}
}
| 17.275862
| 55
| 0.572854
|
0ee7459f026e01cc0ac3fccd93dc898a537eecf8
| 225
|
/** Simulate coin flip */
public class Flip {
public static void main(String[] args) {
if (Math.random() < 0.5)
System.out.println("Head");
else
System.out.println("Tail");
}
}
| 22.5
| 44
| 0.528889
|
ffa7ac61e04bd53e2f0070ef790e325b5d822029
| 3,013
|
package com.java110.user.smo.impl;
import com.java110.core.base.smo.BaseServiceSMO;
import com.java110.dto.PageDto;
import com.java110.dto.rentingPoolAttr.RentingPoolAttrDto;
import com.java110.intf.user.IRentingPoolAttrInnerServiceSMO;
import com.java110.po.rentingPoolAttr.RentingPoolAttrPo;
import com.java110.user.dao.IRentingPoolAttrServiceDao;
import com.java110.utils.util.BeanConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @ClassName FloorInnerServiceSMOImpl
* @Description 出租房屋属性内部服务实现类
* @Author wuxw
* @Date 2019/4/24 9:20
* @Version 1.0
* add by wuxw 2019/4/24
**/
@RestController
public class RentingPoolAttrInnerServiceSMOImpl extends BaseServiceSMO implements IRentingPoolAttrInnerServiceSMO {
@Autowired
private IRentingPoolAttrServiceDao rentingPoolAttrServiceDaoImpl;
@Override
public int saveRentingPoolAttr(@RequestBody RentingPoolAttrPo rentingPoolAttrPo) {
int saveFlag = 1;
rentingPoolAttrServiceDaoImpl.saveRentingPoolAttrInfo(BeanConvertUtil.beanCovertMap(rentingPoolAttrPo));
return saveFlag;
}
@Override
public int updateRentingPoolAttr(@RequestBody RentingPoolAttrPo rentingPoolAttrPo) {
int saveFlag = 1;
rentingPoolAttrServiceDaoImpl.updateRentingPoolAttrInfo(BeanConvertUtil.beanCovertMap(rentingPoolAttrPo));
return saveFlag;
}
@Override
public int deleteRentingPoolAttr(@RequestBody RentingPoolAttrPo rentingPoolAttrPo) {
int saveFlag = 1;
rentingPoolAttrPo.setStatusCd("1");
rentingPoolAttrServiceDaoImpl.updateRentingPoolAttrInfo(BeanConvertUtil.beanCovertMap(rentingPoolAttrPo));
return saveFlag;
}
@Override
public List<RentingPoolAttrDto> queryRentingPoolAttrs(@RequestBody RentingPoolAttrDto rentingPoolAttrDto) {
//校验是否传了 分页信息
int page = rentingPoolAttrDto.getPage();
if (page != PageDto.DEFAULT_PAGE) {
rentingPoolAttrDto.setPage((page - 1) * rentingPoolAttrDto.getRow());
}
List<RentingPoolAttrDto> rentingPoolAttrs = BeanConvertUtil.covertBeanList(rentingPoolAttrServiceDaoImpl.getRentingPoolAttrInfo(BeanConvertUtil.beanCovertMap(rentingPoolAttrDto)), RentingPoolAttrDto.class);
return rentingPoolAttrs;
}
@Override
public int queryRentingPoolAttrsCount(@RequestBody RentingPoolAttrDto rentingPoolAttrDto) {
return rentingPoolAttrServiceDaoImpl.queryRentingPoolAttrsCount(BeanConvertUtil.beanCovertMap(rentingPoolAttrDto));
}
public IRentingPoolAttrServiceDao getRentingPoolAttrServiceDaoImpl() {
return rentingPoolAttrServiceDaoImpl;
}
public void setRentingPoolAttrServiceDaoImpl(IRentingPoolAttrServiceDao rentingPoolAttrServiceDaoImpl) {
this.rentingPoolAttrServiceDaoImpl = rentingPoolAttrServiceDaoImpl;
}
}
| 35.869048
| 214
| 0.782277
|
d5a480428fbd5d9a76728bbf922dc11c4dc68967
| 344
|
package com.woowrale.jroomapp.data.datasource;
import com.woowrale.jroomapp.domain.model.Contact;
import java.util.List;
public interface LocalDataSource {
Boolean isEmpty();
void saveContacts(List<Contact> contacts);
List<Contact> getPopularContacts();
Contact findById(Integer id);
void update(Contact contact);
}
| 18.105263
| 50
| 0.747093
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.