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
|
|---|---|---|---|---|---|
e0bd9c7732bb3fc6096d12575ac00236da99492d
| 238
|
package 刷题.待面试.字节跳动;
/**
* https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order/
*
* @author zhushuangquan
*/
public class _21_440_字典序的第K小数字 {
public int findKthNumber(int n, int k) {
return 0;
}
}
| 18.307692
| 75
| 0.668067
|
697ab997972edcad7efdc9fe4946cf76d1341f8f
| 323
|
package com.java110.user.bmo.owner;
import com.alibaba.fastjson.JSONObject;
import com.java110.po.owner.OwnerPo;
import org.springframework.http.ResponseEntity;
public interface IChangeOwnerPhone {
/**
* 修改业主手机号
* @param ownerPo
* @return
*/
ResponseEntity<String> change(OwnerPo ownerPo);
}
| 20.1875
| 51
| 0.718266
|
3a2b9961cf32c72abb7aac769279b04e1f418bf8
| 6,287
|
/*
* Copyright (c) 2017, Harald Kuhr
* 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 copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.imageio.plugins.bmp;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.bmp.BMPImageWriteParam;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.ByteOrder;
/**
* BMPImageWriter
*/
public final class BMPImageWriter extends DIBImageWriter {
protected BMPImageWriter(ImageWriterSpi provider) {
super(provider);
}
@Override
public ImageWriteParam getDefaultWriteParam() {
// We can use the existing BMPImageWriteParam, as it's part of the javax.imageio API.
return new BMPImageWriteParam(getLocale());
}
@Override
public IIOMetadata getDefaultImageMetadata(ImageTypeSpecifier imageType, ImageWriteParam param) {
// TODO
return null;
}
@Override
public IIOMetadata convertImageMetadata(IIOMetadata inData, ImageTypeSpecifier imageType, ImageWriteParam param) {
// TODO: Support both our own and the com.sun.. metadata + standard metadata
return null;
}
@Override
public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
assertOutput();
if (image == null) {
throw new IllegalArgumentException("image may not be null");
}
if (image.hasRaster()) {
// TODO: The default BMPWriter seems to support this, consider doing so as well
throw new UnsupportedOperationException("image has a Raster!");
}
imageOutput.setByteOrder(ByteOrder.LITTLE_ENDIAN);
clearAbortRequest();
processImageStarted(0);
if (param == null) {
param = getDefaultWriteParam();
}
// Default to bottom-up
// TODO: top-down only allowed for RGB and BITFIELDS compressions (not RLE or PNG)!
// Though Windows seems to support top-down for RLE too...
final boolean isTopDown = param instanceof BMPImageWriteParam && ((BMPImageWriteParam) param).isTopDown();
// int compression = DIB.COMPRESSION_ALPHA_BITFIELDS; // BMP can use BIFTFIELDS or ALPHA_BITFIELDS
int compression = DIB.COMPRESSION_RGB;
// TODO: Fix
BufferedImage img = (BufferedImage) image.getRenderedImage();
int height = img.getHeight();
int width = img.getWidth();
// Write File header
// TODO: Always use V4/V5 header, when writing with alpha, to avoid ambiguity
// TODO: Allow writing normal BITMAP_INFO_HEADER_SIZE with "fake" alpha as well?
int infoHeaderSize = DIB.BITMAP_INFO_HEADER_SIZE;
boolean hasExtraMasks = infoHeaderSize == DIB.BITMAP_INFO_HEADER_SIZE && (compression == DIB.COMPRESSION_BITFIELDS || compression == DIB.COMPRESSION_ALPHA_BITFIELDS);
// TODO: Allow writing without file header for ICO/CUR support
writeFileHeader(infoHeaderSize, DIB.BMP_FILE_HEADER_SIZE + infoHeaderSize + width * height * 4, hasExtraMasks);
writeDIBHeader(infoHeaderSize, img.getWidth(), img.getHeight(), isTopDown, img.getColorModel().getPixelSize(), compression);
// writeDIBHeader(infoHeaderSize, img, isTopDown, DIB.COMPRESSION_RGB);
if (hasExtraMasks) {
imageOutput.writeInt(0x000000FF); // B
imageOutput.writeInt(0x0000FF00); // G
imageOutput.writeInt(0x00FF0000); // R
imageOutput.writeInt(0xFF000000); // A
}
writeUncompressed(isTopDown, img, height, width);
processImageComplete();
}
private void writeFileHeader(int infoHeaderSize, int fileSize, boolean hasMasks) throws IOException {
// 14 bytes
imageOutput.writeShort('M' << 8 | 'B');
imageOutput.writeInt(fileSize + (hasMasks ? 16 : 0)); // File size (only known at this time if uncompressed!)
imageOutput.writeShort(0); // Reserved
imageOutput.writeShort(0); // Reserved
imageOutput.writeInt(DIB.BMP_FILE_HEADER_SIZE + infoHeaderSize + (hasMasks ? 16 : 0)); // Offset to image data
}
public static void main(String[] args) throws IOException {
File input = new File(args[0]);
File output = new File(args[0].replace('.', '_') + "_copy.bmp");
try (ImageOutputStream stream = ImageIO.createImageOutputStream(output)) {
DIBImageWriter writer = new BMPImageWriter(null);
writer.setOutput(stream);
writer.write(ImageIO.read(input));
}
}
}
| 41.635762
| 174
| 0.703038
|
539f57131fd7be3ab7aba17808c0139a0e2d36fd
| 3,039
|
/*
* Copyright 2019 Arcus Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package arcus.cornea.model;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
public class TemplateTextField {
/**
* The text the {@link com.iris.client.model.RuleTemplateModel} shows for this portion of the string.
*/
private String text;
/**
* The name of the field according to the resolve attributes.
*/
private String fieldName;
/**
* Used for title casing names/other fields that may want to be title cased.
*/
private boolean properName = false;
/**
* UIHint
*
* If the rule text portion is able to be edited.
*/
private boolean isEditable;
public TemplateTextField(String text, String fieldName, boolean isEditable) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(text));
Preconditions.checkArgument(!Strings.isNullOrEmpty(fieldName));
this.text = text;
this.fieldName = fieldName;
this.isEditable = isEditable;
}
public void setText(String text) {
if (!Strings.isNullOrEmpty(text)) {
this.text = text;
}
}
public String getText() {
return text;
}
public boolean isEditable() {
return isEditable;
}
public String getFieldName() {
return fieldName;
}
public void setProperName(boolean isProperName) {
this.properName = isProperName;
}
public boolean isProperName() {
return properName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TemplateTextField that = (TemplateTextField) o;
if (isEditable != that.isEditable) {
return false;
}
if (!text.equals(that.text)) {
return false;
}
return fieldName.equals(that.fieldName);
}
@Override
public int hashCode() {
int result = text.hashCode();
result = 31 * result + (isEditable ? 1 : 0);
result = 31 * result + fieldName.hashCode();
return result;
}
@Override
public String toString() {
return "TemplateTextField{" +
"text='" + text + '\'' +
", fieldName='" + fieldName + '\'' +
", isEditable=" + isEditable +
'}';
}
}
| 25.974359
| 105
| 0.602172
|
8646514243f8268b5a7cfdbfab69ea678f2369b7
| 11,226
|
package cz.tomkren.fishtron.latticegen;
import net.fishtron.types.Sub;
import net.fishtron.types.Type;
import net.fishtron.types.TypeTerm;
import net.fishtron.types.Types;
import net.fishtron.utils.ABC;
import net.fishtron.utils.Checker;
import net.fishtron.utils.F;
import net.fishtron.utils.Log;
import org.json.JSONObject;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/** Created by tom on 13. 9. 2016.*/
public class LSolverTester {
// TODO decide (2)
private static int initNextVarDecision_forTesting(Type t) {
return t.getNextVarId(); // vs. return 0;
}
private static final Gamma g_testGamma = Gamma.mk(
"s", "(a -> (b -> c)) -> ((a -> b) -> (a -> c))",
"k", "a -> (b -> a)",
"seri", "(Dag a b) -> ((Dag b c) -> (Dag a c))",
"para", "(Dag a b) -> ((Dag c d) -> (Dag (P a c) (P b d))",
"mkDag", "(a -> b) -> (Dag a b)",
"deDag", "(Dag a b) -> (a -> b)",
"mkP", "a -> (b -> (P a b))",
"fst", "(P a b) -> a",
"snd", "(P a b) -> b"
);
private static final Type g_testGoal = Types.parse("(P A (P A A)) -> (P A (P A A))");
public static void main(String[] args) {
main_2();
}
private static void main_sep_290_256() {
//todo - ale už vim že je to vázaný na caching....
Checker ch = new Checker();
boolean isCachingUsed = true;
LSolver.Opts opts = new LSolver.Opts(isCachingUsed, true);
LSolver s = new LSolver(opts, g_testGamma, ch.getRandom());
}
private static void main_1() {
boolean wasOk = true;
int k = 6;
int seed = 0;//452;
while (wasOk) {
wasOk = separateError_strictlyWellTyped(seed, g_testGamma, k, g_testGoal, LSolver.Opts.mkDefault());
Log.it("----------------------------------");
seed++;
}
}
private static void main_2() {
Checker ch = new Checker(7404398919224944163L);
LSolver.Opts opts = LSolver.Opts.mkDefault();
testNormalizations(ch);
tests_subs_1(ch, opts);
tests_subs_k(ch, opts);
tests_treeGenerating(ch, 6, 100, opts);
ch.results();
}
private static boolean separateError_strictlyWellTyped(int seed, Gamma gamma, int k, Type t, LSolver.Opts opts) {
Checker ch = new Checker((long) seed);
LSolver s = new LSolver(opts, gamma, ch.getRandom());
boolean wasOk = true;
AppTree newTree = s.genOne(k, t);
if (newTree != null) {
boolean isStrictlyWellTyped = newTree.isStrictlyWellTyped(gamma);
ch.is(isStrictlyWellTyped, "Is tree strictly well typed?");
JSONObject typeTrace = newTree.getTypeTrace();
Log.it(typeTrace);
if (!isStrictlyWellTyped) {
Log.it("tree is not strictly well-typed: " + newTree + "\n" + typeTrace.toString());
AppTree.writeErrorTreeToFile(typeTrace);
wasOk = false;
}
}
if (!wasOk) {
ch.results();
}
return wasOk;
}
private static void tests_treeGenerating(
Checker ch,int k_max, int numSamples, LSolver.Opts opts)
{
Log.it("\n== TREE GENERATING TESTS =======================================================\n");
Type t = Types.parse("(P A (P A A)) -> (P A (P A A))");
for (int k = 1; k <= k_max; k++) {
testTreeGenerating(ch, k, t, g_testGamma, numSamples,opts);
}
}
private static void testTreeGenerating(Checker ch, int k, Type t, Gamma gamma, int numSamples, LSolver.Opts opts) {
String argStr = "("+k+", "+t+")";
LSolver s = new LSolver(opts, gamma, ch.getRandom());
Log.it_noln("s.num"+argStr+" = ");
BigInteger num = s.getNum(k, t, initNextVarDecision_forTesting(t));
Log.it(num);
Log.it_noln("s.generateOne"+argStr+" = ");
AppTree tree = s.genOne(k, t);
Log.it(tree);
if (F.isZero(num) || tree == null) {
ch.is(F.isZero(num) && tree == null, "num = 0 iff genOne = null");
}
if (!F.isZero(num) && num.compareTo(BigInteger.valueOf(100000)) < 0) {
int intNum = num.intValueExact();
Log.it_noln("|s.ts_k"+argStr+"| = ");
List<ABC<String,Sub,Integer>> allTrees = s.ts_k(k,t, initNextVarDecision_forTesting(t));
Log.it(allTrees.size());
ch.is(tree != null, "genOne not null");
ch.is(intNum == allTrees.size(), "num = |genAll|");
if (intNum < 40000) {
Map<String,Integer> testMap = new TreeMap<>();
for (ABC<String,Sub,Integer> tree_p : allTrees) {
testMap.put(tree_p._1(),0);
}
//Log.list(allTrees);
double sampleRate = ((double)numSamples) / intNum;
boolean allGeneratedWereInGenAll = true;
boolean allTreesWereStrictlyWellTyped = true;
for (int i = 0; i < numSamples; i++){
if ((i+1)%100 == 0) {
Log.it(i+1);
}
AppTree newTree = s.genOne(k, t);
if (newTree != null) {
if (!newTree.isStrictlyWellTyped(gamma)) {
ch.fail("tree is not strictly well-typed: "+newTree+"\n"+newTree.getTypeTrace().toString());
allTreesWereStrictlyWellTyped = false;
}
String key = newTree.toRawString();
if (testMap.containsKey(key)) {
testMap.compute(key, (_key,n) -> n+1);
} else {
allGeneratedWereInGenAll = false;
ch.fail(key +" is not in genAll list.");
}
} else {
ch.fail("generated tree is null");
}
}
ch.is(allGeneratedWereInGenAll,"All generated trees were in GenAll list.");
ch.is(allTreesWereStrictlyWellTyped,"All trees were strictly well typed.");
Log.it("\nSample rate : "+ sampleRate);
for (Map.Entry<String,Integer> e : testMap.entrySet()) {
String tree_p = e.getKey();
int numGenerated = e.getValue();
Log.it(tree_p +" "+ numGenerated);
}
}
}
Log.it();
}
private static void tests_subs_k(Checker ch, LSolver.Opts opts) {
Log.it("\n== ts_k & subs_k tests ===================================================\n");
Gamma gamma1 = Gamma.mk(
"f", "X -> X",
"seri", "(a -> b) -> ((b -> c) -> (a -> c))"
);
test_ts_k(ch, 1, "X -> X", gamma1, opts);
test_ts_k(ch, 2, "X -> X", gamma1, opts);
test_ts_k(ch, 3, "X -> X", gamma1, opts);
}
private static void tests_subs_1(Checker ch, LSolver.Opts opts) {
Log.it("\n== ts_1 & subs_1 tests ===================================================\n");
Gamma gamma1 = Gamma.mk(
"s", "(a -> (b -> c)) -> ((a -> b) -> (a -> c))",
"s2","(x5 -> (x0 -> x1)) -> ((x5 -> x0) -> (x5 -> x1))",
"s3","(y5 -> (x0 -> x1)) -> ((y5 -> x0) -> (y5 -> x1))",
"k", "a -> (b -> a)",
"k2","x1 -> (x0 -> x1)",
"+", "Int -> (Int -> Int)",
"42", "Int",
"magicVal", "alpha"
);
test_ts_k(ch, 1, "Int -> Int", gamma1, opts);
test_ts_k(ch, 1, "x1 -> x0", gamma1, opts);
}
private static void test_ts_k(Checker ch, int k, String tStr, Gamma gamma, LSolver.Opts opts) {
test_ts_k(ch, k, Types.parse(tStr), gamma, opts);
}
private static void test_ts_k(Checker ch, int k, Type t, Gamma gamma, LSolver.Opts opts) {
NF p_nf = new NF(opts.isNormalizationPerformed(), t);
Type t_nf = p_nf.getTypeInNF();
Sub t2nf = p_nf.getToNF();
Log.it();
Log.it("-- LIB gamma -------------");
Log.listLn(gamma.getSymbols());
Log.it("-- GOAL TYPE t -----");
Log.it("t: "+t);
Log.it("t_nf: "+t_nf);
Log.it("t2nf: "+t2nf);
ch.it(t2nf.apply(t), t_nf.toString());
Log.it();
List<ABC<String, Sub,Integer>> ts = LSolver.ts_k(gamma).apply(k, t_nf, initNextVarDecision_forTesting(t_nf));
Log.it("-- ts_"+k+"(gamma, t_nf) ------------");
Log.listLn(ts);
List<ABC<BigInteger,Sub,Integer>> subs = LSolver.subs_k(gamma).apply(k, t_nf, initNextVarDecision_forTesting(t_nf));
Log.it("-- subs_"+k+"(gamma, t_nf) ----------");
Log.listLn(subs);
Log.it("Creating LSolver ... initial state:");
LSolver solver = new LSolver(opts, gamma, ch.getRandom());
Log.it(solver);
List<ABC<BigInteger,Sub,Integer>> subs2 = solver.subs_k(k, t_nf, initNextVarDecision_forTesting(t_nf));
Log.it("-- LSolver.subs_"+k+"(gamma, t_nf) ----------");
Log.listLn(subs);
Log.it("... LSolver after subs_k call:");
Log.it(solver);
ch.list(subs2,subs);
Log.it("-------------------------------------------------------");
}
private static void testNormalizations(Checker ch) {
Log.it("\n== normalization tests ===================================================\n");
Type t1 = Types.parse("(x111 -> (x11 -> x1)) -> ((x111 -> x11) -> (x111 -> x1))");
Type t2 = Types.parse("(x0 -> (x11 -> x1)) -> ((x0 -> x11) -> (x0 -> x1))");
Type t3 = Types.parse("(x2 -> (x1 -> x0)) -> ((x2 -> x1) -> (x2 -> x0))");
Type t4 = Types.parse("(x2 -> (x0 -> x1)) -> ((x2 -> x0) -> (x2 -> x1))");
ch.it(t1);
ch.it(((TypeTerm)t1).fold(Object::toString, Object::toString) +"\n");
checkNormalisation(ch, t1);
checkNormalisation(ch, t2);
checkNormalisation(ch, t3);
checkNormalisation(ch, t4);
checkNormalisation(ch, "(x1 -> (x4 -> (x4 -> (x5 -> (x66 -> (x0 -> (x0 -> (x3 -> (x77 -> (x4 -> (x66 -> (x5 -> (x77 -> (x88 -> (x1 -> x2)))))))))))))))");
checkNormalisation(ch, "(x10 -> (x0 -> (x4 -> (x55 -> (x4 -> (x55 -> (x0 -> (x33 -> (x8 -> (x7 -> (x6 -> (x5 -> (x7 -> (x8 -> (x6 -> x2)))))))))))))))");
}
private static void checkNormalisation(Checker ch, String tStr) {
checkNormalisation(ch, Types.parse(tStr));
}
private static void checkNormalisation(Checker ch, Type t) {
NF p = new NF(t);
Type typeInNF = p.getTypeInNF();
Sub toNF = p.getToNF();
Sub fromNF = p.getFromNF();
ch.it(t);
ch.it(typeInNF);
ch.it(toNF);
Log.it("----------------------------------");
ch.it(toNF.apply(t),typeInNF.toString());
ch.it(fromNF.apply(toNF.apply(t)),t.toString());
Log.it();
}
}
| 32.53913
| 162
| 0.485035
|
29056a57f609dc9573bdb9ad2f2cc6c84f7de659
| 580
|
package com.eagle.adventurersamulets.api.amp;
import net.minecraft.item.ItemStack;
public interface IAMPItem {
/**
* Returns the amount of AMP stored in the ItemStack.
*/
int getCurrentAMP(ItemStack itemStack);
/**
* Returns the maximum amount of AMP that can be stored in the ItemStack.
*/
int getMaximumAMP(ItemStack itemStack);
/**
* Sets the current AMP in the ItemStack.
*/
void setCurrentAMP(ItemStack itemStack, int amp);
/**
* Returns the type of AMP the ItemStack can receive.
*/
IAMPType getAMPType(ItemStack itemStack);
}
| 20.714286
| 75
| 0.703448
|
438d0f5c3d5717495efb1ad7eda3e21efabdef4a
| 15,362
|
package urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.opendaylight.yangtools.concepts.Builder;
import org.opendaylight.yangtools.yang.binding.Augmentation;
import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
import org.opendaylight.yangtools.yang.binding.DataObject;
import com.fasterxml.jackson.annotation.JsonProperty;
import urn.ietf.params.xml.ns.yang.nfvo.mano.types.rev150423.PlacementGroupInfo.Strategy;
import urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.placement.groups.MemberVnfd;
/**
* Class that builds {@link urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups} instances.
*
* @see urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups
*
*/
public class PlacementGroupsBuilder implements Builder<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups> {
private PlacementGroupsKey _key;
private List<MemberVnfd> _memberVnfd;
private java.lang.String _name;
private java.lang.String _requirement;
private Strategy _strategy;
Map<java.lang.Class<? extends Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>>, Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>> augmentation = Collections.emptyMap();
public PlacementGroupsBuilder() {
}
public PlacementGroupsBuilder(urn.ietf.params.xml.ns.yang.nfvo.mano.types.rev150423.PlacementGroupInfo arg) {
this._name = arg.getName();
this._requirement = arg.getRequirement();
this._strategy = arg.getStrategy();
}
public PlacementGroupsBuilder(PlacementGroups base) {
if (base.getKey() == null) {
this._key = new PlacementGroupsKey(
base.getName()
);
this._name = base.getName();
} else {
this._key = base.getKey();
this._name = _key.getName();
}
this._memberVnfd = base.getMemberVnfd();
this._requirement = base.getRequirement();
this._strategy = base.getStrategy();
if (base instanceof PlacementGroupsImpl) {
PlacementGroupsImpl impl = (PlacementGroupsImpl) base;
if (!impl.augmentation.isEmpty()) {
this.augmentation = new HashMap<>(impl.augmentation);
}
} else if (base instanceof AugmentationHolder) {
@SuppressWarnings("unchecked")
AugmentationHolder<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups> casted =(AugmentationHolder<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>) base;
if (!casted.augmentations().isEmpty()) {
this.augmentation = new HashMap<>(casted.augmentations());
}
}
}
/**
*Set fields from given grouping argument. Valid argument is instance of one of following types:
* <ul>
* <li>org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.nfvo.mano.types.rev150423.PlacementGroupInfo</li>
* </ul>
*
* @param arg grouping object
* @throws IllegalArgumentException if given argument is none of valid types
*/
public void fieldsFrom(DataObject arg) {
boolean isValidArg = false;
if (arg instanceof urn.ietf.params.xml.ns.yang.nfvo.mano.types.rev150423.PlacementGroupInfo) {
this._name = ((urn.ietf.params.xml.ns.yang.nfvo.mano.types.rev150423.PlacementGroupInfo)arg).getName();
this._requirement = ((urn.ietf.params.xml.ns.yang.nfvo.mano.types.rev150423.PlacementGroupInfo)arg).getRequirement();
this._strategy = ((urn.ietf.params.xml.ns.yang.nfvo.mano.types.rev150423.PlacementGroupInfo)arg).getStrategy();
isValidArg = true;
}
if (!isValidArg) {
throw new IllegalArgumentException(
"expected one of: [org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.nfvo.mano.types.rev150423.PlacementGroupInfo] \n" +
"but was: " + arg
);
}
}
public PlacementGroupsKey getKey() {
return _key;
}
public List<MemberVnfd> getMemberVnfd() {
return _memberVnfd;
}
public java.lang.String getName() {
return _name;
}
public java.lang.String getRequirement() {
return _requirement;
}
public Strategy getStrategy() {
return _strategy;
}
@SuppressWarnings("unchecked")
public <E extends Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>> E getAugmentation(java.lang.Class<E> augmentationType) {
if (augmentationType == null) {
throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!");
}
return (E) augmentation.get(augmentationType);
}
public PlacementGroupsBuilder setKey(final PlacementGroupsKey value) {
this._key = value;
return this;
}
public PlacementGroupsBuilder setMemberVnfd(final List<MemberVnfd> value) {
this._memberVnfd = value;
return this;
}
public PlacementGroupsBuilder setName(final java.lang.String value) {
this._name = value;
return this;
}
public PlacementGroupsBuilder setRequirement(final java.lang.String value) {
this._requirement = value;
return this;
}
public PlacementGroupsBuilder setStrategy(final Strategy value) {
this._strategy = value;
return this;
}
public PlacementGroupsBuilder addAugmentation(java.lang.Class<? extends Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>> augmentationType, Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups> augmentationValue) {
if (augmentationValue == null) {
return removeAugmentation(augmentationType);
}
if (!(this.augmentation instanceof HashMap)) {
this.augmentation = new HashMap<>();
}
this.augmentation.put(augmentationType, augmentationValue);
return this;
}
public PlacementGroupsBuilder removeAugmentation(java.lang.Class<? extends Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>> augmentationType) {
if (this.augmentation instanceof HashMap) {
this.augmentation.remove(augmentationType);
}
return this;
}
@Override
public PlacementGroups build() {
return new PlacementGroupsImpl(this);
}
public static final class PlacementGroupsImpl implements PlacementGroups {
@Override
public java.lang.Class<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups> getImplementedInterface() {
return urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups.class;
}
private final PlacementGroupsKey _key;
@JsonProperty("member-vnfd")
private final List<MemberVnfd> _memberVnfd;
@JsonProperty("name")
private final java.lang.String _name;
@JsonProperty("requirement")
private final java.lang.String _requirement;
@JsonProperty("strategy")
private final Strategy _strategy;
private Map<java.lang.Class<? extends Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>>, Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>> augmentation = Collections.emptyMap();
private PlacementGroupsImpl(PlacementGroupsBuilder base) {
if (base.getKey() == null) {
this._key = new PlacementGroupsKey(
base.getName()
);
this._name = base.getName();
} else {
this._key = base.getKey();
this._name = _key.getName();
}
this._memberVnfd = base.getMemberVnfd();
this._requirement = base.getRequirement();
this._strategy = base.getStrategy();
switch (base.augmentation.size()) {
case 0:
this.augmentation = Collections.emptyMap();
break;
case 1:
final Map.Entry<java.lang.Class<? extends Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>>, Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>> e = base.augmentation.entrySet().iterator().next();
this.augmentation = Collections.<java.lang.Class<? extends Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>>, Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>>singletonMap(e.getKey(), e.getValue());
break;
default :
this.augmentation = new HashMap<>(base.augmentation);
}
}
public PlacementGroupsImpl(){
this( new PlacementGroupsBuilder() );
}
@Override
public PlacementGroupsKey getKey() {
return _key;
}
@Override
public List<MemberVnfd> getMemberVnfd() {
return _memberVnfd;
}
@Override
public java.lang.String getName() {
return _name;
}
@Override
public java.lang.String getRequirement() {
return _requirement;
}
@Override
public Strategy getStrategy() {
return _strategy;
}
@SuppressWarnings("unchecked")
@Override
public <E extends Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>> E getAugmentation(java.lang.Class<E> augmentationType) {
if (augmentationType == null) {
throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!");
}
return (E) augmentation.get(augmentationType);
}
private int hash = 0;
private volatile boolean hashValid = false;
@Override
public int hashCode() {
if (hashValid) {
return hash;
}
final int prime = 31;
int result = 1;
result = prime * result + Objects.hashCode(_key);
result = prime * result + Objects.hashCode(_memberVnfd);
result = prime * result + Objects.hashCode(_name);
result = prime * result + Objects.hashCode(_requirement);
result = prime * result + Objects.hashCode(_strategy);
result = prime * result + Objects.hashCode(augmentation);
hash = result;
hashValid = true;
return result;
}
@Override
public boolean equals(java.lang.Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DataObject)) {
return false;
}
if (!urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups.class.equals(((DataObject)obj).getImplementedInterface())) {
return false;
}
urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups other = (urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups)obj;
if (!Objects.equals(_key, other.getKey())) {
return false;
}
if (!Objects.equals(_memberVnfd, other.getMemberVnfd())) {
return false;
}
if (!Objects.equals(_name, other.getName())) {
return false;
}
if (!Objects.equals(_requirement, other.getRequirement())) {
return false;
}
if (!Objects.equals(_strategy, other.getStrategy())) {
return false;
}
if (getClass() == obj.getClass()) {
// Simple case: we are comparing against self
PlacementGroupsImpl otherImpl = (PlacementGroupsImpl) obj;
if (!Objects.equals(augmentation, otherImpl.augmentation)) {
return false;
}
} else {
// Hard case: compare our augments with presence there...
for (Map.Entry<java.lang.Class<? extends Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>>, Augmentation<urn.ietf.params.xml.ns.yang.nfvo.nsd.rev141027.nsd.descriptor.PlacementGroups>> e : augmentation.entrySet()) {
if (!e.getValue().equals(other.getAugmentation(e.getKey()))) {
return false;
}
}
// .. and give the other one the chance to do the same
if (!obj.equals(this)) {
return false;
}
}
return true;
}
@Override
public java.lang.String toString() {
java.lang.String name = "PlacementGroups [";
java.lang.StringBuilder builder = new java.lang.StringBuilder (name);
if (_key != null) {
builder.append("_key=");
builder.append(_key);
builder.append(", ");
}
if (_memberVnfd != null) {
builder.append("_memberVnfd=");
builder.append(_memberVnfd);
builder.append(", ");
}
if (_name != null) {
builder.append("_name=");
builder.append(_name);
builder.append(", ");
}
if (_requirement != null) {
builder.append("_requirement=");
builder.append(_requirement);
builder.append(", ");
}
if (_strategy != null) {
builder.append("_strategy=");
builder.append(_strategy);
}
final int builderLength = builder.length();
final int builderAdditionalLength = builder.substring(name.length(), builderLength).length();
if (builderAdditionalLength > 2 && !builder.substring(builderLength - 2, builderLength).equals(", ")) {
builder.append(", ");
}
builder.append("augmentation=");
builder.append(augmentation.values());
return builder.append(']').toString();
}
}
}
| 41.407008
| 301
| 0.59543
|
2d501864c1d1b96164f3ed3d87d95747d490b697
| 7,021
|
package com.hdw.common.exception;
import com.hdw.common.result.ResultMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.io.IOException;
/**
* @Description 全局异常拦截处理器
* @Author TuMinglong
* @Date 2018/12/10 14:01
*/
@ControllerAdvice
//@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 处理自定义异常
*/
@ExceptionHandler(GlobalException.class)
public ResultMap handleGlobalException(GlobalException e){
ResultMap r = new ResultMap();
r.put("code", e.getCode());
r.put("msg", e.getMessage());
return r;
}
@ExceptionHandler(NoHandlerFoundException.class)
public ResultMap handlerNoFoundException(Exception e) {
logger.error(e.getMessage(), e);
return ResultMap.error(404, "路径不存在,请检查路径是否正确");
}
@ExceptionHandler(DuplicateKeyException.class)
public ResultMap handleDuplicateKeyException(DuplicateKeyException e){
logger.error(e.getMessage(), e);
return ResultMap.error("数据库中已存在该记录");
}
@ExceptionHandler(Exception.class)
public ResultMap handleException(Exception e){
logger.error(e.getMessage(), e);
return ResultMap.error();
}
/**
* 运行异常
* @param e
* @return
*/
@ExceptionHandler(value = RuntimeException.class)
public ResultMap handleGlobalException(RuntimeException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "运行异常");
}
/**
* 空指针异常
* @param e
* @return
*/
@ExceptionHandler(NullPointerException.class)
public ResultMap handlerNullPointerException(NullPointerException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "空指针异常");
}
/**
* 类型转换异常
* @param e
* @return
*/
@ExceptionHandler(ClassCastException.class)
public ResultMap handlerClassCastException(ClassCastException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "类型转换异常");
}
/**
* IO异常
* @param e
* @return
*/
@ExceptionHandler(IOException.class)
public ResultMap handlerIOException(IOException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "IO异常");
}
/**
* 未知方法异常
* @param e
* @return
*/
@ExceptionHandler(NoSuchMethodException.class)
public ResultMap handlerNoSuchMethodException(NoSuchMethodException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "未知方法异常");
}
/**
* 数组越界异常
* @param e
* @return
*/
@ExceptionHandler(IndexOutOfBoundsException.class)
public ResultMap handlerIndexOutOfBoundsException(IndexOutOfBoundsException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "数组越界异常");
}
/**
* 400错误
* @param e
* @return
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResultMap handlerRequestNotReadable(HttpMessageNotReadableException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(400, "http消息不可读异常");
}
/**
* 类型匹配异常
* @param e
* @return
*/
@ExceptionHandler(TypeMismatchException.class)
public ResultMap handlerRequestTypeMismatch(TypeMismatchException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(400, "类型匹配异常");
}
/**
* 错误服务请求参数异常
* @param e
* @return
*/
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResultMap handlerRequestMissingServletRequest(MissingServletRequestParameterException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(400, "错误服务请求参数异常");
}
/**
*不支持的request请求异常
* @param e
* @return
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResultMap handlerRequest405(HttpRequestMethodNotSupportedException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(405, "不支持的request方法请求异常");
}
/**
* 不可接受的HTTP协议异常
* @param e
* @return
*/
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
public ResultMap handlerRequest406(HttpMediaTypeNotAcceptableException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(406, "不可接受的HTTP协议异常");
}
/**
* 转换不支持异常
* @param e
* @return
*/
@ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
public ResultMap handlerServer500(RuntimeException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "转换不支持异常");
}
/**
* 栈溢出异常
* @param e
* @return
*/
@ExceptionHandler(StackOverflowError.class)
public ResultMap handlerRequestStackOverflow(StackOverflowError e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "栈溢出异常");
}
/**
* hibernate validator异常
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResultMap handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "hibernate validator异常");
}
/**
* 数据绑定异常
* @param e
* @return
*/
@ExceptionHandler(BindException.class)
public ResultMap bindExceptionHandler(BindException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "数据绑定异常");
}
/**
* 超过最大上传数量异常
* @param e
* @return
*/
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResultMap maxUploadSizeExceededExceptionHandler(MaxUploadSizeExceededException e) {
logger.error(e.getMessage(), e);
return ResultMap.error(500, "超过最大上传数量异常");
}
}
| 29.012397
| 101
| 0.683663
|
3f5c418e2c37efc38fbbb028dfa13a6de56f72ac
| 2,088
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.policyinsights.v2018_07_01_preview;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Policy evaluation details.
*/
public class PolicyEvaluationDetails {
/**
* Details of the evaluated expressions.
*/
@JsonProperty(value = "evaluatedExpressions")
private List<ExpressionEvaluationDetails> evaluatedExpressions;
/**
* Evaluation details of IfNotExists effect.
*/
@JsonProperty(value = "ifNotExistsDetails")
private IfNotExistsEvaluationDetails ifNotExistsDetails;
/**
* Get details of the evaluated expressions.
*
* @return the evaluatedExpressions value
*/
public List<ExpressionEvaluationDetails> evaluatedExpressions() {
return this.evaluatedExpressions;
}
/**
* Set details of the evaluated expressions.
*
* @param evaluatedExpressions the evaluatedExpressions value to set
* @return the PolicyEvaluationDetails object itself.
*/
public PolicyEvaluationDetails withEvaluatedExpressions(List<ExpressionEvaluationDetails> evaluatedExpressions) {
this.evaluatedExpressions = evaluatedExpressions;
return this;
}
/**
* Get evaluation details of IfNotExists effect.
*
* @return the ifNotExistsDetails value
*/
public IfNotExistsEvaluationDetails ifNotExistsDetails() {
return this.ifNotExistsDetails;
}
/**
* Set evaluation details of IfNotExists effect.
*
* @param ifNotExistsDetails the ifNotExistsDetails value to set
* @return the PolicyEvaluationDetails object itself.
*/
public PolicyEvaluationDetails withIfNotExistsDetails(IfNotExistsEvaluationDetails ifNotExistsDetails) {
this.ifNotExistsDetails = ifNotExistsDetails;
return this;
}
}
| 29.408451
| 117
| 0.715996
|
5caf0de62220f94ae341614d7b0749d253147223
| 3,202
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.wildfly.test.cloud.microprofile.reactive.messaging.strimzi;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.wildfly.test.cloud.common.KubernetesResource;
import org.wildfly.test.cloud.common.Resource;
import org.wildfly.test.cloud.common.ResourceType;
import org.wildfly.test.cloud.common.WildFlyCloudTestCase;
import org.wildfly.test.cloud.common.WildFlyKubernetesIntegrationTest;
import io.restassured.RestAssured;
import io.restassured.http.Headers;
import io.restassured.response.Response;
/**
* @author <a href="mailto:kabir.khan@jboss.com">Kabir Khan</a>
*/
@WildFlyKubernetesIntegrationTest(
namespace = "kafka",
kubernetesResources = {
@KubernetesResource(definitionLocation = "https://strimzi.io/install/latest?namespace=kafka"),
@KubernetesResource(
definitionLocation = "src/test/container/strimzi-cluster.yml",
additionalResourcesCreated = {
@Resource(type = ResourceType.DEPLOYMENT, name = "my-cluster-entity-operator")
}),
@KubernetesResource(definitionLocation = "src/test/container/strimzi-topic.yml")
})
public class ReactiveMessagingWithStrimziIT extends WildFlyCloudTestCase {
@Test
public void test() throws Exception {
int status = getHelper().doWithWebPortForward("one",
url -> RestAssured.given().header("Content-Type", MediaType.TEXT_PLAIN).post(url).getStatusCode());
Assertions.assertEquals(200, status);
status = getHelper().doWithWebPortForward("two",
url -> RestAssured.given().header("Content-Type", MediaType.TEXT_PLAIN).post(url).getStatusCode());
Assertions.assertEquals(200, status);
List<String> list = new ArrayList<>();
long end = System.currentTimeMillis() + 20000;
while (list.size() != 2 && System.currentTimeMillis() < end) {
list = getHelper().doWithWebPortForward("", url -> {
Response r = RestAssured.get(url);
Assertions.assertEquals(200, r.getStatusCode());
return r.as(List.class);
});
Thread.sleep(1000);
}
Assertions.assertArrayEquals(new String[]{"one", "two"}, list.toArray(new String[list.size()]));
}
}
| 41.051282
| 115
| 0.674891
|
2ffb91ef47dad22a1bca998f94686ff8e6639447
| 23,129
|
/**
* 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.zookeeper.server;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.jute.Record;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.proto.ReplyHeader;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.persistence.Util;
import org.apache.zookeeper.server.util.ZxidUtils;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.txn.SetDataTxn;
import org.apache.zookeeper.txn.TxnHeader;
import org.jboss.netty.channel.Channel;
import org.junit.Assert;
import org.junit.Test;
/**
* Test stand-alone server.
*
*/
public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
protected static final Logger LOG =
LoggerFactory.getLogger(ZooKeeperServerMainTest.class);
public static class MainThread extends Thread {
final File confFile;
final TestZKSMain main;
final File tmpDir;
final File dataDir;
final File logDir;
public MainThread(int clientPort, boolean preCreateDirs) throws IOException {
this(clientPort, preCreateDirs, ClientBase.createTmpDir());
}
public MainThread(int clientPort, boolean preCreateDirs, File tmpDir) throws IOException {
super("Standalone server with clientPort:" + clientPort);
this.tmpDir = tmpDir;
confFile = new File(this.tmpDir, "zoo.cfg");
FileWriter fwriter = new FileWriter(confFile);
fwriter.write("tickTime=2000\n");
fwriter.write("initLimit=10\n");
fwriter.write("syncLimit=5\n");
dataDir = new File(this.tmpDir, "data");
logDir = new File(dataDir.toString() + "_txnlog");
if (preCreateDirs) {
if (!dataDir.mkdir()) {
throw new IOException("unable to mkdir " + dataDir);
}
if (!logDir.mkdir()) {
throw new IOException("unable to mkdir " + logDir);
}
}
String dataDirPath = dataDir.toString();
String logDirPath = logDir.toString();
// Convert windows path to UNIX to avoid problems with "\"
String osname = java.lang.System.getProperty("os.name");
if (osname.toLowerCase().contains("windows")) {
dataDirPath = dataDirPath.replace('\\', '/');
logDirPath = logDirPath.replace('\\', '/');
}
fwriter.write("dataDir=" + dataDirPath + "\n");
fwriter.write("dataLogDir=" + logDirPath + "\n");
fwriter.write("clientPort=" + clientPort + "\n");
fwriter.flush();
fwriter.close();
main = new TestZKSMain();
}
public void run() {
String args[] = new String[1];
args[0] = confFile.toString();
try {
main.initializeAndRun(args);
} catch (Exception e) {
// test will still fail even though we just log/ignore
LOG.error("unexpected exception in run", e);
}
}
public void shutdown() throws IOException {
main.shutdown();
}
void deleteDirs() throws IOException{
delete(tmpDir);
}
void delete(File f) throws IOException {
if (f.isDirectory()) {
for (File c : f.listFiles())
delete(c);
}
if (!f.delete())
// double check for the file existence
if (f.exists()) {
throw new IOException("Failed to delete file: " + f);
}
}
ServerCnxnFactory getCnxnFactory() {
return main.getCnxnFactory();
}
}
public static class TestZKSMain extends ZooKeeperServerMain {
public void shutdown() {
super.shutdown();
}
}
/**
* Test case for https://issues.apache.org/jira/browse/ZOOKEEPER-2247.
* Test to verify that even after non recoverable error (error while
* writing transaction log) on ZooKeeper service will be available
*/
@Test(timeout = 30000)
public void testNonRecoverableError() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
MainThread main = new MainThread(CLIENT_PORT, true);
main.start();
Assert.assertTrue("waiting for server being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
CONNECTION_TIMEOUT));
ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
ClientBase.CONNECTION_TIMEOUT, this);
zk.create("/foo1", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Assert.assertEquals(new String(zk.getData("/foo1", null, null)), "foobar");
// inject problem in server
ZooKeeperServer zooKeeperServer = main.getCnxnFactory()
.getZooKeeperServer();
FileTxnSnapLog snapLog = zooKeeperServer.getTxnLogFactory();
FileTxnSnapLog fileTxnSnapLogWithError = new FileTxnSnapLog(
snapLog.getDataDir(), snapLog.getSnapDir()) {
@Override
public void commit() throws IOException {
throw new IOException("Input/output error");
}
};
ZKDatabase newDB = new ZKDatabase(fileTxnSnapLogWithError);
zooKeeperServer.setZKDatabase(newDB);
try {
// do create operation, so that injected IOException is thrown
zk.create("/foo2", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
fail("IOException is expected as error is injected in transaction log commit funtionality");
} catch (Exception e) {
// do nothing
}
zk.close();
Assert.assertTrue("waiting for server down",
ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
ClientBase.CONNECTION_TIMEOUT));
fileTxnSnapLogWithError.close();
main.shutdown();
main.deleteDirs();
}
/**
* Tests that the ZooKeeper server will fail to start if the
* snapshot directory is read only.
*
* This test will fail if it is executed as root user.
*/
@Test(timeout = 30000)
public void testReadOnlySnapshotDir() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
// Start up the ZK server to automatically create the necessary directories
// and capture the directory where data is stored
MainThread main = new MainThread(CLIENT_PORT, true);
File tmpDir = main.tmpDir;
main.start();
Assert.assertTrue("waiting for server being up", ClientBase
.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
CONNECTION_TIMEOUT / 2));
main.shutdown();
// Make the snapshot directory read only
File snapDir = new File(main.dataDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
snapDir.setWritable(false);
// Restart ZK and observe a failure
main = new MainThread(CLIENT_PORT, false, tmpDir);
main.start();
Assert.assertFalse("waiting for server being up", ClientBase
.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
CONNECTION_TIMEOUT / 2));
main.shutdown();
snapDir.setWritable(true);
main.deleteDirs();
}
/**
* Tests that the ZooKeeper server will fail to start if the
* transaction log directory is read only.
*
* This test will fail if it is executed as root user.
*/
@Test(timeout = 30000)
public void testReadOnlyTxnLogDir() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
// Start up the ZK server to automatically create the necessary directories
// and capture the directory where data is stored
MainThread main = new MainThread(CLIENT_PORT, true);
File tmpDir = main.tmpDir;
main.start();
Assert.assertTrue("waiting for server being up", ClientBase
.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
CONNECTION_TIMEOUT / 2));
main.shutdown();
// Make the transaction log directory read only
File logDir = new File(main.logDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
logDir.setWritable(false);
// Restart ZK and observe a failure
main = new MainThread(CLIENT_PORT, false, tmpDir);
main.start();
Assert.assertFalse("waiting for server being up", ClientBase
.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
CONNECTION_TIMEOUT / 2));
main.shutdown();
logDir.setWritable(true);
main.deleteDirs();
}
/**
* Verify the ability to start a standalone server instance.
*/
@Test
public void testStandalone() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
MainThread main = new MainThread(CLIENT_PORT, true);
main.start();
Assert.assertTrue("waiting for server being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
CONNECTION_TIMEOUT));
ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
ClientBase.CONNECTION_TIMEOUT, this);
zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Assert.assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
zk.close();
main.shutdown();
main.join();
main.deleteDirs();
Assert.assertTrue("waiting for server down",
ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
ClientBase.CONNECTION_TIMEOUT));
}
/**
* Test verifies the auto creation of data dir and data log dir.
*/
@Test(timeout = 30000)
public void testAutoCreateDataLogDir() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
MainThread main = new MainThread(CLIENT_PORT, false);
String args[] = new String[1];
args[0] = main.confFile.toString();
main.start();
Assert.assertTrue("waiting for server being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
CONNECTION_TIMEOUT));
ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
ClientBase.CONNECTION_TIMEOUT, this);
zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Assert.assertEquals(new String(zk.getData("/foo", null, null)),
"foobar");
zk.close();
main.shutdown();
main.join();
main.deleteDirs();
Assert.assertTrue("waiting for server down", ClientBase
.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
ClientBase.CONNECTION_TIMEOUT));
}
@Test
public void testJMXRegistrationWithNIO() throws Exception {
ClientBase.setupTestEnv();
File tmpDir_1 = ClientBase.createTmpDir();
ServerCnxnFactory server_1 = startServer(tmpDir_1);
File tmpDir_2 = ClientBase.createTmpDir();
ServerCnxnFactory server_2 = startServer(tmpDir_2);
server_1.shutdown();
server_2.shutdown();
deleteFile(tmpDir_1);
deleteFile(tmpDir_2);
}
@Test
public void testJMXRegistrationWithNetty() throws Exception {
String originalServerCnxnFactory = System
.getProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
NettyServerCnxnFactory.class.getName());
try {
ClientBase.setupTestEnv();
File tmpDir_1 = ClientBase.createTmpDir();
ServerCnxnFactory server_1 = startServer(tmpDir_1);
File tmpDir_2 = ClientBase.createTmpDir();
ServerCnxnFactory server_2 = startServer(tmpDir_2);
server_1.shutdown();
server_2.shutdown();
deleteFile(tmpDir_1);
deleteFile(tmpDir_2);
} finally {
// setting back
if (originalServerCnxnFactory == null
|| originalServerCnxnFactory.isEmpty()) {
System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
} else {
System.setProperty(
ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
originalServerCnxnFactory);
}
}
}
/**
* Test case to verify that ZooKeeper server is able to shutdown properly
* when there are pending request(s) in the RequestProcessor chain.
*
* {@link https://issues.apache.org/jira/browse/ZOOKEEPER-2347}
*/
@Test(timeout = 30000)
public void testRaceBetweenSyncFlushAndZKShutdown() throws Exception {
File tmpDir = ClientBase.createTmpDir();
File testDir = File.createTempFile("test", ".dir", tmpDir);
testDir.delete();
// Following are the sequence of steps to simulate the deadlock
// situation - SyncRequestProcessor#shutdown holds a lock and waits on
// FinalRequestProcessor to complete a pending operation, which in turn
// also needs the ZooKeeperServer lock
// 1. start zk server
FileTxnSnapLog ftsl = new FileTxnSnapLog(testDir, testDir);
final SimpleZooKeeperServer zkServer = new SimpleZooKeeperServer(ftsl);
zkServer.startup();
// 2. Wait for setting up request processor chain. At the end of setup,
// it will add a mock request into the chain
// 3. Also, waiting for FinalRequestProcessor to start processing request
zkServer.waitForFinalProcessRequest();
// 4. Above step ensures that there is a request in the processor chain.
// Now invoke shutdown, which will acquire zks lock
Thread shutdownThread = new Thread() {
public void run() {
zkServer.shutdown();
};
};
shutdownThread.start();
// 5. Wait for SyncRequestProcessor to trigger shutdown function.
// This is to ensure that zks lock is acquired
zkServer.waitForSyncReqProcessorShutdown();
// 6. Now resume FinalRequestProcessor which in turn call
// zks#decInProcess() function and tries to acquire zks lock.
// This results in deadlock
zkServer.resumeFinalProcessRequest();
// 7. Waiting to finish server shutdown. Testing that
// SyncRequestProcessor#shutdown holds a lock and waits on
// FinalRequestProcessor to complete a pending operation, which in turn
// also needs the ZooKeeperServer lock
shutdownThread.join();
}
private class SimpleZooKeeperServer extends ZooKeeperServer {
private SimpleSyncRequestProcessor syncProcessor;
private SimpleFinalRequestProcessor finalProcessor;
SimpleZooKeeperServer(FileTxnSnapLog ftsl) throws IOException {
super(ftsl, 2000, 2000, 4000, null, new ZKDatabase(ftsl));
}
@Override
protected void setupRequestProcessors() {
finalProcessor = new SimpleFinalRequestProcessor(this);
syncProcessor = new SimpleSyncRequestProcessor(this,
finalProcessor);
syncProcessor.start();
firstProcessor = new PrepRequestProcessor(this, syncProcessor);
((PrepRequestProcessor) firstProcessor).start();
// add request to the chain
addRequestToSyncProcessor();
}
private void addRequestToSyncProcessor() {
long zxid = ZxidUtils.makeZxid(3, 7);
TxnHeader hdr = new TxnHeader(1, 1, zxid, 1,
ZooDefs.OpCode.setData);
Record txn = new SetDataTxn("/foo" + zxid, new byte[0], 1);
byte[] buf;
try {
buf = Util.marshallTxnEntry(hdr, txn);
} catch (IOException e) {
LOG.error("IOException while adding request to SyncRequestProcessor", e);
Assert.fail("IOException while adding request to SyncRequestProcessor!");
return;
}
NettyServerCnxnFactory factory = new NettyServerCnxnFactory();
final MockNettyServerCnxn nettyCnxn = new MockNettyServerCnxn(null,
this, factory);
Request req = new Request(nettyCnxn, 1, 1, ZooDefs.OpCode.setData,
ByteBuffer.wrap(buf), null);
req.hdr = hdr;
req.txn = txn;
syncProcessor.processRequest(req);
}
void waitForFinalProcessRequest() throws InterruptedException {
Assert.assertTrue("Waiting for FinalRequestProcessor to start processing request",
finalProcessor.waitForProcessRequestToBeCalled());
}
void waitForSyncReqProcessorShutdown() throws InterruptedException {
Assert.assertTrue("Waiting for SyncRequestProcessor to shut down",
syncProcessor.waitForShutdownToBeCalled());
}
void resumeFinalProcessRequest() throws InterruptedException {
finalProcessor.resumeProcessRequest();
}
}
private class MockNettyServerCnxn extends NettyServerCnxn {
public MockNettyServerCnxn(Channel channel, ZooKeeperServer zks,
NettyServerCnxnFactory factory) {
super(null, null, factory);
}
@Override
protected synchronized void updateStatsForResponse(long cxid, long zxid,
String op, long start, long end) {
return;
}
@Override
public synchronized void sendResponse(ReplyHeader h, Record r,
String tag) {
return;
}
}
private class SimpleFinalRequestProcessor extends FinalRequestProcessor {
private CountDownLatch finalReqProcessCalled = new CountDownLatch(1);
private CountDownLatch resumeFinalReqProcess = new CountDownLatch(1);
private volatile boolean interrupted = false;
public SimpleFinalRequestProcessor(ZooKeeperServer zks) {
super(zks);
}
@Override
public void processRequest(Request request) {
finalReqProcessCalled.countDown();
try {
resumeFinalReqProcess.await(ClientBase.CONNECTION_TIMEOUT,
TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
LOG.error("Interrupted while waiting to process request", e);
interrupted = true; // Marked as interrupted
resumeFinalReqProcess.countDown();
return;
}
super.processRequest(request);
}
boolean waitForProcessRequestToBeCalled() throws InterruptedException {
return finalReqProcessCalled.await(ClientBase.CONNECTION_TIMEOUT,
TimeUnit.MILLISECONDS);
}
void resumeProcessRequest() throws InterruptedException {
resumeFinalReqProcess.countDown();
resumeFinalReqProcess.await(ClientBase.CONNECTION_TIMEOUT,
TimeUnit.MILLISECONDS);
Assert.assertFalse("Interrupted while waiting to process request",
interrupted);
}
}
private class SimpleSyncRequestProcessor extends SyncRequestProcessor {
private final CountDownLatch shutdownCalled = new CountDownLatch(1);
public SimpleSyncRequestProcessor(ZooKeeperServer zks,
RequestProcessor nextProcessor) {
super(zks, nextProcessor);
}
@Override
public void shutdown() {
shutdownCalled.countDown();
super.shutdown();
}
boolean waitForShutdownToBeCalled() throws InterruptedException {
return shutdownCalled.await(ClientBase.CONNECTION_TIMEOUT / 3,
TimeUnit.MILLISECONDS);
}
}
private void deleteFile(File f) throws IOException {
if (f.isDirectory()) {
for (File c : f.listFiles())
deleteFile(c);
}
if (!f.delete())
// double check for the file existence
if (f.exists()) {
throw new IOException("Failed to delete file: " + f);
}
}
private ServerCnxnFactory startServer(File tmpDir) throws IOException,
InterruptedException {
final int CLIENT_PORT = PortAssignment.unique();
ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(CLIENT_PORT, -1);
f.startup(zks);
Assert.assertNotNull("JMX initialization failed!", zks.jmxServerBean);
Assert.assertTrue("waiting for server being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
CONNECTION_TIMEOUT));
return f;
}
public void process(WatchedEvent event) {
// ignore for this test
}
}
| 37.547078
| 104
| 0.619006
|
1f06c7a10389f4ee59d7e380c9d21c0a78cd888f
| 1,420
|
package com.sap.cloud.lm.sl.cf.process.steps;
import java.util.List;
import org.cloudfoundry.client.lib.domain.CloudApplication;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.sap.cloud.lm.sl.cf.process.Constants;
import com.sap.cloud.lm.sl.cf.process.message.Messages;
import com.sap.cloud.lm.sl.common.util.JsonUtil;
@Component("prepareToUndeployAppsStep")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class PrepareToUndeployAppsStep extends SyncActivitiStep {
@Override
protected StepPhase executeStep(ExecutionWrapper execution) {
List<CloudApplication> appsToUndeploy = StepsUtil.getAppsToUndeploy(execution.getContext());
getStepLogger().debug(Messages.APPS_TO_UNDEPLOY, JsonUtil.toJson(appsToUndeploy, true));
prepareAppsToUndeploy(execution.getContext(), appsToUndeploy);
return StepPhase.DONE;
}
private void prepareAppsToUndeploy(DelegateExecution context, List<CloudApplication> appsToUndeploy) {
context.setVariable(Constants.VAR_APPS_TO_UNDEPLOY_COUNT, appsToUndeploy.size());
context.setVariable(Constants.VAR_APPS_TO_UNDEPLOY_INDEX, 0);
context.setVariable(Constants.VAR_INDEX_VARIABLE_NAME, Constants.VAR_APPS_TO_UNDEPLOY_INDEX);
}
}
| 40.571429
| 106
| 0.800704
|
f73d9bbc161becea462c06bd82cc7dbe5ea63a7b
| 3,060
|
/**
* 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.xml.security.encryption;
/**
* <code>CipherData</code> provides encrypted data. It must either contain the
* encrypted octet sequence as base64 encoded text of the
* <code>CipherValue</code> element, or provide a reference to an external
* location containing the encrypted octet sequence via the
* <code>CipherReference</code> element.
* <p>
* The schema definition is as follows:
* <xmp>
* <element name='CipherData' type='xenc:CipherDataType'/>
* <complexType name='CipherDataType'>
* <choice>
* <element name='CipherValue' type='base64Binary'/>
* <element ref='xenc:CipherReference'/>
* </choice>
* </complexType>
* </xmp>
*
* @author Axl Mattheus
*/
public interface CipherData {
/** VALUE_TYPE ASN */
int VALUE_TYPE = 0x00000001;
/** REFERENCE_TYPE ASN */
int REFERENCE_TYPE = 0x00000002;
/**
* Returns the type of encrypted data contained in the
* <code>CipherData</code>.
*
* @return <code>VALUE_TYPE</code> if the encrypted data is contained as
* <code>CipherValue</code> or <code>REFERENCE_TYPE</code> if the
* encrypted data is contained as <code>CipherReference</code>.
*/
int getDataType();
/**
* Returns the cipher value as a base64 encoded <code>byte</code> array.
*
* @return the <code>CipherData</code>'s value.
*/
CipherValue getCipherValue();
/**
* Sets the <code>CipherData</code>'s value.
*
* @param value the value of the <code>CipherData</code>.
* @throws XMLEncryptionException
*/
void setCipherValue(CipherValue value) throws XMLEncryptionException;
/**
* Returns a reference to an external location containing the encrypted
* octet sequence (<code>byte</code> array).
*
* @return the reference to an external location containing the encrypted
* octet sequence.
*/
CipherReference getCipherReference();
/**
* Sets the <code>CipherData</code>'s reference.
*
* @param reference an external location containing the encrypted octet sequence.
* @throws XMLEncryptionException
*/
void setCipherReference(CipherReference reference) throws XMLEncryptionException;
}
| 33.26087
| 85
| 0.688889
|
a646dc6b2d2381dacd317fcc4f329a6bb0d051c9
| 3,109
|
package com.heaven7.android.glew.app;
import android.app.Activity;
import android.opengl.GLES20;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.microedition.khronos.opengles.GL10;
public abstract class IGLRender implements GLSurfaceView.Renderer {
protected final Activity context;
public IGLRender(Activity context) {
this.context = context;
}
protected int mProgram;
public int getRenderMode(){
return GLSurfaceView.RENDERMODE_CONTINUOUSLY;
}
public int getEGLVersion(){
return 3;
}
public void setUp(Runnable next){
next.run();
}
public GLSurfaceView createGLSurfaceView(Activity activity) {
return new GLSurfaceView(activity);
}
public void loadAndLinkShaderFromAssets(String vertexPath, String fragPath){
String vertex = loadTextFromAsset(vertexPath);
String frag = loadTextFromAsset(fragPath);
linkProgram(vertex, frag);
}
public int linkProgram(String vertexShader, String fragShader){
int verS = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);
if (verS != 0) {
GLES20.glShaderSource(verS, vertexShader);
GLES20.glCompileShader(verS);
}else {
throw new IllegalStateException("glCreateShader(GL_VERTEX_SHADER) error");
}
int fragS = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);
if (fragS != 0) {
GLES20.glShaderSource(fragS, fragShader);
GLES20.glCompileShader(fragS);
}else {
throw new IllegalStateException("glCreateShader(GL_FRAGMENT_SHADER) error");
}
mProgram = GLES20.glCreateProgram();
if (mProgram != 0) {
GLES20.glAttachShader(mProgram, verS);
GLES20.glAttachShader(mProgram, fragS);
GLES20.glLinkProgram(mProgram);
}else {
throw new IllegalStateException("glCreateProgram error");
}
return mProgram;
}
public String loadTextFromAsset(String fname) {
String result = null;
try {
InputStream in = context.getAssets().open(fname);
int ch = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((ch = in.read()) != -1) {
baos.write(ch);
}
byte[] buff = baos.toByteArray();
baos.close();
in.close();
result = new String(buff, "UTF-8");
result = result.replaceAll("\\r\\n", "\n");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void checkGlError(String glOperation) {
int error;
while ((error = GLES30.glGetError()) != GLES30.GL_NO_ERROR) {
Log.e("IGLRender", glOperation + ": glError " + error);
throw new RuntimeException(glOperation + ": glError " + error);
}
}
public void onDestroy() {
}
}
| 29.609524
| 88
| 0.616919
|
d85cfd460df913ebb6ee97bf6b8901be2b326630
| 8,682
|
// This file was automatically generated from IFCDOC at https://technical.buildingsmart.org/.
// Very slight modifications were made to made content align with ifcXML reference examples.
// Use this class library to create IFC-compliant (web) applications with XML and JSON data.
// Author: Pieter Pauwels, Eindhoven University of Technology
package com.buildingsmart.tech.ifc.IfcDateTimeResource;
import com.buildingsmart.tech.annotations.DataMember;
import com.buildingsmart.tech.annotations.Description;
import com.buildingsmart.tech.annotations.Guid;
import com.buildingsmart.tech.ifc.IfcMeasureResource.IfcBoolean;
import com.buildingsmart.tech.ifc.IfcMeasureResource.IfcLabel;
import com.buildingsmart.tech.ifc.IfcMeasureResource.IfcPositiveRatioMeasure;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
@Guid("d5120875-1fc0-4135-8be9-51f5bd59fc0c")
@JsonIgnoreProperties(ignoreUnknown=true)
public class IfcResourceTime extends IfcSchedulingTime
{
@Description("Indicates the total work (e.g. person-hours) allocated to the task on behalf of the resource. Note: this is not necessarily the same as the task duration (IfcTaskTime.ScheduleDuration); it may vary according to the resource usage ratio and other resources assigned to the task.")
@DataMember(Order = 0)
@Guid("4b4bfb0c-4091-4fff-a712-fe4f2a6ab96e")
@JacksonXmlProperty(isAttribute=false, localName = "scheduleWork")
private IfcDuration scheduleWork;
@Description("Indicates the amount of the resource used concurrently. For example, 100% means 1 worker, 300% means 3 workers, 50% means half of 1 worker's time for scenarios where multitasking is feasible. If not provided, then the usage ratio is considered to be 100%.")
@DataMember(Order = 1)
@Guid("de98a5df-400e-4d81-917e-b5a94759d675")
@JacksonXmlProperty(isAttribute=false, localName = "scheduleUsage")
private IfcPositiveRatioMeasure scheduleUsage;
@Description("Indicates the time when the resource is scheduled to start working.")
@DataMember(Order = 2)
@Guid("d5861bd0-7d6c-40c8-9b69-1904295e0d92")
@JacksonXmlProperty(isAttribute=false, localName = "scheduleStart")
private IfcDateTime scheduleStart;
@Description("Indicates the time when the resource is scheduled to finish working.")
@DataMember(Order = 3)
@Guid("45829cf5-93e2-4391-bff7-547516787758")
@JacksonXmlProperty(isAttribute=false, localName = "scheduleFinish")
private IfcDateTime scheduleFinish;
@Description("Indicates how a resource should be leveled over time by adjusting the resource usage according to a specified curve. Standard values include: 'Flat', 'BackLoaded', 'FrontLoaded', 'DoublePeak', 'EarlyPeak', 'LatePeak', 'Bell', and 'Turtle'. Custom values may specify a custom name or formula.")
@DataMember(Order = 4)
@Guid("162cf71d-e04c-4489-84e3-5cdad4978cee")
@JacksonXmlProperty(isAttribute=false, localName = "scheduleContour")
private IfcLabel scheduleContour;
@Description("Indicates a delay in the ScheduleStart caused by leveling.")
@DataMember(Order = 5)
@Guid("f46b3261-321d-4a92-bacc-06ccd902aafc")
@JacksonXmlProperty(isAttribute=false, localName = "levelingDelay")
private IfcDuration levelingDelay;
@Description("Indicates that the resource is scheduled in excess of its capacity.")
@DataMember(Order = 6)
@Guid("7af92579-02b6-4fca-a69f-4c670bb7aa78")
@JacksonXmlProperty(isAttribute=false, localName = "isOverAllocated")
private IfcBoolean isOverAllocated;
@Description("Indicates the date and time for which status values are applicable; particularly completion, actual, and remaining values. If values are time-phased (the referencing IfcConstructionResource has associated time series values for attributes), then the status values may be determined from such time-phased data as of the StatusTime.")
@DataMember(Order = 7)
@Guid("cf3f1225-d2b5-4b1f-8ac3-4a2f01807ca7")
@JacksonXmlProperty(isAttribute=false, localName = "statusTime")
private IfcDateTime statusTime;
@Description("Indicates the actual work performed by the resource as of the StatusTime.")
@DataMember(Order = 8)
@Guid("b21864c5-499d-4d90-8593-9eeedfd3c29d")
@JacksonXmlProperty(isAttribute=false, localName = "actualWork")
private IfcDuration actualWork;
@Description("Indicates the actual amount of the resource used concurrently.")
@DataMember(Order = 9)
@Guid("6a504f50-8aac-406c-9874-26733470043c")
@JacksonXmlProperty(isAttribute=false, localName = "actualUsage")
private IfcPositiveRatioMeasure actualUsage;
@Description("Indicates the time when the resource actually started working.")
@DataMember(Order = 10)
@Guid("e137ba6a-c21b-4606-aa20-b9e7c30e0881")
@JacksonXmlProperty(isAttribute=false, localName = "actualStart")
private IfcDateTime actualStart;
@Description("Indicates the time when the resource actually finished working.")
@DataMember(Order = 11)
@Guid("a5335e6f-18fd-4d92-ba1d-ea662f05df7a")
@JacksonXmlProperty(isAttribute=false, localName = "actualFinish")
private IfcDateTime actualFinish;
@Description("Indicates the work remaining to be completed by the resource.")
@DataMember(Order = 12)
@Guid("920d1d67-aec5-4c96-9b9d-d2a8c61bc3ea")
@JacksonXmlProperty(isAttribute=false, localName = "remainingWork")
private IfcDuration remainingWork;
@DataMember(Order = 13)
@Guid("3f98d797-f920-4f52-9739-48be47b047e3")
@JacksonXmlProperty(isAttribute=false, localName = "remainingUsage")
private IfcPositiveRatioMeasure remainingUsage;
@Description("Indicates the percent completion of this resource. If the resource is assigned to a task, then indicates completion of the task on behalf of the resource; if the resource is partitioned into sub-allocations, then indicates overall completion of sub-allocations.")
@DataMember(Order = 14)
@Guid("2a9a0478-4070-40f3-b8c8-736ceb9d9c9d")
@JacksonXmlProperty(isAttribute=false, localName = "completion")
private IfcPositiveRatioMeasure completion;
public IfcResourceTime()
{
}
public IfcDuration getScheduleWork() {
return this.scheduleWork;
}
public void setScheduleWork(IfcDuration scheduleWork) {
this.scheduleWork = scheduleWork;
}
public IfcPositiveRatioMeasure getScheduleUsage() {
return this.scheduleUsage;
}
public void setScheduleUsage(IfcPositiveRatioMeasure scheduleUsage) {
this.scheduleUsage = scheduleUsage;
}
public IfcDateTime getScheduleStart() {
return this.scheduleStart;
}
public void setScheduleStart(IfcDateTime scheduleStart) {
this.scheduleStart = scheduleStart;
}
public IfcDateTime getScheduleFinish() {
return this.scheduleFinish;
}
public void setScheduleFinish(IfcDateTime scheduleFinish) {
this.scheduleFinish = scheduleFinish;
}
public IfcLabel getScheduleContour() {
return this.scheduleContour;
}
public void setScheduleContour(IfcLabel scheduleContour) {
this.scheduleContour = scheduleContour;
}
public IfcDuration getLevelingDelay() {
return this.levelingDelay;
}
public void setLevelingDelay(IfcDuration levelingDelay) {
this.levelingDelay = levelingDelay;
}
public IfcBoolean getIsOverAllocated() {
return this.isOverAllocated;
}
public void setIsOverAllocated(IfcBoolean isOverAllocated) {
this.isOverAllocated = isOverAllocated;
}
public IfcDateTime getStatusTime() {
return this.statusTime;
}
public void setStatusTime(IfcDateTime statusTime) {
this.statusTime = statusTime;
}
public IfcDuration getActualWork() {
return this.actualWork;
}
public void setActualWork(IfcDuration actualWork) {
this.actualWork = actualWork;
}
public IfcPositiveRatioMeasure getActualUsage() {
return this.actualUsage;
}
public void setActualUsage(IfcPositiveRatioMeasure actualUsage) {
this.actualUsage = actualUsage;
}
public IfcDateTime getActualStart() {
return this.actualStart;
}
public void setActualStart(IfcDateTime actualStart) {
this.actualStart = actualStart;
}
public IfcDateTime getActualFinish() {
return this.actualFinish;
}
public void setActualFinish(IfcDateTime actualFinish) {
this.actualFinish = actualFinish;
}
public IfcDuration getRemainingWork() {
return this.remainingWork;
}
public void setRemainingWork(IfcDuration remainingWork) {
this.remainingWork = remainingWork;
}
public IfcPositiveRatioMeasure getRemainingUsage() {
return this.remainingUsage;
}
public void setRemainingUsage(IfcPositiveRatioMeasure remainingUsage) {
this.remainingUsage = remainingUsage;
}
public IfcPositiveRatioMeasure getCompletion() {
return this.completion;
}
public void setCompletion(IfcPositiveRatioMeasure completion) {
this.completion = completion;
}
}
| 36.478992
| 348
| 0.792329
|
141cf898663555b2bad5bef1ba320a594f7aa1b1
| 4,396
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
import com.ctre.phoenix.motorcontrol.NeutralMode;
import com.ctre.phoenix.motorcontrol.TalonFXInvertType;
import edu.wpi.first.math.kinematics.DifferentialDriveKinematics;
/**
* The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean
* constants. This class should not be used for any other purpose. All constants should be declared
* globally (i.e. public static). Do not put anything functional in this class.
*
* <p>It is advised to statically import this class (or one of its inner classes) wherever the
* constants are needed, to reduce verbosity.
*/
public final class Constants {
public static final boolean DEBUG = false;
// MOTORS
// Drive Motors
// LEFT
public static final int LLEADER = 1;
public static final int LFOLLOWER = 2;
public static final int L2FOLLOWER = 3;
// RIGHT
public static final int RLEADER = 4;
public static final int RFOLLOWER = 5;
public static final int R2FOLLOWER = 6;
//OTHER MOTORS
//Climb Motors
public static final int CLEADER = 13;
public static final int CFOLLOWER = 14;
//GREGS REQUEST
public static final int INTAKE = 7;
// Shooter
public static final int LeftShoot = 8;// temporary value will fill in later.
public static final int RightShoot = 9;
//Feed
public static final int BeltNeo = 10;
public static final int WheelNeo = 11;
//Indexer
public static final int Indexer = 12;//Temporary subject to change.
//Shooter Velocity
public static final double spinupVel = 1600.0; //Bottom Goal
public static final double spinupVel2 = 3100.0;//Top Goal
public static final double spinUpVel3 = 3000.0;//top fender
// JOYSTICKS
public static final int DRIVEJS = 1;
public static final int DRIVEMP = 0;
// SENSORS
public static final int IMU = 0;
// PARAMETERS
public static final TalonFXInvertType LEFT_INVERTED = TalonFXInvertType.Clockwise;
public static final TalonFXInvertType RIGHT_INVERTED = TalonFXInvertType.CounterClockwise;
public static final NeutralMode MOTOR_MODE = NeutralMode.Coast;
public static final int UNITS_PER_REVOLUTION = 2048;
public static final double WHEEL_CIRC_METERS = 0.478;
public static final double WHEEL_GEAR_RATIO = 12.27;
// LIMELIGHT
// height of the lime light from the ground, in meters
// public static final double LIME_HEIGHTM = 0.1397; // small chassis
// // x axis angle of limelight from the horizontal plane
// public static final double LIME_ANGLE = 511;
// height of the high goal (8ft 8in, 264cm) in meters
public static final double HIGHGOAL_HEIGHTM = 2.416; //2.416 is real goal height
// the optimal shooting distance from the high goal for shooting into the high goal, roughly around tarmac line, in meters
public static final double OPTIMAL_SHOOTING_DISTANCEM = 2;
// offsets for the x and y angle crosshair of the limelight, changing where the target should be for optimal shooting, in degs
public static final double X_CROSS_OFFSET = 0;
public static final double Y_CROSS_OFFSET = 0;
//large chassis
public static final double LIME_HEIGHTM = 0.762;
public static final double LIME_ANGLE = 59.198; // old is 65.64 //old 60.612 // 1.143 to goal, 1.27 del hight
// PATH FOLLOWING CONSTANTS
public static final double kTrackWidthMeters = 0.584;
public static final DifferentialDriveKinematics kDriveKinematics = new DifferentialDriveKinematics(kTrackWidthMeters);
// Feedback
public static final double ksVolts = 0.22;
public static final double kvVoltSecondsPerMeter = 1.98;
public static final double kaVoltSecondsSquaredPerMeter = 0.2;
public static final double kPDriveVel = 8.5;
// Robot Speed
public static final double kMaxSpeedMetersPerSecond = 3;
public static final double kMaxAccelerationMetersPerSecondSquared = 3;
// Ramsete Controller
public static final double kRamseteB = 2;
public static final double kRamseteZeta = 0.7;
}
| 40.703704
| 130
| 0.713376
|
060d68796fb59999e7bf65a9a8435a9084707bc2
| 372
|
package ru.job4j.array;
/**
* Square.
*
* @author Maksym Mateiuk (maxymmateuk@gmail.com)
*/
public class Square {
public int[] calculate(int bound) {
int[] rst = new int[bound];
int start = 1;
for (int i = 0; i < rst.length; i++) {
rst[i] = (int) Math.pow(start, 2);
start++;
}
return rst;
}
}
| 18.6
| 49
| 0.497312
|
4bca49a5b83298c4716609b946cfcca177675aed
| 2,462
|
/*
* ported to v0.56
* using automatic conversion tool v0.01
*/
package WIP.mame056.sndhrdw;
import static arcadeflex056.fucPtr.*;
import static mame056.sound.samples.*;
import static mame056.sound.samplesH.*;
public class gotya
{
public static class gotya_sample
{
public int sound_command;
public int channel;
public int looping;
public gotya_sample(int sound_command, int channel, int looping){
this.sound_command = sound_command;
this.channel = channel;
this.looping = looping;
}
};
static gotya_sample gotya_samples[] =
{
new gotya_sample( 0x01, 0, 0 ),
new gotya_sample( 0x02, 1, 0 ),
new gotya_sample( 0x03, 2, 0 ),
new gotya_sample( 0x05, 2, 0 ),
new gotya_sample( 0x06, 3, 0 ),
new gotya_sample( 0x07, 3, 0 ),
new gotya_sample( 0x08, 0, 1 ),
new gotya_sample( 0x0a, 0, 0 ),
new gotya_sample( 0x0b, 0, 0 ),
/* all the speech can go to one channel? */
new gotya_sample( 0x10, 3, 0 ),
new gotya_sample( 0x11, 3, 0 ),
new gotya_sample( 0x12, 0, 0 ), /* this should stop the main tune */
new gotya_sample( 0x13, 3, 0 ),
new gotya_sample( 0x14, 3, 0 ),
new gotya_sample( 0x15, 3, 0 ),
new gotya_sample( 0x16, 3, 0 ),
new gotya_sample( 0x17, 3, 0 ),
new gotya_sample( 0x18, 3, 0 ),
new gotya_sample( 0x19, 3, 0 ),
new gotya_sample( 0x1a, 3, 0 )
//{ -1, 0, 0 ) /* end of array */
};
static int theme_playing;
public static WriteHandlerPtr gotya_soundlatch_w = new WriteHandlerPtr() {public void handler(int offset, int data)
{
int sample_number;
if (data == 0)
{
sample_stop(0);
theme_playing = 0;
return;
}
/* search for sample to play */
for (sample_number = 0;
gotya_samples[sample_number].sound_command != -1;
sample_number++)
{
if (gotya_samples[sample_number].sound_command == data)
{
if (gotya_samples[sample_number].looping != 0 &&
theme_playing != 0)
{
/* don't restart main theme */
return;
}
sample_start(gotya_samples[sample_number].channel,
sample_number,
gotya_samples[sample_number].looping);
if (gotya_samples[sample_number].channel == 0)
{
theme_playing = gotya_samples[sample_number].looping;
}
return;
}
}
} };
}
| 24.868687
| 117
| 0.594232
|
b0e6a4c0ae062a6874b7386ebee2964b10ea54db
| 6,912
|
package com.ruoyi.project.device.devList.controller;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.jwt.JwtUtil;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.device.devList.domain.DevList;
import com.ruoyi.project.device.devList.service.IDevListService;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 硬件 信息操作处理
*
* @author ruoyi
* @date 2019-04-08
*/
@Controller
@RequestMapping("/device/devList")
public class DevListController extends BaseController
{
private String prefix = "device/devList";
@Autowired
private IDevListService devListService;
@RequiresPermissions("device:devList:view")
@GetMapping()
public String devList()
{
return prefix + "/devList";
}
/**
* 查询硬件列表
*/
@RequiresPermissions("device:devList:list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(DevList devList,HttpServletRequest request)
{
startPage();
List<DevList> list = devListService.selectDevListList(devList,request);
return getDataTable(list);
}
/**
* 导出硬件列表
*/
@RequiresPermissions("device:devList:export")
@PostMapping("/export")
@ResponseBody
public AjaxResult export(DevList devList,HttpServletRequest request)
{
List<DevList> list = devListService.selectDevListList(devList,request);
ExcelUtil<DevList> util = new ExcelUtil<DevList>(DevList.class);
return util.exportExcel(list, "devList");
}
/**
* 添加
* @return
*/
@GetMapping("/add")
public String add(){
return prefix+"/add";
}
/**
* 新增保存硬件
*/
@RequiresPermissions("device:devList:add")
@Log(title = "硬件", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(int devModelId)
{
return toAjax(devListService.insertDevList(devModelId));
}
/**
* 修改硬件
*/
@RequiresPermissions("device:devList:edit")
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") Integer id, ModelMap mmap)
{
DevList devList = devListService.selectDevListById(id);
mmap.put("devList", devList);
return prefix + "/edit";
}
/**
* 修改保存硬件
*/
@RequiresPermissions("device:devList:edit")
@Log(title = "硬件", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(DevList devList,HttpServletRequest request)
{
return toAjax(devListService.updateDevList(devList,request));
}
/**
* 删除硬件
*/
@RequiresPermissions("device:devList:remove")
@Log(title = "硬件", businessType = BusinessType.DELETE)
@PostMapping( "/remove")
@ResponseBody
public AjaxResult remove(String ids,HttpServletRequest request)
{
return toAjax(devListService.deleteDevListByIds(ids,request));
}
@Log(title = "硬件状态", businessType = BusinessType.UPDATE)
@PostMapping("/changeStatus")
@ResponseBody
@Transactional(rollbackFor = Exception.class)
@RequiresPermissions("device:devList:edit")
public AjaxResult changeStatus(DevList devList,HttpServletRequest request){
return toAjax(devListService.updateDevList(devList,request));
}
/**
* 获取所有没有配置的硬件编号
* @return
*/
@ResponseBody
@RequestMapping("/no/config")
public List<String> selectNoConfigDevice(){
return devListService.selectNoConfigDevice();
}
/**
* 修改是否配置硬件状态、一般是服务器管理员操作权限
* @param devList
* @return
*/
@PostMapping("/configDev")
@ResponseBody
@RequiresPermissions("device:devList:configDev")
public AjaxResult configDev(DevList devList,HttpServletRequest request){
return toAjax(devListService.updateDevList(devList,request));
}
/**
* 生产条形码
* @return
*/
@GetMapping("/code")
public String initCode(int id,ModelMap mmap){
mmap.put("dev",devListService.selectDevListAndIoById(id));
return prefix +"/code";
}
/**
* 用户添加硬件信息
* @return
*/
//获取添加硬件
@GetMapping("/add1")
public String addDev(){
return prefix +"/add1";
}
/**
* 硬件验证是否存在,及其是否被使用
* @param code
* @return
*/
@ResponseBody
@PostMapping("/validate")
public int deviceValidate(String code,HttpServletRequest request){
return devListService.deviceValidate(code,request);
}
/**
* 修改保存硬件
*/
@RequiresPermissions("device:devList:addsave")
@Log(title = "用户添加硬件", businessType = BusinessType.UPDATE)
@PostMapping("/addSave")
@ResponseBody
public AjaxResult add1Save(DevList devList,HttpServletRequest request)
{
User user = JwtUtil.getTokenUser(request);
if(user == null){
return toAjax(0);
}
devList.setCompanyId(user.getCompanyId());
return toAjax(devListService.addSave(devList,request));
}
@RequiresPermissions("production:productionLine:devconfig")
@Log(title = "查询硬件配置", businessType = BusinessType.UPDATE)
@PostMapping("/all")
@ResponseBody
public Map<String,Object> selectAll(HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
map.put("code",devListService.selectAll(request.getCookies()));
return map;
}
@RequiresPermissions("device:devList:createCode")
@Log(title = "生成硬件编号", businessType = BusinessType.INSERT)
@PostMapping("/createCode")
@ResponseBody
public AjaxResult createDevCode(){
try {
devListService.createDevCode();
return success();
}catch (BusinessException e){
return error(e.getMessage());
}catch (Exception e){
return error("添加失败");
}
}
/**
* 扫码
* @param id
* @return
*/
@RequestMapping("/rqcode/{id}")
public String decRqCode(@PathVariable("id")int id,ModelMap modelMap){
modelMap.put("d",devListService.selectDevListAndIoById(id));
return prefix+"/rqcode";
}
/******************************************************************************************************
*********************************** app端硬件交互逻辑 *************************************************
******************************************************************************************************/
/**
* app端查询硬件列表
*/
@PostMapping("/applist")
@ResponseBody
public AjaxResult appSelectDevList(@RequestBody DevList devList){
try {
if (devList != null) {
devList.appStartPage();
return AjaxResult.success(devListService.appSelectDevList(devList));
}
return error();
} catch (Exception e) {
return AjaxResult.error();
}
}
}
| 25.6
| 105
| 0.698351
|
16b1da710c312f2743727730465fcf3db780a3d2
| 1,050
|
package net.shadowpie.sadiinso.sfc.commands.handlers;
import net.shadowpie.sadiinso.sfc.commands.Commands;
import net.shadowpie.sadiinso.sfc.commands.context.CommandContext;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class GroupedCommandHandler extends AbstractCommandHandler {
public final Map<String, AbstractCommandHandler> subCommands = new HashMap<>();
public GroupedCommandHandler(String name, String description, byte allowFrom) {
super(name, null, null, description, allowFrom, null);
}
public boolean addCommandHandler(AbstractCommandHandler handler) {
return (subCommands.put(handler.name.toLowerCase(), handler) == null);
}
@Override
public int execute(@NotNull CommandContext ctx) {
String prefix = ctx.prefix();
if(prefix == null) {
return Commands.COMMAND_SUCCESS;
} else {
AbstractCommandHandler handler = subCommands.get(prefix.toLowerCase());
return (handler == null ? Commands.COMMAND_NOT_FOUND : handler.execute(ctx.pullPrefix()));
}
}
}
| 30.882353
| 93
| 0.771429
|
17b109ea7d1376910f6c3580dd550715287d7d89
| 803
|
package com.vogella.javastarter.exercises1;
class Person {
String firstName;
String lastName;
int age;
private Address address;
public Person(String a, String b, int value) {
firstName = a;
lastName = b;
age=value;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return firstName + " " + lastName;
}
}
| 14.6
| 47
| 0.686177
|
dc3bfcfb2a4e4a7a5129e8e597ca8d05f63ed4a9
| 481
|
package net.minecraft.world.level.block;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.level.block.state.BlockBehaviour;
public class StainedGlassBlock extends AbstractGlassBlock implements BeaconBeamBlock {
private final DyeColor color;
public StainedGlassBlock(DyeColor pDyeColor, BlockBehaviour.Properties pProperties) {
super(pProperties);
this.color = pDyeColor;
}
public DyeColor getColor() {
return this.color;
}
}
| 28.294118
| 88
| 0.769231
|
0afe7560238b51fcced5dac5ee7a5f414af92170
| 3,287
|
package com.viettel.android.gsm.services;
import android.os.Bundle;
import com.viettel.android.gsm.ViettelClient;
import com.viettel.android.gsm.ViettelClient.OnConnectionCallbacks;
import com.viettel.android.gsm.ViettelError;
/**
*
* Use ViettelClientSimpleActivity with no service in my app.
* You can custom listener {@link #onConnectionCallbacks} for connection callback use @Override method
* {@link #onConnectionCallbacks()}. see more an example of onConnectionCallbacks():
*
* <pre class="prettyprint">
* //@Override
* public OnConnectionCallbacks onConnectionCallbacks() {
* return new OnConnectionCallbacks() {
* //@Override
* public void onConnected() {
* //TODO Something...
* }
*
* //@Override
* public void onConnectFail(ViettelError messageErrors) {
* //TODO Something...
* }
* };
* }
* </pre>
*
*/
public abstract class ViettelClientSimpleActivity extends AbstractViettelActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Validate
mClassExitApp = classExitApp();
ensureClassExitApp();
//call method startClient() connect to server if autoConnectServer() return true.
//you can call method startClient() at other times and autoConnectServer() return false.
if(autoConnectServer()){
startClient();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
onDestroy(mClassExitApp);
}
@Override
public void onConnectFail(ViettelError arg0) {
onDestroy(getClass());
if (customCallbacks != null) {
customCallbacks.onConnectFail(arg0);
}
// TODO something.
}
@Override
public void onConnected() {
if (customCallbacks != null) {
customCallbacks.onConnected();
}
// TODO something.
}
@Override
public OnConnectionCallbacks onConnectionCallbacks() {
return null;
}
@Override
public ViettelClient getViettelClient() {
return ViettelLocalSimple.getInstances().getViettelClient();
}
@Override
public void startClient() {
startClient(null);
}
@Override
public void startClient(OnConnectionCallbacks callbacks) {
InitializeParams params = initParams();
if(params == null){
throw new NullPointerException("InitializeParams is null.");
}
if(equalsMainClass(mClassExitApp)){
customCallbacks = (callbacks != null) ? callbacks : onConnectionCallbacks();
ViettelLocalSimple.getInstances().initialize(ViettelClientSimpleActivity.this, (callbacks != null) ? callbacks : ViettelClientSimpleActivity.this);
ViettelLocalSimple.getInstances().setViettelId(params.getPublisherId(), params.getAppId());
ViettelLocalSimple.getInstances().setTestDevice(params.isTestDevice());
if(params.getReadRequestTimeout() > 0){
ViettelLocalSimple.getInstances().setReadRequestTimeout(params.getReadRequestTimeout());
}
ViettelLocalSimple.getInstances().startClient();
}
}
// destroy ViettelClient if current Activity is mClassExitApp.
//Note: Call method when exit the application or you dont want to use ViettelClient (SDK of Viettel).
private void onDestroy(Class<?> activityExit) {
if (activityExit == null) {
throw new NullPointerException("activityExit");
}
if(equalsMainClass(activityExit)){
ViettelLocalSimple.getInstances().onDestroy();
}
}
}
| 27.391667
| 150
| 0.736234
|
690df731472c0f3b1551345a91910a027646bddf
| 2,768
|
package org.firstinspires.ftc.redshiftrobotics.config;
import android.util.Log;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.*;
/**
* Created by adam on 9/29/16.
*/
public class Config <E extends Number> { //template class can be used with any numerical constant, i.e.: double, float, long, etc.
private Map<String, ConfigVariable<E>> variables = null; //map of names to config variables. All config variables must have the same type as the containing class.
public Config() {
this.variables = new HashMap<>();
}
public void add(String name, ConfigVariable<E> val) {
this.variables.put(name, val);
} //add a value
public void readFrom(String filename) throws Exception { //fill in table with values from a json file
FileInputStream fis;
try {
fis = new FileInputStream(filename);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
int read;
StringBuilder str = new StringBuilder();
while ((read = fis.read()) != -1) {
str.append((char) read);
}
JSONObject obj = new JSONObject(str.toString()); //variables are stored in a json meta-object called variables
/* i.e.:
{
"variables":{
"varname":{
"val": _,
"min": _,
"max": _"
},
...
}
*/
JSONObject vars = obj.getJSONObject("variables");
Iterator<String> keys = vars.keys(); //iterator for keys in variables json object
JSONObject current; //the current object
E value, min, max; //the min, max, and value data extracted from the current object
while (keys.hasNext()) {
String key = keys.next();
if (vars.get(key) instanceof JSONObject) {
current = vars.getJSONObject(key);
try {
value = (E) current.get("val");
} catch (Exception e) {
e.printStackTrace();
return;
}
String name = key;
ConfigVariable<E> c = new ConfigVariable<>(value);
this.variables.put(name, c);
}
}
}
public ConfigVariable<E> get(String name) {
if (this.variables.containsKey(name)) {
return this.variables.get(name);
} else {
return null;
}
}
public void set (String name, ConfigVariable<E> var) {
this.variables.put(name, var);
}
}
| 30.417582
| 166
| 0.539379
|
15fb1e8bad60890d020d548db0af1758456b3437
| 258
|
package org.rs.core.page;
public abstract interface IDialect {
public abstract StringBuilder bulildPageSql(String paramString, IPage paramIPage);
public abstract boolean supportsPaged();
public abstract String getSelectCountSql(String paramString);
}
| 23.454545
| 83
| 0.817829
|
13da5663439755cd087100752d22c44641ea7ed5
| 2,013
|
package com.cc.cairou.main;
import java.util.Calendar;
import java.util.Random;
import com.cc.cairou.R;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.widget.Toast;
/**
*
* @ClassName: AlarmReceiver
* @Description: 闹铃时间到了会进入这个广播,这个时候可以做一些该做的业务。
* @author HuHood
* @date 2013-11-25 下午4:44:30
*
*/
public class AlarmReceiver extends BroadcastReceiver {
private String[] message = {
"不好意思,今天没推送,不信你点?。",
"别看了,今天没推送,不信你点?",
"戳我看看?",
"[点击查看]"
};
@Override
public void onReceive(Context context, Intent intent) {
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int length = message.length;
Random random = new Random();
int index = random.nextInt(length);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder1 = new Notification.Builder(context);
builder1.setSmallIcon(R.drawable.chat); //设置图标
builder1.setTicker("C: 你有一则来自cc的未读消息。");
builder1.setContentTitle("给你"); //设置标题
builder1.setContentText(message[index]); //消息内容
builder1.setWhen(System.currentTimeMillis()); //发送时间
builder1.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音,振动方式,灯光
builder1.setAutoCancel(true);//打开程序后图标消失
Intent intent1 =new Intent (context,MessageActivity.class);
// 创建一个PendingIntent,和Intent类似,不同的是由于不是马上调用,需要在下拉状态条出发的activity,所以采用的是PendingIntent,即点击Notification跳转启动到哪个Activity
PendingIntent pendingIntent =PendingIntent.getActivity(context, 0, intent1, 0);
builder1.setContentIntent(pendingIntent);
Notification notification1 = builder1.build();
manager.notify(124, notification1); // 通过通知管理器发送通知
}
}
| 27.958333
| 121
| 0.754098
|
9b0411572b6b52ea958836849363098259a1b391
| 2,779
|
package edu.nyu.oop.util;
import xtc.lang.JavaFiveParser;
import xtc.parser.Result;
import xtc.tree.GNode;
import xtc.tree.Node;
import xtc.tree.Token;
import xtc.tree.Visitor;
import java.io.*;
import java.util.List;
import java.util.LinkedList;
public class NodeUtil {
// A class representing a location inside the Ast.
// Useful when trying to extract a location out of the Ast from inside a Visitor.
public static class AstIndex {
public GNode node;
public int childIdx;
public AstIndex(GNode n, int idx) {
this.node = n;
this.childIdx = idx;
}
}
// Takes a node and concatenates all its children into a string with the specified delimiter
public static String mkString(Node node, String delim) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < node.size() ; i++) {
buf.append(Token.cast(node.get(i)));
if (i < node.size() - 1) buf.append(delim);
}
return buf.toString();
}
// Searches Ast for a node with specified name. Returns first that it finds.
public static Node dfs(Node node, String nodeName) {
if (node.size() == 0) {
return null;
} else if (node.hasName(nodeName)) {
return node;
} else {
for (Object o : node) {
if (o instanceof Node) {
Node casted = (Node) o;
Node target = dfs(casted, nodeName);
if (target != null) return target;
}
}
}
return null;
}
// Searches Ast for a node with specified name. Returns all that it finds.
public static List<Node> dfsAll(Node root, final String nodeName) {
final List<Node> nodes = new LinkedList<Node>();
new Visitor() {
public void visit(Node n) {
if(nodeName.equals(n.getName())) {
nodes.add(n);
}
for (Object o : n) {
if (o instanceof Node) dispatch((Node) o);
}
}
} .dispatch(root);
return nodes;
}
// Parses a Java source file into an Xtc Ast
public static Node parseJavaFile(File file) {
try {
InputStream instream = new FileInputStream(file);
Reader in = new BufferedReader(new InputStreamReader(instream));
JavaFiveParser parser = new JavaFiveParser(in, file.toString(), (int)file.length());
Result result = parser.pCompilationUnit(0);
return (Node) parser.value(result);
} catch (Exception e) {
throw new RuntimeException("Unable to parse Java file " + file.getName(), e);
}
}
}
| 32.694118
| 96
| 0.563512
|
fc474852cf7ba98f8d1605f797fb6ab7c8c50c17
| 976
|
package cn.enncy.scs.swing.frame.base.view.index.card.courses;
import cn.enncy.scs.pojo.Course;
import cn.enncy.scs.pojo.Teacher;
import cn.enncy.scs.swing.component.ScsList;
import cn.enncy.scs.swing.component.dialog.ScsDialog;
import cn.enncy.scs.swing.component.panel.ScsWhitePanel;
import javax.swing.*;
import java.awt.*;
/**
* //TODO
* <br/>Created in 19:36 2021/5/30
*
* @author: enncy
*/
public class CourseInfoDialog extends ScsDialog {
public CourseInfoDialog(Course course, Teacher teacher) {
super("课程详情");
JPanel container = this.getContainer();
JPanel jPanel = new ScsWhitePanel(new GridLayout(1,2));
System.out.println(course);
jPanel.add(new ScsList("教师信息",teacher));
jPanel.add(new ScsList("课程信息",course));
container.add(jPanel, BorderLayout.CENTER);
this.pack();
this.setCanResize(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
| 27.111111
| 63
| 0.683402
|
073a362d9c59e3a24557303ca9919aec8ac14f71
| 1,652
|
package com.wu.lewei.web.rest;
import com.codahale.metrics.annotation.Timed;
import com.wu.lewei.dto.BusRouteDTO;
import com.wu.lewei.service.BusRouteService;
import com.wu.lewei.web.rest.resource.BusRouteResource;
import com.wu.lewei.web.rest.resourceassembler.BusRouteResourceAssembler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.inject.Inject;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by cn40580 at 2016-10-12 10:21 AM.
*/
@RestController
@RequestMapping("/app/rest")
public class BusRouteWebService {
private static final Log LOG = LogFactory.getLog(BusRouteWebService.class);
@Inject
private BusRouteService busRouteService;
@Inject
private BusRouteResourceAssembler busRouteResourceAssembler;
@RequestMapping(value = "/busroute/all",
method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_ATOM_XML_VALUE})
@Timed
public ResponseEntity<List<BusRouteResource>> getAllBusRoute() {
List<BusRouteDTO> us = busRouteService.findAll();
List<BusRouteResource> res = us.stream().map(n -> busRouteResourceAssembler.toResource(n)).collect(Collectors.toList());
return new ResponseEntity<>(res, HttpStatus.OK);
}
}
| 35.913043
| 128
| 0.779056
|
bfe362ebabbf2e5c57f86d58f5e848595988b411
| 3,954
|
package services.impl;
import com.google.common.base.Strings;
import com.google.common.primitives.Longs;
import com.google.inject.Inject;
import io.jsonwebtoken.*;
import models.PrivateRoom;
import play.Logger;
import play.Play;
import play.mvc.Http;
import security.Secured;
import services.PrivateRoomService;
import services.SecurityService;
import java.util.Date;
import java.util.Optional;
/**
* Created by kevin on 6/3/15.
*/
public class SecurityServiceImpl implements SecurityService {
private final PrivateRoomService privateRoomService;
private static final String SIGNING_KEY = Play.application().configuration()
.getString("jwt.signing.key", "default_signing_key");
private static final String ISSUER = "ZipChat";
// 1 day in millis
private static final long EXPIRATION_TIME_MILLIS = 1000L * 60L * 60L * 24L;
@Inject
public SecurityServiceImpl(final PrivateRoomService privateRoomService) {
this.privateRoomService = privateRoomService;
}
@Override
public String generateAuthToken(long userId) {
long issuedMillis = System.currentTimeMillis();
long expMillis = issuedMillis + EXPIRATION_TIME_MILLIS;
return Jwts.builder()
.setSubject(Long.toString(userId))
.setIssuer(ISSUER)
.setIssuedAt(new Date(issuedMillis))
.setExpiration(new Date(expMillis))
.signWith(SignatureAlgorithm.HS512, SIGNING_KEY)
.compact();
}
@Override
public Optional<Long> getUserId(String jwt) {
if (Strings.isNullOrEmpty(jwt)) {
return Optional.empty();
}
Claims claims;
try {
claims = Jwts.parser().setSigningKey(SIGNING_KEY).parseClaimsJws(jwt).getBody();
} catch (SignatureException signatureException) {
Logger.error("JWT has a different signing key", signatureException);
return Optional.empty();
} catch (ExpiredJwtException expiredJwtException) {
Logger.debug("JWT is expired");
return Optional.empty();
} catch (MalformedJwtException e) {
Logger.warn("JWT is malformed", e);
return Optional.empty();
} catch (UnsupportedJwtException e) {
Logger.debug("JWT is unsupported", e);
return Optional.empty();
}
String issuer = claims.getIssuer();
if (!issuer.equals(ISSUER)) {
Logger.error("JWT has unknown issuer: " + issuer);
return Optional.empty();
}
String userIdStr = claims.getSubject();
Optional<Long> userIdOptional = Optional.ofNullable(Longs.tryParse(userIdStr));
if (!userIdOptional.isPresent()) {
throw new RuntimeException("JWT userId " + userIdStr + "can't be converted to a long");
}
return userIdOptional;
}
@Override
public boolean isUnauthorized(long userId) {
return userId != getTokenUserId() && Play.isProd();
}
@Override
public boolean isUnauthorized(PrivateRoom privateRoom) {
return !privateRoomService.isUserInRoom(privateRoom, getTokenUserId()) && Play.isProd();
}
@Override
public boolean isUnauthorized(String authToken, long userId) {
Optional<Long> userIdOptional = getUserId(authToken);
return (!userIdOptional.isPresent() || userIdOptional.get() != userId)
&& Play.isProd();
}
@Override
public boolean isUnauthorized(String authToken, PrivateRoom privateRoom) {
Optional<Long> userIdOptional = getUserId(authToken);
return (!userIdOptional.isPresent() || !privateRoomService.isUserInRoom(privateRoom, userIdOptional.get()))
&& Play.isProd();
}
@Override
public long getTokenUserId() {
return Play.isProd() ? (long) Http.Context.current().args.get(Secured.USER_ID_KEY) : 1;
}
}
| 33.226891
| 115
| 0.652251
|
59522dfa93051a9cf9fe965784795c65e8a00a0d
| 2,984
|
/*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.ast;
import org.eclipse.jdt.internal.compiler.codegen.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
public abstract class BranchStatement extends Statement {
public char[] label;
public BranchLabel targetLabel;
public SubRoutineStatement[] subroutines;
public int initStateIndex = -1;
/**
* BranchStatement constructor comment.
*/
public BranchStatement(char[] label, int sourceStart,int sourceEnd) {
this.label = label ;
this.sourceStart = sourceStart;
this.sourceEnd = sourceEnd;
}
protected void setSubroutineSwitchExpression(SubRoutineStatement sub) {
// Do nothing
}
protected void restartExceptionLabels(CodeStream codeStream) {
// do nothing
}
/**
* Branch code generation
*
* generate the finallyInvocationSequence.
*/
@Override
public void generateCode(BlockScope currentScope, CodeStream codeStream) {
if ((this.bits & ASTNode.IsReachable) == 0) {
return;
}
int pc = codeStream.position;
// generation of code responsible for invoking the finally
// blocks in sequence
if (this.subroutines != null){
for (int i = 0, max = this.subroutines.length; i < max; i++){
SubRoutineStatement sub = this.subroutines[i];
SwitchExpression se = sub.getSwitchExpression();
setSubroutineSwitchExpression(sub);
boolean didEscape = sub.generateSubRoutineInvocation(currentScope, codeStream, this.targetLabel, this.initStateIndex, null);
sub.setSwitchExpression(se);
if (didEscape) {
codeStream.recordPositionsFrom(pc, this.sourceStart);
SubRoutineStatement.reenterAllExceptionHandlers(this.subroutines, i, codeStream);
if (this.initStateIndex != -1) {
codeStream.removeNotDefinitelyAssignedVariables(currentScope, this.initStateIndex);
codeStream.addDefinitelyAssignedVariables(currentScope, this.initStateIndex);
}
restartExceptionLabels(codeStream);
return;
}
}
}
// checkAndLoadSyntheticVars(codeStream);
codeStream.goto_(this.targetLabel);
codeStream.recordPositionsFrom(pc, this.sourceStart);
SubRoutineStatement.reenterAllExceptionHandlers(this.subroutines, -1, codeStream);
if (this.initStateIndex != -1) {
codeStream.removeNotDefinitelyAssignedVariables(currentScope, this.initStateIndex);
codeStream.addDefinitelyAssignedVariables(currentScope, this.initStateIndex);
}
}
@Override
public void resolve(BlockScope scope) {
// nothing to do during name resolution
}
}
| 33.52809
| 127
| 0.72252
|
7c9ed8aa572202951530bad79ba190c86f0ca8d4
| 24,123
|
package com.github.thorqin.webapi.utility;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
public class JsonSchema {
public static class JsonValidateException extends Exception {
private static final long serialVersionUID = -2303623192224225975L;
public JsonValidateException(String message) {
super(message);
}
public JsonValidateException(String message, Throwable cause) {
super(message, cause);
}
}
public static class ErrorStack {
StringBuffer sb = new StringBuffer();
public void push(String message) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append(message);
}
public void reset() {
sb.setLength(0);
}
public String getMessage() {
return sb.toString();
}
}
public static interface Validator {
public static enum JsonType {
NULL, ANY, BOOLEAN, STRING, NUMBER, ARRAY, OBJECT
}
public JsonType getType();
public boolean validate(JsonElement value, ErrorStack stack);
}
public class NullValidator implements Validator {
@Override
public JsonType getType() {
return JsonType.NULL;
}
@Override
public boolean validate(JsonElement value, ErrorStack stack) {
if (!(value instanceof JsonNull)) {
stack.push("Expect null");
return false;
} else {
return true;
}
}
}
public class AnyValidator implements Validator {
@Override
public JsonType getType() {
return JsonType.ANY;
}
@Override
public boolean validate(JsonElement value, ErrorStack stack) {
return true;
}
}
public class BooleanValidator implements Validator {
public BooleanValidator() {
}
@Override
public JsonType getType() {
return JsonType.BOOLEAN;
}
@Override
public boolean validate(JsonElement value, ErrorStack stack) {
if (!(value instanceof JsonPrimitive)) {
stack.push("Expect a boolean");
return false;
}
JsonPrimitive primitive = ((JsonPrimitive) value);
if (!primitive.isBoolean()) {
stack.push("Expect a boolean");
return false;
}
return true;
}
}
public class StringValidator implements Validator {
private Pattern pattern;
private Long minLength;
private Long maxLength;
private String[] options;
private boolean isEnumerate;
public StringValidator() {
this(null, null, null);
}
public StringValidator(String regex, Long minLength, Long maxLength)
throws PatternSyntaxException {
if (regex == null) {
pattern = null;
} else {
pattern = Pattern.compile(regex);
}
this.minLength = minLength;
this.maxLength = maxLength;
isEnumerate = false;
}
public StringValidator(String[] options) {
this.options = options;
isEnumerate = true;
}
public String[] getOptions() {
return options;
}
public boolean isEnumerate() {
return isEnumerate;
}
public Long getMinLength() {
return minLength;
}
public Long getMaxLength() {
return maxLength;
}
@Override
public JsonType getType() {
return JsonType.STRING;
}
@Override
public boolean validate(JsonElement value, ErrorStack stack) {
if (!(value instanceof JsonPrimitive)) {
stack.push("Expect a string");
return false;
}
JsonPrimitive primitive = ((JsonPrimitive) value);
if (!primitive.isString()) {
stack.push("Expect a string");
return false;
}
String strValue = primitive.getAsString();
if (isEnumerate) {
for (String v : options) {
if (v.equals(strValue)) {
return true;
}
}
stack.push("String value is not one of the options.");
return false;
} else {
if (minLength != null && strValue.length() < minLength) {
stack.push("String is too short, expect greater than or equal " + minLength);
return false;
}
if (maxLength != null && strValue.length() > maxLength) {
stack.push("String value is too long, expect less than or equal " + maxLength);
return false;
}
if (pattern != null) {
Matcher matcher = pattern.matcher(strValue);
if (!matcher.matches()) {
stack.push("String value didn't match the rule: " + pattern.pattern());
return false;
}
}
return true;
}
}
}
public class NumberValidator implements Validator {
private BigDecimal minValue;
private BigDecimal maxValue;
private boolean isOnlyInteger;
private boolean isEnumerate;
private BigDecimal[] options;
public NumberValidator() {
this(null, null, false);
}
public NumberValidator(BigDecimal minValue, BigDecimal maxValue, boolean onlyInteger) {
this.minValue = minValue;
this.maxValue = maxValue;
this.isOnlyInteger = onlyInteger;
isEnumerate = false;
}
public NumberValidator(BigDecimal[] options) {
this.options = options;
isEnumerate = true;
}
@Override
public JsonType getType() {
return JsonType.NUMBER;
}
public BigDecimal[] getOptions() {
return options;
}
public boolean isEnumerate() {
return isEnumerate;
}
public BigDecimal getMinValue() {
return minValue;
}
public BigDecimal getMaxValue() {
return maxValue;
}
public boolean isOnlyInteger() {
return isOnlyInteger;
}
@Override
public boolean validate(JsonElement value, ErrorStack stack) {
if (!(value instanceof JsonPrimitive)) {
stack.push("Expect a number");
return false;
}
JsonPrimitive primitive = ((JsonPrimitive) value);
if (!primitive.isNumber()) {
stack.push("Expect a number");
return false;
}
BigDecimal numberValue = primitive.getAsBigDecimal();
if (isEnumerate) {
for (BigDecimal v : options) {
if (v.compareTo(value.getAsBigDecimal()) == 0) {
return true;
}
}
stack.push("Number value is not one of the options.");
return false;
} else {
if (minValue != null && numberValue.compareTo(minValue) == -1) {
stack.push("Number is too small, expect greater than or equal " + minValue);
return false;
}
if (maxValue != null && numberValue.compareTo(maxValue) == 1) {
stack.push("Number is too large, expect less than or equal " + maxValue);
return false;
}
if (isOnlyInteger) {
try {
numberValue.toBigIntegerExact();
} catch (ArithmeticException e) {
stack.push("Number value must be an integer.");
return false;
}
}
return true;
}
}
}
public class ArrayValidator implements Validator {
private Long minItems;
private Long maxItems;
private String[] allowedTypes;
public ArrayValidator() {
this(null, null, new String[]{"any"});
}
public ArrayValidator(Long minItems, Long maxItems, String[] allowedTypes) {
this.minItems = minItems;
this.maxItems = maxItems;
this.allowedTypes = allowedTypes;
}
@Override
public JsonType getType() {
return JsonType.ARRAY;
}
public Long getMinItems() {
return minItems;
}
public Long getMaxItems() {
return maxItems;
}
public Validator[] getAllowedTypes() {
Validator[] resultArry = new Validator[allowedTypes.length];
for (int i = 0; i < allowedTypes.length; i++) {
resultArry[i] = definedTypes.get(allowedTypes[i]);
}
return resultArry;
}
@Override
public boolean validate(JsonElement value, ErrorStack stack) {
if (!(value instanceof JsonArray)) {
stack.push("Expect an array");
return false;
}
JsonArray array = (JsonArray) value;
if (minItems != null && array.size() < minItems) {
stack.push("Array items are too few, expect greater than or equal " + minItems);
return false;
}
if (maxItems != null && array.size() > maxItems) {
stack.push("Array items are too much, expect less than or equal " + maxItems);
return false;
}
for (int i = 0; i < array.size(); i++) {
JsonElement subItem = array.get(i);
boolean succeeded = false;
for (String type : allowedTypes) {
if (type.equals("any")
|| definedTypes.get(type).validate(subItem, stack)) {
stack.reset();
succeeded = true;
break;
}
}
if (!succeeded) {
stack.push("Array item type invalid, position: " + i);
return false;
}
}
return true;
}
}
public class ObjectValidator implements Validator {
private HashMap<String, String[]> properties;
private boolean isAllowOtherProperties;
public ObjectValidator() {
this(new HashMap<String, String[]>(), true);
}
public ObjectValidator(HashMap<String, String[]> properties, boolean allowOtherProperties) {
this.properties = properties;
this.isAllowOtherProperties = allowOtherProperties;
}
@Override
public JsonType getType() {
return JsonType.OBJECT;
}
public Set<Entry<String, Validator[]>> getProperties() {
HashMap<String, Validator[]> resultProperties = new HashMap<>();
for (Entry<String, String[]> entry : properties.entrySet()) {
String[] propertyArray = entry.getValue();
Validator[] validatorArray = new Validator[propertyArray.length];
for (int i = 0; i < propertyArray.length; i++) {
validatorArray[i] = definedTypes.get(propertyArray[i]);
}
resultProperties.put(entry.getKey(), validatorArray);
}
return resultProperties.entrySet();
}
@Override
public boolean validate(JsonElement value, ErrorStack stack) {
if (!(value instanceof JsonObject)) {
stack.push("Expect an object");
return false;
}
JsonObject object = (JsonObject) value;
Set<Entry<String, JsonElement>> entrySet = object.entrySet();
for (Entry<String, JsonElement> entry : entrySet) {
if (properties.containsKey(entry.getKey())) {
String[] allowedSchemas = properties.get(entry.getKey());
boolean succeeded = false;
for (String type : allowedSchemas) {
if (type.equals("any")
|| definedTypes.get(type).validate(entry.getValue(), stack)) {
stack.reset();
succeeded = true;
break;
}
}
if (!succeeded) {
stack.push("Property type invalid: " + entry.getKey());
return false;
}
} else {
if (!isAllowOtherProperties) {
stack.push("Property not allowed: " + entry.getKey());
return false;
}
}
}
for (Entry<String, String[]> entry : properties.entrySet()) {
String[] schemas = entry.getValue();
boolean allowNull = false;
for (String schema : schemas) {
if (schema.equals("null") || schema.equals("any")) {
allowNull = true;
break;
}
}
if (!allowNull) {
if (!object.has(entry.getKey())) {
stack.push("Property required: " + entry.getKey());
return false;
}
}
}
return true;
}
}
private HashMap<String, Validator> definedTypes;
private HashSet<String> rootTypes;
public Validator[] getRootTypes() {
LinkedList<Validator> validators = new LinkedList<>();
for (String typeName : rootTypes) {
validators.add(definedTypes.get(typeName));
}
return validators.toArray(new Validator[validators.size()]);
}
public JsonSchema(InputStream jsonStream, String charset) throws JsonValidateException, IOException {
InputStreamReader reader = new InputStreamReader(jsonStream, charset);
internalInit(reader);
}
public JsonSchema(String resourceName, String charset) throws JsonValidateException, IOException {
InputStream in = null;
try {
in = JsonSchema.class.getClassLoader().getResourceAsStream(resourceName);
InputStreamReader reader = new InputStreamReader(in, charset);
internalInit(reader);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
public JsonSchema(String jsonString) throws JsonValidateException {
StringReader reader = new StringReader(jsonString);
internalInit(reader);
}
public JsonSchema(Reader jsonReader) throws JsonValidateException {
internalInit(jsonReader);
}
private void internalInit(Reader jsonReader) throws JsonValidateException {
try {
JsonParser parser = new JsonParser();
JsonObject root = (JsonObject) parser.parse(new JsonReader(jsonReader));
HashMap<String, String> checkList
= new HashMap<>();
definedTypes = new HashMap<>();
rootTypes = new HashSet<>();
definedTypes.put("any", new AnyValidator());
definedTypes.put("null", new NullValidator());
definedTypes.put("boolean", new BooleanValidator());
definedTypes.put("string", new StringValidator());
definedTypes.put("number", new NumberValidator());
definedTypes.put("object", new ObjectValidator());
definedTypes.put("array", new ArrayValidator());
HashSet<String> preDefined = new HashSet<>();
preDefined.add("any");
preDefined.add("null");
preDefined.add("boolean");
preDefined.add("string");
preDefined.add("number");
preDefined.add("object");
preDefined.add("array");
JsonObject define = (JsonObject) root.get("define");
if (define != null) {
for (Entry<String, JsonElement> entry : define.entrySet()) {
JsonObject definedType = (JsonObject) entry.getValue();
if (definedTypes.containsKey(entry.getKey())) {
throw new JsonValidateException("Schema type redefined: " + entry.getKey());
}
JsonPrimitive primitiveType = (JsonPrimitive) definedType.get("type");
if (primitiveType == null || !primitiveType.isString()) {
throw new JsonValidateException("Schema type define error, must specify 'type': " + entry.getKey());
}
String typeName = primitiveType.getAsString();
switch (typeName) {
case "string": {
JsonArray options = (JsonArray) definedType.get("options");
if (options != null) {
// An string enumerate
String[] optionArray = new String[options.size()];
for (int i = 0; i < options.size(); i++) {
JsonPrimitive item = (JsonPrimitive) options.get(i);
if (!item.isString()) {
throw new JsonValidateException("String options must be a string: " + entry.getKey());
}
optionArray[i] = item.getAsString();
}
StringValidator stringValidator = new StringValidator(optionArray);
definedTypes.put(entry.getKey(), stringValidator);
} else {
JsonPrimitive value;
Long min = null;
value = (JsonPrimitive) definedType.get("min");
if (value != null) {
if (value.isNumber()) {
try {
min = value.getAsBigDecimal().longValueExact();
} catch (ArithmeticException e) {
throw new JsonValidateException("String 'min' length must be an integer: " + entry.getKey());
}
} else {
throw new JsonValidateException("String 'min' length must be an integer: " + entry.getKey());
}
}
Long max = null;
value = (JsonPrimitive) definedType.get("max");
if (value != null) {
if (value.isNumber()) {
try {
max = value.getAsBigDecimal().longValueExact();
} catch (ArithmeticException e) {
throw new JsonValidateException("String 'max' length must be an integer: " + entry.getKey());
}
} else {
throw new JsonValidateException("String 'max' length must be an integer: " + entry.getKey());
}
}
String match = null;
value = (JsonPrimitive) definedType.get("match");
if (value != null) {
if (value.isString()) {
match = value.getAsString();
} else {
throw new JsonValidateException("String 'match' must be a regex expression: " + entry.getKey());
}
}
StringValidator stringValidator = new StringValidator(match, min, max);
definedTypes.put(entry.getKey(), stringValidator);
}
break;
}
case "number": {
JsonArray options = (JsonArray) definedType.get("options");
if (options != null) {
// An string enumerate
BigDecimal[] optionArray = new BigDecimal[options.size()];
for (int i = 0; i < options.size(); i++) {
JsonPrimitive item = (JsonPrimitive) options.get(i);
if (!item.isNumber()) {
throw new JsonValidateException("Number options must be a number: " + entry.getKey());
}
optionArray[i] = item.getAsBigDecimal();
}
NumberValidator numberValidator = new NumberValidator(optionArray);
definedTypes.put(entry.getKey(), numberValidator);
} else {
JsonPrimitive value;
BigDecimal min = null;
value = (JsonPrimitive) definedType.get("min");
if (value != null) {
if (value.isNumber()) {
min = value.getAsBigDecimal();
} else {
throw new JsonValidateException("Number 'min' value must be a number: " + entry.getKey());
}
}
BigDecimal max = null;
value = (JsonPrimitive) definedType.get("max");
if (value != null) {
if (value.isNumber()) {
max = value.getAsBigDecimal();
} else {
throw new JsonValidateException("Number 'max' value must be a number: " + entry.getKey());
}
}
boolean mustInteger = false;
value = (JsonPrimitive) definedType.get("integer");
if (value != null) {
if (value.isBoolean()) {
mustInteger = value.getAsBoolean();
} else {
throw new JsonValidateException("Number 'integer' must be a boolean value: " + entry.getKey());
}
}
NumberValidator numberValidator = new NumberValidator(min, max, mustInteger);
definedTypes.put(entry.getKey(), numberValidator);
}
break;
}
case "array": {
JsonPrimitive value;
Long min = null;
value = (JsonPrimitive) definedType.get("min");
if (value != null) {
if (value.isNumber()) {
try {
min = value.getAsBigDecimal().longValueExact();
} catch (ArithmeticException e) {
throw new JsonValidateException("Array 'min' size must be an integer: " + entry.getKey());
}
} else {
throw new JsonValidateException("Array 'min' size must be an integer: " + entry.getKey());
}
}
Long max = null;
value = (JsonPrimitive) definedType.get("max");
if (value != null) {
if (value.isNumber()) {
try {
max = value.getAsBigDecimal().longValueExact();
} catch (ArithmeticException e) {
throw new JsonValidateException("Array 'max' size must be an integer: " + entry.getKey());
}
} else {
throw new JsonValidateException("Array 'max' size must be an integer: " + entry.getKey());
}
}
String[] allow;
JsonArray array = (JsonArray) definedType.get("allow");
if (array != null) {
allow = new String[array.size()];
for (int i = 0; i < array.size(); i++) {
if (!array.get(i).isJsonPrimitive()) {
throw new JsonValidateException("Array 'allow' type must be an array of string: " + entry.getKey());
}
value = (JsonPrimitive) array.get(i);
if (!value.isString()) {
throw new JsonValidateException("Array 'allow' type must be an array of string: " + entry.getKey());
}
allow[i] = value.getAsString();
if (!checkList.containsKey(allow[i])) {
checkList.put(allow[i], "Type not define, used by: " + entry.getKey());
}
}
} else {
allow = new String[]{"any"};
}
ArrayValidator arrayValidator = new ArrayValidator(min, max, allow);
definedTypes.put(entry.getKey(), arrayValidator);
break;
}
case "object": {
boolean scalable = true;
JsonPrimitive value;
value = (JsonPrimitive) definedType.get("scalable");
if (value != null) {
if (value.isBoolean()) {
scalable = value.getAsBoolean();
} else {
throw new JsonValidateException("Object 'scalable' must be a boolean: " + entry.getKey());
}
}
HashMap<String, String[]> properties = new HashMap<>();
JsonObject propertyDefine = (JsonObject) definedType.get("properties");
if (propertyDefine != null) {
for (Entry<String, JsonElement> propertyItem : propertyDefine.entrySet()) {
String key = propertyItem.getKey();
JsonArray array = (JsonArray) propertyItem.getValue();
String[] allow = new String[array.size()];
for (int i = 0; i < array.size(); i++) {
if (!array.get(i).isJsonPrimitive()) {
throw new JsonValidateException("Object property type must be an array of string: " + entry.getKey());
}
value = (JsonPrimitive) array.get(i);
if (!value.isString()) {
throw new JsonValidateException("Object property type must be an array of string: " + entry.getKey());
}
allow[i] = value.getAsString();
if (!checkList.containsKey(allow[i])) {
checkList.put(allow[i], "Type not define, used by: " + entry.getKey());
}
}
properties.put(key, allow);
}
}
ObjectValidator objectValidator = new ObjectValidator(properties, scalable);
definedTypes.put(entry.getKey(), objectValidator);
break;
}
}
}
}
JsonArray jsonRoot = (JsonArray) root.get("root");
if (jsonRoot == null) {
throw new JsonValidateException("Schema must define a root node.");
}
for (int i = 0; i < jsonRoot.size(); i++) {
JsonPrimitive value = (JsonPrimitive) jsonRoot.get(i);
if (!value.isString()) {
throw new JsonValidateException("Schema root must be an array of string.");
}
rootTypes.add(value.getAsString());
if (!checkList.containsKey(value.getAsString())) {
checkList.put(value.getAsString(), "Type not define, used by root.");
}
}
if (rootTypes.isEmpty()) {
throw new JsonValidateException("Schema root must at least specify one type.");
}
for (Entry<String, String> entry : checkList.entrySet()) {
if (!definedTypes.containsKey(entry.getKey())) {
throw new JsonValidateException(entry.getValue());
}
}
for (Entry<String, Validator> entry : definedTypes.entrySet()) {
String key = entry.getKey();
if (!checkList.containsKey(key) && !preDefined.contains(key)) {
System.out.println("WARN: JSON schema type was defined but not used: " + key);
}
}
} catch (Exception e) {
throw new JsonValidateException("JSON schema error", e);
}
}
public JsonElement validate(String jsonString) throws JsonValidateException {
StringReader reader = new StringReader(jsonString);
return validate(reader);
}
public JsonElement validate(InputStream jsonStream, String charset) throws JsonValidateException, IOException {
InputStreamReader reader = new InputStreamReader(jsonStream, charset);
return validate(reader);
}
public JsonElement validate(Reader reader) throws JsonValidateException {
try {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new JsonReader(reader));
Validator[] types = getRootTypes();
ErrorStack stack = new ErrorStack();
for (Validator type : types) {
if (type.validate(jsonElement, stack)) {
return jsonElement;
}
}
throw new JsonValidateException("JSON validate failed: " + stack.getMessage());
} catch (JsonSyntaxException e) {
throw new JsonValidateException("JSON validate failed", e);
}
}
}
| 29.671587
| 113
| 0.638768
|
6b66fa9a4c4aec1ec079cf817d7d05ec72f3bdfc
| 4,171
|
package com.jetbrains.env.python.dotNet;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.projectRoots.Sdk;
import com.jetbrains.TestEnv;
import com.jetbrains.env.EnvTestTagsRequired;
import com.jetbrains.env.PyEnvTestCase;
import com.jetbrains.env.Staging;
import com.jetbrains.python.psi.PyFile;
import com.jetbrains.python.sdk.InvalidSdkException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
/**
* IronPython.NET specific tests
*
* @author Ilya.Kazakevich
*/
@EnvTestTagsRequired(tags = "iron", skipOnOSes = {TestEnv.LINUX, TestEnv.MAC})
@Staging
public final class PyIronPythonTest extends PyEnvTestCase {
/**
* IronPython tag
*/
static final String IRON_TAG = "iron";
/**
* Tests skeleton generation
*/
@Test
public void testSkeletons() {
runPythonTest(new SkeletonTestTask(
"dotNet/expected.skeleton.java.py",
"com.just.like.java",
"testSkeleton.py",
null
));
}
/**
* Tests skeleton generation with "from" statements
*/
@Test
public void testClassFromModule() {
runPythonTest(new SkeletonTestTask(
"dotNet/expected.skeleton.java.py",
"com.just.like.java",
"import_class_from_module.py",
null
));
}
/**
* Tests skeleton generation when imported as alias
*/
@Test
public void testClassFromModuleAlias() {
runPythonTest(new SkeletonTestTask(
"dotNet/expected.skeleton.java.py",
"com.just.like.java",
"import_class_from_module_alias.py",
null
));
}
/**
* Tests skeleton generation when module is imported
*/
@Test
public void testModuleFromPackage() {
runPythonTest(new SkeletonTestTask(
"dotNet/expected.skeleton.java.py",
"com.just.like.java",
"import_module_from_package.py",
null
));
}
/**
* Tests skeleton generation when several classes are imported
*/
@Test
public void testSeveralClasses() {
runPythonTest(new SkeletonTestTask(
"dotNet/expected.skeleton.java.py",
"com.just.like.java",
"import_several_classes_from_module.py",
"com.just.like.java.LikeJavaClass"
));
}
/**
* Tests skeletons for built-in classes. We can't compare files (CLR class may be changed from version to version),
* but we are sure there should be class System.Web.AspNetHostingPermissionLevel which is part of public API
*/
@Test
public void testImportBuiltInSystem() {
final SkeletonTestTask task = new SkeletonTestTask(
null,
"System.Web",
"import_system.py",
null
) {
@Override
public void runTestOn(@NotNull final String sdkHome, @Nullable Sdk existingSdk) throws IOException, InvalidSdkException {
super.runTestOn(sdkHome, existingSdk);
ApplicationManager.getApplication().runReadAction(() -> {
final PyFile skeleton = (PyFile)myFixture.getFile();
Assert.assertNotNull("System.Web does not contain class AspNetHostingPermissionLevel. Error generating stub? It has classes " +
skeleton.getTopLevelClasses(),
skeleton.findTopLevelClass("AspNetHostingPermissionLevel"));
});
}
};
runPythonTest(task);
}
/**
* Test importing of inner classes
*/
@Test
public void testImportInnerClass() {
runPythonTest(new SkeletonTestTask(
"dotNet/expected.skeleton.Deep.py",
"SingleNameSpace.Some.Deep",
"inner_class.py",
null
));
}
/**
* Test importing of the whole namespace
*/
@Test
public void testWholeNameSpace() {
runPythonTest(new SkeletonTestTask(
"dotNet/expected.skeleton.SingleNameSpace.py",
"SingleNameSpace",
"whole_namespace.py",
null
));
}
/**
* Test importing of single class
*/
@Test
public void testSingleClass() {
runPythonTest(new SkeletonTestTask(
"dotNet/expected.skeleton.SingleNameSpace.py",
"SingleNameSpace",
"single_class.py",
null
));
}
}
| 25.746914
| 138
| 0.672501
|
02d0da84ccdb89d56ab7277d5ec688fb8069a39f
| 6,548
|
package resources.projects.pluginwizard;
import ca.cgjennings.ui.EditorPane;
import ca.cgjennings.ui.JIconList;
import ca.cgjennings.ui.wizard.WizardModel;
import java.util.EnumSet;
import javax.swing.DefaultListModel;
import static resources.Language.string;
/**
* A standard plug-in wizard page that allows the user to choose a kind of
* plug-in to create. This allows the user to select from the basic plug-in
* types ({@code ACTIVATED}, {@code INJECTED}, or {@code EXTENSION}),
* and, optionally, a theme or library.
*
* @author Chris Jennings <https://cgjennings.ca/contact>
* @since 3.0
*/
@SuppressWarnings("serial")
public final class ContentTypePage extends javax.swing.JPanel {
private WizardModel model;
/**
* Creates new plug-in type selection page that allows selection from
* the specified types.
* @param allowedTypes a set describing the plug-in types to allow
* @param model the model that the page will be placed in
* @throws IllegalArgumentException if no types are allowed
*/
public ContentTypePage( EnumSet<ContentType> allowedTypes, WizardModel model ) {
if( allowedTypes.isEmpty() ) throw new IllegalArgumentException("allowedTypes is empty");
initComponents();
DefaultListModel m = new DefaultListModel();
for( ContentType t : allowedTypes ) {
m.addElement( t );
}
typeList.setModel( m );
typeList.setSelectedIndex(0);
this.model = model;
}
/**
* Creates new plug-in type selection page that includes the basic plug-in
* types and may optionally include themes and libraries.
*
* @param allowThemes if {@code true}, then the user will be allowed
* to select a theme plug-in (.setheme file type).
* @param allowLibraries if {@code true}, then the user will be allowed
* to select a library plug-in type (.selibrary file type).
* @param model the model that the page will be placed in
*/
public ContentTypePage( boolean allowThemes, boolean allowLibraries, WizardModel model ) {
this( getDefaultEnumSet( allowThemes, allowLibraries ), model );
}
private static EnumSet<ContentType> getDefaultEnumSet( boolean allowThemes, boolean allowLibraries ) {
if( allowThemes ) {
if( allowLibraries ) {
return EnumSet.allOf( ContentType.class );
} else {
return EnumSet.of( ContentType.ACTIVATED, ContentType.INJECTED, ContentType.EXTENSION, ContentType.THEME );
}
} else {
if( allowLibraries ) {
return EnumSet.of( ContentType.ACTIVATED, ContentType.INJECTED, ContentType.EXTENSION, ContentType.LIBRARY );
} else {
return EnumSet.of( ContentType.ACTIVATED, ContentType.INJECTED, ContentType.EXTENSION );
}
}
}
/**
* Returns the selected plug-in content type.
*
* @return the selected content type
*/
public ContentType getSelectedContentType() {
return (ContentType) typeList.getSelectedValue();
}
/**
* Changes the type of plug-in content that is selected.
* @param t the content type to select
*/
public void setSelectedContentType( ContentType t ) {
typeList.setSelectedValue( t, true );
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
descField = new EditorPane();
jScrollPane2 = new javax.swing.JScrollPane();
typeList = new JIconList() ;
jLabel1.setText(string("prj-l-plugin-wiz-choose-type")); // NOI18N
descField.setEditable(false);
descField.setContentType("text/html"); // NOI18N
jScrollPane1.setViewportView(descField);
typeList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
typeList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
typeListValueChanged(evt);
}
});
jScrollPane2.setViewportView(typeList);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void typeListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_typeListValueChanged
ContentType t = (ContentType) typeList.getSelectedValue();
if( t == null ) {
descField.setText( "" );
} else {
descField.setText( t.getDescription() );
}
if( model != null ) {
model.setProgressBlocked( t == null );
}
descField.select(0,0);
}//GEN-LAST:event_typeListValueChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JEditorPane descField;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JList typeList;
// End of variables declaration//GEN-END:variables
}
| 39.684848
| 136
| 0.700214
|
0fa40dd8fea7cb9cca4f40dcd36f595bf435dd98
| 31,175
|
package oghamcloudhopper.it;
import static fr.sii.ogham.testing.assertion.OghamAssertions.assertThat;
import static fr.sii.ogham.testing.assertion.hamcrest.ExceptionMatchers.hasAnyCause;
import static fr.sii.ogham.testing.sms.simulator.bean.NumberingPlanIndicator.ISDN;
import static fr.sii.ogham.testing.sms.simulator.bean.TypeOfNumber.UNKNOWN;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThrows;
import static testutils.SessionStrategyTestHelper.by;
import static testutils.SessionStrategyTestHelper.cleaned;
import static testutils.SessionStrategyTestHelper.closed;
import static testutils.SessionStrategyTestHelper.expirationOfLastRequest;
import static testutils.SessionStrategyTestHelper.isNull;
import static testutils.SessionStrategyTestHelper.not;
import static testutils.SessionStrategyTestHelper.opened;
import static testutils.SessionStrategyTestHelper.requests;
import static testutils.SessionStrategyTestHelper.sent;
import static testutils.SessionStrategyTestHelper.session;
import static testutils.SessionStrategyTestHelper.verifyThat;
import static testutils.SessionStrategyTestHelper.waitUntil;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import org.jsmpp.bean.SubmitSm;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cloudhopper.smpp.SmppClient;
import com.cloudhopper.smpp.SmppSession;
import com.cloudhopper.smpp.impl.DefaultSmppClient;
import fr.sii.ogham.core.exception.MessagingException;
import fr.sii.ogham.sms.builder.cloudhopper.CloudhopperBuilder;
import fr.sii.ogham.sms.builder.cloudhopper.SmppClientSupplier;
import fr.sii.ogham.sms.message.Sms;
import fr.sii.ogham.sms.sender.impl.CloudhopperSMPPSender;
import fr.sii.ogham.sms.sender.impl.cloudhopper.exception.SmppException;
import fr.sii.ogham.testing.assertion.sms.AssertSms;
import fr.sii.ogham.testing.assertion.sms.ExpectedAddressedPhoneNumber;
import fr.sii.ogham.testing.assertion.sms.ExpectedSms;
import fr.sii.ogham.testing.extension.junit.LoggingTestRule;
import fr.sii.ogham.testing.extension.junit.sms.config.ServerConfig;
import fr.sii.ogham.testing.sms.simulator.SmppServerException;
import fr.sii.ogham.testing.sms.simulator.jsmpp.JSMPPServer;
import fr.sii.ogham.testing.sms.simulator.jsmpp.SubmitSmAdapter;
import testutils.SessionStrategyTestHelper.SessionAware;
import testutils.SessionStrategyTestHelper.TestContext;
import testutils.TrackClientAndSessionsDecorator;
public class ReuseSessionStrategyTest implements Supplier<TestContext> {
private static final Logger LOG = LoggerFactory.getLogger(ReuseSessionStrategyTest.class);
private static final String RECIPIENT = "0203040506";
private static final String SENDER = "+33203040506";
@Rule public final LoggingTestRule loggingRule = new LoggingTestRule();
@Rule public final MockitoRule mockito = MockitoJUnit.rule();
private CloudhopperSMPPSender sender;
private CloudhopperBuilder builder;
private JSMPPServer manualServer;
@Spy SmppClient client1 = new DefaultSmppClient();
@Spy SmppClient client2 = new DefaultSmppClient();
List<SmppClient> clients;
List<SmppSession> allSessions = new ArrayList<>();
@Spy SmppClientSupplier supplier = new TrackClientAndSessionsDecorator(() -> clients, () -> allSessions);
@Before
public void setup() throws IOException {
clients = asList(client1, client2);
builder = new CloudhopperBuilder()
.host("127.0.0.1")
.clientSupplier(supplier)
.session()
.connectRetry()
.fixedDelay()
.maxRetries(10)
.delay(500L)
.and()
.and()
.and();
// @formatter:on
}
@After
public void cleanup() throws SmppServerException {
if (manualServer != null) {
manualServer.stop();
}
}
// @formatter:off
/**
*
* <pre>{@code
* ┌─────────┐ ┌─────────┐
* │ Client │ │ Server │
* └────┬────┘ └────┬────┘
* │ ├─┐ start()
* │ │<┘
* │ │
* │ │
* ├─┐ send(Sms(sms content 1 / session 1)) │
* │<┘ │
* │ connect [session 1] │
* ├─────────────────────────────────────────────>│
* │ connected │
* │<─────────────────────────────────────────────┤
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* : :
* : wait for expiration of last request (200ms) : (?) expiration is configured to 100ms (=> need to send EnquireLink)
* : :
* │ │
* │ │
* ├─┐ send(Sms(sms content 2 / session 1)) │
* │<┘ │
* │ send EnquireLink │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* : :
* : wait for expiration of last request (200ms) : (?) expiration is configured to 100ms (=> need to send EnquireLink)
* : :
* │ │
* │ │
* ├─┐ send(Sms(sms content 3 / session 1)) │
* │<┘ │
* │ send EnquireLink │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
*
* }</pre>
*
*/
@Test
@SuppressWarnings("javadoc")
public void reuseSession() throws Exception {
manualServer = new JSMPPServer(new ServerConfig().randomPort().build());
manualServer.start();
// @formatter:off
sender = builder
.port(manualServer.getPort())
.session()
.responseTimeout(200L)
.reuseSession()
.enable(true)
.responseTimeout(100L)
.lastInteractionExpiration(100L)
.and()
.and()
.build();
// @formatter:on
// send one SMS
sender.send(new Sms().content("sms content 1 / session 1").from(SENDER).to(RECIPIENT));
waitUntil(expirationOfLastRequest(200));
// send another SMS with same session
sender.send(new Sms().content("sms content 2 / session 1").from(SENDER).to(RECIPIENT));
waitUntil(expirationOfLastRequest(200));
// send another SMS with same session
sender.send(new Sms().content("sms content 3 / session 1").from(SENDER).to(RECIPIENT));
AssertSms.assertEquals(
Arrays.asList(
new ExpectedSms("sms content 1 / session 1",
new ExpectedAddressedPhoneNumber(SENDER, UNKNOWN, ISDN),
new ExpectedAddressedPhoneNumber(RECIPIENT, UNKNOWN, ISDN)),
new ExpectedSms("sms content 2 / session 1",
new ExpectedAddressedPhoneNumber(SENDER, UNKNOWN, ISDN),
new ExpectedAddressedPhoneNumber(RECIPIENT, UNKNOWN, ISDN)),
new ExpectedSms("sms content 3 / session 1",
new ExpectedAddressedPhoneNumber(SENDER, UNKNOWN, ISDN),
new ExpectedAddressedPhoneNumber(RECIPIENT, UNKNOWN, ISDN))),
convert(manualServer.getReceivedMessages()));
// ensure that connection has been done only one time
// and 2 EnquireLink requests have been sent
verifyThat(this)
.sessions(opened(1))
.enquireLinks(sent(requests(2), by(session(0))));
// ensure that session is still running
verifyThat(this)
.session(0, opened())
.client(client1, not(cleaned()))
.session(1, isNull())
.client(client2, not(cleaned()));
// manual cleanup
sender.clean();
// ensure that session is correctly closed
verifyThat(this)
.session(0, closed())
.client(client1, cleaned())
.session(1, isNull())
.client(client2, not(cleaned()));
}
// @formatter:off
/**
*
* <pre>{@code
* ┌─────────┐ ┌─────────┐
* │ Client │ │ Server │
* └────┬────┘ └────┬────┘
* │ ├─┐ start()
* │ │<┘
* │ │
* │ │
* ├─┐ send(Sms(sms content 1 / session 1)) │
* │<┘ │
* │ connect [session 1] │
* ├─────────────────────────────────────────────>│
* │ connected │
* │<─────────────────────────────────────────────┤
* │ │
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* : :
* : wait for expiration of last request (200ms) : (?) expiration is configured to 100ms (=> need to send EnquireLink)
* : :
* │ │
* │ │
* ├─┐ send(Sms(sms content 2 / session 1)) │
* │<┘ │
* │ send EnquireLink │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ ├─┐ wait(200ms)
* │ │<┘
* : :
* : wait for expiration of last request (200ms) : (?) expiration is configured to 100ms (=> need to send EnquireLink)
* : :
* │ │
* │ │
* : :
* : wait for reception of messages :
* : :
* │ │
* │ ├─┐ stop() (?) session is closed by the server => need a new session
* │ │<┘
* │ ├─┐ start()
* │ │<┘
* │ │
* ├─┐ send(Sms(sms content 3 / session 2)) │
* │<┘ │
* │ send EnquireLink │
* ├─────────────────────────────────────────────>│
* │ /!\ failure │ (?) ClosedChannelException
* │<─────────────────────────────────────────────┤
* ├─┐ closing [session 1] │
* │<┘ │
* │ │
* │ connect [session 2] │
* ├─────────────────────────────────────────────>│
* │ connected │
* │<─────────────────────────────────────────────┤
* │ │
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* │ │
* │ │
* ├─┐ send(Sms(sms content 4 / session 2)) │
* │<┘ │
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
*
* }</pre>
*
*/
// @formatter:on
@Test
@SuppressWarnings("javadoc")
public void reuseSessionButSessionClosedByServer() throws Exception {
/**
* GIVEN
*/
// @formatter:off
manualServer = new JSMPPServer(new ServerConfig().randomPort().build());
// @formatter:on
manualServer.start();
// @formatter:off
sender = builder
.port(manualServer.getPort())
.session()
.responseTimeout(500L)
.reuseSession()
.enable(true)
.responseTimeout(200L)
.lastInteractionExpiration(100L)
.and()
.and()
.build();
// @formatter:on
/**
* WHEN
*/
// send one SMS
sender.send(new Sms().content("sms content 1 / session 1").from(SENDER).to(RECIPIENT));
waitUntil(expirationOfLastRequest(200));
// send another SMS with same session
sender.send(new Sms().content("sms content 2 / session 1").from(SENDER).to(RECIPIENT));
waitUntil(expirationOfLastRequest(200));
// stop the server
manualServer.stop();
List<SubmitSm> session1Messages = manualServer.getReceivedMessages();
// restart the server
manualServer.start();
// send another SMS with new session
sender.send(new Sms().content("sms content 3 / session 2").from(SENDER).to(RECIPIENT));
// send another SMS with same session
sender.send(new Sms().content("sms content 4 / session 2").from(SENDER).to(RECIPIENT));
List<SubmitSm> session2Messages = manualServer.getReceivedMessages();
/**
* THEN
*/
assertThat(convert(session1Messages))
.count(is(2))
.message(0).content(is("sms content 1 / session 1")).and()
.message(1).content(is("sms content 2 / session 1"));
assertThat(convert(session2Messages))
.count(is(2))
.message(0).content(is("sms content 3 / session 2")).and()
.message(1).content(is("sms content 4 / session 2"));
// ensure that connection has been done two times
// and 2 EnquireLink requests have been sent by first session
// and no EnquireLink requests has been sent by second session
verifyThat(this)
.sessions(opened(2))
.enquireLinks(sent(requests(2), by(session(0))))
.enquireLinks(sent(requests(0), by(session(1))));
// ensure that first session has been automatically closed
// and second session is still running
verifyThat(this)
.session(0, closed())
.client(client1, cleaned())
.session(1, opened())
.client(client2, not(cleaned()));
// manual cleanup
sender.clean();
// ensure that all sessions are correctly closed
verifyThat(this)
.session(0, closed())
.client(client1, cleaned())
.session(1, closed())
.client(client2, cleaned());
}
// @formatter:off
/**
*
* <pre>{@code
* ┌─────────┐ ┌─────────┐
* │ Client │ │ Server │
* └────┬────┘ └────┬────┘
* │ ├─┐ start()
* │ │<┘
* │ │
* │ │
* ├─┐ send(Sms(sms content 1 / session 1)) │
* │<┘ │
* │ connect [session 1] │
* ├─────────────────────────────────────────────>│
* │ connected │
* │<─────────────────────────────────────────────┤
* │ │
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* : :
* : wait for expiration of last request (50ms) : (?) expiration is configured to 20ms
* : :
* │ │
* │ │
* ├─┐ send(Sms(sms content 2 / session 2)) │
* │<┘ │
* │ send EnquireLink │
* ├─────────────────────────────────────────────>│
* │ ├─┐ wait(300ms)
* ├─┐ timeout (100ms) │ │
* │<┘ │ │
* │ │ :
* │ │
* │ unbind [session 1] │
* ├─────────────────────────────────────────────>│
* │ disconnected │
* │<─────────────────────────────────────────────┤
* │ │
* │ connect [session 2] │
* ├─────────────────────────────────────────────>│
* │ connected │
* │<─────────────────────────────────────────────┤
* │ │
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
*
* }</pre>
*
*/
// @formatter:on
@Test
@SuppressWarnings("javadoc")
public void reuseSessionButEnquireLinkTimeout() throws Exception {
/**
* GIVEN
*/
// @formatter:off
manualServer = new JSMPPServer(new ServerConfig()
.randomPort()
.slow()
.sendEnquireLinkRespDelay(300L)
.and()
.build());
// @formatter:on
manualServer.start();
// @formatter:off
sender = builder
.port(manualServer.getPort())
.session()
.reuseSession()
.enable(true)
.responseTimeout(100L)
.lastInteractionExpiration(20L) // do not send EnquireLink the first time but send the second time
.and()
.and()
.build();
// @formatter:on
/**
* WHEN
*/
// send one SMS with new session (no EnquireLink on first connection)
sender.send(new Sms().content("sms content 1 / session 1").from(SENDER).to(RECIPIENT));
waitUntil(expirationOfLastRequest(50));
// send another SMS with new session (EnquireLink has timed-out)
sender.send(new Sms().content("sms content 2 / session 2").from(SENDER).to(RECIPIENT));
/**
* THEN
*/
assertThat(convert(manualServer.getReceivedMessages()))
.count(is(2))
.message(0).content(is("sms content 1 / session 1")).and()
.message(1).content(is("sms content 2 / session 2"));
// ensure that connection has been done two times
// ensure that EnquireLink has been sent to check if session is still active on session 1 (but failed)
// ensure that EnquireLink has not been sent to check if session is still active on session 2
verifyThat(this)
.sessions(opened(2))
.enquireLinks(sent(requests(1), by(session(0))))
.enquireLinks(sent(requests(0), by(session(1))));
// ensure that first session has been automatically closed
// and second session is still running
verifyThat(this)
.session(0, closed())
.client(client1, cleaned())
.session(1, opened())
.client(client2, not(cleaned()));
// manual cleanup
sender.clean();
// ensure that all sessions are correctly closed
verifyThat(this)
.session(0, closed())
.client(client1, cleaned())
.session(1, closed())
.client(client2, cleaned());
}
// @formatter:off
/**
*
* <pre>{@code
* ┌─────────┐ ┌─────────┐
* │ Client │ │ Server │
* └────┬────┘ └────┬────┘
* │ ├─┐ start()
* │ │<┘
* │ │
* │ │
* ├─┐ send(Sms(sms content 1 / session 1)) │
* │<┘ │
* │ connect [session 1] │
* ├─────────────────────────────────────────────>│
* │ connected │
* │<─────────────────────────────────────────────┤
* │ │
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* │ ├─┐ stop() (?) session is closed by the server => need a new session
* │ │<┘
* │ │
* ├─┐ send(Sms(can't be sent)) │
* │<┘ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ /!\ failure │
* │<─────────────────────────────────────────────┤
* │ │
* ├─┐ closing [session 1] │
* │<┘ │
* │ unbind [session 1] │
* ├─────────────────────────────────────────────>│
* │ disconnected │
* │<─────────────────────────────────────────────┤
* │ │
* : ├─┐ start()
* : │<┘
* : wait for server ready │
* : │
* : │
* ├─┐ send(Sms(sms content 2 / session 2)) │
* │<┘ │
* │ connect [session 2] │
* ├─────────────────────────────────────────────>│
* │ connected │
* │<─────────────────────────────────────────────┤
* │ │
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* │ │
* │ ├─┐ wait(200ms)
* │ │<┘
* : :
* : wait for expiration of last request (200ms) : (?) expiration is configured to 100ms (=> need to send EnquireLink)
* : :
* │ │
* │ │
* │ │
* ├─┐ send(Sms(sms content 3 / session 2)) │
* │<┘ │
* │ send EnquireLink │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
* │ │
* │ send SubmitSm │
* ├─────────────────────────────────────────────>│
* │ response │
* │<─────────────────────────────────────────────┤
*
* }</pre>
*
*/
// @formatter:on
@Test
@SuppressWarnings("javadoc")
public void reuseSessionButSendFailsDueToSessionClosedByServer() throws Exception {
/**
* GIVEN
*/
manualServer = new JSMPPServer(new ServerConfig().randomPort().build());
manualServer.start();
// @formatter:off
sender = builder
.port(manualServer.getPort())
.session()
.responseTimeout(500L)
.reuseSession()
.enable(true)
.responseTimeout(200L)
.lastInteractionExpiration(100L)
.and()
.and()
.build();
// @formatter:on
/**
* WHEN
*/
// send one SMS
sender.send(new Sms().content("sms content 1 / session 1").from(SENDER).to(RECIPIENT));
// stop the server
LOG.debug("Stopping server...");
manualServer.stop();
LOG.debug("Server stopped");
List<SubmitSm> session1Messages = manualServer.getReceivedMessages();
MessagingException sendFailure = assertThrows("should indicate that message couldn't be sent", MessagingException.class, () -> {
sender.send(new Sms().content("can't be sent").from(SENDER).to(RECIPIENT));
});
// restart the server
LOG.debug("Restarting server...");
manualServer.start();
LOG.debug("Server restarted...");
// send another SMS with new session
sender.send(new Sms().content("sms content 2 / session 2").from(SENDER).to(RECIPIENT));
waitUntil(expirationOfLastRequest(200));
// send another SMS with same session
sender.send(new Sms().content("sms content 3 / session 2").from(SENDER).to(RECIPIENT));
List<SubmitSm> session2Messages = manualServer.getReceivedMessages();
/**
* THEN
*/
assertThat("should indicate why message couldn't be sent", sendFailure, hasAnyCause(SmppException.class));
assertThat("should indicate source of send failure", sendFailure, hasAnyCause(ClosedChannelException.class));
assertThat(convert(session1Messages))
.count(is(1))
.message(0).content(is("sms content 1 / session 1"));
assertThat(convert(session2Messages))
.count(is(2))
.message(0).content(is("sms content 2 / session 2")).and()
.message(1).content(is("sms content 3 / session 2"));
// ensure that connection has been done two times
// and 2 EnquireLink requests have been sent by first session
// and no EnquireLink requests has been sent by second session
verifyThat(this)
.sessions(opened(2))
.enquireLinks(sent(requests(0), by(session(0))))
.enquireLinks(sent(requests(1), by(session(1))));
// ensure that first session has been automatically closed
// and second session is still running
verifyThat(this)
.session(0, closed())
.client(client1, cleaned())
.session(1, opened())
.client(client2, not(cleaned()));
// manual cleanup
sender.clean();
// ensure that all sessions are correctly closed
verifyThat(this)
.session(0, closed())
.client(client1, cleaned())
.session(1, closed())
.client(client2, cleaned());
}
@Override
public TestContext get() {
return new ReuseSessionTestContext();
}
class ReuseSessionTestContext implements TestContext, SessionAware {
public List<SmppClient> getClients() {
return clients;
}
public List<SmppSession> getSessions() {
return allSessions;
}
public SmppClientSupplier getSupplier() {
return supplier;
}
}
private List<fr.sii.ogham.testing.sms.simulator.bean.SubmitSm> convert(List<SubmitSm> rawMessages) {
return rawMessages.stream().map(m -> new SubmitSmAdapter(m)).collect(toList());
}
}
| 43.17867
| 146
| 0.395477
|
c926bcf4a6be84896fb59e9fb060433a1ef76bf6
| 7,542
|
package graphql.nadel.engine.transformation;
import graphql.language.Argument;
import graphql.language.AstNodeAdapter;
import graphql.language.Field;
import graphql.language.FragmentDefinition;
import graphql.language.InlineFragment;
import graphql.language.Node;
import graphql.language.NodeVisitorStub;
import graphql.language.ObjectField;
import graphql.language.Value;
import graphql.nadel.engine.FieldMetadataUtil;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLFieldsContainer;
import graphql.schema.GraphQLInputObjectField;
import graphql.schema.GraphQLInputObjectType;
import graphql.schema.GraphQLInputValueDefinition;
import graphql.schema.GraphQLOutputType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLUnmodifiedType;
import graphql.util.TraversalControl;
import graphql.util.TraverserContext;
import graphql.util.TraverserVisitorStub;
import graphql.util.TreeTransformer;
import graphql.util.TreeTransformerUtil;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import static graphql.Assert.assertNotNull;
import static graphql.introspection.Introspection.TypeNameMetaFieldDef;
import static graphql.schema.GraphQLTypeUtil.unwrapAll;
/**
* Traverses a query and saves type information while doing it.
* Ever field gets an additionalData entry pointing to an {@link OverallTypeInfo}
*/
public class RecordOverallTypeInformation {
public <T extends Node> OverallTypeInformation<T> recordOverallTypes(T node, GraphQLSchema graphQLSchema, GraphQLOutputType rootOutputType) {
Map<String, OverallTypeInfo> overallTypeInfoMap = new LinkedHashMap<>();
NodeVisitorStub recordTypeInfos = new NodeVisitorStub() {
@Override
public TraversalControl visitArgument(Argument argument, TraverserContext<Node> context) {
GraphQLFieldDefinition fieldDefinition = context.getVarFromParents(GraphQLFieldDefinition.class);
GraphQLArgument graphQLArgument = fieldDefinition.getArgument(argument.getName());
context.setVar(GraphQLArgument.class, graphQLArgument);
context.setVar(GraphQLInputValueDefinition.class, graphQLArgument);
String id = UUID.randomUUID().toString();
OverallTypeInfo overallTypeInfo = new OverallTypeInfo(null, fieldDefinition, graphQLArgument, null);
overallTypeInfoMap.put(id, overallTypeInfo);
Argument changedArgument = FieldMetadataUtil.setOverallTypeInfoId(argument, id);
return TreeTransformerUtil.changeNode(context, changedArgument);
}
@Override
public TraversalControl visitObjectField(ObjectField node, TraverserContext<Node> context) {
GraphQLInputValueDefinition graphQLInputValueDefinition = context.getVarFromParents(GraphQLInputValueDefinition.class);
GraphQLUnmodifiedType unmodifiedType = unwrapAll(graphQLInputValueDefinition.getType());
// technically a scalar type can have an AST object field - eg field( arg : Json) -> field(arg : { ast : "here" })
if (unmodifiedType instanceof GraphQLInputObjectType) {
GraphQLInputObjectType inputObjectType = (GraphQLInputObjectType) unmodifiedType;
GraphQLInputObjectField inputObjectTypeField = inputObjectType.getField(node.getName());
context.setVar(GraphQLInputValueDefinition.class, inputObjectTypeField);
}
return TraversalControl.CONTINUE;
}
@Override
protected TraversalControl visitValue(Value<?> value, TraverserContext<Node> context) {
GraphQLArgument graphQLArgument = context.getVarFromParents(GraphQLArgument.class);
GraphQLInputValueDefinition graphQLInputValueDefinition = context.getVarFromParents(GraphQLInputValueDefinition.class);
String id = UUID.randomUUID().toString();
OverallTypeInfo overallTypeInfo = new OverallTypeInfo(
null,
null,
graphQLArgument,
graphQLInputValueDefinition);
overallTypeInfoMap.put(id, overallTypeInfo);
Value changedValue = FieldMetadataUtil.setOverallTypeInfoId(value, id);
return TreeTransformerUtil.changeNode(context, changedValue);
}
@Override
public TraversalControl visitFragmentDefinition(FragmentDefinition fragmentDefinition, TraverserContext<Node> context) {
GraphQLOutputType outputType = (GraphQLOutputType) assertNotNull(graphQLSchema.getType(fragmentDefinition.getTypeCondition().getName()));
context.setVar(GraphQLOutputType.class, outputType);
return TraversalControl.CONTINUE;
}
@Override
public TraversalControl visitInlineFragment(InlineFragment inlineFragment, TraverserContext<Node> context) {
if (inlineFragment.getTypeCondition() == null) {
return TraversalControl.CONTINUE;
}
GraphQLOutputType outputType = (GraphQLOutputType) assertNotNull(graphQLSchema.getType(inlineFragment.getTypeCondition().getName()));
context.setVar(GraphQLOutputType.class, outputType);
return TraversalControl.CONTINUE;
}
@Override
public TraversalControl visitField(Field field, TraverserContext<Node> context) {
if (field.getName().equals(TypeNameMetaFieldDef.getName())) {
return TraversalControl.CONTINUE;
}
GraphQLFieldsContainer fieldsContainer = (GraphQLFieldsContainer) unwrapAll(context.getVarFromParents(GraphQLOutputType.class));
GraphQLFieldDefinition fieldDefinition = assertNotNull(fieldsContainer.getFieldDefinition(field.getName()), "field %s not found for type %s", field.getName(), fieldsContainer.getName());
context.setVar(GraphQLFieldDefinition.class, fieldDefinition);
GraphQLOutputType newOutputType = fieldDefinition.getType();
context.setVar(GraphQLOutputType.class, newOutputType);
String id = UUID.randomUUID().toString();
OverallTypeInfo overallTypeInfo = new OverallTypeInfo(fieldsContainer, fieldDefinition, null, null);
overallTypeInfoMap.put(id, overallTypeInfo);
Field changedField = FieldMetadataUtil.setOverallTypeInfoId(field, id);
return TreeTransformerUtil.changeNode(context, changedField);
}
};
TreeTransformer<Node> treeTransformer = new TreeTransformer<>(AstNodeAdapter.AST_NODE_ADAPTER);
Map<Class<?>, Object> rootVars = new LinkedHashMap<>();
if (rootOutputType != null) {
rootVars.put(GraphQLOutputType.class, rootOutputType);
}
Node newNode = treeTransformer.transform(node, new TraverserVisitorStub<Node>() {
@Override
public TraversalControl enter(TraverserContext<Node> context) {
return context.thisNode().accept(context, recordTypeInfos);
}
},
rootVars
);
return new OverallTypeInformation<>((T) newNode, overallTypeInfoMap);
}
}
| 52.375
| 202
| 0.695306
|
7e7fa19c1fe169a1217e4264f0bbdcb3d1662c2c
| 1,693
|
package presentacion.eventos;
/**
* The Class EventosLibro.
*/
public class EventosLibro {
/** The Constant ALTA_LIBRO. */
public static final int ALTA_LIBRO = 51;// TODO
/** The Constant ALTA_LIBRO_KO. */
public static final int ALTA_LIBRO_KO = 57;
/** The Constant ALTA_LIBRO_OK. */
// Resultados de las operaciones
public static final int ALTA_LIBRO_OK = 56;
/** The Constant BAJA_LIBRO. */
public static final int BAJA_LIBRO = 52;
/** The Constant BAJA_LIBRO_KO. */
public static final int BAJA_LIBRO_KO = 59;
/** The Constant BAJA_LIBRO_OK. */
public static final int BAJA_LIBRO_OK = 58;
/** The Constant BUSCAR_LIBRO. */
public static final int BUSCAR_LIBRO = 74;
/** The Constant BUSCAR_LIBRO_KO. */
public static final int BUSCAR_LIBRO_KO = 70;
/** The Constant BUSCAR_LIBRO_OK. */
public static final int BUSCAR_LIBRO_OK = 69;
/** The Constant LISTAR_LIBROS. */
public static final int LISTAR_LIBROS = 55;
/** The Constant LISTAR_LIBROS_KO. */
public static final int LISTAR_LIBROS_KO = 65;
/** The Constant LISTAR_LIBROS_OK. */
public static final int LISTAR_LIBROS_OK = 64;
/** The Constant MODIFICAR_LIBRO. */
public static final int MODIFICAR_LIBRO = 53;
/** The Constant MODIFICAR_LIBRO_KO. */
public static final int MODIFICAR_LIBRO_KO = 61;
/** The Constant MODIFICAR_LIBRO_OK. */
public static final int MODIFICAR_LIBRO_OK = 60;
/** The Constant MOSTRAR_LIBRO. */
public static final int MOSTRAR_LIBRO = 54;
/** The Constant MOSTRAR_LIBRO_KO. */
public static final int MOSTRAR_LIBRO_KO = 63;
/** The Constant MOSTRAR_LIBRO_OK. */
public static final int MOSTRAR_LIBRO_OK = 62;
}
| 26.453125
| 50
| 0.710573
|
36c12ff42e0c63cb7de9d464a2bb79b00adc5c33
| 219
|
package com.example.skincancer;
public class YoutubeConfig {
public YoutubeConfig(){
}
private static final String API_key = "";
public static String getAPI_key() {
return API_key;
}
}
| 16.846154
| 48
| 0.648402
|
03f384ddc2328820f1a3801e9de1c9afed77b782
| 525
|
package pl.uw.mim.jnp.rock.paper.money.app.usecases.game;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import pl.uw.mim.jnp.rock.paper.money.api.models.GameProgress;
import pl.uw.mim.jnp.rock.paper.money.app.services.GameInfoService;
import reactor.core.publisher.Mono;
@Component
@AllArgsConstructor
public class GameInfo {
private final GameInfoService gameInfoService;
public Mono<GameProgress> execute(Long gameId) {
return gameInfoService.getGameProgress(gameId);
}
}
| 27.631579
| 67
| 0.809524
|
4713bab5ae39c671f902a020c7fd59238736545c
| 1,021
|
package com.hujiayi.auxiliaryteach.edu.controller.dto;
import com.hujiayi.auxiliaryteach.common.dto.ChapterDto;
import com.hujiayi.auxiliaryteach.edu.entity.Chapter;
import com.hujiayi.auxiliaryteach.edu.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/edu/chapter/dto")
@RestController
public class ChapterDtoController {
@Autowired
private ChapterService chapterService;
@RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
public ChapterDto selectChapter(@PathVariable("id") String id) {
ChapterDto chapterDto = new ChapterDto();
Chapter chapter = chapterService.getById(id);
chapterDto.setTitle(chapter.getTitle());
return chapterDto;
}
}
| 36.464286
| 72
| 0.787463
|
9b29ad3a7482cfd306ad8e78640f75e8a9118814
| 6,374
|
/**
* There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
*/
package com.zhongxin.ctsms.modules.coal.entity;
import com.zhongxin.ctsms.common.persistence.DataEntity;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 合同Entity
*
* @author Blue Devil
* @version 2013-07-01
*/
@Entity
@Table(name = "t_contract_info")
@DynamicInsert @DynamicUpdate
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Contract extends DataEntity implements Serializable {
private static final long serialVersionUID = 1L;
private Long contractSid; // 主键ID
private String contractId; // 合同编号
private String processInstanceId; // 流程实例ID
private String contractType; // 合同类型
private String supplyId; // 供方编码
private String demandId; // 需方编码
private Long number; // 数量
private Long amount; // 金额
private String feeSts; //费用状态
private Integer feeItemId; // 费用流水
private String sts; // 状态
private Date stsDate; //状态时间
private Date signDate; //签订日期
private Date startDate; //开始时间
private Date endDate; //结束时间
private String coalType; // 煤种
private Integer calorie; // 热卡
private Float price; // 执行单价
private String deliveryPlace; // 交货地点
private String taxFlag; // 是否含税 0:不含 1:含
private String payMode; // 结算方式
private String transType; // 运输类型
private String payType; // 结算类型
private List<PFile> files; // 上传的项目相关文件
@Transient
private List<CommonsMultipartFile> fileData;
public Contract() {
super();
this.sts = "0";
this.stsDate = new Date();
}
public Contract(Long id) {
this();
this.contractSid = id;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getContractSid() {
return contractSid;
}
public void setContractSid(Long contractSid) {
this.contractSid = contractSid;
}
@NotNull
public String getContractId() {
return contractId;
}
public void setContractId(String contractId) {
this.contractId = contractId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@NotNull
public String getContractType() {
return contractType;
}
public void setContractType(String contractType) {
this.contractType = contractType;
}
public String getSupplyId() {
return supplyId;
}
public void setSupplyId(String supplyId) {
this.supplyId = supplyId;
}
public String getDemandId() {
return demandId;
}
public void setDemandId(String demandId) {
this.demandId = demandId;
}
@NotNull
public Long getNumber() {
return number;
}
public void setNumber(Long number) {
this.number = number;
}
@NotNull
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public String getFeeSts() {
return feeSts;
}
public void setFeeSts(String feeSts) {
this.feeSts = feeSts;
}
public Integer getFeeItemId() {
return feeItemId;
}
public void setFeeItemId(Integer feeItemId) {
this.feeItemId = feeItemId;
}
@NotNull
public String getSts() {
return sts;
}
public void setSts(String sts) {
this.sts = sts;
}
@NotNull
public Date getStsDate() {
return stsDate;
}
public void setStsDate(Date stsDate) {
this.stsDate = stsDate;
}
@NotNull(message = "签订日期不能为空")
public Date getSignDate() {
return signDate;
}
public void setSignDate(Date signDate) {
this.signDate = signDate;
}
@NotNull(message = "合同开始时间不能为空")
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@NotNull(message = "合同到期时间不能为空")
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@OneToMany(cascade = { CascadeType.REFRESH, CascadeType.PERSIST,CascadeType.MERGE, CascadeType.REMOVE },mappedBy="contract")
public List<PFile> getFiles() {
return files;
}
public void setFiles(List<PFile> files) {
this.files = files;
}
@Transient
public List<CommonsMultipartFile> getFileData() {
return fileData;
}
@Transient
public void setFileData(List<CommonsMultipartFile> fileData) {
this.fileData = fileData;
}
public String getCoalType() {
return coalType;
}
public void setCoalType(String coalType) {
this.coalType = coalType;
}
public Integer getCalorie() {
return calorie;
}
public void setCalorie(Integer calorie) {
this.calorie = calorie;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getDeliveryPlace() {
return deliveryPlace;
}
public void setDeliveryPlace(String deliveryPlace) {
this.deliveryPlace = deliveryPlace;
}
public String getTaxFlag() {
return taxFlag;
}
public void setTaxFlag(String taxFlag) {
this.taxFlag = taxFlag;
}
public String getPayMode() {
return payMode;
}
public void setPayMode(String payMode) {
this.payMode = payMode;
}
public String getTransType() {
return transType;
}
public void setTransType(String transType) {
this.transType = transType;
}
public String getPayType() {
return payType;
}
public void setPayType(String payType) {
this.payType = payType;
}
}
| 22.131944
| 128
| 0.6401
|
2c43d7c7028a75620503d8886acb70424b6d18b2
| 26,229
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chromoting;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.util.Pair;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ViewConfiguration;
import java.util.ArrayList;
import java.util.List;
/**
* This class is responsible for handling Touch input from the user. Touch events which manipulate
* the local canvas are handled in this class and any input which should be sent to the remote host
* are passed to the InputStrategyInterface implementation set by the DesktopView.
*/
public class TouchInputHandler {
private static final float EPSILON = 0.001f;
private final List<Pair<Object, Event<?>>> mAttachedEvents = new ArrayList<>();
private final Desktop mDesktop;
private final RenderData mRenderData;
private final DesktopCanvas mDesktopCanvas;
private final RenderStub mRenderStub;
private final GestureDetector mScroller;
private final ScaleGestureDetector mZoomer;
private final TapGestureDetector mTapDetector;
/** Used to disambiguate a 2-finger gesture as a swipe or a pinch. */
private final SwipePinchDetector mSwipePinchDetector;
// Used for processing cursor & scroller fling animations.
// May consider using a List of AnimationJob if we have more than two animation jobs in
// the future.
private final FlingAnimationJob mCursorAnimationJob;
private final FlingAnimationJob mScrollAnimationJob;
private InputStrategyInterface mInputStrategy;
/**
* Used for tracking swipe gestures. Only the Y-direction is needed for responding to swipe-up
* or swipe-down.
*/
private float mTotalMotionY;
/**
* Distance in pixels beyond which a motion gesture is considered to be a swipe. This is
* initialized using the Context passed into the ctor.
*/
private float mSwipeThreshold;
/**
* Distance, in pixels, from the edge of the screen in which a touch event should be considered
* as having originated from that edge.
*/
private final int mEdgeSlopInPx;
/**
* Defines an inset boundary within which pan gestures are allowed. Pan gestures which
* originate outside of this boundary will be ignored.
*/
private Rect mPanGestureBounds = new Rect();
/**
* Set to true to prevent any further movement of the cursor, for example, when showing the
* keyboard to prevent the cursor wandering from the area where keystrokes should be sent.
*/
private boolean mSuppressCursorMovement;
/**
* Set to true to suppress the fling animation at the end of a gesture, for example, when
* dragging whilst a button is held down.
*/
private boolean mSuppressFling;
/**
* Set to true when 2-finger fling (scroll gesture with final velocity) is detected to trigger
* a scrolling animation.
*/
private boolean mScrollFling;
/**
* Set to true when 3-finger swipe gesture is complete, so that further movement doesn't
* trigger more swipe actions.
*/
private boolean mSwipeCompleted;
/**
* Set to true when a 1 finger pan gesture originates with a longpress. This means the user
* is performing a drag operation.
*/
private boolean mIsDragging;
private Event.ParameterCallback<Boolean, Void> mProcessAnimationCallback;
/**
* This class implements fling animation for cursor
*/
private class CursorAnimationJob extends FlingAnimationJob {
public CursorAnimationJob(Context context) {
super(context);
}
@Override
protected void processAction(float deltaX, float deltaY) {
float[] delta = {deltaX, deltaY};
Matrix canvasToImage = new Matrix();
mRenderData.transform.invert(canvasToImage);
canvasToImage.mapVectors(delta);
moveViewportByOffset(-delta[0], -delta[1]);
}
}
/**
* This class implements fling animation for scrolling
*/
private class ScrollAnimationJob extends FlingAnimationJob {
public ScrollAnimationJob(Context context) {
super(context);
}
@Override
protected void processAction(float deltaX, float deltaY) {
mInputStrategy.onScroll(-deltaX, -deltaY);
}
}
/**
* This class provides a NULL implementation which will be used until a real input
* strategy has been created and set. Using this as the default implementation will prevent
* crashes if the owning class does not create/set a real InputStrategy before the host size
* information is received (or if the user interacts with the screen in that case). This class
* has default values which will also allow the user to pan/zoom the desktop image until an
* InputStrategy implementation has been set.
*/
private static class NullInputStrategy implements InputStrategyInterface {
NullInputStrategy() {}
@Override
public boolean onTap(int button) {
return false;
}
@Override
public boolean onPressAndHold(int button) {
return false;
}
@Override
public void onMotionEvent(MotionEvent event) {
return;
}
@Override
public void onScroll(float distanceX, float distanceY) {
return;
}
@Override
public void injectCursorMoveEvent(int x, int y) {
return;
}
@Override
public @RenderStub.InputFeedbackType int getShortPressFeedbackType() {
return RenderStub.InputFeedbackType.NONE;
}
@Override
public @RenderStub.InputFeedbackType int getLongPressFeedbackType() {
return RenderStub.InputFeedbackType.NONE;
}
@Override
public boolean isIndirectInputMode() {
return false;
}
}
public TouchInputHandler(DesktopView viewer, Desktop desktop, RenderStub renderStub,
final InputEventSender injector) {
Preconditions.notNull(viewer);
Preconditions.notNull(desktop);
Preconditions.notNull(renderStub);
Preconditions.notNull(injector);
mDesktop = desktop;
mRenderStub = renderStub;
mRenderData = new RenderData();
mDesktopCanvas = new DesktopCanvas(renderStub, mRenderData);
GestureListener listener = new GestureListener();
mScroller = new GestureDetector(desktop, listener, null, false);
// If long-press is enabled, the gesture-detector will not emit any further onScroll
// notifications after the onLongPress notification. Since onScroll is being used for
// moving the cursor, it means that the cursor would become stuck if the finger were held
// down too long.
mScroller.setIsLongpressEnabled(false);
mZoomer = new ScaleGestureDetector(desktop, listener);
mTapDetector = new TapGestureDetector(desktop, listener);
mSwipePinchDetector = new SwipePinchDetector(desktop);
// The threshold needs to be bigger than the ScaledTouchSlop used by the gesture-detectors,
// so that a gesture cannot be both a tap and a swipe. It also needs to be small enough so
// that intentional swipes are usually detected.
float density = desktop.getResources().getDisplayMetrics().density;
mSwipeThreshold = 40 * density;
mEdgeSlopInPx = ViewConfiguration.get(desktop).getScaledEdgeSlop();
mInputStrategy = new NullInputStrategy();
mCursorAnimationJob = new CursorAnimationJob(desktop);
mScrollAnimationJob = new ScrollAnimationJob(desktop);
mProcessAnimationCallback = new Event.ParameterCallback<Boolean, Void>() {
@Override
public Boolean run(Void p) {
return processAnimation();
}
};
attachEvent(viewer.onTouch(), new Event.ParameterRunnable<TouchEventParameter>() {
@Override
public void run(TouchEventParameter parameter) {
parameter.handled = handleTouchEvent(parameter.event);
}
});
attachEvent(desktop.onInputModeChanged(),
new Event.ParameterRunnable<InputModeChangedEventParameter>() {
@Override
public void run(InputModeChangedEventParameter parameter) {
handleInputModeChanged(parameter, injector);
}
});
attachEvent(desktop.onSystemUiVisibilityChanged(),
new Event.ParameterRunnable<SystemUiVisibilityChangedEventParameter>() {
@Override
public void run(SystemUiVisibilityChangedEventParameter parameter) {
mDesktopCanvas.onSystemUiVisibilityChanged(parameter);
}
});
attachEvent(renderStub.onClientSizeChanged(),
new Event.ParameterRunnable<SizeChangedEventParameter>() {
@Override
public void run(SizeChangedEventParameter parameter) {
handleClientSizeChanged(parameter.width, parameter.height);
}
});
attachEvent(renderStub.onHostSizeChanged(),
new Event.ParameterRunnable<SizeChangedEventParameter>() {
@Override
public void run(SizeChangedEventParameter parameter) {
handleHostSizeChanged(parameter.width, parameter.height);
}
});
}
private <ParamT> void attachEvent(Event<ParamT> event,
Event.ParameterRunnable<ParamT> runnable) {
mAttachedEvents.add(new Pair<Object, Event<?>>(event.add(runnable), event));
}
/**
* Detaches all registered event listeners. This function should be called exactly once.
*/
public void detachEventListeners() {
Preconditions.isTrue(!mAttachedEvents.isEmpty());
abortAnimation();
for (Pair<Object, Event<?>> pair : mAttachedEvents) {
pair.second.remove(pair.first);
}
mAttachedEvents.clear();
}
/**
* Steps forward the animation.
* @return true if the animation is not finished yet.
*/
private boolean processAnimation() {
return mCursorAnimationJob.processAnimation() || mScrollAnimationJob.processAnimation();
}
/**
* Start stepping animation when onCanvasRendered is triggered.
*/
private void startAnimation() {
mRenderStub.onCanvasRendered().addSelfRemovable(mProcessAnimationCallback);
}
/**
* Abort all animations.
*/
private void abortAnimation() {
mCursorAnimationJob.abortAnimation();
mScrollAnimationJob.abortAnimation();
}
private void handleInputModeChanged(
InputModeChangedEventParameter parameter, InputEventSender injector) {
final @Desktop.InputMode int inputMode = parameter.inputMode;
final @CapabilityManager.HostCapability int hostTouchCapability = parameter.hostCapability;
// We need both input mode and host input capabilities to select the input
// strategy.
if (!CapabilityManager.hostCapabilityIsSet(inputMode)
|| !CapabilityManager.hostCapabilityIsSet(hostTouchCapability)) {
return;
}
switch (inputMode) {
case Desktop.InputMode.TRACKPAD:
setInputStrategy(new TrackpadInputStrategy(mRenderData, injector));
mDesktopCanvas.adjustViewportForSystemUi(true);
moveCursorToScreenCenter();
break;
case Desktop.InputMode.TOUCH:
mDesktopCanvas.adjustViewportForSystemUi(false);
if (CapabilityManager.hostCapabilityIsSupported(hostTouchCapability)) {
setInputStrategy(new TouchInputStrategy(mRenderData, injector));
} else {
setInputStrategy(
new SimulatedTouchInputStrategy(mRenderData, injector, mDesktop));
}
break;
default:
// Unreachable, but required by Google Java style and findbugs.
assert false : "Unreached";
}
// Ensure the cursor state is updated appropriately.
mRenderStub.setCursorVisibility(mRenderData.drawCursor);
}
private boolean handleTouchEvent(MotionEvent event) {
// Give the underlying input strategy a chance to observe the current motion event before
// passing it to the gesture detectors. This allows the input strategy to react to the
// event or save the payload for use in recreating the gesture remotely.
mInputStrategy.onMotionEvent(event);
// Avoid short-circuit logic evaluation - ensure all gesture detectors see all events so
// that they generate correct notifications.
boolean handled = mScroller.onTouchEvent(event);
handled |= mZoomer.onTouchEvent(event);
handled |= mTapDetector.onTouchEvent(event);
mSwipePinchDetector.onTouchEvent(event);
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
abortAnimation();
mSuppressCursorMovement = false;
mSuppressFling = false;
mSwipeCompleted = false;
mIsDragging = false;
break;
case MotionEvent.ACTION_POINTER_DOWN:
mTotalMotionY = 0;
break;
default:
break;
}
return handled;
}
private void handleClientSizeChanged(int width, int height) {
mRenderData.screenWidth = width;
mRenderData.screenHeight = height;
mDesktopCanvas.setSafeInsets(mDesktop.getSafeInsets());
mPanGestureBounds = new Rect(
mEdgeSlopInPx, mEdgeSlopInPx, width - mEdgeSlopInPx, height - mEdgeSlopInPx);
resizeImageToFitScreen();
mDesktop.sendPreferredHostResolution();
}
private void handleHostSizeChanged(int width, int height) {
mRenderData.imageWidth = width;
mRenderData.imageHeight = height;
resizeImageToFitScreen();
}
private void resizeImageToFitScreen() {
if (mRenderData.imageWidth == 0 || mRenderData.imageHeight == 0
|| mRenderData.screenWidth == 0 || mRenderData.screenHeight == 0) {
return;
}
mDesktopCanvas.resizeImageToFitScreen();
moveCursorToScreenCenter();
}
private void moveCursorToScreenCenter() {
float screenCenterX = (float) mRenderData.screenWidth / 2;
float screenCenterY = (float) mRenderData.screenHeight / 2;
float[] imagePoint = mapScreenPointToImagePoint(screenCenterX, screenCenterY);
mDesktopCanvas.setCursorPosition(imagePoint[0], imagePoint[1]);
moveCursorToScreenPoint(screenCenterX, screenCenterY);
}
private void setInputStrategy(InputStrategyInterface inputStrategy) {
// Since the rules for flinging differ between input modes, we want to stop running the
// current fling animation when the mode changes to prevent a wonky experience.
abortAnimation();
mInputStrategy = inputStrategy;
}
/** Moves the desired center of the viewport using the specified deltas. */
private void moveViewportByOffset(float deltaX, float deltaY) {
// If we are in an indirect mode or are in the middle of a drag operation, then we want to
// invert the direction of the operation (i.e. follow the motion of the finger).
boolean followCursor = (mInputStrategy.isIndirectInputMode() || mIsDragging);
if (followCursor) {
deltaX = -deltaX;
deltaY = -deltaY;
}
// Determine the center point from which to apply the delta.
// For indirect input modes (i.e. trackpad), the view generally follows the cursor.
// For direct input modes (i.e. touch) the should track the user's motion.
// If the user is dragging, then the viewport should always follow the user's finger.
if (mInputStrategy.isIndirectInputMode()) {
PointF newCursorPos = mDesktopCanvas.moveCursorPosition(deltaX, deltaY);
moveCursor(newCursorPos.x, newCursorPos.y);
} else {
mDesktopCanvas.moveViewportCenter(deltaX, deltaY);
}
}
/** Moves the cursor to the specified position on the screen. */
private void moveCursorToScreenPoint(float screenX, float screenY) {
float[] imagePoint = mapScreenPointToImagePoint(screenX, screenY);
moveCursor(imagePoint[0], imagePoint[1]);
}
/** Moves the cursor to the specified position on the remote host. */
private void moveCursor(float newX, float newY) {
boolean cursorMoved = mRenderData.setCursorPosition(newX, newY);
if (cursorMoved) {
mInputStrategy.injectCursorMoveEvent((int) newX, (int) newY);
}
mRenderStub.moveCursor(mRenderData.getCursorPosition());
}
/** Processes a (multi-finger) swipe gesture. */
private boolean onSwipe() {
if (mTotalMotionY > mSwipeThreshold) {
// Swipe down occurred.
mDesktop.showSystemUi();
} else if (mTotalMotionY < -mSwipeThreshold) {
// Swipe up occurred.
mDesktop.showKeyboard();
} else {
return false;
}
mSuppressCursorMovement = true;
mSuppressFling = true;
mSwipeCompleted = true;
return true;
}
/** Translates a point in screen coordinates to a location on the desktop image. */
private float[] mapScreenPointToImagePoint(float screenX, float screenY) {
float[] mappedPoints = {screenX, screenY};
Matrix screenToImage = new Matrix();
mRenderData.transform.invert(screenToImage);
screenToImage.mapPoints(mappedPoints);
return mappedPoints;
}
/** Responds to touch events filtered by the gesture detectors. */
private class GestureListener extends GestureDetector.SimpleOnGestureListener
implements ScaleGestureDetector.OnScaleGestureListener,
TapGestureDetector.OnTapListener {
/**
* Called when the user drags one or more fingers across the touchscreen.
*/
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
int pointerCount = e2.getPointerCount();
// Check to see if the motion originated at the edge of the screen.
// If so, then the user is likely swiping in to display system UI.
if (!mPanGestureBounds.contains((int) e1.getX(), (int) e1.getY())) {
// Prevent the cursor being moved or flung by the gesture.
mSuppressCursorMovement = true;
return false;
}
if (pointerCount >= 3 && !mSwipeCompleted) {
// Note that distance values are reversed. For example, dragging a finger in the
// direction of increasing Y coordinate (downwards) results in distanceY being
// negative.
mTotalMotionY -= distanceY;
return onSwipe();
}
if (pointerCount == 2 && mSwipePinchDetector.isSwiping()) {
if (!mInputStrategy.isIndirectInputMode()) {
// Ensure the cursor is located at the coordinates of the original event,
// otherwise the target window may not receive the scroll event correctly.
moveCursorToScreenPoint(e1.getX(), e1.getY());
}
mInputStrategy.onScroll(distanceX, distanceY);
// Prevent the cursor being moved or flung by the gesture.
mSuppressCursorMovement = true;
mScrollFling = true;
return true;
}
if (pointerCount != 1 || mSuppressCursorMovement) {
return false;
}
float[] delta = {distanceX, distanceY};
Matrix canvasToImage = new Matrix();
mRenderData.transform.invert(canvasToImage);
canvasToImage.mapVectors(delta);
moveViewportByOffset(delta[0], delta[1]);
if (!mInputStrategy.isIndirectInputMode() && mIsDragging) {
// Ensure the cursor follows the user's finger when the user is dragging under
// direct input mode.
moveCursorToScreenPoint(e2.getX(), e2.getY());
}
return true;
}
/**
* Called when a fling gesture is recognized.
*/
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (mSuppressFling) {
return false;
}
if (mScrollFling) {
mScrollAnimationJob.startAnimation(velocityX, velocityY);
startAnimation();
mScrollFling = false;
return true;
}
if (mSuppressCursorMovement) {
return false;
}
// If cursor movement is suppressed, fling also needs to be suppressed, as the
// gesture-detector will still generate onFling() notifications based on movement of
// the fingers, which would result in unwanted cursor movement.
mCursorAnimationJob.startAnimation(velocityX, velocityY);
startAnimation();
return true;
}
/** Called when the user is in the process of pinch-zooming. */
@Override
public boolean onScale(ScaleGestureDetector detector) {
if (!mSwipePinchDetector.isPinching()) {
return false;
}
mDesktopCanvas.scaleAndRepositionImage(detector.getScaleFactor(), detector.getFocusX(),
detector.getFocusY(), mInputStrategy.isIndirectInputMode());
return true;
}
/** Called whenever a gesture starts. Always accepts the gesture so it isn't ignored. */
@Override
public boolean onDown(MotionEvent e) {
return true;
}
/**
* Called when the user starts to zoom. Always accepts the zoom so that
* onScale() can decide whether to respond to it.
*/
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
/** Called when the user is done zooming. Defers to onScale()'s judgement. */
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
onScale(detector);
}
/** Called when the user taps the screen with one or more fingers. */
@Override
public boolean onTap(int pointerCount, float x, float y) {
int button = mouseButtonFromPointerCount(pointerCount);
if (button == InputStub.BUTTON_UNDEFINED) {
return false;
}
if (!mInputStrategy.isIndirectInputMode()) {
if (screenPointLiesOutsideImageBoundary(x, y)) {
return false;
}
moveCursorToScreenPoint(x, y);
}
if (mInputStrategy.onTap(button)) {
PointF pos = mRenderData.getCursorPosition();
mRenderStub.showInputFeedback(mInputStrategy.getShortPressFeedbackType(), pos);
}
return true;
}
/** Called when a long-press is triggered for one or more fingers. */
@Override
public void onLongPress(int pointerCount, float x, float y) {
int button = mouseButtonFromPointerCount(pointerCount);
if (button == InputStub.BUTTON_UNDEFINED) {
return;
}
if (!mInputStrategy.isIndirectInputMode()) {
if (screenPointLiesOutsideImageBoundary(x, y)) {
return;
}
moveCursorToScreenPoint(x, y);
}
if (mInputStrategy.onPressAndHold(button)) {
PointF pos = mRenderData.getCursorPosition();
mRenderStub.showInputFeedback(mInputStrategy.getLongPressFeedbackType(), pos);
mSuppressFling = true;
mIsDragging = true;
}
}
/** Maps the number of fingers in a tap or long-press gesture to a mouse-button. */
private int mouseButtonFromPointerCount(int pointerCount) {
switch (pointerCount) {
case 1:
return InputStub.BUTTON_LEFT;
case 2:
return InputStub.BUTTON_RIGHT;
case 3:
return InputStub.BUTTON_MIDDLE;
default:
return InputStub.BUTTON_UNDEFINED;
}
}
/** Determines whether the given screen point lies outside the desktop image. */
private boolean screenPointLiesOutsideImageBoundary(float screenX, float screenY) {
float[] mappedPoints = mapScreenPointToImagePoint(screenX, screenY);
float imageWidth = (float) mRenderData.imageWidth + EPSILON;
float imageHeight = (float) mRenderData.imageHeight + EPSILON;
return mappedPoints[0] < -EPSILON || mappedPoints[0] > imageWidth
|| mappedPoints[1] < -EPSILON || mappedPoints[1] > imageHeight;
}
}
}
| 37.793948
| 99
| 0.626292
|
ef37a0398aecb6554ea57295647bcbc9faefae7a
| 7,219
|
/*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.lib.el;
import org.junit.Assert;
import org.junit.Test;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TestTimeNowEL {
@Test
public void testTimeToAmerica_New_York() {
// 1484320146987 GMT: Fri, 13 Jan 2017 15:09:06.987 GMT
Assert.assertEquals("2017-01-13 10:09:06.987",
TimeNowEL.extractStringFromDateTZ(new Date(1484320146987L), "America/New_York", "yyyy-MM-dd HH:mm:ss.SSS")
);
}
@Test
public void testTimeToGMT() {
// 1484320146987 GMT: Fri, 13 Jan 2017 15:09:06.987 GMT
Assert.assertEquals("2017-01-13 15:09:06",
TimeNowEL.extractStringFromDateTZ(new Date(1484320146987L), "GMT", "yyyy-MM-dd HH:mm:ss")
);
}
@Test
public void testTimeToGMT_0800() {
// 1484320146987 GMT: Fri, 13 Jan 2017 15:09:06.987 GMT
Assert.assertEquals("2017-01-13 07:09:06 GMT-08:00",
TimeNowEL.extractStringFromDateTZ(new Date(1484320146987L), "GMT-0800", "yyyy-MM-dd HH:mm:ss zzz")
);
Assert.assertEquals("2017-01-13 07:09:06 GMT-08:00",
TimeNowEL.extractStringFromDateTZ(new Date(1484320146987L), "GMT-08:00", "yyyy-MM-dd HH:mm:ss zzz")
);
}
@Test
public void testTimeTo_0500() {
// 1484320146987 GMT: Fri, 13 Jan 2017 15:09:06.987 GMT
// must be GMT-05:00 not -05:00
Assert.assertEquals("",
TimeNowEL.extractStringFromDateTZ(new Date(1484320146987L), "-05:00", "yyyy-MM-dd HH:mm:ss ZZZ")
);
}
@Test
public void testTimeTo_EDT() {
// 1484320146987 GMT: Fri, 13 Jan 2017 15:09:06.987 GMT
// EDT is not valid.
Assert.assertEquals("",
TimeNowEL.extractStringFromDateTZ(new Date(1484320146987L), "EDT", "yyyy-MM-dd HH:mm:ss ZZZ")
);
}
@Test
public void testTimeTo_EST() {
// 1484320146987 GMT: Fri, 13 Jan 2017 15:09:06.987 GMT
// EST is valid 3-letter short timezone but gives the wrong result for DST. This non-DST date works...
Assert.assertEquals("2017-01-13 10:09:06 -0500",
TimeNowEL.extractStringFromDateTZ(new Date(1484320146987L), "EST", "yyyy-MM-dd HH:mm:ss ZZZ")
);
// This date in US daylight savings time does not work.
// 1472393106987 Sun, 28 Aug 2016 14:05:06 GMT
// should by 10:05:06, but comes out as 09:05:06. and -0500 is misleading. should be -0400
Assert.assertEquals("2016-08-28 09:05:06 -0500",
TimeNowEL.extractStringFromDateTZ(new Date(1472393106987L), "EST", "yyyy-MM-dd HH:mm:ss ZZZZZ")
);
}
@Test
public void testTimeTo_EST5EDT() {
// 1484320146987 GMT: Fri, 13 Jan 2017 15:09:06.987 GMT
// EST5EDT works for both daylight savings and standard time.
Assert.assertEquals("2017-01-13 10:09:06 Eastern Standard Time",
TimeNowEL.extractStringFromDateTZ(new Date(1484320146987L), "EST5EDT", "yyyy-MM-dd HH:mm:ss zzzzz")
);
// This date in US daylight savings time does not work.
// 1472393106987 Sun, 28 Aug 2016 14:05:06 GMT
Assert.assertEquals("2016-08-28 10:05:06 Eastern Daylight Time",
TimeNowEL.extractStringFromDateTZ(new Date(1472393106987L), "EST5EDT", "yyyy-MM-dd HH:mm:ss zzzzz")
);
}
@Test
public void testTimeTo_America_Los_Angeles() {
// 1484320146987 GMT: Fri, 13 Jan 2017 15:09:06.987 GMT
// America/Los_Angeles works for both daylight savings and standard time.
Assert.assertEquals("2017-01-13 07:09:06 Pacific Standard Time",
TimeNowEL.extractStringFromDateTZ(new Date(1484320146987L), "America/Los_Angeles", "yyyy-MM-dd HH:mm:ss zzzzz")
);
// This date is in US daylight savings time.
// 1472393106987 Sun, 28 Aug 2016 14:05:06 GMT
Assert.assertEquals("2016-08-28 07:05:06 Pacific Daylight Time",
TimeNowEL.extractStringFromDateTZ(new Date(1472393106987L), "America/Los_Angeles", "yyyy-MM-dd HH:mm:ss zzzzz")
);
}
@Test
public void testTimeToAsiaRiyadh() {
// 1484320146987 GMT: Fri, 13 Jan 2017 15:09:06.987 GMT
// AST: 1/13/2017, 18:09:06 AM GMT-5:00
Assert.assertEquals("2017-01-13 18:09:06 +0300",
TimeNowEL.extractStringFromDateTZ(new Date(1484320146987L), "Asia/Riyadh", "yyyy-MM-dd HH:mm:ss ZZZZZ")
);
}
@Test
public void testCreateDatefromStringTZ() {
String in = "2016-07-14 11:23:45";
String tz = "Pacific/Honolulu";
String fmt = "yyyy-MM-dd HH:mm:ss";
String fmt2 = "yyyy-MM-dd HH:mm:ss zzzz";
Date dt = TimeNowEL.createDateFromStringTZ(in, tz, fmt);
Assert.assertNotNull(dt);
// prevents conversion to local time.
SimpleDateFormat formatter = new SimpleDateFormat(fmt2);
TimeZone theZone = TimeZone.getTimeZone(tz);
formatter.setTimeZone(theZone);
Assert.assertEquals("2016-07-14 11:23:45 Hawaii Standard Time", formatter.format(dt));
}
@Test
public void testTimeZoneOffset() {
long HOUR = 60*60*1000;
long HALF = 30*60*1000;
// Pure timezone
Assert.assertEquals(0, TimeNowEL.timeZoneOffset("GMT"));
Assert.assertEquals(-5*HOUR, TimeNowEL.timeZoneOffset("GMT-05:00"));
Assert.assertEquals(1*HOUR, TimeNowEL.timeZoneOffset("GMT+01:00"));
Assert.assertEquals(5*HOUR+HALF, TimeNowEL.timeZoneOffset("IST"));
// And offset for a given date
Date july = new Date(2018 - 1900, 8, 1);
Date february = new Date(2018 - 1900, 1, 1);
Assert.assertEquals(-7*HOUR, TimeNowEL.timeZoneOffset(july,"PST")); // Daylight saving time
Assert.assertEquals(-8*HOUR, TimeNowEL.timeZoneOffset(february,"PST"));
}
@Test
public void testExtractNanosecondsFromString() {
String timestampNanosWithoutMillis = "105000";
String timestampWithoutNanosStr = "2005-02-08 14:00:00.100";
String timestamp = "2005-02-08 14:00:00.100105000";
Timestamp timestampWithoutNanos = Timestamp.valueOf(timestampWithoutNanosStr);
String parsedTimestamp = TimeNowEL.extractNanosecondsFromString(timestamp);
String[] timestampParts = parsedTimestamp.split(TimeNowEL.OFFSET_VALUE_NANO_SEPARATOR);
Assert.assertEquals(2, timestampParts.length);
Assert.assertEquals(timestampNanosWithoutMillis, timestampParts[1]);
Assert.assertEquals(timestampWithoutNanos.getTime(), Long.valueOf(timestampParts[0]).longValue());
timestamp = "2005-02-08 14:00:00.100";
parsedTimestamp = TimeNowEL.extractNanosecondsFromString(timestamp);
timestampParts = parsedTimestamp.split(TimeNowEL.OFFSET_VALUE_NANO_SEPARATOR);
Assert.assertEquals(1, timestampParts.length);
Assert.assertEquals(timestampWithoutNanos.getTime(), Long.valueOf(timestampParts[0]).longValue());
}
}
| 35.561576
| 119
| 0.700651
|
f2a30f0719a90c0ee2d09bad9b7c02a18b6d5aa6
| 343
|
/**
* このパッケージは、リソースやストリームに対する入出力処理に関するクラスを提供します。<br>
* <p>
* Java標準APIで提供されるストリームやファイルに対するシステム入出力処理を拡張した特殊な入出力処理を行うためのクラス等を提供します。<br>
* </p>
*
*<!--
* 更新日 更新者 更新内容
* 2017/06/09 Kitagawa 新規作成
* 2018/05/16 Kitagawa 再構築(SourceForge.jpからGitHubへの移行に併せて全面改訂)
*-->
*/
package org.ideaccum.libs.commons.io;
| 26.384615
| 75
| 0.658892
|
56a44a979c6534fc95d448e77d5d144e684b3ac5
| 3,279
|
package com.ceco.geekit.app.adapter;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import com.ceco.geekit.R;
import java.util.AbstractMap;
import java.util.List;
/**
* @author Tsvetan Dimitrov <tsvetan.dimitrov23@gmail.com>
* @since 30 May 2015
*/
public class BookDetailsExpandableListAdapter extends BaseExpandableListAdapter {
private static final int CHILDREN_COUNT = 1;
private Context context;
private List<AbstractMap.SimpleEntry<String, String>> bookDetailsPair;
public BookDetailsExpandableListAdapter(Context context, List<AbstractMap.SimpleEntry<String, String>> bookDetailsPair) {
this.context = context;
this.bookDetailsPair = bookDetailsPair;
}
@Override
public int getGroupCount() {
return bookDetailsPair.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return CHILDREN_COUNT;
}
@Override
public Object getGroup(int groupPosition) {
return this.bookDetailsPair.get(groupPosition).getKey();
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return this.bookDetailsPair.get(groupPosition).getValue();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.book_details_exp_list_item, parent, false);
}
TextView bookDetailsHeader = (TextView) convertView
.findViewById(R.id.book_details_exp_list_header);
bookDetailsHeader.setTypeface(null, Typeface.BOLD);
bookDetailsHeader.setText(headerTitle);
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String detailsValue = (String) getChild(groupPosition,childPosition);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.book_details_exp_child_list_item, parent, false);
}
TextView bookDetailsHeaderValue = (TextView) convertView
.findViewById(R.id.book_details_child_list_item_value_holder);
bookDetailsHeaderValue.setText(detailsValue);
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
| 31.228571
| 125
| 0.706008
|
463975bf0f5f81df702ee66815c03cb3362ab558
| 1,809
|
package land.basso.android.popularmovies;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.squareup.picasso.Picasso;
/**
* Created by jbasso on 7/10/2015.
*/
public class ImageAdapter extends BaseAdapter
{
private Context mContext;
public ImageAdapter(Context c)
{
mContext = c;
}
public int getCount()
{
if(((MainActivity)mContext).mMovies == null)
return 0; //return mThumbIds.length;
else
return ((MainActivity)mContext).mMovies.size();
}
public Object getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
AspectRatioImageView imageView;// = new AspectRatioImageView(mContext);
if (convertView == null)
{
// if it's not recycled, initialize some attributes
imageView = new AspectRatioImageView(mContext);
} else
{
imageView = (AspectRatioImageView)convertView;
}
if(((MainActivity)mContext).mMovies != null)
{
if(((MainActivity)mContext).mMovies.get(position).posterURL != null && ((MainActivity)mContext).mMovies.get(position).posterURL.length() > 0)
{
Picasso.with(mContext)
.load(((MainActivity) mContext).mMovies.get(position).posterURL)
.error(R.drawable.error)
.into(imageView); //
// .placeholder(R.drawable.loading)
}
}
return imageView;
}
}
| 26.602941
| 153
| 0.599226
|
7b878ae8212efda3e0116669549b80882a2b082a
| 883
|
package dao.entities;
public class CrownableArtist {
private final String artistName;
private final int playNumber;
private final int maxPlaynumber;
private final int rank;
private final int totalListeners;
public CrownableArtist(String artistName, int playNumber, int maxPlaynumber, int rank, int totalListeners) {
this.artistName = artistName;
this.playNumber = playNumber;
this.maxPlaynumber = maxPlaynumber;
this.rank = rank;
this.totalListeners = totalListeners;
}
public String getArtistName() {
return artistName;
}
public int getPlayNumber() {
return playNumber;
}
public int getMaxPlaynumber() {
return maxPlaynumber;
}
public int getRank() {
return rank;
}
public int getTotalListeners() {
return totalListeners;
}
}
| 22.641026
| 112
| 0.656852
|
aa895c6f3222820dbacbc7f9f83d7a3934910c00
| 1,535
|
package com.alipay.api.response;
import java.util.List;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
import com.alipay.api.domain.ItemVO;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.open.mini.item.page.query response.
*
* @author auto create
* @since 1.0, 2021-09-13 20:58:10
*/
public class AlipayOpenMiniItemPageQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 6254488814448158777L;
/**
* 当前页码
*/
@ApiField("current_page_num")
private Long currentPageNum;
/**
* 小程序商品列表
*/
@ApiListField("data_list")
@ApiField("item_v_o")
private List<ItemVO> dataList;
/**
* 每页项数
*/
@ApiField("per_page_count")
private Long perPageCount;
/**
* 总共项数
*/
@ApiField("total_count")
private Long totalCount;
public void setCurrentPageNum(Long currentPageNum) {
this.currentPageNum = currentPageNum;
}
public Long getCurrentPageNum( ) {
return this.currentPageNum;
}
public void setDataList(List<ItemVO> dataList) {
this.dataList = dataList;
}
public List<ItemVO> getDataList( ) {
return this.dataList;
}
public void setPerPageCount(Long perPageCount) {
this.perPageCount = perPageCount;
}
public Long getPerPageCount( ) {
return this.perPageCount;
}
public void setTotalCount(Long totalCount) {
this.totalCount = totalCount;
}
public Long getTotalCount( ) {
return this.totalCount;
}
}
| 20.743243
| 74
| 0.694463
|
da95c42a744c6d597628355728b8db9e486dae67
| 3,252
|
/*
* 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.chemistry.opencmis.commons.impl;
public class JSONConstraints {
public static final int MAX_OBJECT_SIZE;
public static final int MAX_ARRAY_SIZE;
public static final int MAX_DEPTH;
public static final int MAX_OBJECT_SIZE_DEFAULT = 1000000;
public static final int MAX_ARRAY_SIZE_DEFAULT = 1000000;
public static final int MAX_DEPTH_DEFAULT = 200;
public static final String MAX_OBJECT_SIZE_SYSTEM_PROPERTY = "org.apache.chemistry.opencmis.JSONConstraints.maxObjectSize";
public static final String MAX_ARRAY_SIZE_SYSTEM_PROPERTY = "org.apache.chemistry.opencmis.JSONConstraints.maxArraySize";
public static final String MAX_DEPTH_SYSTEM_PROPERTY = "org.apache.chemistry.opencmis.JSONConstraints.maxDepth";
static {
int maxObjectSize = MAX_OBJECT_SIZE_DEFAULT;
try {
String maxObjectSizeStr = System.getProperty(MAX_OBJECT_SIZE_SYSTEM_PROPERTY);
if (maxObjectSizeStr != null) {
maxObjectSize = Integer.parseInt(maxObjectSizeStr);
// check for sane values
if (maxObjectSize < 100) {
maxObjectSize = MAX_OBJECT_SIZE_DEFAULT;
}
}
} catch (NumberFormatException e) {
// ignore
}
MAX_OBJECT_SIZE = maxObjectSize;
int maxArraySize = MAX_ARRAY_SIZE_DEFAULT;
try {
String maxArraySizeStr = System.getProperty(MAX_ARRAY_SIZE_SYSTEM_PROPERTY);
if (maxArraySizeStr != null) {
maxArraySize = Integer.parseInt(maxArraySizeStr);
// check for sane values
if (maxArraySize < 1000) {
maxArraySize = MAX_ARRAY_SIZE_DEFAULT;
}
}
} catch (NumberFormatException e) {
// ignore
}
MAX_ARRAY_SIZE = maxArraySize;
int maxDepth = MAX_DEPTH_DEFAULT;
try {
String maxDepthStr = System.getProperty(MAX_DEPTH_SYSTEM_PROPERTY);
if (maxDepthStr != null) {
maxDepth = Integer.parseInt(maxDepthStr);
// check for sane values
if (maxDepth < 10) {
maxDepth = MAX_DEPTH_DEFAULT;
}
}
} catch (NumberFormatException e) {
// ignore
}
MAX_DEPTH = maxDepth;
}
private JSONConstraints() {
}
}
| 36.954545
| 127
| 0.648831
|
c425d1fd217fec28041c15f5a0d4dc14b4735cea
| 1,059
|
class Solution {
public void nextPermutation(int[] num) {
int n = num.length;
if (n < 2)
return;
int index = n - 1;
while (index > 0) {
if (num[index - 1] < num[index])
break;
index--;
}
if (index == 0) {
reverseSort(num, 0, n - 1);
return;
} else {
int val = num[index - 1];
int j = n - 1;
while (j >= index) {
if (num[j] > val)
break;
j--;
}
swap(num, j, index - 1);
reverseSort(num, index, n - 1);
return;
}
}
public void swap(int[] num, int i, int j) {
int temp = 0;
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
public void reverseSort(int[] num, int start, int end) {
if (start > end)
return;
for (int i = start; i <= (end + start) / 2; i++)
swap(num, i, start + end - i);
}
}
| 25.214286
| 60
| 0.374882
|
b6a3a0ea9d88b8e303ed53895f73072a3fee6f18
| 2,161
|
package langModel;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
/**
* This JUnit Test Class has been generated by right clicking on the NgramUtils class
* and selecting "New > Junit Test Case". After that, you have to select the methods
* for which you would like to generate tests.
* In practice, you will duplicate manually the test methods to possibly create
* several tests for one method.
*
* Your work is then to remove the fail parts and to implement each test.
* One method is given as an example
*
* To run them:
* either right click on the class name or simply on the method name and
* select "Run As Junit Test".
*
* @author N. Hernandez and S. Quiniou (2015)
*
*/
public class NgramUtilsTest {
String sentence = "<s> cette phrase est de taille 9 . </s>";
String ngram = "où commence l' historique de cet n-gramme";
/**
* Test method for {@link langModel.NgramUtils#getSequenceSize(java.lang.String)}.
*/
@Test
public void testGetSequenceSize() {
System.out.println(NgramUtils.getSequenceSize(sentence));
// on the left the expected value and on the right the actual one
// (i.e. the one returned by your method)
assertEquals(9, NgramUtils.getSequenceSize(sentence));
}
/**
* Test method for {@link langModel.NgramUtils#generateNgrams(java.lang.String, int, int)}.
*/
@Test
public void testGenerateNgrams() {
fail("Not yet implemented");
}
/**
* Test method for {@link langModel.NgramUtils#getHistory(java.lang.String, int)}.
*/
@Test
public void testGetHistory() {
fail("Not yet implemented");
}
/**
* Test method for {@link langModel.NgramUtils#decomposeIntoNgrams(java.lang.String, int)}.
*/
@Test
public void testDecomposeIntoNgrams() {
fail("Not yet implemented");
}
/**
* The following code displays a separator
* between each method output
*
* (manually added)
**/
@Rule
public TestName name = new TestName();
@Before
public void printSeparator()
{
System.out.println("\n=== " + name.getMethodName() + " =====================");
}
}
| 24.280899
| 92
| 0.689033
|
a5424f2c894d2c109ea175f247cc56d949e956b1
| 107
|
package tech.arauk.ark.activesupport.ace.base;
public class Case {
public static class Dice {
}
}
| 15.285714
| 46
| 0.700935
|
320014ea0f7bf85aded015e5553aa6eb70c381fb
| 548
|
package command;
/**
* Interface for commands implementing various program functions.
* The only method is getResult() which formats results, which are computed by void execute() method. Execute itself cannot be part of interface,
* since every command requires different set of arguments. Results of execute() methods should be stored in private fields, which are used by
* getResult(). Execute should always be used before getResult() for that reason.
*/
public interface ICommand
{
//void execute (arguments);
String getResult();
}
| 42.153846
| 145
| 0.760949
|
3429b2c4fddd54cf73b4f436753006edaeac53ed
| 1,081
|
package implementation;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Boj10984 {
public static final String SPACE = " ";
public static final String NEW_LINE = "\n";
public static final Double TEN = 10.0;
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int T = Integer.parseInt(br.readLine());
while(T > 0){
int sumC = 0;
double GPA = 0, sumG = 0, tmp = 0;
int N = Integer.parseInt(br.readLine());
for(int i = 0; i < N; i++){
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int C = Integer.parseInt(st.nextToken());
double G = Double.parseDouble(st.nextToken());
sumC += C;
sumG += G;
tmp += C * G;
}
GPA = Math.round((tmp / sumC) * TEN) / TEN;
sb.append(sumC).append(SPACE).append(GPA).append(NEW_LINE);
T--;
}
System.out.println(sb.toString());
}
}
| 27.025
| 76
| 0.625347
|
fecaa574ab3c88f250916ea9a89e6da952518511
| 596
|
package psd.parser.layer.additional;
import java.io.IOException;
import psd.parser.PsdInputStream;
import psd.parser.layer.LayerAdditionalInformationParser;
public class LayerIdParser implements LayerAdditionalInformationParser {
public static final String TAG = "lyid";
private final LayerIdHandler handler;
public LayerIdParser(LayerIdHandler handler) {
this.handler = handler;
}
@Override
public void parse(PsdInputStream stream, String tag, int size) throws IOException {
int layerId = stream.readInt();
if (handler != null) {
handler.layerIdParsed(layerId);
}
}
}
| 22.923077
| 84
| 0.77349
|
ab469394ecd3c2dfc437bcdc8097eaa3d6452efa
| 869
|
package pepmhc.junit;
import java.io.File;
import java.util.List;
import jene.peptide.ProteinChange;
import jene.tcga.TumorBarcode;
import pepmhc.miss.MissCleavageDriver;
import pepmhc.miss.MissCleavageRecord;
import pepmhc.miss.MissCleavageTable;
import org.junit.*;
import static org.junit.Assert.*;
public class MissCleavageDriverTest {
private static final File outputFile = new File("data/test/miss-cleavage-test.txt");
private static final String propFile = "data/test/miss-cleavage.prop";
@Test public void testRun() {
MissCleavageDriver.run(propFile);
MissCleavageTable table = MissCleavageTable.load(outputFile);
assertEquals(43, table.count());
outputFile.delete();
}
public static void main(String[] args) {
org.junit.runner.JUnitCore.main("pepmhc.junit.MissCleavageDriverTest");
}
}
| 25.558824
| 88
| 0.733026
|
2dca67d8d57d861a58d2aacaddea70e10f5cfbcd
| 3,310
|
package com.ty.nanfangscanner.bean;
public class CheckInfo {
/**
* brandName : 未知品牌
* productName : 未知产品
* registrationTime : 2018/07/24 14:38:25
* activationTime : 2018/07/24 14:39:09
* activationStatus : 已激活
* activationCount : 2
* seqNumCount : 2
* status : 1
* enterpriseSeqnumStart : 554
* enterpriseSeqnumEnd : 555
* productFactoryName : 未知工厂
* factoryName : 蒙牛印刷厂
* resultMsg : 处理成功
*/
private String brandName;
private String productName;
private String registrationTime;
private String activationTime;
private String activationStatus;
private int activationCount;
private int seqNumCount;
private int status;
private int enterpriseSeqnumStart;
private int enterpriseSeqnumEnd;
private String productFactoryName;
private String factoryName;
private String resultMsg;
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getRegistrationTime() {
return registrationTime;
}
public void setRegistrationTime(String registrationTime) {
this.registrationTime = registrationTime;
}
public String getActivationTime() {
return activationTime;
}
public void setActivationTime(String activationTime) {
this.activationTime = activationTime;
}
public String getActivationStatus() {
return activationStatus;
}
public void setActivationStatus(String activationStatus) {
this.activationStatus = activationStatus;
}
public int getActivationCount() {
return activationCount;
}
public void setActivationCount(int activationCount) {
this.activationCount = activationCount;
}
public int getSeqNumCount() {
return seqNumCount;
}
public void setSeqNumCount(int seqNumCount) {
this.seqNumCount = seqNumCount;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getEnterpriseSeqnumStart() {
return enterpriseSeqnumStart;
}
public void setEnterpriseSeqnumStart(int enterpriseSeqnumStart) {
this.enterpriseSeqnumStart = enterpriseSeqnumStart;
}
public int getEnterpriseSeqnumEnd() {
return enterpriseSeqnumEnd;
}
public void setEnterpriseSeqnumEnd(int enterpriseSeqnumEnd) {
this.enterpriseSeqnumEnd = enterpriseSeqnumEnd;
}
public String getProductFactoryName() {
return productFactoryName;
}
public void setProductFactoryName(String productFactoryName) {
this.productFactoryName = productFactoryName;
}
public String getFactoryName() {
return factoryName;
}
public void setFactoryName(String factoryName) {
this.factoryName = factoryName;
}
public String getResultMsg() {
return resultMsg;
}
public void setResultMsg(String resultMsg) {
this.resultMsg = resultMsg;
}
}
| 23.81295
| 69
| 0.669184
|
ff275eeaeb5c2e4550550dea99ea617a85612903
| 4,510
|
package io.renren.controller;
import io.renren.annotation.SysLog;
import io.renren.entity.YlDepartmentEntity;
import io.renren.entity.YlHospitalEntity;
import io.renren.entity.YlOrganizationEntity;
import io.renren.service.YlDepartmentService;
import io.renren.service.YlHospitalService;
import io.renren.service.YlOrganizationService;
import io.renren.utils.PageUtils;
import io.renren.utils.Query;
import io.renren.utils.R;
import io.renren.validator.ValidatorUtils;
import io.renren.vo.YlTreeEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 科室信息
*
* @author tangty
* @email tianyaTTY@gmail.com
* @date 2017年7月11日 下午6:43:36
*/
@RestController
@RequestMapping("/yl/department")
public class YlDepartmentController extends AbstractController {
@Autowired
private YlDepartmentService ylDepartmentService;
@Autowired
private YlHospitalService ylHospitalService;
@Autowired
private YlOrganizationService ylOrganizationService;
/**
* 所有科室信息列表
*/
@RequestMapping("/list")
@RequiresPermissions("yl:department:list")
public R list(@RequestParam Map<String, Object> params){
//查询列表数据
Query query = new Query(params);
List<YlDepartmentEntity> departmentList = ylDepartmentService.queryList(query);
int total = ylDepartmentService.queryTotal(query);
PageUtils pageUtil = new PageUtils(departmentList, total, query.getLimit(), query.getPage());
return R.ok().put("page", pageUtil);
}
/**
* 配置科室信息
*/
@RequestMapping("/info/{id}")
@RequiresPermissions("yl:department:info")
public R info(@PathVariable("id") Integer id){
YlDepartmentEntity department = ylDepartmentService.queryObject(id);
YlHospitalEntity hospital = ylHospitalService.queryObject(department.getHospitalId());
YlOrganizationEntity organization = ylOrganizationService.queryObject(hospital.getOrgId());
return R.ok().put("department", department).put("hospital",hospital).put("organization",organization);
}
/**
* 查询专家所属的机构树
*/
@RequestMapping("/select")
@RequiresPermissions("yl:department:select")
public R select(){
//TODO 选择树节点提交的数据,修改跟进进来的节点
//查询树结构
List<YlOrganizationEntity> orgList = ylOrganizationService.queryList(null);
List<YlHospitalEntity> hosList = ylHospitalService.queryList(null);
List<YlDepartmentEntity> depList = ylDepartmentService.queryList(null);
List<YlTreeEntity> ylList = new ArrayList<YlTreeEntity>();
for(int i=0;i<orgList.size();i++){
YlTreeEntity ylTreeEntity = new YlTreeEntity();
ylTreeEntity.setId(orgList.get(i).getId());
ylTreeEntity.setName(orgList.get(i).getName());
ylTreeEntity.setParentId(0);
ylTreeEntity.setOpen(true);
ylList.add(ylTreeEntity);
}
for(int j=0;j<hosList.size();j++){
YlTreeEntity ylTreeEntity = new YlTreeEntity();
ylTreeEntity.setId(hosList.get(j).getId()+1000);
ylTreeEntity.setName(hosList.get(j).getName());
ylTreeEntity.setParentId(hosList.get(j).getOrgId());
ylTreeEntity.setOpen(true);
ylList.add(ylTreeEntity);
}
for(int k=0;k<depList.size();k++){
YlTreeEntity ylTreeEntity = new YlTreeEntity();
ylTreeEntity.setId(depList.get(k).getId()+2000);
ylTreeEntity.setName(depList.get(k).getName());
ylTreeEntity.setParentId(depList.get(k).getHospitalId()+1000);
ylTreeEntity.setOpen(true);
ylList.add(ylTreeEntity);
}
//添加顶级菜单
YlTreeEntity root = new YlTreeEntity();
root.setId(0);
root.setName("医疗信息");
root.setParentId(-1);
root.setOpen(true);
ylList.add(root);
return R.ok().put("ylList", ylList);
}
/**
* 保存科室信息
*/
@SysLog("保存科室信息")
@RequestMapping("/save")
@RequiresPermissions("yl:department:save")
public R save(@RequestBody YlDepartmentEntity department){
ValidatorUtils.validateEntity(department);
ylDepartmentService.save(department);
return R.ok();
}
/**
* 修改科室信息
*/
@SysLog("修改科室信息")
@RequestMapping("/update")
@RequiresPermissions("yl:department:update")
public R update(@RequestBody YlDepartmentEntity department){
ValidatorUtils.validateEntity(department);
ylDepartmentService.update(department);
return R.ok();
}
/**
* 删除科室信息
*/
@SysLog("删除科室信息")
@RequestMapping("/delete")
@RequiresPermissions("yl:department:delete")
public R delete(@RequestBody Integer[] ids){
//关联删除部门下面的专家
ylDepartmentService.deleteBatch(ids);
return R.ok();
}
}
| 28.726115
| 104
| 0.747228
|
33e934d3f7f0b448d0119dbc90d490e2f68561c2
| 840
|
package com.study.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName ConfigClientController
* @Author Yutian Hui
* @date 2020.07.23 15:32
*/
@RestController
@RequestMapping("/nclient")
@RefreshScope //表示支持配置动态刷新的注解
public class ConfigClientController {
@Value("${spring.info}")
private String info;
@GetMapping("/info")
public String info(HttpServletResponse httpResponse){
httpResponse.addHeader("Name-Service-Provider","Leibohui");
return info;
}
}
| 26.25
| 72
| 0.771429
|
fec451bab9bd653e522d2f448dad2a4fc59924c5
| 7,535
|
/*
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009, 2010, 2011 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.io;
import java.io.IOException;
import java.io.OutputStream;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.CCNSegmenter;
import org.ccnx.ccn.impl.security.crypto.ContentKeys;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.profiles.SegmentationProfile;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.profiles.security.access.AccessControlManager;
import org.ccnx.ccn.protocol.CCNTime;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.KeyLocator;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
import org.ccnx.ccn.protocol.SignedInfo.ContentType;
/**
* This abstract class is the superclass of all classes for writing an output stream of
* bytes segmented and stored in CCN.
*
* @see SegmentationProfile for description of CCN segmentation
*/
public abstract class CCNAbstractOutputStream extends OutputStream {
protected CCNHandle _handle = null;
protected CCNSegmenter _segmenter = null;
/**
* The name for the content fragments, up to just before the sequence number.
*/
protected ContentName _baseName = null;
/**
* type of content null == DATA (or ENCR if encrypted)
*/
protected ContentType _type;
protected ContentKeys _keys;
protected KeyLocator _locator;
protected PublisherPublicKeyDigest _publisher;
/**
* Base constructor for all output streams.
* The behavior of an output stream derived class is determined
* largely by its buffering, segmentation configuration (embodied
* in a CCNSegmenter) and flow control (embodied in a CCNFlowControl,
* contained within the segmenter), as well as the way it constructs is names.
* @param baseName specifies the base name to write. Can be null, and set later.
* @param type specifies the type of data to write.
* @param locator the key locator to be used in written segments. If null, default
* is used.
* @param publisher the key with which to sign the output. If null, default for user
* is used.
* @param segmenter The segmenter used to construct and sign output segments, specified
* by subclasses to provide various kinds of behavior.
*/
public CCNAbstractOutputStream(ContentName baseName,
KeyLocator locator,
PublisherPublicKeyDigest publisher,
ContentType type,
ContentKeys keys,
CCNSegmenter segmenter) {
super();
_baseName = baseName;
_type = type;
_segmenter = segmenter;
_handle = _segmenter.getLibrary();
if (null == _handle) {
_handle = CCNHandle.getHandle();
}
// If these are null, the handle defaults will be used.
_locator = locator;
if (null == locator)
_locator = _handle.keyManager().getKeyLocator(publisher);
_publisher = publisher;
// Initialize keys here now.
_keys = keys;
Log.info(Log.FAC_IO, "CCNAbstractOutputStream: {0} blocksize is {1}", baseName, _segmenter.getBlockSize());
}
/**
* Special purpose constructor used in tests.
*/
protected CCNAbstractOutputStream() {}
/**
* Override in subclasses that need to do something special with start writes
* (see CCNFlowControl#startWrite(ContentName, Shape)). They should call this
* superclass method, though, to initialize keys (may need to move this later).
* @throws IOException
*/
protected void startWrite() throws IOException {
if (null == _keys) {
Log.info(Log.FAC_IO, "CCNAbstractOutputStream: startWrite -- searching for keys.");
_keys = AccessControlManager.keysForOutput(_baseName, _publisher, getType(), _handle);
}
}
/**
* Method for streams used by CCNFilterListeners to output a block
* in response to an Interest callback.
* We've received an Interest prior to setting up this stream. Use
* a method to push this Interest, rather than passing it in in the
* constructor to make sure we have completed initializing the stream,
* and to limit the number of constructor types.
* (If the Interest doesn't match this stream's content,
* no initial block will be output; the stream will wait for matching Interests prior
* to writing its blocks.)
* @param outstandingInterest An interest received prior to constructing
* this stream, ideally on the same CCNHandle that the stream is using
* for output. Only one stream should attempt to put() a block in response
* to this Interest; it is up to the caller to make sure that is the case.
*/
public void addOutstandingInterest(Interest outstandingInterest) {
_segmenter.getFlowControl().handleInterest(outstandingInterest);
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(int b) throws IOException {
byte buf[] = {(byte)b};
write(buf, 0, 1);
}
/**
* @return The name used as a prefix for segments of this stream (not including the segment number).
*/
public ContentName getBaseName() {
return _baseName;
}
/**
* @return The version of the stream being written, if its name is versioned.
*/
public CCNTime getVersion() {
if (null == _baseName)
return null;
return VersioningProfile.getTerminalVersionAsTimestampIfVersioned(_baseName);
}
public ContentType getType() { return _type; }
/**
* Return the first segment of this stream.
*
* @return The first segment of this stream or null if no segments generated yet
*/
public ContentObject getFirstSegment() {
if (null != _segmenter) {
return _segmenter.getFirstSegment();
} else {
return null;
}
}
/**
*
* Returns the digest of the first segment of this stream.
*
* @return The digest of the first segment of this stream or null if no segments generated yet.
*/
public byte[] getFirstDigest() {
ContentObject firstSegment = _segmenter.getFirstSegment();
if (null != firstSegment) {
return firstSegment.digest();
} else {
return null;
}
}
/**
* Returns the first segment number for this stream.
* @return The index of the first segment of stream data or null if no segments generated yet.
*/
public Long firstSegmentNumber() {
ContentObject firstSegment = _segmenter.getFirstSegment();
if (null != firstSegment) {
return SegmentationProfile.getSegmentNumber(firstSegment.name());
} else {
return null;
}
}
/**
* @return The CCNSegmenter responsible for segmenting and signing stream content.
*/
protected CCNSegmenter getSegmenter() {
return _segmenter;
}
/**
* Set the timeout that will be used for all content writes on this stream.
* Default is 10 seconds
* @param timeout in milliseconds
*/
public void setTimeout(int timeout) {
getSegmenter().setTimeout(timeout);
}
}
| 33.193833
| 109
| 0.729662
|
80a81f31e59f2f669666fa1c8a40ac5a68c815f0
| 671
|
package co.uk.acme.deliveryday;
import java.time.LocalDate;
/**
* @author psamatt
*/
final public class ScheduleDeliveryDay {
final private DeliveryDayId deliveryDayId;
final private Capacity capacity;
final private LocalDate date;
public ScheduleDeliveryDay(DeliveryDayId deliveryDayId, Capacity capacity, LocalDate date) {
this.deliveryDayId = deliveryDayId;
this.capacity = capacity;
this.date = date;
}
public DeliveryDayId getDeliveryDayId() {
return deliveryDayId;
}
public Capacity getCapacity() {
return capacity;
}
public LocalDate getDate() {
return date;
}
}
| 20.96875
| 96
| 0.678092
|
da8dbbfae192ae6a28dc6dd2c6734582291a1c4b
| 9,132
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.android.apps.exposurenotification.notify;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;
import com.google.android.apps.exposurenotification.R;
import com.google.android.apps.exposurenotification.home.ExposureNotificationViewModel;
import com.google.android.apps.exposurenotification.notify.ShareDiagnosisViewModel.Step;
import com.google.android.apps.exposurenotification.storage.DiagnosisEntity;
import com.google.android.apps.exposurenotification.utils.RequestCodes;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import dagger.hilt.android.AndroidEntryPoint;
/**
* Activity for adding and viewing a positive diagnosis.
*
* <p>
* <ul>
* <li>Flow for adding a new positive diagnosis starting with {@link
* ShareDiagnosisBeginFragment}
* <li>Flow for viewing a previously diagnosis starting with {@link ShareDiagnosisViewFragment}
* </ul>
* <p>
*/
@AndroidEntryPoint
public class ShareDiagnosisActivity extends AppCompatActivity {
private static final String TAG = "ShareDiagnosisActivity";
static final String SHARE_EXPOSURE_FRAGMENT_TAG =
"ShareExposureActivity.POSITIVE_TEST_FRAGMENT_TAG";
static final String ACTIVITY_START_INTENT = "ShareDiagnosisActivity.ACTIVITY_START_INTENT";
private static final String EXTRA_VIEW_POSITIVE_DIAGNOSIS_ID =
"ShareExposureActivity.EXTRA_VIEW_POSITIVE_DIAGNOSIS_ID";
private static final String EXTRA_STEP =
"ShareExposureActivity.EXTRA_STEP";
/**
* Creates an intent for adding a positive diagnosis flow.
*/
public static Intent newIntentForAddFlow(Context context) {
return new Intent(context, ShareDiagnosisActivity.class);
}
private ShareDiagnosisViewModel viewModel;
private ExposureNotificationViewModel exposureNotificationViewModel;
/**
* Creates an intent for viewing a positive diagnosis flow.
*
* @param entity the {@link DiagnosisEntity} to view
*/
public static Intent newIntentForViewFlow(Context context, DiagnosisEntity entity) {
Intent intent = new Intent(context, ShareDiagnosisActivity.class);
intent.putExtra(EXTRA_VIEW_POSITIVE_DIAGNOSIS_ID, entity.getId());
intent.putExtra(EXTRA_STEP,
ShareDiagnosisFlowHelper.getMaxStepForDiagnosisEntity(entity).name());
return intent;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_diagnosis);
exposureNotificationViewModel =
new ViewModelProvider(this).get(ExposureNotificationViewModel.class);
exposureNotificationViewModel
.getResolutionRequiredLiveEvent()
.observe(
this,
apiException -> {
try {
Log.d(TAG, "startResolutionForResult");
apiException
.getStatus()
.startResolutionForResult(
this, RequestCodes.REQUEST_CODE_START_EXPOSURE_NOTIFICATION);
} catch (SendIntentException e) {
Log.w(TAG, "Error calling startResolutionForResult", apiException);
}
});
viewModel = new ViewModelProvider(this).get(ShareDiagnosisViewModel.class);
if (viewModel.isCloseOpen()) {
ShareDiagnosisActivity.showCloseWarningAlertDialog(this, viewModel);
}
if (savedInstanceState == null) {
if (getIntent().hasExtra(EXTRA_VIEW_POSITIVE_DIAGNOSIS_ID)) {
viewModel
.setCurrentDiagnosisId(getIntent().getLongExtra(EXTRA_VIEW_POSITIVE_DIAGNOSIS_ID, -1));
viewModel
.nextStepIrreversible(Step.valueOf(getIntent().getStringExtra(EXTRA_STEP)));
} else {
viewModel.nextStepIrreversible(Step.BEGIN);
}
}
// This line can be removed once the fix to flickering issue
// https://issuetracker.google.com/166155034 is in the androidx.fragment release.
FragmentManager.enableNewStateManager(false);
viewModel.getCurrentStepLiveData()
.observe(this, step -> {
Bundle fragmentArguments = new Bundle();
fragmentArguments.putParcelable(ACTIVITY_START_INTENT, getIntent());
Fragment fragment = fragmentForStep(step);
fragment.setArguments(fragmentArguments);
getSupportFragmentManager()
.beginTransaction()
.replace(
R.id.share_exposure_fragment,
fragment,
SHARE_EXPOSURE_FRAGMENT_TAG)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
});
}
@NonNull
private static Fragment fragmentForStep(Step step) {
switch (step) {
case CODE:
return new ShareDiagnosisCodeFragment();
case ONSET:
return new ShareDiagnosisOnsetDateFragment();
case REVIEW:
return new ShareDiagnosisReviewFragment();
case SHARED:
return new ShareDiagnosisSharedFragment();
case NOT_SHARED:
return new ShareDiagnosisNotSharedFragment();
case TRAVEL_STATUS:
return new ShareDiagnosisTravelStatusFragment();
case VIEW:
return new ShareDiagnosisViewFragment();
case BEGIN:
default:
// We "shouldn't" get here, but start at the beginning if we somehow do.
return new ShareDiagnosisBeginFragment();
}
}
@Override
public void onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// Propagate to the fragments.
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.share_exposure_fragment);
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, data);
}
onResolutionComplete(requestCode, resultCode);
}
@Override
public void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
// Fire a TYPE_WINDOW_STATE_CHANGED event so that the accessibility service will be notified
// of window title change.
getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
@Override
public void onBackPressed() {
// Only use android back stack if backStepIfPossible() is false, otherwise the ViewModel will
// handle it.
if (!viewModel.backStepIfPossible()) {
super.onBackPressed();
}
}
/**
* Shows an alert dialog warning of closing. Closes the activity as the positive action.
*
* @param activity the activity to finish if the user chooses to close
*/
public static void showCloseWarningAlertDialog(Activity activity,
ShareDiagnosisViewModel shareDiagnosisViewModel) {
shareDiagnosisViewModel.setCloseOpen(true);
new MaterialAlertDialogBuilder(activity)
.setTitle(R.string.share_close_title)
.setMessage(R.string.share_close_detail)
.setPositiveButton(R.string.btn_resume_later, (d, w) -> activity.finish())
.setNegativeButton(R.string.btn_cancel,
(d, w) -> {
shareDiagnosisViewModel.setCloseOpen(false);
d.dismiss();
})
.setOnCancelListener((d) -> shareDiagnosisViewModel.setCloseOpen(false))
.show();
}
/**
* Called when opt-in resolution is completed by user.
*
* <p>Modeled after {@code Activity#onActivityResult} as that's how the API sends callback to
* apps.
*/
public void onResolutionComplete(int requestCode, int resultCode) {
if (requestCode != RequestCodes.REQUEST_CODE_START_EXPOSURE_NOTIFICATION) {
return;
}
if (resultCode == Activity.RESULT_OK) {
exposureNotificationViewModel.startResolutionResultOk();
} else {
exposureNotificationViewModel.startResolutionResultNotOk();
}
}
}
| 36.528
| 100
| 0.720543
|
c66ba8626f1135a9b5c1667eb2a0fd1a996e7c3f
| 7,356
|
package com.test.leetcode.hard;
import java.util.*;
/**
* Created by ben on 2017/7/18.
*/
public class _30_SubstringWithConcatenationOfAllWords {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> result = new ArrayList<>();
if (null == s || s.length() == 0 || words == null || words.length == 0) {
return result;
}
if (words.length > s.length()) {
return result;
}
if (words[0].length() > s.length()) {
return result;
}
Map<String, Integer> map = new HashMap<>();
for (String w : words) {
int i = map.getOrDefault(w, 0) + 1;
map.put(w, i);
}
int len = words[0].length();
int end1 = s.length() - len * words.length + 1;
String str;
boolean found;
Map<String, Integer> temp = new HashMap<>();
int start, end;
for (int i = 0; i < end1; i++) {
temp.clear();
str = s.substring(i, i + len);
if (map.get(str) != null) {
temp.put(str, 1);
found = true;
for (int j = 1; j < words.length; j++) {
start = i + j * len;
end = start + len;
str = s.substring(start, end);
Integer b = map.get(str);
if (b != null) {
int a = temp.getOrDefault(str, 0) + 1;
if (a > b) {
found = false;
break;
}
temp.put(str, a);
} else {
found = false;
}
}
if (found)
result.add(i);
}
}
return result;
}
public List<Integer> findSubstring1(String s, String[] words) {
/**
* Let n=s.length, k=words[0].length traverse s with indices i, i+k,
* i+2k, ... for 0<=i<k, so that the time complexity is O(n).
*/
List<Integer> res = new ArrayList<Integer>();
int n = s.length(), m = words.length, k;
if (n == 0 || m == 0 || (k = words[0].length()) == 0)
return res;
HashMap<String, Integer> wDict = new HashMap<String, Integer>();
for (String word : words) {
if (wDict.containsKey(word))
wDict.put(word, wDict.get(word) + 1);
else
wDict.put(word, 1);
}
int i, j, start, x, wordsLen = m * k;
HashMap<String, Integer> curDict = new HashMap<String, Integer>();
String test, temp;
for (i = 0; i < k; i++) {
curDict.clear();
start = i;
if (start + wordsLen > n)
return res;
for (j = i; j + k <= n; j += k) {
test = s.substring(j, j + k);
if (wDict.containsKey(test)) {
if (!curDict.containsKey(test)) {
curDict.put(test, 1);
start = checkFound(res, start, wordsLen, j, k, curDict, s);
continue;
}
// curDict.containsKey(test)
x = curDict.get(test);
if (x < wDict.get(test)) {
curDict.put(test, x + 1);
start = checkFound(res, start, wordsLen, j, k, curDict, s);
continue;
}
// curDict.get(test)==wDict.get(test), slide start to
// the next word of the first same word as test
while (!(temp = s.substring(start, start + k)).equals(test)) {
decreaseCount(curDict, temp);
start += k;
}
start += k;
if (start + wordsLen > n)
break;
continue;
}
// totally failed up to index j+k, slide start and reset all
start = j + k;
if (start + wordsLen > n)
break;
curDict.clear();
}
}
return res;
}
public int checkFound(List<Integer> res, int start, int wordsLen, int j, int k,
HashMap<String, Integer> curDict, String s) {
if (start + wordsLen == j + k) {
res.add(start);
// slide start to the next word
decreaseCount(curDict, s.substring(start, start + k));
return start + k;
}
return start;
}
public void decreaseCount(HashMap<String, Integer> curDict, String key) {
// remove key if curDict.get(key)==1, otherwise decrease it by 1
int x = curDict.get(key);
if (x == 1)
curDict.remove(key);
else
curDict.put(key, x - 1);
}
public List<Integer> findSubstring2(String s, String[] words) {
List<Integer> res = new ArrayList<Integer>();
if (s == null || s.equals("") || words.length == 0 || words == null) return res;
int lenS = s.length(), lenW = words[0].length(), lenWs = words.length;
if (lenS < lenW * lenWs) return res;
int last = lenS - lenW + 1;
//将words中不同的单词加入map,并用一个辅助数组记录它们各自的出现次数
int[][] tabel = new int[2][lenWs];
int index = 0, count = 0;
Map<String, Integer> mapping = new HashMap<String, Integer>(lenWs);
for (int i = 0; i < lenWs; i++) {
Integer value = mapping.get(words[i]);
if (value == null) {
++count;
mapping.put(words[i], index);
value = index++;
}
++tabel[0][value];
}
//遍历一遍s,用一个辅助数组记录下words里每个字符串出现的位置,-1表示该位置没有出现words里的字符串
int[] occurances = new int[last];
for (int i = 0; i < last; i++) {
String word = s.substring(i, i + lenW);
Integer value = mapping.get(word);
if (value == null) occurances[i] = -1;
else occurances[i] = value;
}
//在线性时间里处理整个字符串
for (int i = 0; i < lenW; i++) {
int currentCount = count;
int left = i, right = i;
Arrays.fill(tabel[1], 0);
while (right < last) {
//查找字符串里第一次全部出现了words里的字符串
while (currentCount > 0 && right < last) {
int target = occurances[right];
if (target != -1 && ++tabel[1][target] == tabel[0][target]) --currentCount;
right += lenW;
}
//判断words里出现的字符串是否是连续出现的
while (currentCount == 0 && left < right) {
int target = occurances[left];
//--tabel[1][target]是因为left最后要左移
if (target != -1 && --tabel[1][target] == tabel[0][target] - 1) {
int length = right - left;
if (length / lenW == lenWs) res.add(left);
++currentCount;
}
left += lenW;
}
}
}
return res;
}
}
| 34.698113
| 95
| 0.430941
|
dafe38d3974029b490f3ddefc6d45a279753d8ad
| 930
|
package louisiana.Classes;
import javafx.scene.shape.Rectangle;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ReferenceTargetPairTest {
@Test
void ReferenceTargetIncreaseWidth(){
int dim1[] = {2000, 500};
int dim2[] = {2000, 500};
Rectangle ref = new Rectangle();
Rectangle tar = new Rectangle();
ref.setX(200);
tar.setX(200);
ref.setY(100);
tar.setY(100);
ref.setWidth(300);
tar.setWidth(700);
ref.setHeight(500);
tar.setHeight(500);
Rectangle newRef = new Rectangle();
newRef.setX(500);
newRef.setY(700);
newRef.setWidth(150);
newRef.setHeight(350);
}
@Test
void setTarRectTest() {
}
@Test
void getTargetRectTest() {
}
@Test
void compareTest() {
}
}
| 21.627907
| 50
| 0.552688
|
7fe6debc520d68e2b6f32eb6609c8473ab0fa116
| 8,585
|
/*
* @(#)DOMOutput.java
*
* Copyright (c) 1996-2010 by the original authors of JHotDraw and all its
* contributors. All rights reserved.
*
* You may not use, copy or modify this file, except in compliance with the
* license agreement you entered into with the copyright holders. For details
* see accompanying license terms.
*/
package org.jhotdraw.xml;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import java.io.*;
/**
* DOMOutput.
* <p>
* Design pattern:<br>
* Name: Adapter.<br>
* Role: Adapter.<br>
* Partners: {@link org.w3c.dom.Document} as Adaptee.
*
* @author Werner Randelshofer
* @version $Id: JavaxDOMOutput.java 717 2010-11-21 12:30:57Z rawcoder $
*/
public class JavaxDOMOutput implements DOMOutput {
/**
* The doctype of the XML document.
*/
private String doctype;
/**
* This map is used to marshall references to objects to
* the XML DOM. A key in this map is a Java Object, a value in this map
* is String representing a marshalled reference to that object.
*/
private HashMap<Object,String> objectids;
/**
* This map is used to cache prototype objects.
*/
private HashMap<String,Object> prototypes;
/**
* The document used for output.
*/
private Document document;
/**
* The current node used for output.
*/
private Node current;
/**
* The factory used to create objects.
*/
private DOMFactory factory;
/** Creates a new instance. */
public JavaxDOMOutput(DOMFactory factory) throws IOException {
this.factory = factory;
}
protected void reset() throws IOException {
try {
objectids = new HashMap<Object,String>();
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
current = document;
} catch (ParserConfigurationException e) {
IOException error = new IOException(e.getMessage());
error.initCause(e);
throw error;
}
}
/**
* Writes the contents of the DOMOutput into the specified output stream.
*/
public void save(OutputStream out) throws IOException {
reset();
try {
if (doctype != null) {
OutputStreamWriter w = new OutputStreamWriter(out, "UTF8");
w.write("<!DOCTYPE ");
w.write(doctype);
w.write(">\n");
w.flush();
}
Transformer t = TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(document), new StreamResult(out));
} catch (TransformerException e) {
IOException error = new IOException(e.getMessage());
error.initCause(e);
throw error;
}
}
/**
* Writes the contents of the DOMOutput into the specified output stream.
*/
public void save(Writer out) throws IOException {
reset();
try {
if (doctype != null) {
out.write("<!DOCTYPE ");
out.write(doctype);
out.write(">\n");
}
Transformer t = TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(document), new StreamResult(out));
} catch (TransformerException e) {
IOException error = new IOException(e.getMessage());
error.initCause(e);
throw error;
}
}
/**
* Puts a new element into the DOM Document.
* The new element is added as a child to the current element in the DOM
* document. Then it becomes the current element.
* The element must be closed using closeElement.
*/
@Override
public void openElement(String tagName) {
Element newElement = document.createElement(tagName);
current.appendChild(newElement);
current = newElement;
}
/**
* Closes the current element of the DOM Document.
* The parent of the current element becomes the current element.
* @exception IllegalArgumentException if the provided tagName does
* not match the tag name of the element.
*/
@Override
public void closeElement() {
/*
if (! ((Element) current).getName().equals(tagName)) {
throw new IllegalArgumentException("Attempt to close wrong element:"+tagName +"!="+((Element) current).getName());
}*/
current = current.getParentNode();
}
/**
* Adds a comment to the current element of the DOM Document.
*/
@Override
public void addComment(String comment) {
current.appendChild(document.createComment(comment));
}
/**
* Adds a text to current element of the DOM Document.
* Note: Multiple consecutives texts will be merged.
*/
@Override
public void addText(String text) {
current.appendChild(document.createTextNode(text));
}
/**
* Adds an attribute to current element of the DOM Document.
*/
@Override
public void addAttribute(String name, String value) {
if (value != null) {
((Element) current).setAttribute(name, value);
}
}
/**
* Adds an attribute to current element of the DOM Document.
*/
@Override
public void addAttribute(String name, int value) {
((Element) current).setAttribute(name, Integer.toString(value));
}
/**
* Adds an attribute to current element of the DOM Document.
*/
@Override
public void addAttribute(String name, boolean value) {
((Element) current).setAttribute(name, Boolean.toString(value));
}
/**
* Adds an attribute to current element of the DOM Document.
*/
@Override
public void addAttribute(String name, float value) {
// Remove the awkard .0 at the end of each number
String str = Float.toString(value);
if (str.endsWith(".0")) str = str.substring(0, str.length() - 2);
((Element) current).setAttribute(name, str);
}
/**
* Adds an attribute to current element of the DOM Document.
*/
@Override
public void addAttribute(String name, double value) {
// Remove the awkard .0 at the end of each number
String str = Double.toString(value);
if (str.endsWith(".0")) str = str.substring(0, str.length() - 2);
((Element) current).setAttribute(name, str);
}
@Override
public void writeObject(Object o) throws IOException {
String tagName = factory.getName(o);
if (tagName == null) throw new IllegalArgumentException("no tag name for:"+o);
openElement(tagName);
if (objectids.containsKey(o)) {
addAttribute("ref", (String) objectids.get(o));
} else {
String id = Integer.toString(objectids.size(), 16);
objectids.put(o, id);
addAttribute("id", id);
factory.write(this,o);
}
closeElement();
}
@Override
public void addAttribute(String name, float value, float defaultValue) {
if (value != defaultValue) {
addAttribute(name, value);
}
}
@Override
public void addAttribute(String name, int value, int defaultValue) {
if (value != defaultValue) {
addAttribute(name, value);
}
}
@Override
public void addAttribute(String name, double value, double defaultValue) {
if (value != defaultValue) {
addAttribute(name, value);
}
}
@Override
public void addAttribute(String name, boolean value, boolean defaultValue) {
if (value != defaultValue) {
addAttribute(name, value);
}
}
@Override
public void addAttribute(String name, String value, String defaultValue) {
if (! value.equals(defaultValue)) {
addAttribute(name, value);
}
}
@Override
public Object getPrototype() {
if (prototypes == null) {
prototypes = new HashMap<String, Object>();
}
if (! prototypes.containsKey(current.getNodeName())) {
prototypes.put(current.getNodeName(), factory.create(current.getNodeName()));
}
return prototypes.get(current.getNodeName());
}
@Override
public void setDoctype(String doctype) {
this.doctype = doctype;
}
}
| 31.5625
| 126
| 0.601281
|
cef807fd5f4596f051ac984d702c17c2b6d863d4
| 1,133
|
package com.nrusev.web.ui.mvp;
import com.google.common.eventbus.EventBus;
import com.vaadin.navigator.Navigator;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.UI;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@SuppressWarnings("serial")
public abstract class MvpPresenter<T extends MvpView> implements View {
private final T view;
private final EventBus eventBus;
public MvpPresenter(final T view, final EventBus eventBus) {
this.eventBus = eventBus;
this.view = view;
}
public T getView() {
return view;
}
public EventBus getEventBus(){
return eventBus;
}
@PostConstruct
private void init(){
// this.eventBus.register(this);
}
@PreDestroy
private void preDestroy(){
// this.eventBus.unregister(this);
System.out.println("pre destroy on abstract class...");
}
@Override
public void enter(ViewChangeListener.ViewChangeEvent viewChangeEvent) {
}
protected void navigate(String path){
UI.getCurrent().getNavigator().navigateTo(path);
}
}
| 21.377358
| 72
| 0.762577
|
698229d46cc21593de34a2acf741bd7ba7e693e8
| 1,392
|
/*
* 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.hm.serviceapp.service.impl;
import com.hm.serviceapp.dao.PaisDAO;
import com.hm.serviceapp.dto.PaisDTO;
import com.hm.serviceapp.model.Pais;
import com.hm.serviceapp.service.PaisService;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
/**
*
* @author humartinez
*/
@Stateless(mappedName = "Pais")
public class PaisServiceImpl implements PaisService {
@EJB
private PaisDAO paisDAO;
private PaisDTO paisDTO;
private Pais pais;
private List<Pais> lPais;
@Override
public List<PaisDTO> getAll() {
List<PaisDTO> lPaisDTO = new ArrayList<>();
lPais = paisDAO.getAll();
for (Pais paisEntity : lPais) {
paisDTO = paisEntity._toConvertPaisEntity(paisEntity);
lPaisDTO.add(paisDTO);
}
return lPaisDTO;
}
@Override
public PaisDTO getById(int idPais) {
pais = paisDAO.getById(idPais);
paisDTO = pais._toConvertPaisEntity(pais);
if (paisDTO != null) {
System.out.println("Tiene contenido");
} else {
System.out.println("Esta vacio");
}
return paisDTO;
}
}
| 24.857143
| 79
| 0.653736
|
22fd2d9885fbe42481bf4de29e39fac77bb4c4ef
| 13,332
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.invertBoolean;
import com.intellij.codeInsight.daemon.impl.RecursiveCallLineMarkerProvider;
import com.intellij.ide.util.SuperMethodWarningUtil;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.LambdaRefactoringUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.Query;
import java.util.HashSet;
import com.intellij.util.containers.MultiMap;
import com.siyeh.ig.psiutils.BoolUtils;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public class JavaInvertBooleanDelegate extends InvertBooleanDelegate {
@Override
public boolean isVisibleOnElement(@NotNull PsiElement element) {
return element instanceof PsiVariable || element instanceof PsiMethod;
}
@Override
public boolean isAvailableOnElement(@NotNull PsiElement element) {
if (element instanceof PsiVariable) {
return PsiType.BOOLEAN.equals(((PsiVariable) element).getType());
}
else if (element instanceof PsiMethod) {
return PsiType.BOOLEAN.equals(((PsiMethod) element).getReturnType());
}
return false;
}
@Override
public PsiElement adjustElement(PsiElement element, Project project, Editor editor) {
if (element instanceof PsiVariable) {
PsiVariable var = (PsiVariable)element;
final PsiType returnType = var.getType();
if (!PsiType.BOOLEAN.equals(returnType)) {
CommonRefactoringUtil.showErrorHint(project, editor,
RefactoringBundle
.getCannotRefactorMessage(RefactoringBundle.message("invert.boolean.wrong.type")),
InvertBooleanHandler.REFACTORING_NAME, InvertBooleanHandler.INVERT_BOOLEAN_HELP_ID);
return null;
}
if (var instanceof PsiParameter) {
final PsiElement declarationScope = ((PsiParameter)var).getDeclarationScope();
if (declarationScope instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)declarationScope;
final PsiMethod superMethod = SuperMethodWarningUtil.checkSuperMethod(method, RefactoringBundle.message("to.refactor"));
if (superMethod == null) {
return null;
}
var = superMethod.getParameterList().getParameters()[method.getParameterList().getParameterIndex((PsiParameter)var)];
}
else if (declarationScope instanceof PsiForeachStatement) {
CommonRefactoringUtil.showErrorHint(project, editor,
RefactoringBundle.message("invert.boolean.foreach"),
InvertBooleanHandler.REFACTORING_NAME, InvertBooleanHandler.INVERT_BOOLEAN_HELP_ID);
return null;
}
}
return var;
}
else if (element instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)element;
final PsiType returnType = method.getReturnType();
if (!PsiType.BOOLEAN.equals(returnType)) {
CommonRefactoringUtil.showErrorHint(project, editor,
RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("invert.boolean.wrong.type")),
InvertBooleanHandler.REFACTORING_NAME,
InvertBooleanHandler.INVERT_BOOLEAN_HELP_ID);
return null;
}
return SuperMethodWarningUtil.checkSuperMethod(method, RefactoringBundle.message("to.refactor"));
}
return null;
}
public void collectRefsToInvert(PsiElement namedElement, Collection<PsiElement> elementsToInvert) {
final Query<PsiReference> query = namedElement instanceof PsiMethod ?
MethodReferencesSearch.search((PsiMethod)namedElement) :
ReferencesSearch.search(namedElement);
final Collection<PsiReference> refs = query.findAll();
for (PsiReference ref : refs) {
final PsiElement element = ref.getElement();
if (!collectElementsToInvert(namedElement, element, elementsToInvert)) {
collectForeignElementsToInvert(namedElement, element, JavaLanguage.INSTANCE, elementsToInvert);
}
}
}
@Override
public boolean collectElementsToInvert(PsiElement namedElement, PsiElement expression, Collection<PsiElement> elementsToInvert) {
boolean toInvert = super.collectElementsToInvert(namedElement, expression, elementsToInvert);
PsiElement parent = expression.getParent();
if (parent instanceof PsiAssignmentExpression && !(parent.getParent() instanceof PsiExpressionStatement)) {
elementsToInvert.add(parent);
}
return toInvert;
}
public PsiElement getElementToInvert(PsiElement namedElement, PsiElement element) {
if (element instanceof PsiReferenceExpression) {
final PsiReferenceExpression refExpr = (PsiReferenceExpression)element;
PsiElement parent = refExpr.getParent();
if (parent instanceof PsiAssignmentExpression && refExpr.equals(((PsiAssignmentExpression)parent).getLExpression())) {
return ((PsiAssignmentExpression)parent).getRExpression();
}
else {
if (namedElement instanceof PsiParameter) { //filter usages in super method calls
PsiElement gParent = refExpr.getParent().getParent();
if (gParent instanceof PsiMethodCallExpression) {
if (!canInvertReferenceElement(((PsiMethodCallExpression)gParent).getMethodExpression(), true)) {
return null;
}
}
}
return refExpr;
}
}
return null;
}
private static boolean canInvertReferenceElement(PsiElement expression, boolean recursive) {
PsiExpression qualifierExpression = expression instanceof PsiReferenceExpression ? ((PsiReferenceExpression)expression).getQualifierExpression()
: null;
if (qualifierExpression == null || !"super".equals(qualifierExpression.getText())) {
PsiElement parent = expression.getParent();
if (parent instanceof PsiMethodCallExpression) {
return !(recursive && RecursiveCallLineMarkerProvider.isRecursiveMethodCall((PsiMethodCallExpression)parent));
} else {
return true;
}
}
return false;
}
@Override
public void replaceWithNegatedExpression(@NotNull PsiElement expression) {
if (!(expression instanceof PsiExpression)) {
return;
}
if (expression.getParent() instanceof PsiMethodCallExpression) {
expression = expression.getParent();
}
while (expression.getParent() instanceof PsiPrefixExpression &&
((PsiPrefixExpression)expression.getParent()).getOperationTokenType() == JavaTokenType.EXCL) {
expression = expression.getParent();
}
if (expression instanceof PsiMethodReferenceExpression) {
final PsiExpression callExpression = LambdaRefactoringUtil.convertToMethodCallInLambdaBody((PsiMethodReferenceExpression)expression);
if (callExpression instanceof PsiCallExpression) {
PsiExpression negatedExpression = JavaPsiFacade.getElementFactory(callExpression.getProject())
.createExpressionFromText(BoolUtils.getNegatedExpressionText(callExpression), callExpression);
callExpression.replace(negatedExpression);
}
}
else if (!(expression.getParent() instanceof PsiExpressionStatement)) {
PsiExpression negatedExpression = JavaPsiFacade.getElementFactory(expression.getProject())
.createExpressionFromText(BoolUtils.getNegatedExpressionText((PsiExpression)expression), expression);
expression.replace(negatedExpression);
}
}
@Override
public void invertElementInitializer(final PsiElement element) {
if (element instanceof PsiField && ((PsiField)element).getInitializer() == null && !((PsiField)element).hasModifierProperty(PsiModifier.FINAL)) {
((PsiField)element).setInitializer(JavaPsiFacade.getElementFactory(element.getProject()).createExpressionFromText("true", element));
} else if (element instanceof PsiVariable) {
final PsiExpression initializer = ((PsiVariable)element).getInitializer();
if (initializer != null) {
replaceWithNegatedExpression(initializer);
}
}
}
public void collectRefElements(final PsiElement element,
final RenameProcessor renameProcessor,
@NotNull final String newName,
final Collection<PsiElement> elementsToInvert) {
collectRefsToInvert(element, elementsToInvert);
if (element instanceof PsiMethod) {
final Collection<PsiMethod> overriders = OverridingMethodsSearch.search((PsiMethod)element).findAll();
if (renameProcessor != null) {
for (PsiMethod overrider : overriders) {
renameProcessor.addElement(overrider, newName);
}
}
Collection<PsiMethod> allMethods = new HashSet<>(overriders);
allMethods.add((PsiMethod)element);
for (PsiMethod method : allMethods) {
method.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitReturnStatement(PsiReturnStatement statement) {
final PsiExpression returnValue = statement.getReturnValue();
if (returnValue != null && PsiType.BOOLEAN.equals(returnValue.getType())) {
elementsToInvert.add(returnValue);
}
}
@Override
public void visitClass(PsiClass aClass) {}
@Override
public void visitLambdaExpression(PsiLambdaExpression expression) {}
});
}
}
else if (element instanceof PsiParameter && ((PsiParameter)element).getDeclarationScope() instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)((PsiParameter)element).getDeclarationScope();
int index = method.getParameterList().getParameterIndex((PsiParameter)element);
assert index >= 0;
final Query<PsiReference> methodQuery = MethodReferencesSearch.search(method);
final Collection<PsiReference> methodRefs = methodQuery.findAll();
for (PsiReference ref : methodRefs) {
PsiElement parent = ref.getElement().getParent();
if (parent instanceof PsiAnonymousClass) {
parent = parent.getParent();
}
if (parent instanceof PsiCall) {
final PsiCall call = (PsiCall)parent;
final PsiReferenceExpression methodExpression = call instanceof PsiMethodCallExpression ?
((PsiMethodCallExpression)call).getMethodExpression() :
null;
final PsiExpressionList argumentList = call.getArgumentList();
if (argumentList != null) {
final PsiExpression[] args = argumentList.getExpressions();
if (index < args.length) {
if (methodExpression == null ||
canInvertReferenceElement(methodExpression,
args[index] instanceof PsiReferenceExpression &&
((PsiReferenceExpression)args[index]).resolve() == element)) {
elementsToInvert.add(args[index]);
}
}
}
}
}
final Collection<PsiMethod> overriders = OverridingMethodsSearch.search(method).findAll();
for (PsiMethod overrider : overriders) {
final PsiParameter overriderParameter = overrider.getParameterList().getParameters()[index];
if (renameProcessor != null) {
renameProcessor.addElement(overriderParameter, newName);
}
collectRefsToInvert(overriderParameter, elementsToInvert);
}
}
}
@Override
public void findConflicts(UsageInfo[] usageInfos, MultiMap<PsiElement, String> conflicts) {
for (UsageInfo info : usageInfos) {
final PsiElement element = info.getElement();
if (element instanceof PsiMethodReferenceExpression) {
conflicts.putValue(element, RefactoringBundle.message("expand.method.reference.warning"));
}
}
}
}
| 45.814433
| 149
| 0.682118
|
92b50c181949e3b3a6410434984dc5ac2a1a6ff9
| 4,498
|
package rivet.cluster.hbase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableInputFormat;
import org.apache.hadoop.hbase.util.Bytes;
import rivet.cluster.spark.Row;
import scala.Tuple2;
import static java.util.Arrays.stream;
import static rivet.cluster.util.Util.setting;
public class HBase {
public static final byte[] DATA_COLUMN_FAMILY = stringToBytes("data");
private static HTableDescriptor newTableDescriptor(TableName name) {
return new HTableDescriptor(name)
.addFamily(
new HColumnDescriptor(
DATA_COLUMN_FAMILY));
}
public static boolean tableExists(String tableName) throws IOException {
try (Connection conn = ConnectionFactory.createConnection()) {
Admin admin = conn.getAdmin();
TableName tn = TableName.valueOf(tableName);
if (admin.tableExists(tn)) return true;
System.out.format("Table '%s' does not exist. Create it? (y/n)" , tableName);
String input = System.console().readLine().toLowerCase();
if (input == "n") return false;
admin.createTable(newTableDescriptor(tn));
return true;
}
}
public static boolean clearTable(String tableName) throws IOException {
//log.log("Clearing table: " + tableName);
try (Connection conn = ConnectionFactory.createConnection()) {
Admin admin = conn.getAdmin();
TableName tn = TableName.valueOf(tableName);
System.out.println("Disabling table: " + tableName);
admin.disableTable(tn);
System.out.println("Deleting table: " + tableName);
admin.deleteTable(tn);
System.out.println("Creating new table: " + tableName);
admin.createTable(newTableDescriptor(tn));
return tableExists(tableName);
}
}
public static Cell newCell(ImmutableBytesWritable row, String column, String value) {
return CellUtil.createCell(
row.get(),
DATA_COLUMN_FAMILY,
stringToBytes(column),
System.currentTimeMillis(),
KeyValue.Type.Maximum.getCode(),
stringToBytes(value));
}
public static Put newPut(ImmutableBytesWritable key, Row row) {
Put put;
try {
put = new Put(key.get());
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Cannot create Put with arg: '" + key.toString() + "'");
}
row.forEach((k, v) -> {
try{ put.add(newCell(key, k, v)); }
catch (IOException e) { e.printStackTrace(); }
});
return put;
}
public static Result newResult(ImmutableBytesWritable key, Row row) {
List<Cell> cells = new ArrayList<>();
row.forEach((k, v) -> cells.add(newCell(key, k, v)));
return Result.create(cells);
}
public static Map<String, String> resultToStrings (Result r) {
Map<String, String> res = new HashMap<>();
res.put("word", bytesToString(r.getRow()));
r.getFamilyMap(DATA_COLUMN_FAMILY).forEach(
(x, y) -> res.put(bytesToString(x), bytesToString(y)));
return res;
}
public static byte[] stringToBytes (String string) { return Bytes.toBytes(string); }
public static String bytesToString (byte[] bytes) { return Bytes.toString(bytes); }
public static byte[] intToBytes (int i) { return Bytes.toBytes(i); }
public static int bytesToInt (byte[] bytes) { return Bytes.toInt(bytes); }
public static String ibwToString(ImmutableBytesWritable ibw) {return bytesToString(ibw.get());}
public static ImmutableBytesWritable stringToIBW(String str) {return new ImmutableBytesWritable(stringToBytes(str));}
@SafeVarargs
public static Configuration newConf (Tuple2<String, String>...settings) {
Configuration conf = HBaseConfiguration.create();
stream(settings).forEach((setting) -> conf.set(setting._1, setting._2));
return conf;
}
public static Configuration newConf (String tableName) {
return newConf(
setting(TableInputFormat.INPUT_TABLE, tableName));
}
}
| 34.6
| 118
| 0.739662
|
8716d1e59aa08894d0c0d6700a083ca9aff0d3d6
| 1,511
|
//Leetcode problem 406 Queue Reconstruction by Height
//Solution written by Xuqiang Fang on 21 April, 2018
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
class Solution{
public int[][] reconstructQueue(int[][] people){
if(people == null || people.length == 0)
return people;
Arrays.sort(people, new queue());
LinkedList<int[]> result = new LinkedList<>();
for(int[] p : people){
if(p[0] != people[0][0]){
result.add(p[1], p);
}
else{
result.add(p);
}
}
for(int i=0; i<people.length; ++i){
people[i] = result.get(i);
}
return people;
}
class queue implements Comparator<int[]>{
@Override
public int compare(int[] a, int[] b){
if(a[0] == b[0]){
return a[1] - b[1];
}
return b[0] - a[0];
}
}
}
public class ReconstructQueue{
public static void main(String[] args){
Solution s = new Solution();
int[][] people = {{7,0},{4,4},{7,1},{5,0},{6,1},{5,2}};
int[][] result = s.reconstructQueue(people);
for(int[] r : result){
System.out.print("[");
System.out.print(r[0]);
System.out.print(",");
System.out.print(r[1]);
System.out.print("]");
System.out.print(",\t");
}
System.out.println("[0,0]");
}
}
| 27.981481
| 63
| 0.487756
|
8f6855be8938f952a590c00a4778955e9f819c19
| 1,645
|
package com.webcheckers.ui;
import static spark.Spark.halt;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Logger;
import spark.ModelAndView;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.TemplateEngine;
import com.webcheckers.appl.GameCenter;
/**
* The UI Controller to expose the sign-in functionality
* and redirect to the game page.
*
* @author <a href='mailto:exo3392@rit.edu'>Efe Ozturkoglu</a>
*/
public class PostSignOutRoute implements Route {
private static final Logger LOG = Logger.getLogger( PostSignOutRoute.class.getName());
private final TemplateEngine templateEngine;
private final GameCenter gameCenter;
/**
* Create the Spark Route (UI controller) for the
* {@code POST /} HTTP request.
*
* @param templateEngine
* the HTML template rendering engine
*/
public PostSignOutRoute(final TemplateEngine templateEngine, final GameCenter gameCenter) {
// validation
Objects.requireNonNull(templateEngine, "templateEngine must not be null");
//
this.templateEngine = templateEngine;
this.gameCenter = gameCenter;
//
LOG.config("PostSignOutRoute is initialized.");
}
/**
* Sign out the player
*
* @param request
* the HTTP request
* @param response
* the HTTP response
*/
@Override
public Object handle(Request request, Response response) {
LOG.finer(" PostSignOutRoute is invoked.");
LOG.severe(request.queryParams("username"));
gameCenter.removePlayer(request.session().id());
response.redirect("/");
return "";
}
}
| 25.307692
| 94
| 0.712462
|
d7e4597dad382bbb15b3207493541498b07755df
| 1,413
|
package com.nettm.exercise.random;
import lombok.experimental.UtilityClass;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@UtilityClass
public class DateTimeGenerator extends BaseDataGenerator {
protected BigDecimal minValue = new BigDecimal("-2209017600000");
protected BigDecimal maxValue = new BigDecimal(System.currentTimeMillis());
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Date generate() {
return generate(minValue.longValue(), maxValue.longValue());
}
public Date generate(String minValue, String maxValue) {
Date min = null;
Date max = null;
try {
min = DATE_FORMAT.parse(minValue);
max = DATE_FORMAT.parse(maxValue);
} catch (ParseException e) {
throw new RuntimeException(e);
}
return generate(min.getTime(), max.getTime());
}
public Date generate(Date minValue, Date maxValue) {
return generate(minValue.getTime(), maxValue.getTime());
}
public Date generate(long minValue, long maxValue) {
BigDecimal min = new BigDecimal(minValue);
BigDecimal max = new BigDecimal(maxValue);
BigDecimal retValue = null;
BigDecimal length = max.subtract(min);
BigDecimal factor = new BigDecimal(RANDOM.nextDouble());
retValue = length.multiply(factor).add(min);
return new Date(retValue.toBigInteger().longValue());
}
}
| 27.705882
| 96
| 0.750885
|
de2676de978b4cac1af44627dd46e7ac28566b4c
| 4,237
|
/*
* ICARUS2 Corpus Modeling Framework
* Copyright (C) 2014-2021 Markus Gärtner <markus.gaertner@ims.uni-stuttgart.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package de.ims.icarus2.query.api.engine.matcher.mark;
import static de.ims.icarus2.util.IcarusUtils.UNSET_INT;
import java.util.stream.IntStream;
import com.google.common.annotations.VisibleForTesting;
/**
* Models a simple bounded interval in {@code int} space.
* <p>
* Note that this utility class does not define any setter methods
* itself, as it is purely used in the context of positional
* {@link Marker markers} to describe legal index ranges for matching.
*
* @author Markus Gärtner
*
*/
public class Interval implements Cloneable, Comparable<Interval> {
public static Interval of(int value) {
Interval iv = new Interval();
iv.from = iv.to = value;
return iv;
}
public static Interval of(int from, int to) {
Interval iv = new Interval();
iv.from = from;
iv.to = to;
return iv;
}
public static Interval blank() { return new Interval(); }
protected Interval() { /* no-op */ }
/** The first legal index */
public int from = UNSET_INT;
/** The last legal index */
public int to = UNSET_INT;
public boolean contains(int index) { return index>=from && index<=to; }
public boolean isValid() { return from!=UNSET_INT && to!=UNSET_INT; }
/** Invalidates the interval */
public void reset() { from = UNSET_INT; to = UNSET_INT; }
/** Sets the entire interval to the new boundaries (which can be {@code -1}). */
public void reset(int from, int to) { this.from = from; this.to = to; }
/** Overwrites this interval with the boudnaries of another interval. */
public void reset(Interval other) { this.from = other.from; this.to = other.to; }
public int size() { return isEmpty() ? 0 : to-from+1; }
@VisibleForTesting
public int indexAt(int idx) {
if(isEmpty() || idx<0 || idx>=size())
throw new ArrayIndexOutOfBoundsException();
return from+idx;
}
public boolean isEmpty() { return to<from || to==UNSET_INT || from==UNSET_INT; }
public IntStream stream() {
if(isEmpty()) {
return IntStream.empty();
}
return IntStream.rangeClosed(from, to);
}
public int[] asArray() { return stream().toArray(); }
/**
* Reduces this interval's boundaries to encompass the index intersection
* between this and the {@code other} interval.
*
* @return {@code true} iff this interval is not empty after intersecting
*/
public boolean intersect(Interval other) {
from = Math.max(from, other.from);
to = Math.min(to, other.to);
return from<=to;
}
public boolean intersect(int grom, int to) {
this.from = Math.max(this.from, from);
this.to = Math.min(this.to, to);
return this.from<=this.to;
}
@Override
public int compareTo(Interval o) {
if(isEmpty()) {
return o.isEmpty() ? 0 : -1 ;
}
int r = from - o.from;
if(r==0) {
r = to - o.to;
}
return r;
}
@Override
public String toString() {
return "["+from+","+to+"]";
}
@Override
public int hashCode() {
return from * to;
}
@Override
public boolean equals(Object obj) {
if(obj==this) {
return true;
} else if(obj instanceof Interval) {
Interval other = (Interval)obj;
return from==other.from && to==other.to;
}
return false;
}
/** Since this implementation only holds pointer values we can do shallow copy */
@Override
public Interval clone() {
try {
return (Interval) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError("Class is cloneable", e);
}
}
}
| 26.816456
| 83
| 0.655417
|
f7d4edc6e3fc75d876772f0aa9398aa34b8474b6
| 48,119
|
package com.abina.basetype;
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.HTMLWriter;
import org.dom4j.io.OutputFormat;
public class StringUtil {
private static Pattern numericPattern = Pattern.compile("^[0-9\\-]+$");
private static Pattern numericStringPattern = Pattern.compile("^[0-9\\-\\-]+$");
private static Pattern floatNumericPattern = Pattern.compile("^[0-9\\-\\.]+$");
private static Pattern abcPattern = Pattern.compile("^[a-z|A-Z]+$");
public static final String splitStrPattern = ",|,|;|;|、|\\.|。|-|_|\\(|\\)|\\[|\\]|\\{|\\}|\\\\|/| | |\"";
private static Pattern chinesePattern = Pattern.compile("[\u4e00-\u9fa5]");
/**
* 判断是否数字表示
*
* @param src
* 源字符串
* @return 是否数字的标志
*/
public static boolean isNumeric(String src) {
boolean return_value = false;
if (src != null && src.length() > 0) {
Matcher m = numericPattern.matcher(src);
if (m.find()) {
return_value = true;
}
}
return return_value;
}
/**
* 判断是否数字表示
*
* @param src
* 源字符串
* @return 是否数字的标志
*/
public static boolean isNumericString(String src) {
boolean return_value = false;
if (src != null && src.length() > 0) {
Matcher m = numericStringPattern.matcher(src);
if (m.find()) {
return_value = true;
}
}
return return_value;
}
/**
* 判断是否纯字母组合
*
* @param src
* 源字符串
* @return 是否纯字母组合的标志
*/
public static boolean isABC(String src) {
boolean return_value = false;
if (src != null && src.length() > 0) {
Matcher m = abcPattern.matcher(src);
if (m.find()) {
return_value = true;
}
}
return return_value;
}
/**
* 判断是否浮点数字表示
*
* @param src
* 源字符串
* @return 是否数字的标志
*/
public static boolean isFloatNumeric(String src) {
boolean return_value = false;
if (src != null && src.length() > 0) {
Matcher m = floatNumericPattern.matcher(src);
if (m.find()) {
return_value = true;
}
}
return return_value;
}
/**
* 将乱码转码成中文
*
* @param str
* @return
*/
public static String toChinese(String str) {
String chineseChar = "";
if (!isContainChinese(str)) {
chineseChar = changCoding(str, "ISO-8859-1", "utf-8");
} else {
chineseChar = str;
}
return chineseChar;
}
/**
* 正则验证字符串是否包含中文字符
*
* @param str
* @return true:包含; false:不包含
*/
public static boolean isContainChinese(String str) {
if (str == null) {
return false;
}
Matcher m = chinesePattern.matcher(str);
if (m.find()) {
return true;
}
return false;
}
/**
* 把string array or list用给定的符号symbol连接成一个字符串
*
* @param array
* @param symbol
* @return
*/
public static String joinString(List array, String symbol) {
String result = "";
if (array != null) {
for (int i = 0; i < array.size(); i++) {
String temp = array.get(i).toString();
if (temp != null && temp.trim().length() > 0)
result += (temp + symbol);
}
if (result.length() > 1)
result = result.substring(0, result.length() - 1);
}
return result;
}
public static String subStringNotEncode(String subject, int size) {
if (subject != null && subject.length() > size) {
subject = subject.substring(0, size) + "...";
}
return subject;
}
/**
* 截取字符串 超出的字符用symbol代替
*
* @param len
* 字符串长度 长度计量单位为一个GBK汉字 两个英文字母计算为一个单位长度
* @param str
* @param symbol
* @return
*/
public static String getLimitLengthString(String str, int len, String symbol) {
int iLen = len * 2;
int counterOfDoubleByte = 0;
String strRet = "";
try {
if (str != null) {
byte[] b = str.getBytes("GBK");
if (b.length <= iLen) {
return str;
}
for (int i = 0; i < iLen; i++) {
if (b[i] < 0) {
counterOfDoubleByte++;
}
}
if (counterOfDoubleByte % 2 == 0) {
strRet = new String(b, 0, iLen, "GBK") + symbol;
return strRet;
} else {
strRet = new String(b, 0, iLen - 1, "GBK") + symbol;
return strRet;
}
} else {
return "";
}
} catch (Exception ex) {
return str.substring(0, len);
} finally {
strRet = null;
}
}
/**
* 截取字符串 超出的字符用symbol代替
*
* @param len
* 字符串长度 长度计量单位为一个GBK汉字 两个英文字母计算为一个单位长度
* @param str
* @param symbol
* @return12
*/
public static String getLimitLengthString(String str, int len) {
return getLimitLengthString(str, len, "...");
}
/**
*
* 截取字符,不转码
*
* @param subject
* @param size
* @return
*/
public static String subStrNotEncode(String subject, int size) {
if (subject.length() > size) {
subject = subject.substring(0, size);
}
return subject;
}
/**
* 把string array or list用给定的符号symbol连接成一个字符串
*
* @param array
* @param symbol
* @return
*/
public static String joinString(String[] array, String symbol) {
String result = "";
if (array != null) {
for (int i = 0; i < array.length; i++) {
String temp = array[i];
if (temp != null && temp.trim().length() > 0)
result += (temp + symbol);
}
if (result.length() > 1)
result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* 取得字符串的实际长度(考虑了汉字的情况)
*
* @param SrcStr
* 源字符串
* @return 字符串的实际长度
*/
public static int getStringLen(String SrcStr) {
int return_value = 0;
if (SrcStr != null) {
char[] theChars = SrcStr.toCharArray();
for (int i = 0; i < theChars.length; i++) {
return_value += (theChars[i] <= 255) ? 1 : 2;
}
}
return return_value;
}
/**
* 检查数据串中是否包含非法字符集
*
* @param str
* @return [true]|[false] 包含|不包含
*/
public static boolean check(String str) {
String sIllegal = "'\"";
int len = sIllegal.length();
if (null == str)
return false;
for (int i = 0; i < len; i++) {
if (str.indexOf(sIllegal.charAt(i)) != -1)
return true;
}
return false;
}
/***************************************************************************
* getHideEmailPrefix - 隐藏邮件地址前缀。
*
* @param email
* - EMail邮箱地址 例如: linwenguo@koubei.com 等等...
* @return 返回已隐藏前缀邮件地址, 如 *********@koubei.com.
* @version 1.0 (2006.11.27) Wilson Lin
**************************************************************************/
public static String getHideEmailPrefix(String email) {
if (null != email) {
int index = email.lastIndexOf('@');
if (index > 0) {
email = repeat("*", index).concat(email.substring(index));
}
}
return email;
}
/***************************************************************************
* repeat - 通过源字符串重复生成N次组成新的字符串。
*
* @param src
* - 源字符串 例如: 空格(" "), 星号("*"), "浙江" 等等...
* @param num
* - 重复生成次数
* @return 返回已生成的重复字符串
* @version 1.0 (2006.10.10) Wilson Lin
**************************************************************************/
public static String repeat(String src, int num) {
StringBuffer s = new StringBuffer();
for (int i = 0; i < num; i++)
s.append(src);
return s.toString();
}
/**
* 根据指定的字符把源字符串分割成一个数组
*
* @param src
* @return
*/
public static List<String> parseString2ListByCustomerPattern(String pattern, String src) {
if (src == null)
return null;
List<String> list = new ArrayList<String>();
String[] result = src.split(pattern);
for (int i = 0; i < result.length; i++) {
list.add(result[i]);
}
return list;
}
/**
* 根据指定的字符把源字符串分割成一个数组
*
* @param src
* @return
*/
public static List<String> parseString2ListByPattern(String src) {
String pattern = ",|,|、|。";
return parseString2ListByCustomerPattern(pattern, src);
}
/**
* 格式化一个float
*
* @param format
* 要格式化成的格式 such as #.00, #.#
*/
public static String formatFloat(float f, String format) {
DecimalFormat df = new DecimalFormat(format);
return df.format(f);
}
/**
* 判断是否是空字符串 null和"" 都返回 true
*
* @author Robin Chang
* @param s
* @return
*/
public static boolean isEmpty(String s) {
if (s != null && !s.equals("")) {
return false;
}
return true;
}
/**
* 自定义的分隔字符串函数 例如: 1,2,3 =>[1,2,3] 3个元素 ,2,3=>[,2,3] 3个元素 ,2,3,=>[,2,3,]
* 4个元素 ,,,=>[,,,] 4个元素
*
* 5.22算法修改,为提高速度不用正则表达式 两个间隔符,,返回""元素
*
* @param split
* 分割字符 默认,
* @param src
* 输入字符串
* @return 分隔后的list
* @author Robin
*/
public static List<String> splitToList(String split, String src) {
// 默认,
String sp = ",";
if (split != null && split.length() == 1) {
sp = split;
}
List<String> r = new ArrayList<String>();
int lastIndex = -1;
int index = src.indexOf(sp);
if (-1 == index && src != null) {
r.add(src);
return r;
}
while (index >= 0) {
if (index > lastIndex) {
r.add(src.substring(lastIndex + 1, index));
} else {
r.add("");
}
lastIndex = index;
index = src.indexOf(sp, index + 1);
if (index == -1) {
r.add(src.substring(lastIndex + 1, src.length()));
}
}
return r;
}
/**
* 把 名=值 参数表转换成字符串 (a=1,b=2 =>a=1&b=2)
*
* @param map
* @return
*/
public static String linkedHashMapToString(LinkedHashMap<String, String> map) {
if (map != null && map.size() > 0) {
String result = "";
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
String name = (String) it.next();
String value = (String) map.get(name);
result += (result.equals("")) ? "" : "&";
result += String.format("%s=%s", name, value);
}
return result;
}
return null;
}
/**
* 解析字符串返回 名称=值的参数表 (a=1&b=2 => a=1,b=2)
*
* @see test.koubei.util.StringUtilTest#testParseStr()
* @param str
* @return
*/
@SuppressWarnings("unchecked")
public static LinkedHashMap<String, String> toLinkedHashMap(String str) {
if (str != null && !str.equals("") && str.indexOf("=") > 0) {
LinkedHashMap result = new LinkedHashMap();
String name = null;
String value = null;
int i = 0;
while (i < str.length()) {
char c = str.charAt(i);
switch (c) {
case 61: // =
value = "";
break;
case 38: // &
if (name != null && value != null && !name.equals("")) {
result.put(name, value);
}
name = null;
value = null;
break;
default:
if (value != null) {
value = (value != null) ? (value + c) : "" + c;
} else {
name = (name != null) ? (name + c) : "" + c;
}
}
i++;
}
if (name != null && value != null && !name.equals("")) {
result.put(name, value);
}
return result;
}
return null;
}
/**
* 根据输入的多个解释和下标返回一个值
*
* @param captions
* 例如:"无,爱干净,一般,比较乱"
* @param index
* 1
* @return 一般
*/
public static String getCaption(String captions, int index) {
if (index > 0 && captions != null && !captions.equals("")) {
String[] ss = captions.split(",");
if (ss != null && ss.length > 0 && index < ss.length) {
return ss[index];
}
}
return null;
}
/**
* 数字转字符串,如果num<=0 则输出"";
*
* @param num
* @return
*/
public static String numberToString(Object num) {
if (num == null) {
return null;
} else if (num instanceof Integer && (Integer) num > 0) {
return Integer.toString((Integer) num);
} else if (num instanceof Long && (Long) num > 0) {
return Long.toString((Long) num);
} else if (num instanceof Float && (Float) num > 0) {
return Float.toString((Float) num);
} else if (num instanceof Double && (Double) num > 0) {
return Double.toString((Double) num);
} else {
return "";
}
}
/**
* 货币转字符串
*
* @param money
* @param style
* 样式 [default]要格式化成的格式 such as #.00, #.#
* @return
*/
public static String moneyToString(Object money, String style) {
if (money != null && style != null && (money instanceof Double || money instanceof Float)) {
Double num = (Double) money;
if (style.equalsIgnoreCase("default")) {
// 缺省样式 0 不输出 ,如果没有输出小数位则不输出.0
if (num == 0) {
// 不输出0
return "";
} else if ((num * 10 % 10) == 0) {
// 没有小数
return Integer.toString((int) num.intValue());
} else {
// 有小数
return num.toString();
}
} else {
DecimalFormat df = new DecimalFormat(style);
return df.format(num);
}
}
return null;
}
/**
* 在sou中是否存在finds 如果指定的finds字符串有一个在sou中找到,返回true;
*
* @param sou
* @param find
* @return
*/
public static boolean strPos(String sou, String... finds) {
if (sou != null && finds != null && finds.length > 0) {
for (int i = 0; i < finds.length; i++) {
if (sou.indexOf(finds[i]) > -1)
return true;
}
}
return false;
}
public static boolean strPos(String sou, List<String> finds) {
if (sou != null && finds != null && finds.size() > 0) {
for (String s : finds) {
if (sou.indexOf(s) > -1)
return true;
}
}
return false;
}
public static boolean strPos(String sou, String finds) {
List<String> t = splitToList(",", finds);
return strPos(sou, t);
}
/**
* 判断两个字符串是否相等 如果都为null则判断为相等,一个为null另一个not null则判断不相等 否则如果s1=s2则相等
*
* @param s1
* @param s2
* @return
*/
public static boolean equals(String s1, String s2) {
if (StringUtil.isEmpty(s1) && StringUtil.isEmpty(s2)) {
return true;
} else if (!StringUtil.isEmpty(s1) && !StringUtil.isEmpty(s2)) {
return s1.equals(s2);
}
return false;
}
public static int toInt(String s) {
if (s != null && !"".equals(s.trim())) {
try {
return Integer.parseInt(s);
} catch (Exception e) {
return 0;
}
}
return 0;
}
public static double toDouble(String s) {
if (s != null && !"".equals(s.trim())) {
return Double.parseDouble(s);
}
return 0;
}
/**
* 把xml 转为object
*
* @param xml
* @return
*/
public static Object xmlToObject(String xml) {
try {
ByteArrayInputStream in = new ByteArrayInputStream(xml.getBytes("UTF8"));
XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(in));
return decoder.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static long toLong(String s) {
try {
if (s != null && !"".equals(s.trim()))
return Long.parseLong(s);
} catch (Exception exception) {
}
return 0L;
}
public static String simpleEncrypt(String str) {
if (str != null && str.length() > 0) {
// str = str.replaceAll("0","a");
str = str.replaceAll("1", "b");
// str = str.replaceAll("2","c");
str = str.replaceAll("3", "d");
// str = str.replaceAll("4","e");
str = str.replaceAll("5", "f");
str = str.replaceAll("6", "g");
str = str.replaceAll("7", "h");
str = str.replaceAll("8", "i");
str = str.replaceAll("9", "j");
}
return str;
}
/**
* 过滤用户输入的URL地址(防治用户广告) 目前只针对以http或www开头的URL地址
* 本方法调用的正则表达式,不建议用在对性能严格的地方例如:循环及list页面等
*
* @author fengliang
* @param str
* 需要处理的字符串
* @return 返回处理后的字符串
*/
public static String removeURL(String str) {
if (str != null)
str = str.toLowerCase().replaceAll("(http|www|com|cn|org|\\.)+", "");
return str;
}
/**
* 随即生成指定位数的含数字验证码字符串
*
* @author Peltason
* @date 2007-5-9
* @param bit
* 指定生成验证码位数
* @return String
*/
public static String numRandom(int bit) {
if (bit == 0)
bit = 6; // 默认6位
String str = "";
str = "0123456789";// 初始化种子
return RandomStringUtils.random(bit, str);// 返回6位的字符串
}
/**
* 随即生成指定位数的含验证码字符串
*
* @author Peltason
*
* @date 2007-5-9
* @param bit
* 指定生成验证码位数
* @return String
*/
public static String random(int bit) {
if (bit == 0)
bit = 6; // 默认6位
// 因为o和0,l和1很难区分,所以,去掉大小写的o和l
String str = "";
str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz";// 初始化种子
return RandomStringUtils.random(bit, str);// 返回6位的字符串
}
/**
* Wap页面的非法字符检查
*
* @author hugh115
* @date 2007-06-29
* @param str
* @return
*/
public static String replaceWapStr(String str) {
if (str != null) {
str = str.replaceAll("<span class=\"keyword\">", "");
str = str.replaceAll("</span>", "");
str = str.replaceAll("<strong class=\"keyword\">", "");
str = str.replaceAll("<strong>", "");
str = str.replaceAll("</strong>", "");
str = str.replace('$', '$');
str = str.replaceAll("&", "&");
str = str.replace('&', '&');
str = str.replace('<', '<');
str = str.replace('>', '>');
}
return str;
}
/**
* 字符串转float 如果异常返回0.00
*
* @param s
* 输入的字符串
* @return 转换后的float
*/
public static Float toFloat(String s) {
try {
return Float.parseFloat(s);
} catch (NumberFormatException e) {
return new Float(0);
}
}
/**
* 页面中去除字符串中的空格、回车、换行符、制表符
*
* @author shazao
* @date 2007-08-17
* @param str
* @return
*/
public static String replaceBlank(String str) {
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
str = m.replaceAll("");
}
return str;
}
/**
* 全角生成半角
*
* @author bailong
* @date 2007-08-29
* @param str
* @return
*/
public static String Q2B(String QJstr) {
String outStr = "";
String Tstr = "";
byte[] b = null;
for (int i = 0; i < QJstr.length(); i++) {
try {
Tstr = QJstr.substring(i, i + 1);
b = Tstr.getBytes("unicode");
} catch (java.io.UnsupportedEncodingException e) {
}
if (b[3] == -1) {
b[2] = (byte) (b[2] + 32);
b[3] = 0;
try {
outStr = outStr + new String(b, "unicode");
} catch (java.io.UnsupportedEncodingException ex) {
}
} else {
outStr = outStr + Tstr;
}
}
return outStr;
}
/**
*
* 转换编码
*
* @param s
* 源字符串
* @param fencode
* 源编码格式
* @param bencode
* 目标编码格式
* @return 目标编码
*/
public static String changCoding(String s, String fencode, String bencode) {
String str;
try {
if (StringUtil.isNotEmpty(s)) {
str = new String(s.getBytes(fencode), bencode);
} else {
str = "";
}
return str;
} catch (UnsupportedEncodingException e) {
return s;
}
}
/**
* @param str
* @return
*************************************************************************
*/
public static String removeHTMLLableExe(String str) {
str = stringReplace(str, ">\\s*<", "><");
str = stringReplace(str, " ", " ");// 替换空格
str = stringReplace(str, "<br ?/?>", "\n");// 去<br><br />
str = stringReplace(str, "<([^<>]+)>", "");// 去掉<>内的字符
str = stringReplace(str, "\\s\\s\\s*", " ");// 将多个空白变成一个空格
str = stringReplace(str, "^\\s*", "");// 去掉头的空白
str = stringReplace(str, "\\s*$", "");// 去掉尾的空白
str = stringReplace(str, " +", " ");
return str;
}
/**
* 除去html标签
*
* @param str
* 源字符串
* @return 目标字符串
*/
public static String removeHTMLLable(String str) {
str = stringReplace(str, "\\s", "");// 去掉页面上看不到的字符
str = stringReplace(str, "<br ?/?>", "\n");// 去<br><br />
str = stringReplace(str, "<([^<>]+)>", "");// 去掉<>内的字符
str = stringReplace(str, " ", " ");// 替换空格
str = stringReplace(str, "&(\\S)(\\S?)(\\S?)(\\S?);", "");// 去<br><br />
return str;
}
/**
* 去掉HTML标签之外的字符串
*
* @param str
* 源字符串
* @return 目标字符串
*/
public static String removeOutHTMLLable(String str) {
str = stringReplace(str, ">([^<>]+)<", "><");
str = stringReplace(str, "^([^<>]+)<", "<");
str = stringReplace(str, ">([^<>]+)$", ">");
return str;
}
/**
*
* 字符串替换
*
* @param str
* 源字符串
* @param sr
* 正则表达式样式
* @param sd
* 替换文本
* @return 结果串
*/
public static String stringReplace(String str, String sr, String sd) {
String regEx = sr;
Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
str = m.replaceAll(sd);
return str;
}
/**
*
* 将html的省略写法替换成非省略写法
*
* @param str
* html字符串
* @param pt
* 标签如table
* @return 结果串
*/
public static String fomateToFullForm(String str, String pt) {
String regEx = "<" + pt + "\\s+([\\S&&[^<>]]*)/>";
Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
String[] sa = null;
String sf = "";
String sf2 = "";
String sf3 = "";
for (; m.find();) {
sa = p.split(str);
if (sa == null) {
break;
}
sf = str.substring(sa[0].length(), str.indexOf("/>", sa[0].length()));
sf2 = sf + "></" + pt + ">";
sf3 = str.substring(sa[0].length() + sf.length() + 2);
str = sa[0] + sf2 + sf3;
sa = null;
}
return str;
}
/**
*
* 得到字符串的子串位置序列
*
* @param str
* 字符串
* @param sub
* 子串
* @param b
* true子串前端,false子串后端
* @return 字符串的子串位置序列
*/
public static int[] getSubStringPos(String str, String sub, boolean b) {
// int[] i = new int[(new Integer((str.length()-stringReplace( str , sub
// , "" ).length())/sub.length())).intValue()] ;
String[] sp = null;
int l = sub.length();
sp = splitString(str, sub);
if (sp == null) {
return null;
}
int[] ip = new int[sp.length - 1];
for (int i = 0; i < sp.length - 1; i++) {
ip[i] = sp[i].length() + l;
if (i != 0) {
ip[i] += ip[i - 1];
}
}
if (b) {
for (int j = 0; j < ip.length; j++) {
ip[j] = ip[j] - l;
}
}
return ip;
}
/**
*
* 根据正则表达式分割字符串
*
* @param str
* 源字符串
* @param ms
* 正则表达式
* @return 目标字符串组
*/
public static String[] splitString(String str, String ms) {
String regEx = ms;
Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
String[] sp = p.split(str);
return sp;
}
/**
* 根据正则表达式提取字符串,相同的字符串只返回一个
*
* @param str源字符串
* @param pattern
* 正则表达式
* @return 目标字符串数据组
*************************************************************************
*/
// ★传入一个字符串,把符合pattern格式的字符串放入字符串数组
// java.util.regex是一个用正则表达式所订制的模式来对字符串进行匹配工作的类库包
public static String[] getStringArrayByPattern(String str, String pattern) {
Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(str);
// 范型
Set<String> result = new HashSet<String>();// 目的是:相同的字符串只返回一个。。。 不重复元素
// boolean find() 尝试在目标字符串里查找下一个匹配子串。
while (matcher.find()) {
for (int i = 0; i < matcher.groupCount(); i++) { // int groupCount()
// 返回当前查找所获得的匹配组的数量。
// org.jeecgframework.core.util.LogUtil.info(matcher.group(i));
result.add(matcher.group(i));
}
}
String[] resultStr = null;
if (result.size() > 0) {
resultStr = new String[result.size()];
return result.toArray(resultStr);// 将Set result转化为String[] resultStr
}
return resultStr;
}
/**
* 得到第一个b,e之间的字符串,并返回e后的子串
*
* @param s
* 源字符串
* @param b
* 标志开始
* @param e
* 标志结束
* @return b,e之间的字符串
*/
/*
* String aaa="abcdefghijklmn"; String[] bbb=StringProcessor.midString(aaa,
* "b","l");
* org.jeecgframework.core.util.LogUtil.info("bbb[0]:"+bbb[0]);//cdefghijk
* org.jeecgframework.core.util.LogUtil.info("bbb[1]:"+bbb[1]);//lmn
* ★这个方法是得到第二个参数和第三个参数之间的字符串,赋给元素0;然后把元素0代表的字符串之后的,赋给元素1
*/
/*
* String aaa="abcdefgllhijklmn5465"; String[]
* bbb=StringProcessor.midString(aaa, "b","l"); //ab cdefg llhijklmn5465 //
* 元素0 元素1
*/
public static String[] midString(String s, String b, String e) {
int i = s.indexOf(b) + b.length();
int j = s.indexOf(e, i);
String[] sa = new String[2];
if (i < b.length() || j < i + 1 || i > j) {
sa[1] = s;
sa[0] = null;
return sa;
} else {
sa[0] = s.substring(i, j);
sa[1] = s.substring(j);
return sa;
}
}
/**
* 带有前一次替代序列的正则表达式替代
*
* @param s
* @param pf
* @param pb
* @param start
* @return
*/
public static String stringReplace(String s, String pf, String pb, int start) {
Pattern pattern_hand = Pattern.compile(pf);
Matcher matcher_hand = pattern_hand.matcher(s);
int gc = matcher_hand.groupCount();
int pos = start;
String sf1 = "";
String sf2 = "";
String sf3 = "";
int if1 = 0;
String strr = "";
while (matcher_hand.find(pos)) {
sf1 = matcher_hand.group();
if1 = s.indexOf(sf1, pos);
if (if1 >= pos) {
strr += s.substring(pos, if1);
pos = if1 + sf1.length();
sf2 = pb;
for (int i = 1; i <= gc; i++) {
sf3 = "\\" + i;
sf2 = replaceAll(sf2, sf3, matcher_hand.group(i));
}
strr += sf2;
} else {
return s;
}
}
strr = s.substring(0, start) + strr;
return strr;
}
/**
* 存文本替换
*
* @param s
* 源字符串
* @param sf
* 子字符串
* @param sb
* 替换字符串
* @return 替换后的字符串
*/
public static String replaceAll(String s, String sf, String sb) {
int i = 0, j = 0;
int l = sf.length();
boolean b = true;
boolean o = true;
String str = "";
do {
j = i;
i = s.indexOf(sf, j);
if (i > j) {
str += s.substring(j, i);
str += sb;
i += l;
o = false;
} else {
str += s.substring(j);
b = false;
}
} while (b);
if (o) {
str = s;
}
return str;
}
// 字符串的替换
public static String replace(String strSource, String strOld, String strNew) {
if (strSource == null) {
return null;
}
int i = 0;
if ((i = strSource.indexOf(strOld, i)) >= 0) {
char[] cSrc = strSource.toCharArray();
char[] cTo = strNew.toCharArray();
int len = strOld.length();
StringBuffer buf = new StringBuffer(cSrc.length);
buf.append(cSrc, 0, i).append(cTo);
i += len;
int j = i;
while ((i = strSource.indexOf(strOld, i)) > 0) {
buf.append(cSrc, j, i - j).append(cTo);
i += len;
j = i;
}
buf.append(cSrc, j, cSrc.length - j);
return buf.toString();
}
return strSource;
}
/**
* 判断是否与给定字符串样式匹配
*
* @param str
* 字符串
* @param pattern
* 正则表达式样式
* @return 是否匹配是true,否false
*/
public static boolean isMatch(String str, String pattern) {
Pattern pattern_hand = Pattern.compile(pattern);
Matcher matcher_hand = pattern_hand.matcher(str);
boolean b = matcher_hand.matches();
return b;
}
/**
* 截取字符串
*
* @param s
* 源字符串
* @param jmp
* 跳过jmp
* @param sb
* 取在sb
* @param se
* 于se
* @return 之间的字符串
*/
public static String subStringExe(String s, String jmp, String sb, String se) {
if (isEmpty(s)) {
return "";
}
int i = s.indexOf(jmp);
if (i >= 0 && i < s.length()) {
s = s.substring(i + 1);
}
i = s.indexOf(sb);
if (i >= 0 && i < s.length()) {
s = s.substring(i + 1);
}
if (se == "") {
return s;
} else {
i = s.indexOf(se);
if (i >= 0 && i < s.length()) {
s = s.substring(i + 1);
}
return s;
}
}
/**
* *************************************************************************
* 用要通过URL传输的内容进行编码
*
* @param 源字符串
* @return 经过编码的内容
*************************************************************************
*/
public static String URLEncode(String src) {
String return_value = "";
try {
if (src != null) {
return_value = URLEncoder.encode(src, "GBK");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return_value = src;
}
return return_value;
}
/**
* *************************************************************************
*
* @author 李锋 2007.4.18
* @param 传入
* 福test照楼(北大门&#
* 24635 ;店)福
* @return 经过解码的内容
*************************************************************************
*/
public static String getGBK(String str) {
return transfer(str);
}
public static String transfer(String str) {
Pattern p = Pattern.compile("&#\\d+;");
Matcher m = p.matcher(str);
while (m.find()) {
String old = m.group();
str = str.replaceAll(old, getChar(old));
}
return str;
}
public static String getChar(String str) {
String dest = str.substring(2, str.length() - 1);
char ch = (char) Integer.parseInt(dest);
return "" + ch;
}
/**
* yahoo首页中切割字符串.
*
* @author yxg
* @date 2007-09-17
* @param str
* @return
*/
public static String subYhooString(String subject, int size) {
subject = subject.substring(1, size);
return subject;
}
public static String subYhooStringDot(String subject, int size) {
subject = subject.substring(1, size) + "...";
return subject;
}
/**
* 泛型方法(通用),把list转换成以“,”相隔的字符串 调用时注意类型初始化(申明类型) 如:List<Integer> intList =
* new ArrayList<Integer>(); 调用方法:StringUtil.listTtoString(intList);
* 效率:list中4条信息,1000000次调用时间为850ms左右
*
* @author fengliang
* @serialData 2008-01-09
* @param <T>
* 泛型
* @param list
* list列表
* @return 以“,”相隔的字符串
*/
public static <T> String listTtoString(List<T> list) {
if (list == null || list.size() < 1)
return "";
Iterator<T> i = list.iterator();
if (!i.hasNext())
return "";
StringBuilder sb = new StringBuilder();
for (;;) {
T e = i.next();
sb.append(e);
if (!i.hasNext())
return sb.toString();
sb.append(",");
}
}
/**
* 把整形数组转换成以“,”相隔的字符串
*
* @author fengliang
* @serialData 2008-01-08
* @param a
* 数组a
* @return 以“,”相隔的字符串
*/
public static String intArraytoString(int[] a) {
if (a == null)
return "";
int iMax = a.length - 1;
if (iMax == -1)
return "";
StringBuilder b = new StringBuilder();
for (int i = 0;; i++) {
b.append(a[i]);
if (i == iMax)
return b.toString();
b.append(",");
}
}
/**
* 判断文字内容重复
*
* @author 沙枣
* @Date 2008-04-17
*/
public static boolean isContentRepeat(String content) {
int similarNum = 0;
int forNum = 0;
int subNum = 0;
int thousandNum = 0;
String startStr = "";
String nextStr = "";
boolean result = false;
float endNum = (float) 0.0;
if (content != null && content.length() > 0) {
if (content.length() % 1000 > 0)
thousandNum = (int) Math.floor(content.length() / 1000) + 1;
else
thousandNum = (int) Math.floor(content.length() / 1000);
if (thousandNum < 3)
subNum = 100 * thousandNum;
else if (thousandNum < 6)
subNum = 200 * thousandNum;
else if (thousandNum < 9)
subNum = 300 * thousandNum;
else
subNum = 3000;
for (int j = 1; j < subNum; j++) {
if (content.length() % j > 0)
forNum = (int) Math.floor(content.length() / j) + 1;
else
forNum = (int) Math.floor(content.length() / j);
if (result || j >= content.length())
break;
else {
for (int m = 0; m < forNum; m++) {
if (m * j > content.length() || (m + 1) * j > content.length()
|| (m + 2) * j > content.length())
break;
startStr = content.substring(m * j, (m + 1) * j);
nextStr = content.substring((m + 1) * j, (m + 2) * j);
if (startStr.equals(nextStr)) {
similarNum = similarNum + 1;
endNum = (float) similarNum / forNum;
if (endNum > 0.4) {
result = true;
break;
}
} else
similarNum = 0;
}
}
}
}
return result;
}
/**
* 判断是否是空字符串 null和"" null返回result,否则返回字符串
*
* @param s
* @return
*/
public static String isEmpty(String s, String result) {
if (s != null && !s.equals("")) {
return s;
}
return result;
}
/**
* 判断对象是否为空
*
* @param str
* @return
*/
public static boolean isNotEmpty(Object str) {
boolean flag = true;
if (str != null && !str.equals("")) {
if (str.toString().length() > 0) {
flag = true;
}
} else {
flag = false;
}
return flag;
}
/**
* 判断集合是否为空
*
* @param str
* @return
*/
public static boolean listIsNotEmpty(List list) {
boolean flag = true;
if (list != null && !list.isEmpty()) {
flag = true;
} else {
flag = false;
}
return flag;
}
/**
* 全角字符变半角字符
*
* @author shazao
* @date 2008-04-03
* @param str
* @return
*/
public static String full2Half(String str) {
if (str == null || "".equals(str))
return "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 65281 && c < 65373)
sb.append((char) (c - 65248));
else
sb.append(str.charAt(i));
}
return sb.toString();
}
/**
* 全角括号转为半角
*
* @author shazao
* @date 2007-11-29
* @param str
* @return
*/
public static String replaceBracketStr(String str) {
if (str != null && str.length() > 0) {
str = str.replaceAll("(", "(");
str = str.replaceAll(")", ")");
}
return str;
}
/**
* 解析字符串返回map键值对(例:a=1&b=2 => a=1,b=2)
*
* @param query
* 源参数字符串
* @param split1
* 键值对之间的分隔符(例:&)
* @param split2
* key与value之间的分隔符(例:=)
* @param dupLink
* 重复参数名的参数值之间的连接符,连接后的字符串作为该参数的参数值,可为null
* null:不允许重复参数名出现,则靠后的参数值会覆盖掉靠前的参数值。
* @return map
* @author sky
*/
@SuppressWarnings("unchecked")
public static Map<String, String> parseQuery(String query, char split1, char split2, String dupLink) {
if (!isEmpty(query) && query.indexOf(split2) > 0) {
Map<String, String> result = new HashMap();
String name = null;
String value = null;
String tempValue = "";
int len = query.length();
for (int i = 0; i < len; i++) {
char c = query.charAt(i);
if (c == split2) {
value = "";
} else if (c == split1) {
if (!isEmpty(name) && value != null) {
if (dupLink != null) {
tempValue = result.get(name);
if (tempValue != null) {
value += dupLink + tempValue;
}
}
result.put(name, value);
}
name = null;
value = null;
} else if (value != null) {
value += c;
} else {
name = (name != null) ? (name + c) : "" + c;
}
}
if (!isEmpty(name) && value != null) {
if (dupLink != null) {
tempValue = result.get(name);
if (tempValue != null) {
value += dupLink + tempValue;
}
}
result.put(name, value);
}
return result;
}
return null;
}
/**
* 将list 用传入的分隔符组装为String
*
* @param list
* @param slipStr
* @return String
*/
@SuppressWarnings("unchecked")
public static String listToStringSlipStr(List list, String slipStr) {
StringBuffer returnStr = new StringBuffer();
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
returnStr.append(list.get(i)).append(slipStr);
}
}
if (returnStr.toString().length() > 0)
return returnStr.toString().substring(0, returnStr.toString().lastIndexOf(slipStr));
else
return "";
}
/**
* 获取从start开始用*替换len个长度后的字符串
*
* @param str
* 要替换的字符串
* @param start
* 开始位置
* @param len
* 长度
* @return 替换后的字符串
*/
public static String getMaskStr(String str, int start, int len) {
if (StringUtil.isEmpty(str)) {
return str;
}
if (str.length() < start) {
return str;
}
// 获取*之前的字符串
String ret = str.substring(0, start);
// 获取最多能打的*个数
int strLen = str.length();
if (strLen < start + len) {
len = strLen - start;
}
// 替换成*
for (int i = 0; i < len; i++) {
ret += "*";
}
// 加上*之后的字符串
if (strLen > start + len) {
ret += str.substring(start + len);
}
return ret;
}
/**
* 根据传入的分割符号,把传入的字符串分割为List字符串
*
* @param slipStr
* 分隔的字符串
* @param src
* 字符串
* @return 列表
*/
public static List<String> stringToStringListBySlipStr(String slipStr, String src) {
if (src == null)
return null;
List<String> list = new ArrayList<String>();
String[] result = src.split(slipStr);
for (int i = 0; i < result.length; i++) {
list.add(result[i]);
}
return list;
}
/**
* 截取字符串
*
* @param str
* 原始字符串
* @param len
* 要截取的长度
* @param tail
* 结束加上的后缀
* @return 截取后的字符串
*/
public static String getHtmlSubString(String str, int len, String tail) {
if (str == null || str.length() <= len) {
return str;
}
int length = str.length();
char c = ' ';
String tag = null;
String name = null;
int size = 0;
String result = "";
boolean isTag = false;
List<String> tags = new ArrayList<String>();
int i = 0;
for (int end = 0, spanEnd = 0; i < length && len > 0; i++) {
c = str.charAt(i);
if (c == '<') {
end = str.indexOf('>', i);
}
if (end > 0) {
// 截取标签
tag = str.substring(i, end + 1);
int n = tag.length();
if (tag.endsWith("/>")) {
isTag = true;
} else if (tag.startsWith("</")) { // 结束符
name = tag.substring(2, end - i);
size = tags.size() - 1;
// 堆栈取出html开始标签
if (size >= 0 && name.equals(tags.get(size))) {
isTag = true;
tags.remove(size);
}
} else { // 开始符
spanEnd = tag.indexOf(' ', 0);
spanEnd = spanEnd > 0 ? spanEnd : n;
name = tag.substring(1, spanEnd);
if (name.trim().length() > 0) {
// 如果有结束符则为html标签
spanEnd = str.indexOf("</" + name + ">", end);
if (spanEnd > 0) {
isTag = true;
tags.add(name);
}
}
}
// 非html标签字符
if (!isTag) {
if (n >= len) {
result += tag.substring(0, len);
break;
} else {
len -= n;
}
}
result += tag;
isTag = false;
i = end;
end = 0;
} else { // 非html标签字符
len--;
result += c;
}
}
// 添加未结束的html标签
for (String endTag : tags) {
result += "</" + endTag + ">";
}
if (i < length) {
result += tail;
}
return result;
}
public static String getProperty(String property) {
if (property.contains("_")) {
return property.replaceAll("_", "\\.");
}
return property;
}
/**
* 解析前台encodeURIComponent编码后的参数
*
* @param encodeURIComponent
* (encodeURIComponent(no))
* @return
*/
public static String getEncodePra(String property) {
String trem = "";
if (isNotEmpty(property)) {
try {
trem = URLDecoder.decode(property, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return trem;
}
// 判断一个字符串是否都为数字
public boolean isDigit(String strNum) {
Pattern pattern = Pattern.compile("[0-9]{1,}");
Matcher matcher = pattern.matcher((CharSequence) strNum);
return matcher.matches();
}
// 截取数字
public String getNumbers(String content) {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
return matcher.group(0);
}
return "";
}
// 截取非数字
public String splitNotNumber(String content) {
Pattern pattern = Pattern.compile("\\D+");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
return matcher.group(0);
}
return "";
}
/**
* 判断某个字符串是否存在于数组中
*
* @param stringArray
* 原数组
* @param source
* 查找的字符串
* @return 是否找到
*/
public static boolean contains(String[] stringArray, String source) {
// 转换为list
List<String> tempList = Arrays.asList(stringArray);
// 利用list的包含方法,进行判断
if (tempList.contains(source)) {
return true;
} else {
return false;
}
}
/**
* html 必须是格式良好的
*
* @param str
* @return
* @throws Exception
*/
public static String formatHtml(String str) throws Exception {
Document document = null;
document = DocumentHelper.parseText(str);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
StringWriter writer = new StringWriter();
HTMLWriter htmlWriter = new HTMLWriter(writer, format);
htmlWriter.write(document);
htmlWriter.close();
return writer.toString();
}
/**
* 首字母大写
*
* @param realName
* @return
*/
public static String firstUpperCase(String realName) {
return StringUtils.replaceChars(realName, realName.substring(0, 1), realName.substring(0, 1).toUpperCase());
}
/**
* 首字母小写
*
* @param realName
* @return
*/
public static String firstLowerCase(String realName) {
return StringUtils.replaceChars(realName, realName.substring(0, 1), realName.substring(0, 1).toLowerCase());
}
/**
* 判断这个类是不是java自带的类
*
* @param clazz
* @return
*/
public static boolean isJavaClass(Class<?> clazz) {
boolean isBaseClass = false;
if (clazz.isArray()) {
isBaseClass = false;
} else if (clazz.isPrimitive() || clazz.getPackage() == null || clazz.getPackage().getName().equals("java.lang")
|| clazz.getPackage().getName().equals("java.math")
|| clazz.getPackage().getName().equals("java.util")) {
isBaseClass = true;
}
return isBaseClass;
}
/**
* 将数组成separator连接成字符串
*
* @param separator 分隔符
* @param array
* @return
*/
public static String splitArr(String separator, Object[] array) {
if (separator == null || array == null) {
return "";
}
String result = "";
for (int i = 0; i < array.length; i++) {
if (i == array.length - 1) {
result += array[i].toString();
} else {
result += array[i].toString() + separator;
}
}
return result;
}
/**
* MD5 加密
* @param str
* @param zero true 追加0, false 不追加0
* @return
*/
public static String md5(String str, boolean zero) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return null;
}
byte[] resultByte = messageDigest.digest(str.getBytes());
StringBuffer result = new StringBuffer();
for (int i = 0; i < resultByte.length; ++i) {
int v = 0xFF & resultByte[i];
if(v<16 && zero)
result.append("0");
result.append(Integer.toHexString(v));
}
return result.toString();
}
/**
* 去除HTML 元素
*
* @param element
* @return
*/
public static String getTxtWithoutHTMLElement(String element) {
if (null == element || "".equals(element.trim())) {
return element;
}
Pattern pattern = Pattern.compile("<[^<|^>]*>");
Matcher matcher = pattern.matcher(element);
StringBuffer txt = new StringBuffer();
while (matcher.find()) {
String group = matcher.group();
if (group.matches("<[\\s]*>")) {
matcher.appendReplacement(txt, group);
} else {
matcher.appendReplacement(txt, "");
}
}
matcher.appendTail(txt);
String temp = txt.toString().replaceAll("\n", "");
temp = temp.replaceAll(" ", "");
return temp;
}
/**
* 根据?占位符,替换传入values
*
* @param message
* 需要被替换字符串
* @param values
* 替换值
* @return
*/
public static String replaceMessage(String message, String... values) {
if (StringUtil.isEmpty(message) || values == null) {
return null;
}
for (int i = 0; i < values.length; i++) {
message = message.replaceFirst("\\?", values[i]);
}
return message.replace("?", "");
}
/**
* 对象属性转换为字段 例如:userName to user_name
*
* @param property
* 字段名
* @return
*/
public static String propertyToField(String property) {
if (null == property) {
return "";
}
char[] chars = property.toCharArray();
StringBuffer sb = new StringBuffer();
for (char c : chars) {
if (CharUtils.isAsciiAlphaUpper(c)) {
sb.append("_" + StringUtils.lowerCase(CharUtils.toString(c)));
} else {
sb.append(c);
}
}
return sb.toString().toUpperCase();
}
private static Pattern linePattern = Pattern.compile("_(\\w)");
private static Pattern humpPattern = Pattern.compile("[A-Z]");
/**
* 下划线转驼峰
* @param str
* @return
*/
public static String lineToHump(String str) {
if (null == str || "".equals(str)) {
return str;
}
str = str.toLowerCase();
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
str = sb.toString();
str = str.substring(0, 1).toUpperCase() + str.substring(1);
return str;
}
/**
* 驼峰转下划线(简单写法,效率低于{@link #humpToLine2(String)})
* @param str
* @return
*/
public static String humpToLine(String str) {
return str.replaceAll("[A-Z]", "_$0").toLowerCase();
}
/**
* 驼峰转下划线,效率比上面高
* @param str
* @return
*/
public static String humpToLine2(String str) {
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 首字母转小写
* @param s
* @return
*/
public static String toLowerCaseFirstOne(String s) {
if (StringUtils.isBlank(s)) {
return s;
}
if (Character.isLowerCase(s.charAt(0))) {
return s;
} else {
return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
/**
* 首字母转大写
* @param s
* @return
*/
public static String toUpperCaseFirstOne(String s) {
if (StringUtils.isBlank(s)) {
return s;
}
if (Character.isUpperCase(s.charAt(0))) {
return s;
} else {
return (new StringBuffer()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
}
| 23.18988
| 119
| 0.534945
|
23df9e28630006daee813de5a46b9d5f4c46404e
| 323
|
package category.thread.ch04.z3_ok.extthread;
import category.thread.ch04.z3_ok.service.MyService;
public class MyThreadA extends Thread {
private MyService myService;
public MyThreadA(MyService myService) {
super();
this.myService = myService;
}
@Override
public void run() {
myService.waitMethod();
}
}
| 16.15
| 52
| 0.749226
|
c887921d2ff65b497b3c5240dd578c47178273a3
| 3,302
|
package com.nortal.sk.client.digidoc4j.processor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
import org.digidoc4j.Container;
import org.digidoc4j.ContainerBuilder;
import org.digidoc4j.DataToSign;
import org.digidoc4j.DigestAlgorithm;
import org.digidoc4j.SignatureBuilder;
import org.digidoc4j.SignatureProfile;
import com.nortal.sk.client.card.model.CardSignStartReq;
import com.nortal.sk.client.card.processor.CardSignProcessor;
import com.nortal.sk.client.model.FileModel;
import com.nortal.sk.client.processor.AbstractProcessor;
import com.nortal.sk.client.processor.SignStateHolder;
import eu.europa.ec.markt.dss.DSSUtils;
public class DigiDoc4JSignProcessor extends AbstractProcessor<SignStateHolder>implements CardSignProcessor {
public DigiDoc4JSignProcessor(SignStateHolder state) {
setState(state);
}
private DigiDoc4JModel getModel() {
return getState().getContainer();
}
@Override
protected void prepare() throws Exception {
ContainerBuilder cb = ContainerBuilder.aContainer();
if (getState().getDoc() != null) {
cb.fromStream(new ByteArrayInputStream(getState().getDoc().getContent()));
}
else {
for (FileModel file : getState().getFiles()) {
cb.withDataFile(new ByteArrayInputStream(file.getContent()), file.getName(), file.getMimeType());
}
}
getState().setContainer(new DigiDoc4JModel(cb.build()));
}
@Override
public void finalize() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
IOUtils.copy(getModel().getContainer().saveAsStream(), os);
os.close();
getState().setDoc(FileModel.of(null, os.toByteArray()));
}
@Override
public String getDigestHex(CardSignStartReq req) {
// @formatter:off
DataToSign dataToSign = SignatureBuilder.aSignature()
.withContainer(getModel().getContainer())
.withSigningCertificate(req.getCert())
.withRoles(req.getClaimedRoles())
.withCity(req.getCity())
.withStateOrProvince(req.getState())
.withCountry(req.getCountry())
.withPostalCode(req.getZip())
.withDigestAlgorithm(DigestAlgorithm.SHA256)
.withSignatureProfile(SignatureProfile.LT)
.buildDataToSign();
// @formatter:off
getModel().setDataToSign(dataToSign);
return DSSUtils.toHex(dataToSign.getDigestToSign());
}
@Override
public void applySignature(String signatureHex) throws Exception {
getModel().getDataToSign().finalize(Hex.decodeHex(signatureHex.toCharArray()));
}
@Override
public void getSignatureConfirmation() throws Exception {
// TODO Auto-generated method stub
}
private class DigiDoc4JModel {
private Container container;
private DataToSign dataToSign;
public DigiDoc4JModel(Container container) {
this.container = container;
}
public Container getContainer() {
return container;
}
public DataToSign getDataToSign() {
return dataToSign;
}
public void setDataToSign(DataToSign dataToSign) {
this.dataToSign = dataToSign;
}
}
}
| 31.447619
| 113
| 0.705936
|
2bbf6556ee987b2ed71ca88232065e99ff936a05
| 271
|
package com.appApi.service;
import com.appApi.model.Mask;
import java.util.List;
public interface MaskService {
List<Mask> getMasks();
Mask createMask(Mask mask);
Mask getMaskById(Long id);
Mask updateMaskById(Long id, Mask mask);
Mask deleteMaskById(Long id);
}
| 20.846154
| 41
| 0.760148
|
f62665c38014d63aa404c370148071bab44f1d56
| 461
|
package Lecture6;
public class CheckIfArrayContains7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 1, 2, 95, 6, 8 };
boolean x = check(arr, 7, 0);
System.out.print(x);
}
public static boolean check(int[] arr, int find, int si) {
if (si==arr.length){
return false;
}
if(arr[si]==7){
return true;
}
else {
boolean x = check (arr, 7 , si+1);
return x;
}
}
}
| 18.44
| 60
| 0.572668
|
8623c4f95e0a18529c888f5fa4d1438748892287
| 1,985
|
package eiteam.esteemedinnovation.api;
import eiteam.esteemedinnovation.api.util.ItemStackUtility;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
public class SteamingRegistry {
/**
* All of the custom steaming recipes for the Steam Heater. These recipes will replace existing smelting recipes.
* <p>
* Key: input, Value: output
*/
private static HashMap<ItemStack, ItemStack> steamingRecipes = new HashMap<>();
/**
* Adds a steaming custom recipe (not a replacement recipe).
* @param input The input ItemStack
* @param output The output ItemStack
*/
public static void addSteamingRecipe(@Nonnull ItemStack input, @Nonnull ItemStack output) {
steamingRecipes.put(input, output);
}
/**
* Removes a steaming custom recipe (not a replacement recipe).
* @param input The input ItemStack.
*/
public static void removeSteamingRecipe(@Nonnull ItemStack input) {
steamingRecipes.remove(input);
}
/**
* Gets the steaming result for the given item. If there is no steaming recipe, returns the result of
* {@link FurnaceRecipes#getSmeltingResult}.
*/
public static ItemStack getSteamingResult(@Nonnull ItemStack input) {
ItemStack steaming = getSteamingResultNoSmelting(input);
return steaming == null ? FurnaceRecipes.instance().getSmeltingResult(input) : steaming;
}
/**
* Gets the steaming result for the given item. If there is no steaming recipe, returns null.
*/
public static ItemStack getSteamingResultNoSmelting(@Nonnull ItemStack input) {
for (Map.Entry<ItemStack, ItemStack> entry : steamingRecipes.entrySet()) {
if (ItemStackUtility.compareItemStacks(input, entry.getKey())) {
return entry.getValue();
}
}
return null;
}
}
| 34.824561
| 117
| 0.688161
|
e15e42841ffda8d928172e6eca84d54758e3261d
| 11,661
|
/**
* Copyright 2016 Crawler-Commons
*
* 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 crawlercommons.robots;
import java.io.Serializable;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Result from parsing a single robots.txt file - which means we get a set of
* rules, and an optional crawl-delay, and an optional sitemap URL. Note that we
* support Google's extensions (Allow directive and '$'/'*' special chars) plus
* the more widely used Sitemap directive.
*
* See https://en.wikipedia.org/wiki/Robots_exclusion_standard See
* https://developers.google.com/search/reference/robots_txt
*/
@SuppressWarnings("serial")
public class SimpleRobotRules extends BaseRobotRules {
public enum RobotRulesMode {
ALLOW_ALL, ALLOW_NONE, ALLOW_SOME
}
/**
* Single rule that maps from a path prefix to an allow flag.
*/
public static class RobotRule implements Comparable<RobotRule>, Serializable {
String _prefix;
boolean _allow;
public RobotRule(String prefix, boolean allow) {
_prefix = prefix;
_allow = allow;
}
public boolean isAllow() {
return this._allow;
}
public String getPrefix() {
return this._prefix;
}
// Sort from longest to shortest rules.
@Override
public int compareTo(RobotRule o) {
if (_prefix.length() < o._prefix.length()) {
return 1;
} else if (_prefix.length() > o._prefix.length()) {
return -1;
} else if (_allow == o._allow) {
return 0;
} else if (_allow) {
// Allow comes before disallow
return -1;
} else {
return 1;
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (_allow ? 1231 : 1237);
result = prime * result + ((_prefix == null) ? 0 : _prefix.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RobotRule other = (RobotRule) obj;
if (_allow != other._allow)
return false;
if (_prefix == null) {
if (other._prefix != null)
return false;
} else if (!_prefix.equals(other._prefix))
return false;
return true;
}
}
protected ArrayList<RobotRule> _rules;
protected RobotRulesMode _mode;
public SimpleRobotRules() {
this(RobotRulesMode.ALLOW_SOME);
}
public SimpleRobotRules(RobotRulesMode mode) {
super();
_mode = mode;
_rules = new ArrayList<>();
}
public void clearRules() {
_rules.clear();
}
public void addRule(String prefix, boolean allow) {
// Convert old-style case of disallow: <nothing>
// into new allow: <nothing>.
if (!allow && (prefix.length() == 0)) {
allow = true;
}
_rules.add(new RobotRule(prefix, allow));
}
public List<RobotRule> getRobotRules() {
return this._rules;
}
public boolean isAllowed(String url) {
if (_mode == RobotRulesMode.ALLOW_NONE) {
return false;
} else if (_mode == RobotRulesMode.ALLOW_ALL) {
return true;
} else {
String pathWithQuery = getPath(url, true);
// Always allow robots.txt
if (pathWithQuery.equals("/robots.txt")) {
return true;
}
for (RobotRule rule : _rules) {
if (ruleMatches(pathWithQuery, rule._prefix)) {
return rule._allow;
}
}
return true;
}
}
private String getPath(String url, boolean getWithQuery) {
try {
URL urlObj = new URL(url);
String path = urlObj.getPath();
if ((path == null) || (path.equals(""))) {
path = "/";
}
String query = urlObj.getQuery();
if (getWithQuery && query != null) {
path += "?" + query;
}
// We used to lower-case the path, but Google says we need to do
// case-sensitive matching.
return URLDecoder.decode(path, "UTF-8");
} catch (Exception e) {
// If the URL is invalid, we don't really care since the fetch
// will fail, so return the root.
return "/";
}
}
private boolean ruleMatches(String text, String pattern) {
int patternPos = 0;
int textPos = 0;
int patternEnd = pattern.length();
int textEnd = text.length();
boolean containsEndChar = pattern.endsWith("$");
if (containsEndChar) {
patternEnd -= 1;
}
while ((patternPos < patternEnd) && (textPos < textEnd)) {
// Find next wildcard in the pattern.
int wildcardPos = pattern.indexOf('*', patternPos);
if (wildcardPos == -1) {
wildcardPos = patternEnd;
}
// If we're at a wildcard in the pattern, find the place in the text
// where the character(s) after the wildcard match up with what's in
// the text.
if (wildcardPos == patternPos) {
patternPos += 1;
if (patternPos >= patternEnd) {
// Pattern ends with '*', we're all good.
return true;
}
// TODO - don't worry about having two '*' in a row?
// Find the end of the pattern piece we need to match.
int patternPieceEnd = pattern.indexOf('*', patternPos);
if (patternPieceEnd == -1) {
patternPieceEnd = patternEnd;
}
boolean matched = false;
int patternPieceLen = patternPieceEnd - patternPos;
while ((textPos + patternPieceLen <= textEnd) && !matched) {
// See if patternPieceLen chars from text at textPos match
// chars from pattern at patternPos
matched = true;
for (int i = 0; i < patternPieceLen && matched; i++) {
if (text.charAt(textPos + i) != pattern.charAt(patternPos + i)) {
matched = false;
}
}
// If we matched, we're all set, otherwise we have to
// advance textPos
if (!matched) {
textPos += 1;
}
}
// If we matched, we're all set, otherwise we failed
if (!matched) {
return false;
}
} else {
// See if the pattern from patternPos to wildcardPos matches the
// text starting at textPos
while ((patternPos < wildcardPos) && (textPos < textEnd)) {
if (text.charAt(textPos++) != pattern.charAt(patternPos++)) {
return false;
}
}
}
}
// If we didn't reach the end of the pattern, make sure we're not at a
// wildcard, that's a 0 or more match, so then we're still OK.
while ((patternPos < patternEnd) && (pattern.charAt(patternPos) == '*')) {
patternPos += 1;
}
// We're at the end, so we have a match if the pattern was completely
// consumed, and either we consumed all the text or we didn't have to
// match it all (no '$' at end of the pattern)
return (patternPos == patternEnd) && ((textPos == textEnd) || !containsEndChar);
}
/**
* In order to match up with Google's convention, we want to match rules
* from longest to shortest. So sort the rules.
*/
public void sortRules() {
Collections.sort(_rules);
}
/**
* Is our ruleset set up to allow all access?
*
* @return true if all URLs are allowed.
*/
@Override
public boolean isAllowAll() {
return _mode == RobotRulesMode.ALLOW_ALL;
}
/**
* Is our ruleset set up to disallow all access?
*
* @return true if no URLs are allowed.
*/
@Override
public boolean isAllowNone() {
return _mode == RobotRulesMode.ALLOW_NONE;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((_mode == null) ? 0 : _mode.hashCode());
result = prime * result + ((_rules == null) ? 0 : _rules.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
SimpleRobotRules other = (SimpleRobotRules) obj;
if (_mode != other._mode)
return false;
if (_rules == null) {
if (other._rules != null)
return false;
} else if (!_rules.equals(other._rules))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
int nRules = _rules.size();
if (nRules == 0) {
sb.append(" - no rules");
if (isAllowNone()) {
sb.append(" (allow none)");
} else if (isAllowAll()) {
sb.append(" (allow all)");
}
sb.append('\n');
} else {
sb.append(" - number of rules: ").append(nRules).append('\n');
int numOfRulesToShow = Math.min(nRules, 10);
for (int i = 0; i < numOfRulesToShow; i++) {
RobotRule r = _rules.get(i);
sb.append(r._allow ? " A" : " Disa").append("llow: ").append(r._prefix).append('\n');
}
}
return sb.toString();
}
}
| 30.76781
| 105
| 0.51565
|
f8377e44021e5f012cb8f336b0b9a9c6ce8e9cf4
| 2,061
|
package mage.cards.f;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.BecomesBlockedByCreatureTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
/**
*
* @author fireshoes & L_J
*/
public final class FlintGolem extends CardImpl {
public FlintGolem(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{4}");
this.subtype.add(SubType.GOLEM);
this.power = new MageInt(2);
this.toughness = new MageInt(3);
// Whenever Flint Golem becomes blocked, defending player puts the top three cards of their library into their graveyard.
this.addAbility(new BecomesBlockedByCreatureTriggeredAbility(new FlintGolemEffect(), false));
}
public FlintGolem(final FlintGolem card) {
super(card);
}
@Override
public FlintGolem copy() {
return new FlintGolem(this);
}
}
class FlintGolemEffect extends OneShotEffect {
public FlintGolemEffect() {
super(Outcome.Detriment);
this.staticText = "defending player mills three cards";
}
public FlintGolemEffect(final FlintGolemEffect effect) {
super(effect);
}
@Override
public FlintGolemEffect copy() {
return new FlintGolemEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Permanent blockingCreature = game.getPermanent(getTargetPointer().getFirst(game, source));
if (blockingCreature != null) {
Player opponent = game.getPlayer(blockingCreature.getControllerId());
if (opponent != null) {
opponent.millCards(3, source, game);
return true;
}
}
return false;
}
}
| 28.625
| 129
| 0.684619
|
f7b9307aba4cf387afb6047dcdbab19f4d2909ac
| 7,646
|
package org.frankframework.frankdoc;
import static org.frankframework.frankdoc.DocWriterNewXmlUtils.addComplexType;
import static org.frankframework.frankdoc.DocWriterNewXmlUtils.addElementWithType;
import static org.frankframework.frankdoc.DocWriterNewXmlUtils.getXmlSchema;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Collection;
import javax.xml.XMLConstants;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.frankframework.frankdoc.wrapper.FrankClassRepository;
import org.frankframework.frankdoc.wrapper.TestUtil;
import org.frankframework.frankdoc.model.AttributeEnum;
import org.frankframework.frankdoc.model.AttributeType;
import org.frankframework.frankdoc.model.ElementChild;
import org.frankframework.frankdoc.model.FrankAttribute;
import org.frankframework.frankdoc.model.FrankDocModel;
import org.frankframework.frankdoc.util.XmlBuilder;
@RunWith(Parameterized.class)
public class AttributeTypeStrategyTest {
private String schemaStringAllowAttributeRef;
private String schemaStringAllowAttributeRefEnumValuesIgnoreCase;
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{"NormalInteger", getIntTestXml("1"), true, true},
{"IntegerWithPlus", getIntTestXml("+1"), true, true},
{"NegativeInteger", getIntTestXml("-12"), true, true},
{"RefAsInteger", getIntTestXml("${myVariable}"), true, true},
{"NonIntegerForInteger", getIntTestXml("aString"), false, false},
{"InvalidRefForInteger", getIntTestXml("${myVariable"), false, false},
{"True", getBoolTestXml("true"), true, true},
{"False", getBoolTestXml("false"), true, true},
{"RefAsBoolean", getBoolTestXml("${myVariable}"), true, true},
{"StringForBoolean", getBoolTestXml("aString"), false, false},
{"InvalidRefForBoolean", getBoolTestXml("${myVariable"), false, false},
{"AttributeActiveTrueLowerCase", getTestXmlActive("true"), true, true},
{"AttributeActiveFalseLowerCase", getTestXmlActive("false"), true, true},
{"AttributeActiveMixedCaseTrue", getTestXmlActive("True"), true, true},
{"AttributeActiveMixedCaseFalse", getTestXmlActive("False"), true, true},
{"RefAsAttributeActive", getTestXmlActive("${myVar}"), true, true},
{"AttributeActiveNotTrue", getTestXmlActive("!true"), true, true},
{"NegatedRefAsAttributeActive", getTestXmlActive("!${myVar}"), true, true},
{"StringForAttributeActive", getTestXmlActive("xxx"), false, false},
{"AttributeActiveConcatsMultipleValidValues", getTestXmlActive("${myVar}true"), false, false},
{"RestrictedAttribute", getEnumTestXml("TWO"), true, true},
{"RestrictedAttributeMixedCase1", getEnumTestXml("Two"), false, true},
{"RestrictedAttributeMixedCase2", getEnumTestXml("twO"), false, true},
{"InvalidValueRestrictedAttribute", getEnumTestXml("xxx"), false, false},
{"ArbitraryString", getStringTestXml("xxx"), true, true},
{"StringContainingVariableRef", getStringTestXml("${myVar}true"), true, true},
{"VariableRefAsString", getStringTestXml("${myVar}"), true, true},
});
}
private static String getBoolTestXml(String value) {
return String.format("<myElement boolAttr=\"%s\"/>", value);
}
private static String getIntTestXml(String value) {
return String.format("<myElement intAttr=\"%s\"/>", value);
}
private static String getStringTestXml(String value) {
return String.format("<myElement stringAttr=\"%s\"/>", value);
}
private static String getEnumTestXml(String value) {
return String.format("<myElement restrictedAttribute=\"%s\"/>", value);
}
private static String getTestXmlActive(String value) {
return String.format("<myElement active=\"%s\"/>", value);
}
@Parameter(0)
public String title;
@Parameter(1)
public String testXml;
@Parameter(2)
public boolean allowPropertyRefShouldAccept;
@Parameter(3)
public boolean allowPropertyRefEnumValuesIgnoreCaseShouldAccept;
@Before
public void setUp() throws IOException {
String packageOfEnum = "org.frankframework.frankdoc.testtarget.attribute.type.strategy.";
FrankClassRepository classRepository = TestUtil.getFrankClassRepositoryDoclet(packageOfEnum);
String digesterRulesFileName = "doc/empty-digester-rules.xml";
FrankDocModel model = FrankDocModel.populate(TestUtil.resourceAsURL(digesterRulesFileName), packageOfEnum + "Container", classRepository);
FrankAttribute attribute = model.findFrankElement(packageOfEnum + "Container").getAttributes(ElementChild.ALL_NOT_EXCLUDED).get(0);
AttributeEnum attributeEnum = model.findAttributeEnum(packageOfEnum + "Container.TestType");
schemaStringAllowAttributeRef = getXsd(AttributeTypeStrategy.ALLOW_PROPERTY_REF, attributeEnum, attribute);
schemaStringAllowAttributeRefEnumValuesIgnoreCase = getXsd(AttributeTypeStrategy.ALLOW_PROPERTY_REF_ENUM_VALUES_IGNORE_CASE, attributeEnum, attribute);
}
private static String getXsd(AttributeTypeStrategy attributeTypeStrategy, AttributeEnum attributeEnum, FrankAttribute enumTypedAttribute) {
XmlBuilder schema = getXmlSchema("1.2.3-SNAPSHOT");
XmlBuilder element = addElementWithType(schema, "myElement");
XmlBuilder complexType = addComplexType(element);
// We do not test mandatory attributes here. Therefore the fourth argument is "false".
attributeTypeStrategy.addAttribute(complexType, "boolAttr", AttributeType.BOOL, false);
attributeTypeStrategy.addAttribute(complexType, "intAttr", AttributeType.INT, false);
attributeTypeStrategy.addAttribute(complexType, "stringAttr", AttributeType.STRING, false);
AttributeTypeStrategy.addAttributeActive(complexType);
// This test does not test whether use="required" is included. It is about
// attribute types. Therefore we take the attribute not to be mandatory.
attributeTypeStrategy.addRestrictedAttribute(complexType, enumTypedAttribute, false);
attributeTypeStrategy.createHelperTypes().forEach(h -> schema.addSubElement(h));
schema.addSubElement(attributeTypeStrategy.createAttributeEnumType(attributeEnum));
return schema.toXML(true);
}
@Test
public void testAllowPropertyRef() {
doTest(allowPropertyRefShouldAccept, schemaStringAllowAttributeRef);
}
@Test
public void testAllowPropertyRefEnumValuesIgnoreCase() {
doTest(allowPropertyRefEnumValuesIgnoreCaseShouldAccept, schemaStringAllowAttributeRefEnumValuesIgnoreCase);
}
private void doTest(boolean expectedValue, String theXsd) {
boolean actualAccepted = true;
try {
validate(testXml, theXsd);
} catch(SAXException e) {
actualAccepted = false;
} catch(IOException e) {
fail(String.format("Got IOException: %s - %s", e.getMessage(), e.getStackTrace()));
}
assertEquals(expectedValue, actualAccepted);
}
private void validate(String testXml, String theXsd) throws SAXException, IOException {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new SAXSource(new InputSource(new StringReader(theXsd))));
Validator validator = schema.newValidator();
SAXSource source = new SAXSource(new InputSource(new StringReader(testXml)));
validator.validate(source);
}
}
| 45.784431
| 153
| 0.78407
|
e97321bce4f4022602faf3e5e537d48473448036
| 2,374
|
package com.cisco.app.dbmigrator.migratorapp.sqlbuilder.queries;
import com.cisco.app.dbmigrator.migratorapp.sqlbuilder.entities.OracleColumn;
import com.cisco.app.dbmigrator.migratorapp.sqlbuilder.entities.OracleTable;
import com.cisco.app.dbmigrator.migratorapp.sqlbuilder.entities.QueryConstants;
import com.cisco.app.dbmigrator.migratorapp.sqlbuilder.sqlcomponents.SQLFilters;
public class UpdateQueryBuilder {
private static final String UPDATE = "UPDATE ";
private static final String SET = "SET";
private final UpdateQueryComponents queryComponents;
public UpdateQueryBuilder(){
super();
queryComponents = new UpdateQueryComponents();
}
public AddTable update(){
return new AddTable();
}
public final class AddTable{
public AddFilter table(OracleTable table){
addTable(table);
return new AddFilter();
}
private AddTable(){}
}
public final class AddFilter{
private AddFilter(){}
public GetQuery addFilter(SQLFilters filter){
where(filter);
return new GetQuery();
}
public String getQuery(){
return buildQuery();
}
}
public final class GetQuery{
private GetQuery(){}
public String getQuery(){
return buildQuery();
}
}
private void addTable(OracleTable table){
queryComponents.setTable(table);
}
private UpdateQueryBuilder where(SQLFilters filters){
queryComponents.setFilters(filters);
return this;
}
private String buildQuery() {
StringBuilder builder = new StringBuilder(UPDATE);
OracleTable table = queryComponents.getTable();
builder.append(table.getTableName()).append(QueryConstants.NEXT_LINE).append(QueryConstants.INDENT).append(SET);
for (OracleColumn column : table.getColumns()) {
builder.append(column.getColumnName()).append(QueryConstants.SPACE).append(QueryConstants.EQUALS)
.append(QueryConstants.SPACE).append(QueryConstants.COLON).append(column.getColumnAlias())
.append(QueryConstants.COMMA).append(QueryConstants.NEXT_LINE);
}
builder.deleteCharAt(builder.lastIndexOf(QueryConstants.COMMA));
if (queryComponents.getFilters() != null) {
builder.append(QueryConstants.WHERE).append(QueryConstants.SPACE);
builder.append(queryComponents.getFilters().getFilterExpression());
builder.append(QueryConstants.NEXT_LINE);
}
return builder.toString().trim();
}
}
| 32.520548
| 115
| 0.743892
|
289df8908b0099964978e0d61fec8e8c94b89e7c
| 408
|
package io.github.vikeshpandey;
import org.aspectj.lang.JoinPoint;
public class TrackOperation {
public void myadvice(JoinPoint jp, Object result)// it is advice (after advice)
{
System.out.println("additional concern");
System.out.println("Method Signature: " + jp.getSignature());
System.out.println("Result in advice: " + result);
System.out.println("end of after returning advice...");
}
}
| 27.2
| 80
| 0.730392
|
612a872db108fda9b012f0e4face90209a7ab048
| 1,211
|
package java.net;
import com.jtransc.annotation.haxe.HaxeMethodBody;
import java.io.UnsupportedEncodingException;
import java.util.BitSet;
public class URLEncoder {
static private BitSet normal = new BitSet(0x100);
static private String normalTable = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_.*";
static {
for (char c : normalTable.toCharArray()) normal.set(c);
}
private URLEncoder() {
}
@Deprecated
public static String encode(String s) {
try {
return encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static String encode(String s, String enc) throws UnsupportedEncodingException {
final StringBuilder sb = new StringBuilder(s.length());
byte[] data = s.getBytes(enc);
//for (byte c : data) System.out.printf("%02X\n", c & 0xFF);
for (byte c : data) {
if (c == (byte) ' ') {
sb.append('+');
} else if (normal.get(c & 0xFF)) {
sb.append((char) c);
} else {
sb.append('%');
sb.append(Character.toUpperCase(Character.forDigit((c >>> 4) & 0xF, 16)));
sb.append(Character.toUpperCase(Character.forDigit((c >>> 0) & 0xF, 16)));
}
}
return sb.toString();
}
}
| 26.326087
| 107
| 0.676301
|
81cd5845e84818516661ad0624913518d667347d
| 3,993
|
/*
* 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 uk.co.objectconnexions.expressiveobjects.core.metamodel.layout.ordermethod;
import java.util.List;
import java.util.StringTokenizer;
import uk.co.objectconnexions.expressiveobjects.core.commons.lang.NameUtils;
import uk.co.objectconnexions.expressiveobjects.core.metamodel.facets.FacetedMethod;
import uk.co.objectconnexions.expressiveobjects.core.metamodel.layout.OrderSet;
public class SimpleOrderSet extends OrderSet {
public static SimpleOrderSet createOrderSet(final String order, final List<FacetedMethod> members) {
SimpleOrderSet set = new SimpleOrderSet(members);
final StringTokenizer st = new StringTokenizer(order, ",");
while (st.hasMoreTokens()) {
String element = st.nextToken().trim();
boolean ends;
if (ends = element.endsWith(")")) {
element = element.substring(0, element.length() - 1).trim();
}
if (element.startsWith("(")) {
final int colon = element.indexOf(':');
final String groupName = element.substring(1, colon).trim();
element = element.substring(colon + 1).trim();
set = set.createSubOrderSet(groupName, element);
} else {
set.add(element);
}
if (ends) {
set = set.parent;
}
}
set.addAnyRemainingMember();
return set;
}
private final SimpleOrderSet parent;
private final List<FacetedMethod> members;
private SimpleOrderSet(final List<FacetedMethod> members) {
super("");
this.members = members;
parent = null;
}
private SimpleOrderSet(final SimpleOrderSet set, final String groupName, final String name, final List<FacetedMethod> members) {
super(groupName);
parent = set;
parent.addElement(this);
this.members = members;
add(name);
}
private void add(final String name) {
final FacetedMethod memberWithName = getMemberWithName(name);
if (memberWithName != null) {
addElement(memberWithName);
}
}
private void addAnyRemainingMember() {
for (int i = 0; i < members.size(); i++) {
if (members.get(i) != null) {
final FacetedMethod member = members.get(i);
addElement(member);
}
}
}
private SimpleOrderSet createSubOrderSet(final String groupName, final String memberName) {
return new SimpleOrderSet(this, groupName, memberName, members);
}
private FacetedMethod getMemberWithName(final String name) {
final String searchName = NameUtils.simpleName(name);
for (int i = 0; i < members.size(); i++) {
final FacetedMethod member = members.get(i);
if (member != null) {
final String testName = NameUtils.simpleName(member.getIdentifier().getMemberName());
if (testName.equals(searchName)) {
members.set(i, null);
return member;
}
}
}
return null;
}
}
| 35.336283
| 132
| 0.627849
|
cf33b524b21f94c9c8cb5c18962fde444ec7dfa6
| 5,032
|
// ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.core.hadoop;
import java.util.Collection;
import java.util.HashSet;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.common.util.EMap;
import org.talend.commons.exception.ExceptionHandler;
import org.talend.core.GlobalServiceRegister;
import org.talend.core.model.properties.Item;
import org.talend.core.model.properties.Property;
import org.talend.core.runtime.hd.IDynamicDistributionManager;
/**
* created by cmeng on Jul 20, 2015 Detailled comment
*
*/
public class BigDataBasicUtil {
/**
* DON'T use cache here!
*/
// private static Collection<String> dynamicDistributionPaths;
public static Object getFramework(Item item) {
if (item == null) {
return null;
}
Property property = item.getProperty();
if (property != null) {
EMap additionalProperties = property.getAdditionalProperties();
if (additionalProperties != null) {
return additionalProperties.get(HadoopConstants.FRAMEWORK);
}
}
return null;
}
public static void reloadAllDynamicDistributions(IProgressMonitor monitor) {
if (GlobalServiceRegister.getDefault().isServiceRegistered(IHadoopDistributionService.class)) {
IHadoopDistributionService hdService = (IHadoopDistributionService) GlobalServiceRegister.getDefault()
.getService(IHadoopDistributionService.class);
if (hdService != null) {
IDynamicDistributionManager ddManager = hdService.getDynamicDistributionManager();
if (ddManager != null && ddManager.isLoaded()) {
try {
ddManager.reloadAllDynamicDistributions(monitor);
} catch (Exception e) {
ExceptionHandler.process(e);
}
}
}
}
}
public static Collection<String> getDynamicDistributionPaths() {
// if (dynamicDistributionPaths == null || dynamicDistributionPaths.isEmpty()) {
Collection<String> dynamicDistributionPaths = new HashSet<>();
IDynamicDistributionManager ddManager = null;
if (GlobalServiceRegister.getDefault().isServiceRegistered(IHadoopDistributionService.class)) {
IHadoopDistributionService hdService = (IHadoopDistributionService) GlobalServiceRegister.getDefault()
.getService(IHadoopDistributionService.class);
if (hdService != null) {
ddManager = hdService.getDynamicDistributionManager();
if (ddManager != null) {
String dynamicDistrPath = ddManager.getUserStoragePath();
dynamicDistributionPaths.add(dynamicDistrPath);
Collection<String> preferencePaths = ddManager.getPreferencePaths();
dynamicDistributionPaths.addAll(preferencePaths);
}
}
}
// }
return dynamicDistributionPaths;
}
public static boolean isInDynamicDistributionPath(String projectTechName, String path) {
Collection<String> distrPaths = getDynamicDistributionPaths();
if (path != null && distrPaths != null && !distrPaths.isEmpty()) {
for (String distrPath : distrPaths) {
if (path.startsWith(projectTechName + "/" + distrPath)) { //$NON-NLS-1$
return true;
}
}
}
return false;
}
public static String getDynamicDistributionCacheVersion() {
if (GlobalServiceRegister.getDefault().isServiceRegistered(IHadoopDistributionService.class)) {
IHadoopDistributionService hdService = (IHadoopDistributionService) GlobalServiceRegister.getDefault()
.getService(IHadoopDistributionService.class);
if (hdService != null) {
IDynamicDistributionManager ddManager = hdService.getDynamicDistributionManager();
if (ddManager != null && ddManager.isLoaded()) {
try {
return ddManager.getDynamicDistributionCacheVersion();
} catch (Exception e) {
ExceptionHandler.process(e);
}
}
}
}
return null;
}
}
| 41.933333
| 115
| 0.594793
|
b4169e2c5ac66d5ae78c0c394682fce73c3c8f18
| 1,365
|
/**
* Created by Edgar on 2016/3/17.
*
* @author Edgar Date 2016/3/17
*/
public class IDMain {
public static void main(String[] args) {
// instagram
// 使用41 bit来存放时间,精确到毫秒,可以使用41年。
// 使用13 bit来存放逻辑分片ID。
// 使用10 bit来存放自增长ID,意味着每台机器,每毫秒最多可以生成1024个ID
int nodes = 10;//分片数
int userId = 31341;
int seqId = 5001;
long id = System.currentTimeMillis();// - epoch;
System.out.println("毫秒:" + id);
//用左移方法填充最左边41位值是
id = id << 22;
System.out.println("毫秒数填充最左边的41位:" + id);
// 再把分片ID放到时间里,假定用户ID是31341,有2000个逻辑分片,则分片ID是31341 % 2000 -> 1341:
//左移填充剩下的13位
id |= (userId % nodes) << 12;
System.out.println("分片ID:" + (userId % nodes));
System.out.println("分片ID填充中间的13位:" + id);
//最后,把自增序列放ID里,假定前一个序列是5000,则新的序列是5001:
//填充剩下的10位
id |= (seqId % 1024);
//最终主键
System.out.println("自增ID:" + (seqId % 1024));
System.out.println("自增填充最后10位:" + id);
//解析数据
//右移23位,得到毫秒数
long mills = id >> 22;
System.out.println("右移23位得到毫秒:" + mills);
long sharedIdWithInc = id ^ (mills << 22);
System.out.println("原ID与毫秒数左移异或得到分片ID和自增主键:" + sharedIdWithInc);
long sharedId = sharedIdWithInc >> 12;
System.out.println("右移10位得到分片ID:" + sharedId);
long incId = sharedIdWithInc ^ (sharedId << 12);
System.out.println("sharedIdWithInc与分片ID左移异或得到自增主键:" + incId);
}
}
| 31.022727
| 69
| 0.630037
|
b387fca37b96e63942d649a6631cc6d2889e1668
| 1,009
|
import java.util.Scanner;
public class P04SeriesOfLetters {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] input = scanner.nextLine().toCharArray();
StringBuilder sb = new StringBuilder();
boolean isCharDifferent = true;
char previousCh = input[0];
sb.append(previousCh);
for (int i = 1; i < input.length; i++) {
char currentCh = input[i];
if (isCharDifferent) {
if (previousCh == currentCh) {
isCharDifferent = false;
} else {
sb.append(currentCh);
previousCh = currentCh;
}
} else {
if (previousCh != currentCh) {
isCharDifferent = true;
sb.append(currentCh);
previousCh = currentCh;
}
}
}
System.out.println(sb.toString());
}
}
| 27.27027
| 56
| 0.481665
|
c4670c2d3477f670303d46f9541603f74125e1b7
| 1,060
|
package io.github.krobbi.fabricmc.endfix.mixin.client;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.block.entity.EndPortalBlockEntity;
import net.minecraft.util.math.Direction;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
/**
* Client-side mixin for End portal block entities to allow all sides of End
* portals to be visible.
* @author Chris Roberts (Krobbizoid)
*/
@Mixin(EndPortalBlockEntity.class) @Environment(EnvType.CLIENT)
public class MixinEndPortalBlockEntity {
/**
* Gets whether a side of an End portal block entity may be drawn. The mod
* overwrites this method to allow all sides of End portals to be visible.
* @author Chris Roberts (Krobbizoid)
* @param direction The side of the End portal block entity to test
* (unused).
* @return Whether the side of the End portal block entity should be drawn
* (always `true`).
*/
@Overwrite @Environment(EnvType.CLIENT)
public boolean shouldDrawSide(Direction direction){ return true; }
}
| 35.333333
| 76
| 0.767925
|
60f0061a376faf0025e4e47b0accb2d253d6d30b
| 4,761
|
/**
* Copyright ${license.git.copyrightYears} the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.submitted.dynsql;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import org.apache.ibatis.BaseDataTest;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DynSqlTest {
protected static SqlSessionFactory sqlSessionFactory;
@BeforeClass
public static void setUp() throws Exception {
try (Reader configReader = Resources.getResourceAsReader("org/apache/ibatis/submitted/dynsql/MapperConfig.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
}
BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
"org/apache/ibatis/submitted/dynsql/CreateDB.sql");
}
@Test
public void testSelect() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(3);
ids.add(5);
Parameter parameter = new Parameter();
parameter.setEnabled(true);
parameter.setSchema("ibtest");
parameter.setIds(ids);
List<Map<String, Object>> answer = sqlSession.selectList("org.apache.ibatis.submitted.dynsql.select", parameter);
assertTrue(answer.size() == 3);
}
}
@Test
public void testSelectSimple() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(3);
ids.add(5);
Parameter parameter = new Parameter();
parameter.setEnabled(true);
parameter.setSchema("ibtest");
parameter.setIds(ids);
List<Map<String, Object>> answer = sqlSession.selectList("org.apache.ibatis.submitted.dynsql.select_simple", parameter);
assertTrue(answer.size() == 3);
}
}
@Test
public void testSelectLike() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
List<Map<String, Object>> answer = sqlSession.selectList("org.apache.ibatis.submitted.dynsql.selectLike", "Ba");
assertTrue(answer.size() == 2);
assertEquals(new Integer(4), answer.get(0).get("ID"));
assertEquals(new Integer(6), answer.get(1).get("ID"));
}
}
@Test
public void testNumerics() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
List<NumericRow> answer = sqlSession.selectList("org.apache.ibatis.submitted.dynsql.selectNumerics");
assertTrue(answer.size() == 1);
NumericRow row = answer.get(0);
assertEquals(1, (int) row.getId());
assertEquals(2, (int) row.getTinynumber());
assertEquals(3, (int) row.getSmallnumber());
assertEquals(4l, (long) row.getLonginteger());
assertEquals(new BigInteger("5"), row.getBiginteger());
assertEquals(new BigDecimal("6.00"), row.getNumericnumber());
assertEquals(new BigDecimal("7.00"), row.getDecimalnumber());
assertEquals((Float) 8.0f, row.getRealnumber());
assertEquals((Float) 9.0f, row.getFloatnumber());
assertEquals((Double) 10.0, row.getDoublenumber());
}
}
@Test
public void testOgnlStaticMethodCall() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
List<Map<String, Object>> answer = sqlSession.selectList("org.apache.ibatis.submitted.dynsql.ognlStaticMethodCall", "Rock 'n Roll");
assertTrue(answer.size() == 1);
assertEquals(new Integer(7), answer.get(0).get("ID"));
}
}
@Test
public void testBindNull() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
DynSqlMapper mapper = sqlSession.getMapper(DynSqlMapper.class);
String description = mapper.selectDescription(null);
assertEquals("Pebbles", description);
}
}
}
| 34.5
| 138
| 0.698803
|
02d35a0331194f25b046069fbf998a904f066a92
| 401
|
package jalgor_gen2.leetcode.part2;
public class Q223_RectangleArea {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int x1 = Math.max(A, E), y1 = Math.max(B, F);
int x2 = Math.max(x1, Math.min(C, G)), y2 = Math.max(y1, Math.min(D, H));
int area1 = (C - A) * (D - B), area2 = (G - E) * (H - F);
return area1 - (x2 - x1) * (y2 - y1) + area2;
}
}
| 33.416667
| 84
| 0.561097
|
5cdc685d23235ba130ba44cd708b3693e16ea4df
| 2,418
|
/*
* 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 solver.dp;
import collection.TList;
import static org.testng.Assert.*;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
*
* @author masao
*/
public class PartialSumShortestNGTest {
public PartialSumShortestNGTest() {
}
@BeforeMethod
public void setUpMethod() throws Exception {
}
@Test
public void testLine() {
System.out.println(test.TestUtils.methodName(0));
TList<Integer> tested = TList.sof(5,2,1,7,6);
TList<Integer> result = KnapsackDP.shortest(tested,12).psolve();
System.out.println(KnapsackDP.shortest(tested,12).psolvew().toWrappedString());
System.out.println(KnapsackDP.shortest(tested,12).psolvew().transform(tt->ReverseDP.shortest(tested,tt).right().first().items()).toString());
Integer expected = 2;
System.out.println("result : "+result);
System.out.println("expected: "+expected);
assertEquals(result.last(), expected);
}
@Test
public void testLine5() {
System.out.println(test.TestUtils.methodName(0));
TList<Integer> tested = TList.sof(4,1,1,1);
TList<Integer> result = KnapsackDP.shortest(tested,5).psolve();
Integer expected = 2;
System.out.println("result : "+result);
System.out.println("expected: "+expected);
assertEquals(result.last(), expected);
}
@Test
public void testLine14() {
System.out.println(test.TestUtils.methodName(0));
TList<Integer> tested = TList.sof(5,2,12,7,23);
TList<Integer> result = KnapsackDP.shortest(tested,14).psolve();
Integer expected = 2;
System.out.println("result : "+result);
System.out.println("expected: "+expected);
assertEquals(result.last(), expected);
}
@Test
public void testLine24() {
System.out.println(test.TestUtils.methodName(0));
TList<Integer> tested = TList.sof(5,2,12,7,23);
TList<Integer> result = KnapsackDP.shortest(tested,24).psolve();
Integer expected = 3;
System.out.println("result : "+result);
System.out.println("expected: "+expected);
assertEquals(result.last(), expected);
}
}
| 35.043478
| 149
| 0.648056
|
79aa463b604b618cabfeaadfdedea62643915e25
| 602
|
package com.rabbit.samples.springjafumongodb.repos;
import com.mongodb.client.result.DeleteResult;
import com.rabbit.samples.springjafumongodb.domain.User;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* @author Matteo Baiguini
* matteo@solidarchitectures.com
* 16 Feb 2019
*/
public interface UserRepository {
Flux<User> findAll();
Mono<User> findById(final String id);
Flux<User> saveAll(final Flux<User> users);
Mono<User> save(final Mono<User> user);
Mono<DeleteResult> deleteAll();
Mono<DeleteResult> deleteById(final String id);
void init();
}
| 19.419355
| 56
| 0.759136
|
c20c0f30d1214218aafe9fa55c56ef0cf12af12e
| 8,405
|
package org.rcsb.cif.api.generated;
import org.rcsb.cif.model.*;
import javax.annotation.Generated;
import java.util.Map;
/**
* This category contains details for the chromatographic steps used in the
* purification of the protein.
*/
@Generated("org.rcsb.cif.generator.SchemaGenerator")
public class PdbxEntitySrcGenChrom extends BaseCategory {
public PdbxEntitySrcGenChrom(String name, Map<String, Column> columns) {
super(name, columns);
}
public PdbxEntitySrcGenChrom(String name, int rowCount, Object[] encodedColumns) {
super(name, rowCount, encodedColumns);
}
public PdbxEntitySrcGenChrom(String name) {
super(name);
}
/**
* The value of _pdbx_entity_src_gen_chrom.entry_id uniquely identifies
* a sample consisting of one or more proteins whose structure is
* to be determined. This is a pointer to _entry.id. This item may
* be a site dependent bar code.
* @return StrColumn
*/
public StrColumn getEntryId() {
return (StrColumn) (isText ? textFields.computeIfAbsent("entry_id", StrColumn::new) :
getBinaryColumn("entry_id"));
}
/**
* The value of _pdbx_entity_src_gen_chrom.entity_id uniquely identifies
* each protein contained in the project target complex proteins whose
* structure is to be determined. This data item is a pointer to _entity.id
* in the ENTITY category. This item may be a site dependent bar code.
* @return StrColumn
*/
public StrColumn getEntityId() {
return (StrColumn) (isText ? textFields.computeIfAbsent("entity_id", StrColumn::new) :
getBinaryColumn("entity_id"));
}
/**
* This item is the unique identifier for this chromatography step.
* @return IntColumn
*/
public IntColumn getStepId() {
return (IntColumn) (isText ? textFields.computeIfAbsent("step_id", IntColumn::new) :
getBinaryColumn("step_id"));
}
/**
* This item unique identifier for the next production step. This allows
* a workflow to have multiple entry points leading to a single product.
* @return IntColumn
*/
public IntColumn getNextStepId() {
return (IntColumn) (isText ? textFields.computeIfAbsent("next_step_id", IntColumn::new) :
getBinaryColumn("next_step_id"));
}
/**
* This item is a pointer to pdbx_construct.id in the PDBX_CONSTRUCT
* category. The referenced sequence is expected to be the amino
* acid sequence of the expressed product after the
* chromatography step.
* @return StrColumn
*/
public StrColumn getEndConstructId() {
return (StrColumn) (isText ? textFields.computeIfAbsent("end_construct_id", StrColumn::new) :
getBinaryColumn("end_construct_id"));
}
/**
* This data item is a pointer to pdbx_robot_system.id
* in the PDBX_ROBOT_SYSTEM category.
* @return StrColumn
*/
public StrColumn getRobotId() {
return (StrColumn) (isText ? textFields.computeIfAbsent("robot_id", StrColumn::new) :
getBinaryColumn("robot_id"));
}
/**
* The date of production step.
* @return StrColumn
*/
public StrColumn getDate() {
return (StrColumn) (isText ? textFields.computeIfAbsent("date", StrColumn::new) :
getBinaryColumn("date"));
}
/**
* The type of column used in this step.
* @return StrColumn
*/
public StrColumn getColumnType() {
return (StrColumn) (isText ? textFields.computeIfAbsent("column_type", StrColumn::new) :
getBinaryColumn("column_type"));
}
/**
* The volume of the column used in this step.
* @return FloatColumn
*/
public FloatColumn getColumnVolume() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("column_volume", FloatColumn::new) :
getBinaryColumn("column_volume"));
}
/**
* The temperature in degrees celsius at which this column was run.
* @return FloatColumn
*/
public FloatColumn getColumnTemperature() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("column_temperature", FloatColumn::new) :
getBinaryColumn("column_temperature"));
}
/**
* This item is a pointer to pdbx_buffer.id in the PDBX_BUFFER category.
* The referenced buffer is that in which the column was equilibrated.
* @return StrColumn
*/
public StrColumn getEquilibrationBufferId() {
return (StrColumn) (isText ? textFields.computeIfAbsent("equilibration_buffer_id", StrColumn::new) :
getBinaryColumn("equilibration_buffer_id"));
}
/**
* The rate at which the equilibration buffer flowed through the column.
* @return FloatColumn
*/
public FloatColumn getFlowRate() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("flow_rate", FloatColumn::new) :
getBinaryColumn("flow_rate"));
}
/**
* This item is a pointer to pdbx_buffer.id in the PDBX_BUFFER category.
* The referenced buffer is that with which the protein was eluted.
* @return StrColumn
*/
public StrColumn getElutionBufferId() {
return (StrColumn) (isText ? textFields.computeIfAbsent("elution_buffer_id", StrColumn::new) :
getBinaryColumn("elution_buffer_id"));
}
/**
* Details of the elution protocol.
* @return StrColumn
*/
public StrColumn getElutionProtocol() {
return (StrColumn) (isText ? textFields.computeIfAbsent("elution_protocol", StrColumn::new) :
getBinaryColumn("elution_protocol"));
}
/**
* Details of the sample preparation prior to running the column.
* @return StrColumn
*/
public StrColumn getSamplePrepDetails() {
return (StrColumn) (isText ? textFields.computeIfAbsent("sample_prep_details", StrColumn::new) :
getBinaryColumn("sample_prep_details"));
}
/**
* The volume of protein solution run on the column.
* @return FloatColumn
*/
public FloatColumn getSampleVolume() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("sample_volume", FloatColumn::new) :
getBinaryColumn("sample_volume"));
}
/**
* The concentration of the protein solution put onto the column.
* @return FloatColumn
*/
public FloatColumn getSampleConcentration() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("sample_concentration", FloatColumn::new) :
getBinaryColumn("sample_concentration"));
}
/**
* The method used to determine the concentration of the protein solution put
* onto the column.
* @return StrColumn
*/
public StrColumn getSampleConcMethod() {
return (StrColumn) (isText ? textFields.computeIfAbsent("sample_conc_method", StrColumn::new) :
getBinaryColumn("sample_conc_method"));
}
/**
* The total volume of all the fractions pooled to give the purified protein
* solution.
* @return FloatColumn
*/
public FloatColumn getVolumePooledFractions() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("volume_pooled_fractions", FloatColumn::new) :
getBinaryColumn("volume_pooled_fractions"));
}
/**
* The yield in milligrams of protein recovered in the pooled fractions.
* @return FloatColumn
*/
public FloatColumn getYieldPooledFractions() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("yield_pooled_fractions", FloatColumn::new) :
getBinaryColumn("yield_pooled_fractions"));
}
/**
* The method used to determine the yield
* @return StrColumn
*/
public StrColumn getYieldMethod() {
return (StrColumn) (isText ? textFields.computeIfAbsent("yield_method", StrColumn::new) :
getBinaryColumn("yield_method"));
}
/**
* Details of any post-chromatographic treatment of the protein sample.
* @return StrColumn
*/
public StrColumn getPostTreatment() {
return (StrColumn) (isText ? textFields.computeIfAbsent("post_treatment", StrColumn::new) :
getBinaryColumn("post_treatment"));
}
}
| 35.167364
| 112
| 0.654491
|
bef5640c9fa90171ff3acc9a85750287f121dd8e
| 2,948
|
/**
* @author Asifur
*/
package org.opensrp.rest.services;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.opensrp.rest.repository.LuceneFormRepository;
import org.opensrp.rest.util.ConvertDateStringToTimestampMills;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.ldriscoll.ektorplucene.LuceneResult;
@Service
public class LuceneFormService {
private LuceneFormRepository luceneFormRepository;
private ConvertDateStringToTimestampMills convertDateStringToTimestampMills;
@Autowired
public LuceneFormService(LuceneFormRepository luceneFormRepository,ConvertDateStringToTimestampMills convertDateStringToTimestampMills){
this.luceneFormRepository = luceneFormRepository;
this.convertDateStringToTimestampMills = convertDateStringToTimestampMills;
}
/**
* This method return Form count as today, this month or this week
* @param start this may be start date of a month or week
* @param end this may be end date of a month or week
* */
public int getFormCount(String start,String end,String anmId,String formName){
/*if(start.equalsIgnoreCase("")){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date today = Calendar.getInstance().getTime();
String makeQueryString ="type:FormSubmission" + " AND " + "anmId:" + anmId + " AND " + "formName:" + formName + " AND " + "serverVersion:["+convertDateStringToTimestampMills.convertDateToTimestampMills(dateFormat.format(today))+" TO "+convertDateStringToTimestampMills.convertDateToTimestampMills(dateFormat.format(today))+"]" ;
LuceneResult result = luceneFormRepository.findDocsByProvider(makeQueryString);
return result.getRows().size();
}else{
String makeQueryString ="type:FormSubmission" + " AND " + "anmId:" + anmId + " AND " + "formName:" + formName + " AND " + "serverVersion:["+convertDateStringToTimestampMills.convertDateToTimestampMills(start)+" TO "+convertDateStringToTimestampMills.convertDateToTimestampMills(end)+"]" ;
LuceneResult result = luceneFormRepository.findDocsByProvider(makeQueryString);
return result.getRows().size();
}*/
if(start.equalsIgnoreCase("")){
String makeQueryString ="type:FormSubmission" + " AND " + "anmId:" + anmId + " AND " + "formName:" + formName;
LuceneResult result = luceneFormRepository.findDocsByProvider(makeQueryString);
return result.getRows().size();
}else{
String makeQueryString ="type:FormSubmission" + " AND " + "anmId:" + anmId + " AND " + "formName:" + formName + " AND " + "serverVersion:["+convertDateStringToTimestampMills.convertDateToTimestampMills(start)+" TO "+convertDateStringToTimestampMills.convertDateToTimestampMills(end)+"]" ;
LuceneResult result = luceneFormRepository.findDocsByProvider(makeQueryString);
return result.getRows().size();
}
}
}
| 51.719298
| 331
| 0.765943
|
63220d8814647c746676967673ff2fdca629bbe5
| 1,621
|
package com.illusion.avrillavigne.adapter;
import java.util.ArrayList;
import com.illusion.avrillavigne.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class EntryAdapter extends ArrayAdapter<Item> {
@SuppressWarnings("unused")
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
public EntryAdapter(Context context, ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
sectionView.setText(si.getTitle());
} else {
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final TextView title = (TextView)v.findViewById(R.id.list_item_entry_title);
final TextView subtitle = (TextView)v.findViewById(R.id.list_item_entry_summary);
if (title != null)
title.setText(ei.title);
if(subtitle != null)
subtitle.setText(ei.subtitle);
}
}
return v;
}
}
| 28.438596
| 88
| 0.732264
|
75d53e581b8982fc943bc6a0133122e801f12ab4
| 119
|
package com.github.burgerguy.handwriter.page;
public enum WordWrapMode {
NONE,
BEFORE_WORD,
AFTER_WORD;
}
| 14.875
| 45
| 0.722689
|
39310339d4b4f6d5350a46a72b4689a5f949c1c3
| 3,653
|
/**********************************************************************;
* Project : simple fuzzy member function library
* Program name : fuzzylib.h
*
* Author : Diego Vallejo
*
* Date created : 12/10/2017
*
* Purpose : data for the study of fuzzy inference systems.
|**********************************************************************/
package fuzzy;
public class GlobalMembers
{
public static final double PI = Math.PI;
/*FUNCIONES DE MEMBRESIA*/
public static double trapecioAbiertoDer(double u, double a, double b)
{
if (u > b)
{
return 1.0;
}
if (u < a)
{
return 0.0;
}
if (a <= u != 0 && u <= b)
{
return (u - a) / (b - a);
}
}
public static double trapecioAbiertoIzq(double u, double a, double b)
{
if (u > b)
{
return 0.0;
}
if (u < a)
{
return 1.0;
}
if (a <= u != 0 && u <= b)
{
return (b - u) / (b - a);
}
}
public static double triangular(double u, double a, double b, double c)
{
if (u < a || u > c)
{
return 0.0;
}
if (a <= u != 0 && u < b)
{
return (u - a) / (b - a);
}
if (b <= u != 0 && u <= c)
{
return (c - u) / (c - b);
}
}
public static double Trapezoidal(double u, double a, double b, double c, double d)
{
if (u < a || u > d)
{
return 0.0;
}
if (b <= u != 0 && u <= c)
{
return 1.0;
}
if (a <= u != 0 && u < b)
{
return (u - a) / (b - a);
}
if (c < u && u <= d)
{
return (d - u) / (d - c);
}
}
public static double curvaS(double u, double a, double b)
{
if (u > b)
{
return 1.0;
}
if (u < a)
{
return 0.0;
}
if (a <= u != 0 && u <= b)
{
return 0.5 * (1 + Math.cos((u - b) / (b - a) * PI));
}
}
public static double curvaZ(double u, double a, double b)
{
if (u > b)
{
return 0.0;
}
if (u < a)
{
return 1.0;
}
if (a <= u != 0 && u <= b)
{
return 0.5 * (1 + Math.cos((u - a) / (b - a) * PI));
}
}
public static double triangularSuave(double u, double a, double b, double c)
{
if (u < a || u > c)
{
return 0.0;
}
if (a <= u != 0 && u < b)
{
return 0.5 * (1 + Math.cos((u - b) / (b - a) * PI));
}
if (b <= u != 0 && u <= c)
{
return 0.5 * (1 + Math.cos((b - u) / (c - b) * PI));
}
}
public static double TrapezoidalSuave(double u, double a, double b, double c, double d)
{
if (u < a || u > d)
{
return 0.0;
}
if (b <= u != 0 && u <= c)
{
return 1.0;
}
if (a <= u != 0 && u < b)
{
return 0.5 * (1 + Math.cos((u - b) / (b - a) * PI));
}
if (c < u && u <= d)
{
return 0.5 * (1 + Math.cos((c - u) / (d - c) * PI));
}
}
/*FUNCIONES DE APOYO*/
public static double Min(double a, double b)
{
if (a < b)
{
return a;
}
return b;
}
public static double Min(double a, double b, double c)
{
if (a < c && a < b)
{
return a;
}
if (b < c && b < a)
{
return b;
}
if (c < a && c < b)
{
return c;
}
}
public static double Max(double a, double b)
{
if (a > b)
{
return a;
}
return b;
}
/*OPERADORES LOGICOS FUZZY*/
public static double compAND(double ma_u, double mb_u)
{
return Min(ma_u, mb_u);
}
public static double compOR(double ma_u, double mb_u)
{
return Max(ma_u, mb_u);
}
/*IMPLICACION FUZZY*/
public static double implicaZadeh(double ma_x, double mb_y)
{
return Max(Min(ma_x, mb_y, -(ma_x)));
}
public static double implicaMamdani(double ma_x, double mb_y)
{
return Min(ma_x, mb_y);
}
public static double implicaGodel(double ma_x, double mb_y)
{
if (ma_x <= mb_y)
{
return 1.0;
}
return mb_y;
}
}
| 16.381166
| 88
| 0.471667
|
267d96e0ce65bdc1313fe4499c217ee8c0c0db96
| 3,539
|
//Copyright 2019 HP Inc.
package com.hp.composer.sdk.api.v1.resources.output.pdf;
import com.hp.composer.sdk.api.v1.resources.common.ResourceIdCollection;
public class PdfResource {
public PdfResource(){}
private Output output;
private String fileName;
private String templateResourceId;
private String dataResourceId;
private String impositionTemplateResourceId;
private ResourceIdCollection assetsLibraryResourceIdCollection;
private Boolean applyImposition;
private Range recordsRange;
private Integer skipRecords;
private Long clientTimestampInMilliseconds;
public Output getOutput() {
return output;
}
public void setOutput(Output output) {
this.output = output;
}
public Integer getSkipRecords() {
return skipRecords;
}
public void setSkipRecords(Integer skipRecords) {
this.skipRecords = skipRecords;
}
public Long getClientTimestampInMilliseconds() {
return clientTimestampInMilliseconds;
}
public void setClientTimestampInMilliseconds(Long clientTimestampInMilliseconds) {
this.clientTimestampInMilliseconds = clientTimestampInMilliseconds;
}
public String getTemplateResourceId() {
return templateResourceId;
}
public void setTemplateResourceId(String templateResourceId) {
this.templateResourceId = templateResourceId;
}
public String getDataResourceId() {
return dataResourceId;
}
public void setDataResourceId(String dataResourceId) {
this.dataResourceId = dataResourceId;
}
public String getImpositionTemplateResourceId() {
return impositionTemplateResourceId;
}
public void setImpositionTemplateResourceId(String impositionTemplateResourceId) {
this.impositionTemplateResourceId = impositionTemplateResourceId;
}
public ResourceIdCollection getAssetsLibraryResourceIdCollection() {
return assetsLibraryResourceIdCollection;
}
public void setAssetsLibraryResourceIdCollection(ResourceIdCollection assetsLibraryResourceIdCollection) {
this.assetsLibraryResourceIdCollection = assetsLibraryResourceIdCollection;
}
public Boolean getApplyImposition() {
return applyImposition;
}
public void setApplyImposition(Boolean applyImposition) {
this.applyImposition = applyImposition;
}
public Range getRecordsRange() {
return recordsRange;
}
public void setRecordsRange(Range recordsRange) {
this.recordsRange = recordsRange;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
@Override
public String toString(){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("PdfResource:{");
stringBuilder.append("output:").append(output).append(", ");
stringBuilder.append("fileName:").append(fileName).append(", ");
stringBuilder.append("templateResourceId:").append(templateResourceId).append(", ");
stringBuilder.append("dataResourceId:").append(dataResourceId).append(", ");
stringBuilder.append("impositionTemplateResourceId:").append(impositionTemplateResourceId).append(", ");
stringBuilder.append("assetsLibraryResourceIdCollection:").append(assetsLibraryResourceIdCollection).append(", ");
stringBuilder.append("applyImposition:").append(applyImposition).append(", ");
stringBuilder.append("recordsRange:").append(recordsRange).append(", ");
stringBuilder.append("skipRecords:").append(skipRecords).append(", ");
stringBuilder.append("clientTimestampInMilliseconds:").append(clientTimestampInMilliseconds).append(", ");
stringBuilder.append("}");
return stringBuilder.toString();
}
}
| 27.015267
| 116
| 0.790054
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.