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
45d525100d501562f77e8a45591c7210a2e9b463
431
package com.github.wesleyegberto.microprofile.reactive.dataprocessor; import javax.ejb.Schedule; import javax.ejb.Stateless; import javax.enterprise.event.Event; import javax.inject.Inject; @Stateless public class TransactionHandler { @Inject Event<String> btcTxEvent; @Schedule(hour = "*", minute = "*", second = "*/5", persistent = false) public void feed() { btcTxEvent.fireAsync("{\"owner\":123,\"amount\":100}"); } }
25.352941
72
0.733179
d302f47e5bdb6909e517f548134f0c58d7314ea1
2,789
package com.jayantkrish.jklol.ccg; import java.util.Arrays; import junit.framework.TestCase; import com.jayantkrish.jklol.ccg.data.CcgSyntaxTreeFormat; import com.jayantkrish.jklol.ccg.data.CcgbankSyntaxTreeFormat; import com.jayantkrish.jklol.data.DataFormat; public class CcgSyntaxTreeTest extends TestCase { private DataFormat<CcgSyntaxTree> reader; private DataFormat<CcgSyntaxTree> ccgbankReader; public void setUp() { reader = new CcgSyntaxTreeFormat(); ccgbankReader = CcgbankSyntaxTreeFormat.defaultFormat(); } public void testParseTerminal() { CcgSyntaxTree tree = reader.parseFrom("N\\N IN NN that eats"); assertTrue(tree.isTerminal()); assertEquals(SyntacticCategory.parseFrom("N\\N"), tree.getRootSyntax()); assertEquals(Arrays.asList("that", "eats"), tree.getWords()); assertEquals(Arrays.asList("IN", "NN"), tree.getPosTags()); assertEquals(0, tree.getSpanStart()); assertEquals(1, tree.getSpanEnd()); } public void testParseNonterminal() { CcgSyntaxTree tree = reader.parseFrom("<N < (N/N) DT the> <N NN NN basketball game>>"); assertTrue(!tree.isTerminal()); assertEquals(SyntacticCategory.parseFrom("N"), tree.getRootSyntax()); assertEquals(0, tree.getSpanStart()); assertEquals(2, tree.getSpanEnd()); assertEquals(SyntacticCategory.parseFrom("N/N"), tree.getLeft().getRootSyntax()); assertEquals(Arrays.asList("the"), tree.getLeft().getWords()); assertEquals(Arrays.asList("DT"), tree.getLeft().getPosTags()); assertEquals(0, tree.getLeft().getSpanStart()); assertEquals(0, tree.getLeft().getSpanEnd()); assertEquals(SyntacticCategory.parseFrom("N"), tree.getRight().getRootSyntax()); assertEquals(Arrays.asList("basketball", "game"), tree.getRight().getWords()); assertEquals(Arrays.asList("NN", "NN"), tree.getRight().getPosTags()); assertEquals(1, tree.getRight().getSpanStart()); assertEquals(2, tree.getRight().getSpanEnd()); } public void testParseCcgbank() { String treeString = "(<T S[dcl] 0 2> (<T S[dcl] 1 2> (<T NP 0 1> (<T N 1 2> (<L N/N NNP NNP Ms. N_254/N_254>) (<L N NNP NNP Haag N>) ) ) (<T S[dcl]\\NP 0 2> (<L (S[dcl]\\NP)/NP VBZ VBZ plays (S[dcl]\\NP_241)/NP_242>) (<T NP 0 1> (<L N NNP NNP Elianti N>) ) ) ) (<L . . . . .>) )"; CcgSyntaxTree tree = ccgbankReader.parseFrom(treeString); assertTrue(!tree.isTerminal()); assertEquals(SyntacticCategory.parseFrom("S[dcl]"), tree.getRootSyntax()); assertEquals(0, tree.getSpanStart()); assertEquals(4, tree.getSpanEnd()); CcgSyntaxTree msTerminal = tree.getLeft().getLeft().getLeft(); assertTrue(msTerminal.isTerminal()); assertEquals(0, msTerminal.getSpanStart()); assertEquals(0, msTerminal.getSpanEnd()); } }
41.014706
284
0.691287
874f2acefc68ff51ad18eb3a51ea3ad6f88e3f50
756
package org.openehealth.ipf.platform.camel.core.dataformat; import org.slf4j.Logger; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; class SimpleSaxErrorHandler implements ErrorHandler { private Logger log; SimpleSaxErrorHandler(Logger log) { this.log = log; } @Override public void warning(SAXParseException exception) throws SAXException { log.warn("Ignored XML validation warning", exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } @Override public void error(SAXParseException exception) throws SAXException { throw exception; } }
22.235294
77
0.714286
62e88289acb66cdf17836ccebf295a221c3c68df
5,250
/* * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package goodman.java.security.cert; import goodman.java.security.InvalidAlgorithmParameterException; import goodman.java.security.cert.CRL; import goodman.java.security.cert.CRLSelector; import goodman.java.security.cert.CertSelector; import goodman.java.security.cert.CertStore; import goodman.java.security.cert.CertStoreException; import goodman.java.security.cert.CertStoreParameters; import goodman.java.security.cert.Certificate; import goodman.java.util.Collection; /** * The <i>Service Provider Interface</i> (<b>SPI</b>) * for the {@link CertStore CertStore} class. All {@code CertStore} * implementations must include a class (the SPI class) that extends * this class ({@code CertStoreSpi}), provides a constructor with * a single argument of type {@code CertStoreParameters}, and implements * all of its methods. In general, instances of this class should only be * accessed through the {@code CertStore} class. * For details, see the Java Cryptography Architecture. * <p> * <b>Concurrent Access</b> * <p> * The public methods of all {@code CertStoreSpi} objects must be * thread-safe. That is, multiple threads may concurrently invoke these * methods on a single {@code CertStoreSpi} object (or more than one) * with no ill effects. This allows a {@code CertPathBuilder} to search * for a CRL while simultaneously searching for further certificates, for * instance. * <p> * Simple {@code CertStoreSpi} implementations will probably ensure * thread safety by adding a {@code synchronized} keyword to their * {@code engineGetCertificates} and {@code engineGetCRLs} methods. * More sophisticated ones may allow truly concurrent access. * * @since 1.4 * @author Steve Hanna */ public abstract class CertStoreSpi { /** * The sole constructor. * * @param params the initialization parameters (may be {@code null}) * @throws InvalidAlgorithmParameterException if the initialization * parameters are inappropriate for this {@code CertStoreSpi} */ public CertStoreSpi(CertStoreParameters params) throws InvalidAlgorithmParameterException { } /** * Returns a {@code Collection} of {@code Certificate}s that * match the specified selector. If no {@code Certificate}s * match the selector, an empty {@code Collection} will be returned. * <p> * For some {@code CertStore} types, the resulting * {@code Collection} may not contain <b>all</b> of the * {@code Certificate}s that match the selector. For instance, * an LDAP {@code CertStore} may not search all entries in the * directory. Instead, it may just search entries that are likely to * contain the {@code Certificate}s it is looking for. * <p> * Some {@code CertStore} implementations (especially LDAP * {@code CertStore}s) may throw a {@code CertStoreException} * unless a non-null {@code CertSelector} is provided that includes * specific criteria that can be used to find the certificates. Issuer * and/or subject names are especially useful criteria. * * @param selector A {@code CertSelector} used to select which * {@code Certificate}s should be returned. Specify {@code null} * to return all {@code Certificate}s (if supported). * @return A {@code Collection} of {@code Certificate}s that * match the specified selector (never {@code null}) * @throws CertStoreException if an exception occurs */ public abstract Collection<? extends Certificate> engineGetCertificates (CertSelector selector) throws CertStoreException; /** * Returns a {@code Collection} of {@code CRL}s that * match the specified selector. If no {@code CRL}s * match the selector, an empty {@code Collection} will be returned. * <p> * For some {@code CertStore} types, the resulting * {@code Collection} may not contain <b>all</b> of the * {@code CRL}s that match the selector. For instance, * an LDAP {@code CertStore} may not search all entries in the * directory. Instead, it may just search entries that are likely to * contain the {@code CRL}s it is looking for. * <p> * Some {@code CertStore} implementations (especially LDAP * {@code CertStore}s) may throw a {@code CertStoreException} * unless a non-null {@code CRLSelector} is provided that includes * specific criteria that can be used to find the CRLs. Issuer names * and/or the certificate to be checked are especially useful. * * @param selector A {@code CRLSelector} used to select which * {@code CRL}s should be returned. Specify {@code null} * to return all {@code CRL}s (if supported). * @return A {@code Collection} of {@code CRL}s that * match the specified selector (never {@code null}) * @throws CertStoreException if an exception occurs */ public abstract Collection<? extends CRL> engineGetCRLs (CRLSelector selector) throws CertStoreException; }
39.473684
79
0.698095
54d775fa27ae4f43709bd20b66f8667112e6eecb
2,037
package atvlista3; import java.util.ArrayList; public class Time { private String nome, fundacao; private ArrayList<Jogador> jogadores = new ArrayList(); private Tecnico tecnico = new Tecnico(); public Time() { } public Time(String novoNome, String novoFundacao, ArrayList novoJogadores, Tecnico novoTecnico) { this.nome = novoNome; this.fundacao = novoFundacao; this.jogadores = novoJogadores; this.tecnico = novoTecnico; } public String getNome() { return nome; } public void setNome(String novoNome) { this.nome = novoNome; } public String getFundacao() { return fundacao; } public void setFundacao(String novoFundacao) { this.fundacao = novoFundacao; } public Tecnico getTecnico() { return tecnico; } public void setTecnico(Tecnico novoTecnico) { this.tecnico = novoTecnico; } public void artilheiro() { int maior = 0, a = 0; for (int i = 0; i < jogadores.size(); i++) { if (jogadores.get(i).getGolsPro() > maior) { maior = jogadores.get(i).getGolsPro(); a = i; } } System.out.println("Artilheiro do time: " + jogadores.get(a).getNome()); } public void experiente() { int maior = 0, a = 0; for (int i = 0; i < jogadores.size(); i++) { if (jogadores.get(i).getPartidas() > maior) { maior = jogadores.get(i).getPartidas(); a = i; } } System.out.println("Mais experiente do time: " + jogadores.get(a).getNome()); } public void statusTime() { for (Jogador status : jogadores) { System.out.println("\nNome: " + status.getNome() + "\nPosição: " + status.getPosicao()); } System.out.println("\nTecnico: " + tecnico.getNome() + "\nData de entrada: " + tecnico.getEntrada() + "\nUltimo time que comandou: " + tecnico.getUltimo()); } }
27.16
164
0.566519
8fd1dd968bcfdf8efad8b4b50376288a62f6c3ea
955
/** * */ package one.tracking.framework.dto; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import io.swagger.annotations.ApiModel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import one.tracking.framework.domain.SurveyStatusType; /** * @author Marko Voß * */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @ApiModel public class SurveyStatusDto { @NotBlank private String nameId; @NotBlank @Size(max = 64) private String title; @Size(max = 256) private String description; @NotNull private Integer countQuestions; @NotNull private SurveyStatusType status; private Long nextQuestionId; @NotBlank private String token; private Long startTime; private Long endTime; private String dependsOn; }
17.685185
55
0.725654
1aa6f635e6c6a9576ac2cc9afd7e1003a54000bc
5,907
/* * 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.flink.runtime.state; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.state.ValueStateDescriptor; import org.apache.flink.api.common.typeutils.base.StringSerializer; import org.apache.flink.runtime.checkpoint.CheckpointOptions; import org.apache.flink.runtime.query.TaskKvStateRegistry; import org.apache.flink.runtime.state.heap.HeapKeyedStateBackend; import org.apache.flink.runtime.state.internal.InternalValueState; import org.apache.flink.runtime.state.memory.MemCheckpointStreamFactory; import org.apache.flink.util.TestLogger; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Test; import java.util.Collections; import java.util.concurrent.RunnableFuture; import static org.mockito.Mockito.mock; public class StateSnapshotCompressionTest extends TestLogger { @Test public void testCompressionConfiguration() throws Exception { ExecutionConfig executionConfig = new ExecutionConfig(); executionConfig.setUseSnapshotCompression(true); AbstractKeyedStateBackend<String> stateBackend = new HeapKeyedStateBackend<>( mock(TaskKvStateRegistry.class), StringSerializer.INSTANCE, StateSnapshotCompressionTest.class.getClassLoader(), 16, new KeyGroupRange(0, 15), true, executionConfig); try { Assert.assertTrue( SnappyStreamCompressionDecorator.INSTANCE.equals(stateBackend.getKeyGroupCompressionDecorator())); } finally { IOUtils.closeQuietly(stateBackend); stateBackend.dispose(); } executionConfig = new ExecutionConfig(); executionConfig.setUseSnapshotCompression(false); stateBackend = new HeapKeyedStateBackend<>( mock(TaskKvStateRegistry.class), StringSerializer.INSTANCE, StateSnapshotCompressionTest.class.getClassLoader(), 16, new KeyGroupRange(0, 15), true, executionConfig); try { Assert.assertTrue( UncompressedStreamCompressionDecorator.INSTANCE.equals(stateBackend.getKeyGroupCompressionDecorator())); } finally { IOUtils.closeQuietly(stateBackend); stateBackend.dispose(); } } @Test public void snapshotRestoreRoundtripWithCompression() throws Exception { snapshotRestoreRoundtrip(true); } @Test public void snapshotRestoreRoundtripUncompressed() throws Exception { snapshotRestoreRoundtrip(false); } private void snapshotRestoreRoundtrip(boolean useCompression) throws Exception { ExecutionConfig executionConfig = new ExecutionConfig(); executionConfig.setUseSnapshotCompression(useCompression); KeyedStateHandle stateHandle = null; ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("test", String.class); stateDescriptor.initializeSerializerUnlessSet(executionConfig); AbstractKeyedStateBackend<String> stateBackend = new HeapKeyedStateBackend<>( mock(TaskKvStateRegistry.class), StringSerializer.INSTANCE, StateSnapshotCompressionTest.class.getClassLoader(), 16, new KeyGroupRange(0, 15), true, executionConfig); try { InternalValueState<VoidNamespace, String> state = stateBackend.createValueState( new VoidNamespaceSerializer(), stateDescriptor); stateBackend.setCurrentKey("A"); state.setCurrentNamespace(VoidNamespace.INSTANCE); state.update("42"); stateBackend.setCurrentKey("B"); state.setCurrentNamespace(VoidNamespace.INSTANCE); state.update("43"); stateBackend.setCurrentKey("C"); state.setCurrentNamespace(VoidNamespace.INSTANCE); state.update("44"); stateBackend.setCurrentKey("D"); state.setCurrentNamespace(VoidNamespace.INSTANCE); state.update("45"); CheckpointStreamFactory streamFactory = new MemCheckpointStreamFactory(4 * 1024 * 1024); RunnableFuture<KeyedStateHandle> snapshot = stateBackend.snapshot(0L, 0L, streamFactory, CheckpointOptions.forFullCheckpoint()); snapshot.run(); stateHandle = snapshot.get(); } finally { IOUtils.closeQuietly(stateBackend); stateBackend.dispose(); } executionConfig = new ExecutionConfig(); stateBackend = new HeapKeyedStateBackend<>( mock(TaskKvStateRegistry.class), StringSerializer.INSTANCE, StateSnapshotCompressionTest.class.getClassLoader(), 16, new KeyGroupRange(0, 15), true, executionConfig); try { stateBackend.restore(Collections.singletonList(stateHandle)); InternalValueState<VoidNamespace, String> state = stateBackend.createValueState( new VoidNamespaceSerializer(), stateDescriptor); stateBackend.setCurrentKey("A"); state.setCurrentNamespace(VoidNamespace.INSTANCE); Assert.assertEquals("42", state.value()); stateBackend.setCurrentKey("B"); state.setCurrentNamespace(VoidNamespace.INSTANCE); Assert.assertEquals("43", state.value()); stateBackend.setCurrentKey("C"); state.setCurrentNamespace(VoidNamespace.INSTANCE); Assert.assertEquals("44", state.value()); stateBackend.setCurrentKey("D"); state.setCurrentNamespace(VoidNamespace.INSTANCE); Assert.assertEquals("45", state.value()); } finally { IOUtils.closeQuietly(stateBackend); stateBackend.dispose(); } } }
32.103261
108
0.774843
863e9ecc0ecfc4cd92739dcbc37451d6ea993ae5
2,131
package com.blog.controller; import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author cier * */ public class ServletImpl extends HttpServlet { private static final long serialVersionUID = 1L; private String contextPath; private ThreadLocal<HttpServletRequest> req = new ThreadLocal<>(); private ThreadLocal<HttpServletResponse> resp = new ThreadLocal<>(); private final String PARAM_KEY = "_paramKey_"; @Override protected final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { this.contextPath = request.getContextPath(); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); request.setAttribute("cxt", this.contextPath); req.set(request); resp.set(response); HashMap<String,Object> params = (HashMap<String,Object>) request.getSession().getAttribute(PARAM_KEY); if(params != null && !params.isEmpty()) { for(Entry<String,Object> e : params.entrySet()) { request.setAttribute(e.getKey(), e.getValue()); } request.getSession().removeAttribute(this.PARAM_KEY); } super.service(request, response); } catch(Exception e) { throw new ServletException(e); } } @Override public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { super.service(arg0, arg1); } public final void forward(String viewName) throws ServletException, IOException { req.get().getRequestDispatcher("/WEB-INF/"+viewName+".jsp").forward(req.get(), resp.get()); } public final void redirect(String uri) throws IOException { resp.get().sendRedirect(this.contextPath + uri); } public final void redirect(String uri,HashMap<String,Object> params) throws IOException { req.get().getSession().setAttribute(this.PARAM_KEY, params); this.redirect(uri); } }
34.370968
126
0.753168
419c1b205e4e4921241d61de78f2a611f667c7e3
5,855
// ============================================================================ // // Copyright (C) 2006-2017 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.components.kafka.runtime; import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; import org.apache.avro.Schema; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.IndexedRecord; import org.apache.avro.io.BinaryDecoder; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DecoderFactory; import org.apache.beam.sdk.coders.ByteArrayCoder; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.io.kafka.KafkaIO; import org.apache.beam.sdk.io.kafka.KafkaRecord; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.Values; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PBegin; import org.apache.beam.sdk.values.PCollection; import org.joda.time.Duration; import org.talend.components.adapter.beam.coders.LazyAvroCoder; import org.talend.components.adapter.beam.transform.ConvertToIndexedRecord; import org.talend.components.api.component.runtime.RuntimableRuntime; import org.talend.components.api.container.RuntimeContainer; import org.talend.components.kafka.input.KafkaInputProperties; import org.talend.daikon.properties.ValidationResult; public class KafkaInputPTransformRuntime extends PTransform<PBegin, PCollection<IndexedRecord>> implements RuntimableRuntime<KafkaInputProperties> { private KafkaInputProperties properties; @Override public PCollection<IndexedRecord> expand(PBegin pBegin) { KafkaIO.Read<byte[], byte[]> kafkaRead = KafkaIO.readBytes() .withBootstrapServers(properties.getDatasetProperties().getDatastoreProperties().brokers.getValue()) .withTopics(Arrays.asList(new String[] { properties.getDatasetProperties().topic.getValue() })) .updateConsumerProperties(KafkaConnection.createInputMaps(properties)); if (properties.useMaxReadTime.getValue()) { kafkaRead = kafkaRead.withMaxReadTime(new Duration(properties.maxReadTime.getValue())); } if (properties.useMaxNumRecords.getValue()) { kafkaRead = kafkaRead.withMaxNumRecords(properties.maxNumRecords.getValue()); } // only consider value of kafkaRecord no matter which format selected PCollection<byte[]> kafkaRecords = pBegin.apply(kafkaRead) // .apply(ParDo.of(new ExtractRecord())) // .apply(Values.<byte[]> create()); switch (properties.getDatasetProperties().valueFormat.getValue()) { case AVRO: { Schema schema = null; if (properties.getDatasetProperties().isHierarchy.getValue()) { // use component's schema directly? should be done on design time, no? schema = new Schema.Parser().parse(properties.getDatasetProperties().avroSchema.getValue()); } else { // use component's schema directly as we are avro natural schema = properties.getDatasetProperties().main.schema.getValue(); } return kafkaRecords.apply(ParDo.of(new ConvertToAvro(schema.toString()))).setCoder(getDefaultOutputCoder()); } case CSV: { // FIXME(bchen) KafkaAvroRegistry do not have way to record adaptation, it infer schema by the data rather // than use the defined schema return ((PCollection) kafkaRecords .apply(ParDo.of(new ExtractCsvSplit(properties.getDatasetProperties().fieldDelimiter.getValue()))) .apply((PTransform) ConvertToIndexedRecord.of())).setCoder(getDefaultOutputCoder()); } default: throw new RuntimeException("To be implemented: " + properties.getDatasetProperties().valueFormat.getValue()); } } @Override public ValidationResult initialize(RuntimeContainer container, KafkaInputProperties properties) { this.properties = properties; return ValidationResult.OK; } @Override public Coder getDefaultOutputCoder() { return LazyAvroCoder.of(); } public static class ExtractRecord extends DoFn<KafkaRecord<byte[], byte[]>, KV<byte[], byte[]>> { @DoFn.ProcessElement public void processElement(ProcessContext c) { c.output(c.element().getKV()); } } public static class ConvertToAvro extends DoFn<byte[], IndexedRecord> { private final String schemaStr; private transient Schema schema; private transient DatumReader<GenericRecord> datumReader; private transient BinaryDecoder decoder; ConvertToAvro(String schemaStr) { this.schemaStr = schemaStr; } @DoFn.ProcessElement public void processElement(ProcessContext c) throws IOException { if (schema == null) { schema = new Schema.Parser().parse(schemaStr); datumReader = new GenericDatumReader<GenericRecord>(schema); } decoder = DecoderFactory.get().binaryDecoder(c.element(), decoder); GenericRecord record = datumReader.read(null, decoder); c.output(record); } } }
42.122302
121
0.678053
fbbf46ecc03e6a92f3eba50e0e46544103b08807
4,790
package com.snakegame; /** * @ProjectName: 23designpattern_java * @Package: com.snakegame * @ClassName: SnakeModel * @Author: chenyang * @Description: * @Date: 2021/7/19 12:00 上午 * @Version: 1.0 */ import java.util.*; import javax.swing.JOptionPane; public class SnakeModel{ private int rows,cols;//行列数 private Location snakeHead,runingDiriction; //运行方向 private LocationRO[][] locRO; //LocationRO类数组 private LinkedList snake,playBlocks; //蛇及其他区域块 private LocationRO snakeFood; //目标食物 private int gameScore=0; //分数 private boolean AddScore=false; //加分 //获得蛇头 public LocationRO getSnakeHead(){ return (LocationRO)(snake.getLast()); } //蛇尾 public LocationRO getSnakeTail(){ return (LocationRO)(snake.getFirst()); } //运行路线 public Location getRuningDiriction(){ return runingDiriction; } //获得蛇实体区域 public LinkedList getSnake(){ return snake; } //其他区域 public LinkedList getOthers(){ return playBlocks; } //获得总分 public int getScore(){ return gameScore; } //获得增加分数 public boolean getAddScore(){ return AddScore; } //设置蛇头方向 private void setSnakeHead(Location snakeHead){ this.snakeHead=snakeHead; } //获得目标食物 public LocationRO getSnakeFood(){ return snakeFood; } //随机设置目标食物 private void setSnakeFood(){ snakeFood=(LocationRO)(playBlocks.get((int)(Math.random()*playBlocks.size()))); } //移动 private void moveTo(Object a,LinkedList fromlist,LinkedList tolist){ fromlist.remove(a); tolist.add(a); } //初始设置 public void init(){ playBlocks.clear(); snake.clear(); gameScore=0; for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ playBlocks.add(locRO[i][j]); } } //初始化蛇的形状 for(int i=4;i<7;i++){ moveTo(locRO[4][i],playBlocks,snake); } //蛇头位置 snakeHead=new Location(4,6); //设置目标食物 snakeFood=new LocationRO(0,0); setSnakeFood(); //初始化运动方向 runingDiriction=new Location(0,1); } //构建器 public SnakeModel(int rows1,int cols1){ rows=rows1; cols=cols1; locRO=new LocationRO[rows][cols]; snake=new LinkedList(); playBlocks=new LinkedList(); for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ locRO[i][j]=new LocationRO(i,j); } } init(); } /**定义布尔型move方法,如果运行成功则返回true,否则返回false *参数direction是Location类型, *direction 的值:(-1,0)表示向上;(1,0)表示向下; *(0,-1)表示向左;(0,1)表示向右 **/ public boolean move(Location direction){ //判断设定的方向跟运行方向是不是相反 if (direction.reverse(runingDiriction)){ snakeHead.setX(snakeHead.getX()+runingDiriction.getX()); snakeHead.setY(snakeHead.getY()+runingDiriction.getY()); }else{ snakeHead.setX(snakeHead.getX()+direction.getX()); snakeHead.setY(snakeHead.getY()+direction.getY()); } //如果蛇吃到了目标食物 try{ if ((snakeHead.getX()==snakeFood.getX()) &&(snakeHead.getY()==snakeFood.getY())) { moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake); setSnakeFood(); gameScore+=10; AddScore=true; }else{ AddScore=false; //是否出界 if((snakeHead.getX()<rows)&&(snakeHead.getY()<cols)&&(snakeHead.getX()>=0&&(snakeHead.getY()>=0))){ //如果不出界,判断是否与自身相交 if(snake.contains(locRO[snakeHead.getX()][snakeHead.getY()])){ //如果相交,结束游戏 JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束", JOptionPane.INFORMATION_MESSAGE); return false; }else{ //如果不相交,就把snakeHead加到snake里面,并且把尾巴移出 moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake); moveTo(snake.getFirst(),snake,playBlocks); } }else{ //出界,游戏结束 JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束", JOptionPane.INFORMATION_MESSAGE); return false; } } }catch(ArrayIndexOutOfBoundsException e){ return false; } //设置运行方向 if (!(direction.reverse(runingDiriction) ||direction.equals(runingDiriction))){ runingDiriction.setX(direction.getX()); runingDiriction.setY(direction.getY()); } return true; } }
29.9375
115
0.547808
dbe14937607458a69c530fa6b954f0dc83b588c0
3,001
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * Redistributions of source code must retain the * above copyright notice, this list of conditions and the following disclaimer. * Redistributions * in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz 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 <COPYRIGHT HOLDER> BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.sirix.diff; import java.util.HashSet; import java.util.Set; import org.checkerframework.checker.nullness.qual.NonNull; import org.sirix.diff.DiffFactory.DiffType; import org.sirix.exception.SirixException; /** * Implements {@link DiffObservable}, which can be used for all classes, which implement the * {@link DiffObservable} interface. * * @author Johannes Lichtenberger, University of Konstanz * */ abstract class AbstractDiffObservable implements DiffObservable { /** * {@link Set} of observers, which want to be notified of the encountered differences. */ private final Set<DiffObserver> diffObservers; /** * Default constructor. */ AbstractDiffObservable() { diffObservers = new HashSet<>(); } @Override public final void fireDiff(final DiffType diff, final @NonNull long newNodeKey, final @NonNull long oldNodeKey, final @NonNull DiffDepth depth) { for (final DiffObserver observer : diffObservers) { observer.diffListener(diff, newNodeKey, oldNodeKey, depth); } } @Override public final void done() throws SirixException { for (final DiffObserver observer : diffObservers) { observer.diffDone(); } } @Override public final void addObserver(final DiffObserver observer) { diffObservers.add(observer); } @Override public final void removeObserver(final DiffObserver observer) { diffObservers.remove(observer); } }
39.486842
100
0.758747
6d66790272c6f532e7417a944410c643c2c6ecf0
5,596
package io.quarkus.devtools.testing.registry.client; import io.quarkus.bootstrap.resolver.maven.BootstrapMavenException; import io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver; import io.quarkus.devtools.messagewriter.MessageWriter; import io.quarkus.maven.ArtifactCoords; import io.quarkus.registry.RegistryResolutionException; import io.quarkus.registry.catalog.ExtensionCatalog; import io.quarkus.registry.catalog.PlatformCatalog; import io.quarkus.registry.catalog.json.JsonCatalogMapperHelper; import io.quarkus.registry.catalog.json.JsonExtensionCatalog; import io.quarkus.registry.catalog.json.JsonPlatformCatalog; import io.quarkus.registry.client.RegistryClient; import io.quarkus.registry.client.spi.RegistryClientEnvironment; import io.quarkus.registry.config.RegistriesConfigLocator; import io.quarkus.registry.config.RegistryConfig; import io.quarkus.registry.config.json.JsonRegistryConfig; import io.quarkus.registry.config.json.RegistriesConfigMapperHelper; import io.quarkus.registry.util.PlatformArtifacts; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.eclipse.aether.artifact.DefaultArtifact; public class TestRegistryClient implements RegistryClient { private final MavenArtifactResolver resolver; private final MessageWriter log; private final RegistryConfig config; private final Path registryDir; public TestRegistryClient(RegistryClientEnvironment env, RegistryConfig clientConfig) { this.resolver = env.resolver(); this.log = env.log(); final Path configYaml = RegistriesConfigLocator.locateConfigYaml(); if (configYaml == null) { throw new IllegalStateException( "Failed to locate the dev tools config file (" + RegistriesConfigLocator.CONFIG_RELATIVE_PATH + ")"); } registryDir = TestRegistryClientBuilder.getRegistryDir(configYaml.getParent(), clientConfig.getId()); if (!Files.exists(registryDir)) { throw new IllegalStateException("The test registry directory " + registryDir + " does not exist"); } final Path configPath = TestRegistryClientBuilder.getRegistryDescriptorPath(registryDir); final JsonRegistryConfig registryConfig; try { registryConfig = RegistriesConfigMapperHelper.deserialize(configPath, JsonRegistryConfig.class); } catch (IOException e) { throw new IllegalStateException("Failed to deserialize registry configuration from " + configPath, e); } registryConfig.setId(clientConfig.getId()); if (clientConfig.getNonPlatformExtensions() != null) { registryConfig.setNonPlatformExtensions(clientConfig.getNonPlatformExtensions()); } if (clientConfig.getPlatforms() != null) { registryConfig.setPlatforms(clientConfig.getPlatforms()); } if (clientConfig.getDescriptor() != null) { registryConfig.setDescriptor(clientConfig.getDescriptor()); } if (clientConfig.getQuarkusVersions() != null) { registryConfig.setQuarkusVersions(clientConfig.getQuarkusVersions()); } this.config = registryConfig; } @Override public ExtensionCatalog resolveNonPlatformExtensions(String quarkusVersion) throws RegistryResolutionException { if (config.getNonPlatformExtensions() == null || config.getNonPlatformExtensions().isDisabled()) { return null; } log.info("%s resolveNonPlatformExtensions %s", config.getId(), quarkusVersion); return null; } @Override public ExtensionCatalog resolvePlatformExtensions(ArtifactCoords platformCoords) throws RegistryResolutionException { final ArtifactCoords coords = PlatformArtifacts.ensureCatalogArtifact(platformCoords); log.debug("%s resolvePlatformExtensions %s", config.getId(), coords); final Path p; try { p = resolver.resolve(new DefaultArtifact(coords.getGroupId(), coords.getArtifactId(), coords.getClassifier(), coords.getType(), coords.getVersion())).getArtifact().getFile().toPath(); } catch (BootstrapMavenException e) { throw new RegistryResolutionException("Failed to resolve " + coords, e); } try { return JsonCatalogMapperHelper.deserialize(p, JsonExtensionCatalog.class); } catch (IOException e) { throw new RegistryResolutionException("Failed to deserialize " + p, e); } } @Override public PlatformCatalog resolvePlatforms(String quarkusVersion) throws RegistryResolutionException { final Path json = TestRegistryClientBuilder.getRegistryPlatformsCatalogPath(registryDir, quarkusVersion); log.debug("%s resolvePlatforms %s", config.getId(), json); try { return JsonCatalogMapperHelper.deserialize(json, JsonPlatformCatalog.class); } catch (IOException e) { throw new RegistryResolutionException("Failed to deserialize " + json, e); } } @Override public RegistryConfig resolveRegistryConfig() throws RegistryResolutionException { return config; } public static RegistryConfig getDefaultConfig() { final JsonRegistryConfig config = new JsonRegistryConfig(); config.setId("test.quarkus.registry"); config.setAny("client-factory-url", TestRegistryClient.class.getProtectionDomain().getCodeSource().getLocation().toExternalForm()); return config; } }
45.868852
121
0.720336
f45db13580af5ff512964d83c8860c22c3372bf3
1,150
package org.knowm.xchange.idex.service; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.knowm.xchange.idex.annotations.Api; import org.knowm.xchange.idex.annotations.ApiOperation; import org.knowm.xchange.idex.annotations.ApiResponse; import org.knowm.xchange.idex.annotations.ApiResponses; import org.knowm.xchange.idex.dto.NextNonceReq; import org.knowm.xchange.idex.dto.ReturnNextNonceResponse; @Path("/returnNextNonce") @Api(description = "the returnNextNonce API") @Consumes("application/json") @Produces("application/json") public interface ReturnNextNonceApi { @POST @Consumes("application/json") @Produces("application/json") @ApiOperation( value = "Returns the lowest nonce that you can use from the given address in one of the trade functions (see below)", notes = "", tags = "trade" ) @ApiResponses( @ApiResponse( code = 200, message = "Sample output: { nonce: 2650 }", response = ReturnNextNonceResponse.class )) ReturnNextNonceResponse nextNonce(NextNonceReq nextNonceReq) throws Exception; }
31.081081
117
0.742609
3317e7d47200e30e79ef022702dcbf1954f3ae38
2,027
package seedu.address.logic.commands.notes; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.testutil.academics.TypicalAssessments.getTypicalAcademics; import static seedu.address.testutil.admin.TypicalDates.getTypicalAdmin; import static seedu.address.testutil.event.TypicalEvents.getTypicalEventHistory; import static seedu.address.testutil.notes.TypicalNotes.getTypicalNotesManager; import static seedu.address.testutil.student.TypicalStudents.getTypicalTeaPet; import org.junit.jupiter.api.Test; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; public class NotesCommandTest { private Model model = new ModelManager(getTypicalTeaPet(), getTypicalAcademics(), getTypicalAdmin(), getTypicalNotesManager(), getTypicalEventHistory(), new UserPrefs()); @Test public void notesCommand_success() throws CommandException { NotesCommand notesCommand = new NotesCommand(); CommandResult commandResult = notesCommand.execute(model); String expectedString = NotesCommand.MESSAGE_SUCCESS; assertEquals(commandResult.getFeedbackToUser(), expectedString); } @Test public void equals() { NotesCommand firstNotesCommand = new NotesCommand(); NotesCommand secondNotesCommand = new NotesCommand(); // same object -> returns true assertTrue(firstNotesCommand.equals(firstNotesCommand)); // same class -> returns true assertTrue(firstNotesCommand.equals(secondNotesCommand)); // different class -> returns false assertFalse(firstNotesCommand.equals(1)); // different class -> returns false assertFalse(firstNotesCommand.equals(null)); } }
37.537037
104
0.768624
5534bc9bd38f8e8f1f2134fd755ce3d1c918ee49
1,636
import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.io.IOException; import java.io.OutputStream; public class FFmpegRawBytes { static void drawFrame(Graphics2D g, int w, int h, int f, int frame) { g.setColor(Color.RED); g.drawLine(0, 0, 20, frame); } static void bgrToRgb(byte[] buffer) { for (int i = 0; i < buffer.length; i += 3) { buffer[i + 0] ^= buffer[i + 2]; buffer[i + 2] ^= buffer[i + 0]; buffer[i + 0] ^= buffer[i + 2]; } } public static void main(String[] args) throws IOException, InterruptedException { int w = 1920; int h = 1080; int f = 60; String cmd = String.format("ffmpeg -f rawvideo -pix_fmt rgb24 -s:v %dx%d -r %d -i - -c:v libx264 output.mp4", w, h, f); Process process = Runtime.getRuntime().exec(cmd); try (OutputStream stream = process.getOutputStream()) { for (int frame = 0; frame < f * 10; frame++) { BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = (Graphics2D) image.getGraphics(); g.setBackground(Color.BLACK); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); drawFrame(g, w, h, f, frame); byte[] buffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); bgrToRgb(buffer); stream.write(buffer); stream.flush(); System.out.println(frame); } } System.out.println(process.waitFor()); } }
26.819672
121
0.685208
a9deccabcfa267931831ee43aca8680a3c13d839
116
package com.example.demo; import javax.persistence.Entity; @Entity public class Customer2 extends BaseEntity { }
12.888889
43
0.793103
7627a38e2a5da2f790f1adf7c4ebea106ea83161
21,311
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.sagemaker.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/DescribeModelQualityJobDefinition" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeModelQualityJobDefinitionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The Amazon Resource Name (ARN) of the model quality job. * </p> */ private String jobDefinitionArn; /** * <p> * The name of the quality job definition. The name must be unique within an AWS Region in the AWS account. * </p> */ private String jobDefinitionName; /** * <p> * The time at which the model quality job was created. * </p> */ private java.util.Date creationTime; /** * <p> * The baseline configuration for a model quality job. * </p> */ private ModelQualityBaselineConfig modelQualityBaselineConfig; /** * <p> * Configures the model quality job to run a specified Docker container image. * </p> */ private ModelQualityAppSpecification modelQualityAppSpecification; /** * <p> * Inputs for the model quality job. * </p> */ private ModelQualityJobInput modelQualityJobInput; private MonitoringOutputConfig modelQualityJobOutputConfig; private MonitoringResources jobResources; /** * <p> * Networking options for a model quality job. * </p> */ private MonitoringNetworkConfig networkConfig; /** * <p> * The Amazon Resource Name (ARN) of an IAM role that Amazon SageMaker can assume to perform tasks on your behalf. * </p> */ private String roleArn; private MonitoringStoppingCondition stoppingCondition; /** * <p> * The Amazon Resource Name (ARN) of the model quality job. * </p> * * @param jobDefinitionArn * The Amazon Resource Name (ARN) of the model quality job. */ public void setJobDefinitionArn(String jobDefinitionArn) { this.jobDefinitionArn = jobDefinitionArn; } /** * <p> * The Amazon Resource Name (ARN) of the model quality job. * </p> * * @return The Amazon Resource Name (ARN) of the model quality job. */ public String getJobDefinitionArn() { return this.jobDefinitionArn; } /** * <p> * The Amazon Resource Name (ARN) of the model quality job. * </p> * * @param jobDefinitionArn * The Amazon Resource Name (ARN) of the model quality job. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withJobDefinitionArn(String jobDefinitionArn) { setJobDefinitionArn(jobDefinitionArn); return this; } /** * <p> * The name of the quality job definition. The name must be unique within an AWS Region in the AWS account. * </p> * * @param jobDefinitionName * The name of the quality job definition. The name must be unique within an AWS Region in the AWS account. */ public void setJobDefinitionName(String jobDefinitionName) { this.jobDefinitionName = jobDefinitionName; } /** * <p> * The name of the quality job definition. The name must be unique within an AWS Region in the AWS account. * </p> * * @return The name of the quality job definition. The name must be unique within an AWS Region in the AWS account. */ public String getJobDefinitionName() { return this.jobDefinitionName; } /** * <p> * The name of the quality job definition. The name must be unique within an AWS Region in the AWS account. * </p> * * @param jobDefinitionName * The name of the quality job definition. The name must be unique within an AWS Region in the AWS account. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withJobDefinitionName(String jobDefinitionName) { setJobDefinitionName(jobDefinitionName); return this; } /** * <p> * The time at which the model quality job was created. * </p> * * @param creationTime * The time at which the model quality job was created. */ public void setCreationTime(java.util.Date creationTime) { this.creationTime = creationTime; } /** * <p> * The time at which the model quality job was created. * </p> * * @return The time at which the model quality job was created. */ public java.util.Date getCreationTime() { return this.creationTime; } /** * <p> * The time at which the model quality job was created. * </p> * * @param creationTime * The time at which the model quality job was created. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withCreationTime(java.util.Date creationTime) { setCreationTime(creationTime); return this; } /** * <p> * The baseline configuration for a model quality job. * </p> * * @param modelQualityBaselineConfig * The baseline configuration for a model quality job. */ public void setModelQualityBaselineConfig(ModelQualityBaselineConfig modelQualityBaselineConfig) { this.modelQualityBaselineConfig = modelQualityBaselineConfig; } /** * <p> * The baseline configuration for a model quality job. * </p> * * @return The baseline configuration for a model quality job. */ public ModelQualityBaselineConfig getModelQualityBaselineConfig() { return this.modelQualityBaselineConfig; } /** * <p> * The baseline configuration for a model quality job. * </p> * * @param modelQualityBaselineConfig * The baseline configuration for a model quality job. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withModelQualityBaselineConfig(ModelQualityBaselineConfig modelQualityBaselineConfig) { setModelQualityBaselineConfig(modelQualityBaselineConfig); return this; } /** * <p> * Configures the model quality job to run a specified Docker container image. * </p> * * @param modelQualityAppSpecification * Configures the model quality job to run a specified Docker container image. */ public void setModelQualityAppSpecification(ModelQualityAppSpecification modelQualityAppSpecification) { this.modelQualityAppSpecification = modelQualityAppSpecification; } /** * <p> * Configures the model quality job to run a specified Docker container image. * </p> * * @return Configures the model quality job to run a specified Docker container image. */ public ModelQualityAppSpecification getModelQualityAppSpecification() { return this.modelQualityAppSpecification; } /** * <p> * Configures the model quality job to run a specified Docker container image. * </p> * * @param modelQualityAppSpecification * Configures the model quality job to run a specified Docker container image. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withModelQualityAppSpecification(ModelQualityAppSpecification modelQualityAppSpecification) { setModelQualityAppSpecification(modelQualityAppSpecification); return this; } /** * <p> * Inputs for the model quality job. * </p> * * @param modelQualityJobInput * Inputs for the model quality job. */ public void setModelQualityJobInput(ModelQualityJobInput modelQualityJobInput) { this.modelQualityJobInput = modelQualityJobInput; } /** * <p> * Inputs for the model quality job. * </p> * * @return Inputs for the model quality job. */ public ModelQualityJobInput getModelQualityJobInput() { return this.modelQualityJobInput; } /** * <p> * Inputs for the model quality job. * </p> * * @param modelQualityJobInput * Inputs for the model quality job. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withModelQualityJobInput(ModelQualityJobInput modelQualityJobInput) { setModelQualityJobInput(modelQualityJobInput); return this; } /** * @param modelQualityJobOutputConfig */ public void setModelQualityJobOutputConfig(MonitoringOutputConfig modelQualityJobOutputConfig) { this.modelQualityJobOutputConfig = modelQualityJobOutputConfig; } /** * @return */ public MonitoringOutputConfig getModelQualityJobOutputConfig() { return this.modelQualityJobOutputConfig; } /** * @param modelQualityJobOutputConfig * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withModelQualityJobOutputConfig(MonitoringOutputConfig modelQualityJobOutputConfig) { setModelQualityJobOutputConfig(modelQualityJobOutputConfig); return this; } /** * @param jobResources */ public void setJobResources(MonitoringResources jobResources) { this.jobResources = jobResources; } /** * @return */ public MonitoringResources getJobResources() { return this.jobResources; } /** * @param jobResources * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withJobResources(MonitoringResources jobResources) { setJobResources(jobResources); return this; } /** * <p> * Networking options for a model quality job. * </p> * * @param networkConfig * Networking options for a model quality job. */ public void setNetworkConfig(MonitoringNetworkConfig networkConfig) { this.networkConfig = networkConfig; } /** * <p> * Networking options for a model quality job. * </p> * * @return Networking options for a model quality job. */ public MonitoringNetworkConfig getNetworkConfig() { return this.networkConfig; } /** * <p> * Networking options for a model quality job. * </p> * * @param networkConfig * Networking options for a model quality job. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withNetworkConfig(MonitoringNetworkConfig networkConfig) { setNetworkConfig(networkConfig); return this; } /** * <p> * The Amazon Resource Name (ARN) of an IAM role that Amazon SageMaker can assume to perform tasks on your behalf. * </p> * * @param roleArn * The Amazon Resource Name (ARN) of an IAM role that Amazon SageMaker can assume to perform tasks on your * behalf. */ public void setRoleArn(String roleArn) { this.roleArn = roleArn; } /** * <p> * The Amazon Resource Name (ARN) of an IAM role that Amazon SageMaker can assume to perform tasks on your behalf. * </p> * * @return The Amazon Resource Name (ARN) of an IAM role that Amazon SageMaker can assume to perform tasks on your * behalf. */ public String getRoleArn() { return this.roleArn; } /** * <p> * The Amazon Resource Name (ARN) of an IAM role that Amazon SageMaker can assume to perform tasks on your behalf. * </p> * * @param roleArn * The Amazon Resource Name (ARN) of an IAM role that Amazon SageMaker can assume to perform tasks on your * behalf. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withRoleArn(String roleArn) { setRoleArn(roleArn); return this; } /** * @param stoppingCondition */ public void setStoppingCondition(MonitoringStoppingCondition stoppingCondition) { this.stoppingCondition = stoppingCondition; } /** * @return */ public MonitoringStoppingCondition getStoppingCondition() { return this.stoppingCondition; } /** * @param stoppingCondition * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeModelQualityJobDefinitionResult withStoppingCondition(MonitoringStoppingCondition stoppingCondition) { setStoppingCondition(stoppingCondition); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getJobDefinitionArn() != null) sb.append("JobDefinitionArn: ").append(getJobDefinitionArn()).append(","); if (getJobDefinitionName() != null) sb.append("JobDefinitionName: ").append(getJobDefinitionName()).append(","); if (getCreationTime() != null) sb.append("CreationTime: ").append(getCreationTime()).append(","); if (getModelQualityBaselineConfig() != null) sb.append("ModelQualityBaselineConfig: ").append(getModelQualityBaselineConfig()).append(","); if (getModelQualityAppSpecification() != null) sb.append("ModelQualityAppSpecification: ").append(getModelQualityAppSpecification()).append(","); if (getModelQualityJobInput() != null) sb.append("ModelQualityJobInput: ").append(getModelQualityJobInput()).append(","); if (getModelQualityJobOutputConfig() != null) sb.append("ModelQualityJobOutputConfig: ").append(getModelQualityJobOutputConfig()).append(","); if (getJobResources() != null) sb.append("JobResources: ").append(getJobResources()).append(","); if (getNetworkConfig() != null) sb.append("NetworkConfig: ").append(getNetworkConfig()).append(","); if (getRoleArn() != null) sb.append("RoleArn: ").append(getRoleArn()).append(","); if (getStoppingCondition() != null) sb.append("StoppingCondition: ").append(getStoppingCondition()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeModelQualityJobDefinitionResult == false) return false; DescribeModelQualityJobDefinitionResult other = (DescribeModelQualityJobDefinitionResult) obj; if (other.getJobDefinitionArn() == null ^ this.getJobDefinitionArn() == null) return false; if (other.getJobDefinitionArn() != null && other.getJobDefinitionArn().equals(this.getJobDefinitionArn()) == false) return false; if (other.getJobDefinitionName() == null ^ this.getJobDefinitionName() == null) return false; if (other.getJobDefinitionName() != null && other.getJobDefinitionName().equals(this.getJobDefinitionName()) == false) return false; if (other.getCreationTime() == null ^ this.getCreationTime() == null) return false; if (other.getCreationTime() != null && other.getCreationTime().equals(this.getCreationTime()) == false) return false; if (other.getModelQualityBaselineConfig() == null ^ this.getModelQualityBaselineConfig() == null) return false; if (other.getModelQualityBaselineConfig() != null && other.getModelQualityBaselineConfig().equals(this.getModelQualityBaselineConfig()) == false) return false; if (other.getModelQualityAppSpecification() == null ^ this.getModelQualityAppSpecification() == null) return false; if (other.getModelQualityAppSpecification() != null && other.getModelQualityAppSpecification().equals(this.getModelQualityAppSpecification()) == false) return false; if (other.getModelQualityJobInput() == null ^ this.getModelQualityJobInput() == null) return false; if (other.getModelQualityJobInput() != null && other.getModelQualityJobInput().equals(this.getModelQualityJobInput()) == false) return false; if (other.getModelQualityJobOutputConfig() == null ^ this.getModelQualityJobOutputConfig() == null) return false; if (other.getModelQualityJobOutputConfig() != null && other.getModelQualityJobOutputConfig().equals(this.getModelQualityJobOutputConfig()) == false) return false; if (other.getJobResources() == null ^ this.getJobResources() == null) return false; if (other.getJobResources() != null && other.getJobResources().equals(this.getJobResources()) == false) return false; if (other.getNetworkConfig() == null ^ this.getNetworkConfig() == null) return false; if (other.getNetworkConfig() != null && other.getNetworkConfig().equals(this.getNetworkConfig()) == false) return false; if (other.getRoleArn() == null ^ this.getRoleArn() == null) return false; if (other.getRoleArn() != null && other.getRoleArn().equals(this.getRoleArn()) == false) return false; if (other.getStoppingCondition() == null ^ this.getStoppingCondition() == null) return false; if (other.getStoppingCondition() != null && other.getStoppingCondition().equals(this.getStoppingCondition()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getJobDefinitionArn() == null) ? 0 : getJobDefinitionArn().hashCode()); hashCode = prime * hashCode + ((getJobDefinitionName() == null) ? 0 : getJobDefinitionName().hashCode()); hashCode = prime * hashCode + ((getCreationTime() == null) ? 0 : getCreationTime().hashCode()); hashCode = prime * hashCode + ((getModelQualityBaselineConfig() == null) ? 0 : getModelQualityBaselineConfig().hashCode()); hashCode = prime * hashCode + ((getModelQualityAppSpecification() == null) ? 0 : getModelQualityAppSpecification().hashCode()); hashCode = prime * hashCode + ((getModelQualityJobInput() == null) ? 0 : getModelQualityJobInput().hashCode()); hashCode = prime * hashCode + ((getModelQualityJobOutputConfig() == null) ? 0 : getModelQualityJobOutputConfig().hashCode()); hashCode = prime * hashCode + ((getJobResources() == null) ? 0 : getJobResources().hashCode()); hashCode = prime * hashCode + ((getNetworkConfig() == null) ? 0 : getNetworkConfig().hashCode()); hashCode = prime * hashCode + ((getRoleArn() == null) ? 0 : getRoleArn().hashCode()); hashCode = prime * hashCode + ((getStoppingCondition() == null) ? 0 : getStoppingCondition().hashCode()); return hashCode; } @Override public DescribeModelQualityJobDefinitionResult clone() { try { return (DescribeModelQualityJobDefinitionResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
35.108731
159
0.650603
0453c32e0faad4445f9b17daf2a753b251a09bbd
2,482
package com.conveyal.gtfs.validator; import com.conveyal.gtfs.error.SQLErrorStorage; import com.conveyal.gtfs.loader.Feed; import com.conveyal.gtfs.model.*; import java.net.URL; import static com.conveyal.gtfs.error.NewGTFSErrorType.FIELD_VALUE_TOO_LONG; /** * MTCValidator runs a set of custom validation checks for GTFS feeds managed by MTC in Data Tools. * The checks consist of validating field lengths at this time per the 511 MTC guidelines at * https://github.com/ibi-group/datatools-ui/files/4438625/511.Transit_Data.Guidelines_V2.0_3-27-2020.pdf. * For specific field lengths, search the guidelines for the word 'character'. * * Note that other validations, e.g. on GTFS+ files, are discussed in * https://github.com/ibi-group/datatools-ui/issues/544. */ public class MTCValidator extends FeedValidator { public MTCValidator(Feed feed, SQLErrorStorage errorStorage) { super(feed, errorStorage); } @Override public void validate() { for (Agency agency : feed.agencies) { validateFieldLength(agency, agency.agency_id, 50); validateFieldLength(agency, agency.agency_name, 50); validateFieldLength(agency, agency.agency_url, 500); } for (Stop stop : feed.stops) { validateFieldLength(stop, stop.stop_name, 100); } for (Trip trip : feed.trips) { validateFieldLength(trip, trip.trip_headsign, 120); validateFieldLength(trip, trip.trip_short_name, 50); } } /** * Checks that the length of a string does not exceed a certain length. * Reports an error if the length is exceeded. * @param entity The containing GTFS entity (for error reporting purposes). * @param value The String value to check. * @param maxLength The length to check, should be positive or zero. * @return true if value.length() is maxLength or less, or if value is null; false otherwise. */ public boolean validateFieldLength(Entity entity, String value, int maxLength) { if (value != null && value.length() > maxLength) { if (errorStorage != null) registerError(entity, FIELD_VALUE_TOO_LONG, "[over " + maxLength + " characters] " + value); return false; } return true; } public boolean validateFieldLength(Entity entity, URL url, int maxLength) { return validateFieldLength(entity, url != null ? url.toString() : "", maxLength); } }
38.78125
130
0.68332
21083f8ff16167324216b405cebd01309defe5ea
652
package program; public class Printers { public static void print2DArray(int[][] arr) { for(int[] m : arr) { for(int n : m) System.out.printf("[%d]", n); System.out.println(); } } public static void print2DArray(char[][] arr) { for(char[] m : arr) { for(char n : m) System.out.printf("[%s]", n); System.out.println(); } } public static void printArray(int[] arr) { for(int i : arr) System.out.printf("[%d]", i); } public static void printArray(byte[] b) { for(byte i : b) System.out.printf("[%d]", i); } public static void printCharArray(char[] c) { for(char s : c) System.out.printf("[%s]", s); } }
20.375
48
0.587423
75f5bfddcfe8f02e486e7e4fda4dcfeb38865746
3,788
package com.codepath.apps.erastustweet.utilities; import android.content.Context; import android.text.Editable; import android.text.Spannable; import android.text.SpannableString; import android.text.TextWatcher; import android.text.style.BackgroundColorSpan; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.codepath.apps.erastustweet.R; public class TweetEditTextBehavior { public static final int MAX_TWEET_CHARS = 280; public static void setComposeTweetEditTextBehaviour(final Context context, final EditText textBody, final TextView charCount, final Button submitText) { textBody.addTextChangedListener(new TextWatcher() { // to prevent an infinite loop because TextWatcher is called // again inside the afterTextChanged method private boolean mChangedByTextWatcher = false; // This method is called to notify you that, within s, // the count characters beginning at start are about to be replaced // by new text with length after. // It is an error to attempt to make changes to s from this callback. @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } // This method is called to notify you that, within s, the count // characters beginning at start have just replaced old text that had length before. // It is an error to attempt to make changes to s from this callback. @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String tweetBody = textBody.getText().toString().trim(); if (tweetBody.length() > MAX_TWEET_CHARS) { submitText.setEnabled(false); charCount.setTextColor(context.getColor(R.color.red)); String length = "-" + (s.length() - MAX_TWEET_CHARS); charCount.setText(length); } else if (tweetBody.length() == 0) { submitText.setEnabled(false); charCount.setTextColor(context.getColor(R.color.green)); charCount.setText(context.getString(R.string.zero)); } else { submitText.setEnabled(true); charCount.setTextColor(context.getColor(R.color.green)); charCount.setText(String.valueOf(s.length())); } } @Override public void afterTextChanged(Editable s) { if (s.length() > 0) { if (s.toString().trim().length() > MAX_TWEET_CHARS) { if (mChangedByTextWatcher) { return; } mChangedByTextWatcher = true; // cursor position will be reset to 0, so save it int cursorPosition = textBody.getSelectionStart(); Spannable tweetColored = new SpannableString(s); tweetColored.setSpan(new BackgroundColorSpan(context.getColor(R.color.RedHighlight)), MAX_TWEET_CHARS, s.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); textBody.setText(tweetColored); textBody.setSelection(cursorPosition); // release, so the TextWatcher can start to listen again. mChangedByTextWatcher = false; } } } }); } }
44.564706
109
0.568374
fe8a90f988456149cbac48b0df9db39c2d3a657b
8,949
/* * 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.brooklyn.util.net; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.fail; import java.net.ServerSocket; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import org.apache.brooklyn.test.Asserts; import org.apache.brooklyn.util.javalang.JavaClassNames; import org.apache.brooklyn.util.time.Duration; import org.apache.brooklyn.util.time.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.net.HostAndPort; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; public class ReachableSocketFinderTest { private static final Logger LOG = LoggerFactory.getLogger(ReachableSocketFinderTest.class); private static final Duration TIMEOUT = Asserts.DEFAULT_LONG_TIMEOUT; private static final Duration SHORT_TIMEOUT = Duration.millis(100); private static final Duration SHORT_WAIT = Duration.millis(100); private final HostAndPort socket1 = HostAndPort.fromParts("1.1.1.1", 1111); private final HostAndPort socket2 = HostAndPort.fromParts("1.1.1.2", 1112); private final HostAndPort socket3 = HostAndPort.fromParts("1.1.1.3", 1113); private final Predicate<HostAndPort> socketTester = new Predicate<HostAndPort>() { @Override public boolean apply(HostAndPort input) { return Boolean.TRUE.equals(reachabilityResults.get(input)); }}; private Map<HostAndPort, Boolean> reachabilityResults; private ListeningExecutorService executor; private ReachableSocketFinder finder; @BeforeMethod(alwaysRun=true) public void setUp() throws Exception { reachabilityResults = Maps.newConcurrentMap(); executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); finder = new ReachableSocketFinder(socketTester); } @AfterMethod(alwaysRun=true) public void tearDown() throws Exception { if (executor != null) executor.shutdownNow(); } @Test(expectedExceptions=IllegalStateException.class) public void testFindWhenNoSocketsThrowsIllegalState() throws Exception { finder.findOpenSocketOnNode(ImmutableList.<HostAndPort>of(), TIMEOUT); } @Test(expectedExceptions=IllegalStateException.class) public void testFindAllWhenNoSocketsThrowsIllegalState() throws Exception { finder.findOpenSocketsOnNode(ImmutableList.<HostAndPort>of(), TIMEOUT); } @Test public void testReturnsReachableSocket() throws Exception { reachabilityResults.put(socket1, true); reachabilityResults.put(socket2, false); assertEquals(finder.findOpenSocketOnNode(ImmutableList.of(socket1, socket2), TIMEOUT), socket1); reachabilityResults.put(socket1, false); reachabilityResults.put(socket2, true); assertEquals(finder.findOpenSocketOnNode(ImmutableList.of(socket1, socket2), TIMEOUT), socket2); } @Test public void testPollsUntilPortReachable() throws Exception { reachabilityResults.put(socket1, false); reachabilityResults.put(socket2, false); final ListenableFuture<HostAndPort> future = executor.submit(new Callable<HostAndPort>() { @Override public HostAndPort call() throws Exception { return finder.findOpenSocketOnNode(ImmutableList.of(socket1, socket2), TIMEOUT); }}); // Should keep trying Asserts.succeedsContinually(ImmutableMap.of("timeout", SHORT_WAIT), new Runnable() { @Override public void run() { assertFalse(future.isDone()); }}); // When port is reached, it completes reachabilityResults.put(socket1, true); assertEquals(future.get(), socket1); } @Test public void testGetReachableSockets() throws Exception { reachabilityResults.put(socket1, true); reachabilityResults.put(socket2, false); reachabilityResults.put(socket3, true); final Iterable<HostAndPort> expected = ImmutableList.of(socket1, socket3); final Iterable<HostAndPort> actual = finder.findOpenSocketsOnNode( ImmutableList.of(socket1, socket2, socket3), TIMEOUT); assertEquals(actual, expected, "expected=" + expected + ", actual=" + Iterables.toString(actual)); } @Test public void testGetAllReachableSocketsEmpty() throws Exception { final Iterable<HostAndPort> expected = ImmutableList.of(); final Iterable<HostAndPort> actual = finder.findOpenSocketsOnNode(ImmutableList.of(socket2), SHORT_TIMEOUT); assertEquals(actual, expected, "expected=" + expected + ", actual=" + Iterables.toString(actual)); } @Test public void testSocketResultIgnoredIfGracePeriodExpiresAfterFirstResultAvailable() { reachabilityResults.put(socket1, false); reachabilityResults.put(socket2, true); // Override the default test grace period. finder = new ReachableSocketFinder(socketTester, Duration.ZERO); final Iterable<HostAndPort> actual = finder.findOpenSocketsOnNode(ImmutableList.of(socket1, socket2), TIMEOUT); // Sleep through the grace period. Time.sleep(50); reachabilityResults.put(socket1, true); assertEquals(actual, ImmutableList.of(socket2)); } // Mark as integration, as can't rely (in Apache infra) for a port to stay unused during test! @Test(groups="Integration") public void testReturnsRealReachableSocket() throws Exception { ReachableSocketFinder realFinder = new ReachableSocketFinder(); ServerSocket socket = connectToPort(); try { HostAndPort addr = HostAndPort.fromParts(socket.getInetAddress().getHostAddress(), socket.getLocalPort()); HostAndPort wrongAddr = HostAndPort.fromParts(socket.getInetAddress().getHostAddress(), findAvailablePort()); assertEquals(realFinder.findOpenSocketOnNode(ImmutableList.of(addr, wrongAddr), TIMEOUT), addr); } finally { if (socket != null) { socket.close(); } } } // Mark as integration, as can't rely (in Apache infra) for a port to stay unused during test! // And slow test - takes 5 seconds. @Test(groups="Integration") public void testFailsIfRealSocketUnreachable() throws Exception { ReachableSocketFinder realFinder = new ReachableSocketFinder(); HostAndPort wrongAddr = HostAndPort.fromParts(Networking.getReachableLocalHost().getHostAddress(), findAvailablePort()); try { HostAndPort result = realFinder.findOpenSocketOnNode(ImmutableList.of(wrongAddr), Duration.FIVE_SECONDS); fail("Expected failure, but got "+result); } catch (NoSuchElementException e) { // success } } private ServerSocket connectToPort() throws Exception { ServerSocket result = new ServerSocket(0); LOG.info("Acquired port "+result+" for test "+JavaClassNames.niceClassAndMethod()); return result; } private int findAvailablePort() throws Exception { final int startPort = 58767; final int endPort = 60000; int port = startPort; do { if (Networking.isPortAvailable(port)) { return port; } port++; // repeat until we can get a port } while (port <= endPort); throw new Exception("could not get a port in range "+startPort+"-"+endPort); } }
43.441748
128
0.7079
c1bc19656b16e8ed1d5747ee84a63267e86c7a15
7,875
package bfd.sys.solr.handler; import bfd.sys.solr.SolrField; import bfd.sys.solr.util.Constants; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import org.apache.solr.common.SolrInputDocument; import java.util.*; import java.util.concurrent.Exchanger; public abstract class BaseItemConsumer extends AbstractTopicConsumer { protected static Logger logger = Logger.getLogger(BaseItemConsumer.class); public BaseItemConsumer(String topic,String group,Exchanger<List<String>> exchanger) { this.topic = topic; this.group = group; this.exchanger = exchanger; this.isDebug = false; } public BaseItemConsumer(String topic,String group,Exchanger<List<String>> exchanger,boolean isDebug) { this.topic = topic; this.group = group; this.exchanger = exchanger; this.isDebug = isDebug; } public void process(ArrayList<SolrInputDocument> docs) { for (int i = 0; i < docs.size(); i++) { try { // String cid = docs.get(i).getFieldValue("cid").toString().replace("_test", ""); if(docs.get(i).containsKey("type") && "newslist".equals(docs.get(i).getFieldValue("type").toString())){ Constants.data.get("hackthon_list").offer(docs.get(i)); logger.info("hackthon_list" + " queue insert_doc :" + docs.get(i).getFieldValue("cid_iid").toString()); } if(docs.get(i).containsKey("type") && "newscontent".equals(docs.get(i).getFieldValue("type").toString())){ Constants.data.get("hackthon_importnew").offer(docs.get(i)); logger.info("hackthon_detail" + " queue insert_doc :" + docs.get(i).getFieldValue("cid_iid").toString()); } } catch (Exception e) { logger.error(docs.get(i)); logger.error(e.getStackTrace()); } } } public ArrayList<SolrInputDocument> updateItem(String msg){ try { logger.info(("updateItem:msg->"+msg)); ArrayList<SolrInputDocument> documents = new ArrayList<>(); JSONObject json = JSONObject.fromObject(msg); String cid = json.getString("cid"); String iid = json.getString("iid"); String cid_iid = new StringBuffer(cid).append("_").append(iid).toString(); SolrInputDocument doc = new SolrInputDocument(); doc.addField("cid", cid); doc.addField("iid", iid); doc.addField("cid_iid", cid_iid); if(json.has("contents")){ doc.addField("contents",json.get("contents").toString()); } if(json.has("html")){ doc.addField("html",json.get("html").toString()); } if(json.has("title")){ doc.addField("title",json.get("title").toString()); } doc.addField("timestamps",((Double)json.getDouble("creation_time")).longValue()); if(json.has("post_time")){ doc.addField("ptime",(long)json.get("post_time")/1000); }else { doc.addField("ptime",((Double)json.getDouble("creation_time")).longValue()); } if(json.has("topic")){ doc.addField("topic",json.get("topic").toString()); } if(json.has("url")){ doc.addField("url",json.get("url").toString()); } if(json.has("keyword")){ doc.addField("keywords",json.get("keyword").toString()); } if(json.has("abs")){ doc.addField("abs",json.get("abs").toString()); } if(json.has("loc")){ doc.addField("loc",json.get("loc").toString()); } if(json.has("pic")){ doc.addField("pic",json.get("pic").toString()); } if(json.has("cat")){ doc.addField("cat",json.get("cat").toString()); } if(json.has("tag")){ doc.addField("tag",json.get("tag").toString()); } if(json.has("type")){ doc.addField("type",json.get("type").toString()); } documents.add(doc); return documents; } catch (Throwable e) { logger.error("BaseItemConsumer.updateItem_error:"+e.getMessage()); e.printStackTrace(); return null; } } public ArrayList<SolrInputDocument> updateListItem(String msg){ try { logger.info(("updateListItem:msg->"+msg)); ArrayList<SolrInputDocument> docs = new ArrayList<>(); SolrInputDocument doc; JSONObject json = JSONObject.fromObject(msg); String cid = json.getString("cid"); String iid,cid_iid; JSONArray items = json.getJSONArray("items");// TODO for(Object object : items){ doc = new SolrInputDocument(); JSONObject jsonObject = JSONObject.fromObject(object); iid = jsonObject.get("iid").toString(); cid_iid = new StringBuffer(cid).append("_").append(iid).toString(); doc.addField("cid", cid); doc.addField("iid", iid); doc.addField("cid_iid", cid_iid); if(jsonObject.has("title")){ doc.addField("title",jsonObject.get("title").toString()); } if(jsonObject.has("smallPic")){ doc.addField("smallPic",jsonObject.get("smallPic").toString()); } if(jsonObject.has("abs")){ doc.addField("abs",jsonObject.get("abs").toString()); } if(jsonObject.has("posttime")){ doc.addField("posttime",jsonObject.get("posttime").toString()); } if(jsonObject.has("infoUrl")){ doc.addField("infoUrl",jsonObject.get("infoUrl").toString()); } if(json.has("type")){ doc.addField("type",json.get("type").toString()); } docs.add(doc); } logger.info(("updateListItem finished! msg->"+msg)); return docs; } catch (Throwable e) { logger.error("BaseItemConsumer.updateItem_error:"+e.getMessage()); e.printStackTrace(); return null; } } private void setAttr(SolrInputDocument doc, Map<String, SolrField> attrs, JSONObject attrJson, String attr, boolean flag) { if(flag && (attrJson.get(attr) instanceof JSONArray)){ JSONArray v = attrJson.getJSONArray(attr); doc.addField(attr, v); }else{ switch (attrs.get(attr).getType()) { case BOOLEAN: doc.addField(attr, attrJson.getBoolean(attr)); break; case INT: doc.addField(attr, attrJson.getInt(attr)); break; case LONG: doc.addField(attr, attrJson.getLong(attr)); break; case FLOAT: doc.addField(attr, Float.valueOf(attrJson.getString(attr))); break; case DOUBLE: doc.addField(attr, attrJson.getDouble(attr)); break; default: doc.addField(attr, attrJson.getString(attr)); break; } } } public ArrayList<SolrInputDocument> rmItem(String msg) { if(isDebug){ info(msg); } ArrayList<SolrInputDocument> documents = new ArrayList<>(); JSONObject json = JSONObject.fromObject(msg); SolrInputDocument doc = new SolrInputDocument(); /*String cacheBaseKey = json.getString("cid") + ":NewsBase:" + json.getString("iid"); info("remove_doc_"+cacheBaseKey.replace(":NewsBase:", "")); NewsBase base = null; try { byte[] value = memc.get(cacheBaseKey); if (null != value) { base = NewsBase.parseFrom(value); } } catch (InvalidProtocolBufferException e) { logger.error(e.getMessage()); } if (base != null) { return null; }*/ doc.addField("cid_iid", json.getString("cid")+"_"+json.getString("iid")); doc.addField("cid", json.getString("cid")); doc.addField("iid", json.getString("iid")); Map<String,Boolean> expired = new HashMap<String, Boolean>(); expired.put("set", true); doc.addField("expired", expired); if(json.has("timestamp")){ doc.addField("timestamp", ((Double)json.getDouble("timestamp")).longValue()); } info("rm doc:"+doc.getField("cid_iid").toString()); documents.add(doc); return documents; } private void addField(SolrInputDocument doc, String field, Collection goods) { if (goods != null && !goods.isEmpty()) { doc.addField(field, goods); } } private void addField(SolrInputDocument doc, String field, List<String> goods, float boost) { if (goods != null && !goods.isEmpty()) { doc.addField(field, goods, boost); } } }
31.882591
111
0.639873
efa9dc04fef61aed797716b4bf159e7f0d98baaa
676
/* * Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made * available under the terms of the MIT License. See the LICENSE file in the project root for more information. */ package com.microsoft.sqlserver.testframework.sqlType; import java.sql.JDBCType; public abstract class SqlNumber extends SqlType { SqlNumber(String name, JDBCType jdbctype, int precision, int scale, Object min, Object max, Object nullvalue, VariableLengthType variableLengthType, Class type) { super(name, jdbctype, precision, scale, min, max, nullvalue, VariableLengthType.Fixed, type); } }
39.764706
117
0.739645
93dae4c6854246ba367b478f1ca80238ebfd0192
3,219
/* * Copyright 2018 - 2020 Paul Hagedorn (Panzer1119) * * 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.codemakers.io.monitor; import de.codemakers.base.Standard; import de.codemakers.io.file.AdvancedFile; import de.codemakers.io.listeners.AdvancedFileChangeListener; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class AdvancedFileMonitorTest { private static final Logger logger = LogManager.getLogger(); public static final void main(String[] args) throws Exception { final AdvancedFile root = new AdvancedFile(args[0]); logger.info("root=" + root); final AdvancedFileMonitor advancedFileMonitor = new AdvancedFileMonitor(root); logger.info("advancedFileMonitor=" + advancedFileMonitor); advancedFileMonitor.addAdvancedFileChangeListeners(new AdvancedFileChangeListener() { @Override public void onFileCreated(AdvancedFile file) { logger.debug("onFileCreated:" + file); } @Override public void onFileModified(AdvancedFile file) { logger.debug("onFileModified:" + file); } @Override public void onFileDeleted(AdvancedFile file) { logger.debug("onFileDeleted:" + file); } @Override public void onFileRenamed(AdvancedFile file) { logger.debug("onFileRenamed:" + file); } @Override public void onDirectoryCreated(AdvancedFile directory) { logger.debug("onDirectoryCreated:" + directory); } @Override public void onDirectoryModified(AdvancedFile directory) { logger.debug("onDirectoryModified:" + directory); } @Override public void onDirectoryDeleted(AdvancedFile directory) { logger.debug("onDirectoryDeleted:" + directory); } @Override public void onDirectoryRenamed(AdvancedFile directory) { logger.debug("onDirectoryRenamed:" + directory); } }); logger.info("advancedFileMonitor=" + advancedFileMonitor); advancedFileMonitor.start(); logger.info("advancedFileMonitor=" + advancedFileMonitor); Standard.addShutdownHook(advancedFileMonitor::stop); Standard.async(() -> { Thread.sleep(20000); logger.info("Exiting"); System.exit(0); }); } }
37
93
0.61137
86191cac5dfd2afbb69f3880df537e4c44e4cfea
2,494
package org.d3ifcool.finpro.dosen; import androidx.test.rule.ActivityTestRule; import org.d3ifcool.finpro.R; import org.d3ifcool.finpro.activities.DosenMainActivity; import org.d3ifcool.finpro.activities.LoginActivity; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu; import static androidx.test.espresso.Espresso.pressBack; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.typeText; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; /** * Created by Faisal Amir * FrogoBox Inc License * ========================================= * Finpro * Copyright (C) 12/01/2019. * All rights reserved * ----------------------------------------- * Name : Muhammad Faisal Amir * E-mail : faisalamircs@gmail.com * Line : bullbee117 * Phone : 081357108568 * Majors : D3 Teknik Informatika 2016 * Campus : Telkom University * ----------------------------------------- * id.amirisback.frogobox */ public class DosenLoginBehaviourTest { @Rule public ActivityTestRule<LoginActivity> loginActivityTestRule = new ActivityTestRule<>(LoginActivity.class); public ActivityTestRule<DosenMainActivity> dosenMainActivityTestRule = new ActivityTestRule<>(DosenMainActivity.class); @Before public void init(){ loginActivityTestRule.getActivity(); dosenMainActivityTestRule.getActivity(); } @Test public void loginTest() throws InterruptedException { String username = "001"; String password = "001"; onView(withId(R.id.act_main_edittext_username)).perform(typeText(username)); onView(withId(R.id.act_main_edittext_password)).perform(typeText(password)); pressBack(); onView(withId(R.id.act_main_button_login)).perform(click()); Thread.sleep(5000); } @Test public void logoutTest() throws InterruptedException { Thread.sleep(2000); openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext()); onView(withText("Keluar")).perform(click()); onView(withText("KELUAR")).perform(click()); Thread.sleep(2000); } }
33.702703
123
0.706095
d36f6e3816dad8c8ac3dc00ceeec213b53016b69
1,747
/** * Copyright (c) 2015, Benny Bobaganoosh. All rights reserved. * License terms are in the included LICENSE.txt file. */ package engine.parsing.json; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import engine.parsing.TokenReader; /** * Reads or writes JSON files. * * @author Benny Bobaganoosh (thebennybox@gmail.com) */ public class JSON { private JSONValue value; /** * Loads a JSON file * * @param fileName * The name and path to the file of interest. * @throws IOException * If the file cannot be loaded. * @throws ParseException * If the file cannot be properly parsed. */ public JSON(String fileName) throws IOException, ParseException { TokenReader tokens; tokens = new TokenReader(new FileReader(fileName)); value = JSONValue.parse(tokens, tokens.next()); String token; tokens.parseAssert((token = tokens.next()) == null, "Expected EOF; instead got " + token); tokens.close(); } /** * Wraps a JSON value for writing. * * @param value * The value to write to file. */ public JSON(JSONValue value) { this.value = value; } /** * Writes a new JSON file. * * @param fileName * The name and path to the file to write to. * @throws IOException * If the file cannot be written. */ public void write(String fileName) throws IOException { BufferedWriter br = new BufferedWriter(new FileWriter(fileName)); value.write(br); br.close(); } /** * Gets the JSONValue for this object * * @return The JSONValue for this object. */ public JSONValue get() { return value; } }
22.397436
67
0.659416
d35b6f297964ac502269d150e518fd9a7edceb3d
8,774
package edu.virginia.vcgr.genii.network.ftp; import java.io.InputStream; import java.io.OutputStream; import java.util.Collection; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.morgan.ftp.FTPException; import org.morgan.ftp.FilePermissions; import org.morgan.ftp.IBackend; import org.morgan.ftp.ListEntry; import org.morgan.ftp.PathAlreadyExistsException; import org.morgan.ftp.PathDoesNotExistException; import edu.virginia.vcgr.genii.client.byteio.ByteIOStreamFactory; import edu.virginia.vcgr.genii.client.resource.TypeInformation; import edu.virginia.vcgr.genii.client.rns.RNSException; import edu.virginia.vcgr.genii.client.rns.RNSPath; import edu.virginia.vcgr.genii.client.rns.RNSPathAlreadyExistsException; import edu.virginia.vcgr.genii.client.rns.RNSPathDoesNotExistException; import edu.virginia.vcgr.genii.client.rns.RNSPathQueryFlags; public class GeniiBackend implements IBackend { static private Log _logger = LogFactory.getLog(GeniiBackend.class); private String _username; private GeniiBackendConfiguration _configuration; public GeniiBackend(GeniiBackendConfiguration configuration) { _configuration = configuration; } @Override public boolean authenticate(String username, String password) throws FTPException { _username = username; return true; } @Override public void cwd(String path) throws FTPException { try { RNSPath newPath = _configuration.getCallingContext().getCurrentPath().lookup(path, RNSPathQueryFlags.MUST_EXIST); _configuration.getCallingContext().setCurrentPath(newPath); } catch (RNSException re) { if (_logger.isDebugEnabled()) _logger.debug("Error trying to look up RNS path \"" + path + "\".", re); throw new PathDoesNotExistException(path); } } @Override public void delete(String entry) throws FTPException { try { RNSPath path = _configuration.getCallingContext().getCurrentPath(); path = path.lookup(entry, RNSPathQueryFlags.MUST_EXIST); path.delete(); } catch (RNSPathDoesNotExistException re) { if (_logger.isDebugEnabled()) _logger.debug("Unable to delete rns path \"" + entry + "\"."); throw new PathDoesNotExistException(entry); } catch (RNSException re) { if (_logger.isDebugEnabled()) _logger.debug("Unable to delete rns path \"" + entry + "\"."); throw new FTPException(451, "Unknown internal error."); } } @Override public boolean exists(String entry) throws FTPException { try { _configuration.getCallingContext().getCurrentPath().lookup(entry, RNSPathQueryFlags.MUST_EXIST); return true; } catch (Throwable t) { return false; } } @Override public String getGreeting() { return "Genesis II FTP Daemon"; } @Override public ListEntry[] list() throws FTPException { FilePermissions rwx = new FilePermissions(0x7, 0x7, 0x7); try { Collection<RNSPath> _paths = _configuration.getCallingContext().getCurrentPath().listContents(); RNSPath[] paths = _paths.toArray(new RNSPath[0]); ListEntry[] ret = new ListEntry[paths.length]; for (int lcv = 0; lcv < paths.length; lcv++) { TypeInformation typeInfo = new TypeInformation(paths[lcv].getEndpoint()); if (typeInfo.isRNS()) { ret[lcv] = new ListEntry(paths[lcv].getName(), new Date(), 0, _username, "genii", rwx, 1, true); } else if (typeInfo.isByteIO()) { String typeDesc = typeInfo.getTypeDescription(); long size = 0; try { size = Long.parseLong(typeDesc); } catch (NumberFormatException nfe) { } ret[lcv] = new ListEntry(paths[lcv].getName(), new Date(), size, _username, "genii", rwx, 1, false); } else { RedirectFile rd = new RedirectFile(paths[lcv].getEndpoint()); ret[lcv] = new ListEntry(paths[lcv].getName() + ".html", new Date(), rd.getSize(), _username, "genii", new FilePermissions(0x5, 0x5, 0x5), 1, false); } } return ret; } catch (RNSException re) { if (_logger.isDebugEnabled()) _logger.debug("Unable to list contents of RNS path.", re); throw new FTPException(451, "Unknown internal error."); } } @Override public String mkdir(String newDir) throws FTPException { try { RNSPath path = _configuration.getCallingContext().getCurrentPath(); RNSPath newPath = path.lookup(newDir, RNSPathQueryFlags.MUST_NOT_EXIST); newPath.mkdir(); return newPath.pwd(); } catch (RNSPathAlreadyExistsException ae) { if (_logger.isDebugEnabled()) _logger.debug("Unable to create a new RNS directory.", ae); throw new PathAlreadyExistsException(newDir); } catch (RNSException re) { if (_logger.isDebugEnabled()) _logger.debug("Unable to create a new RNS directory.", re); throw new FTPException(451, "Unknown error trying to create new RNS directory."); } } @Override public String pwd() throws FTPException { return _configuration.getCallingContext().getCurrentPath().pwd(); } @Override public void removeDirectory(String directory) throws FTPException { delete(directory); } @Override public void rename(String oldEntry, String newEntry) throws FTPException { try { RNSPath path = _configuration.getCallingContext().getCurrentPath(); RNSPath oldPath = path.lookup(oldEntry, RNSPathQueryFlags.MUST_EXIST); RNSPath newPath = path.lookup(newEntry, RNSPathQueryFlags.MUST_NOT_EXIST); newPath.link(oldPath.getEndpoint()); oldPath.unlink(); } catch (RNSPathAlreadyExistsException ae) { if (_logger.isDebugEnabled()) _logger.debug("Error trying to rename RNS entries.", ae); throw new PathAlreadyExistsException(newEntry); } catch (RNSPathDoesNotExistException dne) { if (_logger.isDebugEnabled()) _logger.debug("Error trying to rename RNS entries.", dne); throw new PathDoesNotExistException(oldEntry); } catch (RNSException re) { if (_logger.isDebugEnabled()) _logger.debug("Error trying to rename RNS entries.", re); throw new FTPException(451, "Unknown internal error."); } } @Override public InputStream retrieve(String entry) throws FTPException { try { RNSPath path = _configuration.getCallingContext().getCurrentPath().lookup(entry, RNSPathQueryFlags.DONT_CARE); if (!path.exists()) { if (entry.endsWith(".html")) { path = _configuration.getCallingContext().getCurrentPath().lookup(entry.substring(0, entry.length() - 5), RNSPathQueryFlags.MUST_EXIST); } else throw new PathDoesNotExistException(entry); } if (new TypeInformation(path.getEndpoint()).isByteIO()) return ByteIOStreamFactory.createInputStream(path); else return (new RedirectFile(path.getEndpoint())).getStream(); } catch (RNSPathDoesNotExistException dne) { if (_logger.isDebugEnabled()) _logger.debug("Couldn't find \"" + entry + "\" to retrieve.", dne); throw new PathDoesNotExistException(entry); } catch (Throwable cause) { if (_logger.isDebugEnabled()) _logger.debug("Unable to retrieve grid entry.", cause); throw new FTPException(451, "Unable to read entry."); } } @Override public long size(String entry) throws FTPException { try { RNSPath path = _configuration.getCallingContext().getCurrentPath().lookup(entry, RNSPathQueryFlags.DONT_CARE); if (!path.exists()) { if (entry.endsWith(".html")) { path = _configuration.getCallingContext().getCurrentPath().lookup(entry.substring(0, entry.length() - 5), RNSPathQueryFlags.MUST_EXIST); } else throw new PathDoesNotExistException(entry); } TypeInformation typeInfo = new TypeInformation(path.getEndpoint()); if (typeInfo.isByteIO()) return typeInfo.getByteIOSize(); else return (new RedirectFile(path.getEndpoint())).getSize(); } catch (RNSPathDoesNotExistException dne) { if (_logger.isDebugEnabled()) _logger.debug("Couldn't find \"" + entry + "\" to retrieve size.", dne); throw new PathDoesNotExistException(entry); } catch (Throwable cause) { if (_logger.isDebugEnabled()) _logger.debug("Unable to retrieve grid entry size.", cause); throw new FTPException(451, "Unable to retrieve entry size."); } } @Override public OutputStream store(String entry) throws FTPException { try { RNSPath path = _configuration.getCallingContext().getCurrentPath(); path = path.lookup(entry, RNSPathQueryFlags.DONT_CARE); if (path.exists()) { if (!(new TypeInformation(path.getEndpoint()).isByteIO())) throw new FTPException(451, "Path is not a file."); } else { path.createNewFile(); } return ByteIOStreamFactory.createOutputStream(path); } catch (Throwable cause) { if (_logger.isDebugEnabled()) _logger.debug("Unable to store a file into the grid.", cause); throw new FTPException(451, "Unable to store file."); } } }
32.984962
116
0.722134
59be32de38bc489ef6b2f2de6630d6aeae07a4e4
4,979
/* * $Id: SimpleAnnotations.java 3373 2008-05-12 16:21:24Z xlv $ * * This code is part of the 'iText Tutorial'. * You can find the complete tutorial at the following address: * http://itextdocs.lowagie.com/tutorial/ * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * itext-questions@lists.sourceforge.net */ package com.lowagie.examples.objects.anchors; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.net.URL; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.example.pdftest.PdfTestRunner; import com.example.pdftest.R; import com.lowagie.text.Annotation; import com.lowagie.text.Chunk; import com.lowagie.text.Document; import com.lowagie.text.Image; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfAction; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfWriter; /** * Creates two documents with different types of Annotations. * * @author blowagie */ public class SimpleAnnotations { /** * Creates documents with some simple annotations. * * @param args * no arguments needed */ public static void main(String[] args) { System.out.println("Simple Annotations"); // step 1: creation of a document-object Document document1 = new Document(PageSize.A4, 10, 10, 10, 10); Document document2 = new Document(PageSize.A4, 10, 10, 10, 10); try { // step 2: PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "SimpleAnnotations1.pdf")); PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "SimpleAnnotations2.pdf")); // step 3: writer2.setPdfVersion(PdfWriter.VERSION_1_5); document1.open(); document2.open(); // step 4: document1.add(new Paragraph("Each square on this page represents an annotation.")); // document1 PdfContentByte cb1 = writer1.getDirectContent(); Annotation a1 = new Annotation("authors", "Maybe it's because I wanted to be an author myself that I wrote iText.", 250f, 700f, 350f, 800f); document1.add(a1); Annotation a2 = new Annotation(250f, 550f, 350f, 650f, new URL("http://www.lowagie.com/iText/")); document1.add(a2); Annotation a3 = new Annotation(250f, 400f, 350f, 500f, "http://www.lowagie.com/iText"); document1.add(a3); //Can't use filename => use byte[] instead // Image image = Image.getInstance("iText.gif"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); Bitmap bitmap = BitmapFactory.decodeResource(PdfTestRunner.getActivity().getResources(), R.drawable.itext_gif); bitmap.compress(Bitmap.CompressFormat.JPEG /* FileType */, 100 /* Ratio */, stream); Image image = Image.getInstance(stream.toByteArray()); image.setAnnotation(a3); document1.add(image); Annotation a4 = new Annotation(250f, 250f, 350f, 350f, PdfAction.LASTPAGE); document1.add(a4); // draw rectangles to show where the annotations were added cb1.rectangle(250, 700, 100, 100); cb1.rectangle(250, 550, 100, 100); cb1.rectangle(250, 400, 100, 100); cb1.rectangle(250, 250, 100, 100); cb1.stroke(); // more content document1.newPage(); for (int i = 0; i < 5; i++) { document1.add(new Paragraph("blahblahblah")); } document1.add(new Annotation("blahblah", "Adding an annotation without specifying coordinates")); for (int i = 0; i < 3; i++) { document1.add(new Paragraph("blahblahblah")); } document1.newPage(); document1.add(new Chunk("marked chunk").setLocalDestination("mark")); // document2 document2.add(new Paragraph("Each square on this page represents an annotation.")); PdfContentByte cb2 = writer2.getDirectContent(); Annotation a5 = new Annotation(100f, 700f, 200f, 800f, "cards.mpg", "video/mpeg", true); document2.add(a5); Annotation a6 = new Annotation(100f, 550f, 200f, 650f, "SimpleAnnotations1.pdf", "mark"); document2.add(a6); Annotation a7 = new Annotation(100f, 400f, 200f, 500f, "SimpleAnnotations1.pdf", 2); document2.add(a7); Annotation a8 = new Annotation(100f, 250f, 200f, 350f, "C://windows/notepad.exe", null, null, null); document2.add(a8); // draw rectangles to show where the annotations were added cb2.rectangle(100, 700, 100, 100); cb2.rectangle(100, 550, 100, 100); cb2.rectangle(100, 400, 100, 100); cb2.rectangle(100, 250, 100, 100); cb2.stroke(); } catch (Exception de) { de.printStackTrace(); } // step 5: we close the document document1.close(); document2.close(); } }
37.43609
223
0.708777
7181966e525395753d1793be8a056629218db608
9,570
package java_test; import java.math.BigInteger; import java.util.Vector; import java_test.GroupElement; import org.bouncycastle.pqc.math.linearalgebra.IntegerFunctions; @SuppressWarnings("unused") public class Curve25519{ private final int BIT_WIDTH = 254; private final BigInteger FIELD_PRIME = GroupElement.FIELD_PRIME; private final BigInteger CURVE_ORDER = GroupElement.CURVE_ORDER; private final BigInteger SUBGROUP_ORDER = GroupElement.SUBGROUP_ORDER; private final BigInteger COEFF_A = new BigInteger("126932"); private final AffinePoint pt; private final Vector<String> snark_input_list; private final boolean make_snarkinput; public Curve25519(AffinePoint p1, boolean make_snarkinput){ this.pt = new AffinePoint(p1); this.make_snarkinput = make_snarkinput; if(this.make_snarkinput) snark_input_list = new Vector<>(); else snark_input_list = null; } public Curve25519(BigInteger px, boolean isMatch_ressol, boolean make_snarkinput){ this.pt = new AffinePoint(); this.pt.x = px; this.pt.y = isMatch_ressol ? computeYCoordinate(px): (computeYCoordinate(px).negate()).mod(FIELD_PRIME); this.make_snarkinput = make_snarkinput; if(this.make_snarkinput) snark_input_list = new Vector<>(); else snark_input_list = null; } public Curve25519(String pxHex, boolean isMatch_ressol, boolean make_snarkinput){ this.pt = new AffinePoint(); this.pt.x = new BigInteger(pxHex, 16); this.pt.y = isMatch_ressol ? computeYCoordinate(this.pt.x): (computeYCoordinate(this.pt.x).negate()).mod(FIELD_PRIME); this.make_snarkinput = make_snarkinput; if(this.make_snarkinput) snark_input_list = new Vector<>(); else snark_input_list = null; } public Curve25519(String px, String py, boolean make_snarkinput){ this.pt = new AffinePoint(px, py); this.make_snarkinput = make_snarkinput; if(this.make_snarkinput) snark_input_list = new Vector<>(); else snark_input_list = null; } private Curve25519(AffinePoint p1, boolean make_snarkinput, Vector<String> List){ this.pt = new AffinePoint(p1); this.make_snarkinput = make_snarkinput; this.snark_input_list = List; } public Curve25519 mul(BigInteger exp) { BigInteger[] secretBits = makesecretbits(exp); AffinePoint[] baseTable = preprocess(this.pt, secretBits); AffinePoint new_p = multiply(baseTable, secretBits); return new Curve25519(new_p, this.make_snarkinput, this.snark_input_list); } public Curve25519 add(Curve25519 ECC2) { AffinePoint new_p; if(ECC2.getPoint().equals(this.pt)) new_p = doubleAffinePoint(this.pt); else new_p = addAffinePoints(this.pt, ECC2.getPoint()); if(make_snarkinput) { String tmp = this.snark_input_list.remove(this.snark_input_list.size() - 1); this.snark_input_list.addAll(ECC2.getSnark_Vector()); this.snark_input_list.add(tmp); } return new Curve25519(new_p, this.make_snarkinput, this.snark_input_list); } public Curve25519 sub(Curve25519 ECC2) { AffinePoint new_p = subAffinePoints(this.pt, ECC2.getPoint()); return new Curve25519(new_p, this.make_snarkinput, this.snark_input_list); } public AffinePoint getPoint(){ return new AffinePoint(this.pt); } private AffinePoint multiply(AffinePoint[] precomputedTable, BigInteger[] secretBits) { AffinePoint result = new AffinePoint(precomputedTable[secretBits.length]); for (int j = secretBits.length - 1; j >= 0; j--) { AffinePoint tmp = addAffinePoints(result, precomputedTable[j]); BigInteger isOne = secretBits[j]; result.x = (result.x.add(isOne.multiply(tmp.x.subtract(result.x)))).mod(FIELD_PRIME); result.y = (result.y.add(isOne.multiply(tmp.y.subtract(result.y)))).mod(FIELD_PRIME); } result = subAffinePoints(result, precomputedTable[secretBits.length]); return result; } private AffinePoint addAffinePoints(AffinePoint p1, AffinePoint p2) { BigInteger two = new BigInteger("2"); BigInteger diffY = p1.y.subtract(p2.y).mod(FIELD_PRIME); BigInteger diffX = p1.x.subtract(p2.x).mod(FIELD_PRIME); BigInteger q = FieldDivision(diffY, diffX); BigInteger q2 = q.multiply(q); BigInteger q3 = q2.multiply(q); BigInteger newX = q2.subtract(COEFF_A).subtract(p1.x).subtract(p2.x).mod(FIELD_PRIME); BigInteger newY = p1.x.multiply(two).add(p2.x).add(COEFF_A).multiply(q).subtract(q3).subtract(p1.y).mod(FIELD_PRIME); return new AffinePoint(newX, newY); } private AffinePoint subAffinePoints(AffinePoint p1, AffinePoint p2) { BigInteger two = new BigInteger("2"); BigInteger diffY = p1.y.add(p2.y).mod(FIELD_PRIME); BigInteger diffX = p1.x.subtract(p2.x).mod(FIELD_PRIME); BigInteger q = FieldDivision(diffY, diffX); BigInteger q2 = q.multiply(q); BigInteger q3 = q2.multiply(q); BigInteger newX = q2.subtract(COEFF_A).subtract(p1.x).subtract(p2.x).mod(FIELD_PRIME); BigInteger newY = p1.x.multiply(two).add(p2.x).add(COEFF_A).multiply(q).subtract(q3).subtract(p1.y).mod(FIELD_PRIME); return new AffinePoint(newX, newY); } public BigInteger FieldDivision(BigInteger a, BigInteger b){ BigInteger c = (a.multiply(b.modInverse(FIELD_PRIME)).mod(FIELD_PRIME)); if(make_snarkinput) { snark_input_list.add(c.toString(16)); } return c; } private boolean isValidPointOnEC(BigInteger x, BigInteger y) { BigInteger ySqr = y.multiply(y).mod(FIELD_PRIME); BigInteger xSqr = x.multiply(x).mod(FIELD_PRIME); BigInteger xCube = xSqr.multiply(x).mod(FIELD_PRIME); return ySqr.equals( xCube.add(xSqr.multiply(COEFF_A)).add(x).mod(FIELD_PRIME)); } private AffinePoint doubleAffinePoint(AffinePoint p) { BigInteger three = new BigInteger("3"); BigInteger two = new BigInteger("2"); BigInteger x_2 = p.x.multiply(p.x).mod(FIELD_PRIME); BigInteger l1 = FieldDivision(x_2.multiply(three).add(p.x.multiply(COEFF_A).multiply(two)).add(BigInteger.ONE), p.y.multiply(two)); BigInteger l2 = l1.multiply(l1); BigInteger newX = l2.subtract(COEFF_A).subtract(p.x).subtract(p.x); BigInteger newY = p.x.multiply(three).add(COEFF_A).subtract(l2).multiply(l1).subtract(p.y); return new AffinePoint(newX.mod(FIELD_PRIME), newY.mod(FIELD_PRIME)); } private AffinePoint[] preprocess(AffinePoint p, BigInteger[] secretBits) { AffinePoint[] precomputedTable = new AffinePoint[secretBits.length+1]; precomputedTable[0] = p; for (int j = 1; j <= secretBits.length; j += 1) { precomputedTable[j] = doubleAffinePoint(precomputedTable[j - 1]); } return precomputedTable; } private BigInteger computeYCoordinate(BigInteger x) { BigInteger xSqred = (x.multiply(x)).mod(FIELD_PRIME); BigInteger xCubed = (xSqred.multiply(x)).mod(FIELD_PRIME); BigInteger ySqred = (xCubed.add(COEFF_A.multiply(xSqred)).add(x)).mod(FIELD_PRIME); return (IntegerFunctions.ressol(ySqred, FIELD_PRIME)).mod(FIELD_PRIME); } private BigInteger[] makesecretbits(BigInteger input){ BigInteger[] qr; qr = input.divideAndRemainder(SUBGROUP_ORDER); if(make_snarkinput) { snark_input_list.add(qr[1].toString(16)); snark_input_list.add(qr[0].toString(16)); } //BigInteger[] temp1 = zeroPadBigIntegers(split(qr[1])); //BigInteger[] output = new BigInteger[BIT_WIDTH]; //System.arraycopy(temp1, 0, output, 0, temp1.length); BigInteger[] temp2 = getBitSplit(qr[1], BIT_WIDTH); return temp2; } private BigInteger[] getBitSplit(BigInteger in, int bitWidth) { BigInteger[] out = new BigInteger[bitWidth]; byte[] byte_arr = in.toByteArray(); byte[] byte_tmp = new byte[1]; int rem = in.bitLength() > bitWidth ? bitWidth%8 : in.bitLength()%8; int len = in.bitLength() > bitWidth ? bitWidth/8 : in.bitLength()/8; int offset = (rem == 0 ? 0 : 1) + (byte_arr[0] == 0 ? 1 : 0); int idx = 0; for (int j = len; j >= offset; j--) { for (int i = 0; i < 8; i++) { byte_tmp[0] = (byte) ((byte_arr[j] >> i) & 0x01); out[idx++] = new BigInteger(1, byte_tmp); } } for (int i = 0; i < rem; i++) { byte_tmp[0] = (byte) ((byte_arr[0] >> i) & 0x01); out[idx++] = new BigInteger(1, byte_tmp); } for (; idx < bitWidth; idx++) out[idx] = BigInteger.ZERO; return out; } public boolean isMatch_ressol(){ return (computeYCoordinate(this.pt.x)).equals((this.pt.y)); } private Vector<String> getSnark_Vector(){ return this.snark_input_list; } public Vector<String> getSnarkTable(){ if(!make_snarkinput) return null; return new Vector<>(this.snark_input_list); } public boolean equals(Curve25519 a){ return (this.pt).equals( a.getPoint() ); } }
37.382813
139
0.639394
606193f2f7af8b1091ff0fc662143bedfea9a48d
2,602
package com.demo.siscon.models.entities; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.List; @Entity @Table(name="PROVEEDORSERVICIO") public class ProveedorServicio implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "IDPROVEEDORSERVICIO") private Integer idProveedorServicio; @Column(name = "RUC") @Size(max = 13) private String RUC; @Column(name = "TELEFONO") @Size(max = 15) private String telefono; @Column(name = "EMAIL") @Email private String email; @Column(name = "DIRECCION") @Size(max = 255) private String direccion; @Column(name = "ESTADO") private boolean estado; @Column(name = "FRECUENCIA") private float frecuencia; @JoinColumn(name = "IDCONDOMINIO", referencedColumnName = "IDCONDOMINIO", nullable = false) @ManyToOne private Condominio condominio; @OneToMany(mappedBy = "proveedorServicio", fetch = FetchType.LAZY) private List<Servicio> servicios; public ProveedorServicio() { } public ProveedorServicio(Integer id) { this.idProveedorServicio = id; } public Integer getIdProveedorServicio() { return idProveedorServicio; } public void setIdProveedorServicio(Integer idProveedorServicio) { this.idProveedorServicio = idProveedorServicio; } public String getRUC() { return RUC; } public void setRUC(String RUC) { this.RUC = RUC; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public boolean isEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } public float getFrecuencia() { return frecuencia; } public void setFrecuencia(float frecuencia) { this.frecuencia = frecuencia; } public Condominio getCondominio() { return condominio; } public List<Servicio> getServicios() { return servicios; } }
21.504132
95
0.652575
57a5e88eba34274ad3696f948a2cb0e4fc7ef523
721
package org.jboss.eap.qe.microprofile.metrics.integration.ft; import java.io.IOException; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.eclipse.microprofile.faulttolerance.Fallback; @ApplicationScoped public class FTCustomCounterIncrementProviderService { private long counter = 0; @Inject FTCustomCounterIncrementProvider provider; @Inject FTCustomCounterIncrementFailSafeProvider failSafeProvider; @Fallback(fallbackMethod = "getIncrementFallback") public int getIncrement() throws IOException { return provider.getIncrement(); } public int getIncrementFallback() { return failSafeProvider.getIncrement(); } }
24.033333
62
0.771151
7333263e0d3aa70ec876771aed1008b697bd6d82
35,033
package com.github.zvreifnitz.jpipeline; import com.github.zvreifnitz.jcore.exc.AppException; import com.github.zvreifnitz.jpipeline.execution.PipelineExecutor; import com.github.zvreifnitz.jpipeline.utils.Funcs; import org.junit.Assert; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.*; import java.util.function.BiFunction; import static com.github.zvreifnitz.jpipeline.BuilderHelper.*; public final class PipelineTest { private static final Executor PIPELINE_EXECUTOR = PipelineExecutor.defaultExecutor(); //Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); private static final Executor AUX_EXECUTOR = Executors.newSingleThreadExecutor(); private static int numOfSteps(final double limit) { int result = 0; double sum = 0.0; while (sum < limit) { result++; sum += ThreadLocalRandom.current().nextDouble(); } return result; } private static double avg(final List<Integer> vals, final double limit) { long sum = 0; for (final int v : vals) { sum += v; } return (vals.size() * limit) / sum; } @org.junit.Before public void setUp() { } @org.junit.After public void tearDown() { } @org.junit.Test public void testNoStep() throws Exception { final PipelineBuilder<Integer, Integer> builder = Funcs::identity; try (final Pipeline<Integer, Integer> pipeline = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final Future<Integer> f = pipeline.execute(7); final int result = f.get(); Assert.assertEquals(7, result); } } @org.junit.Test public void testNoStepPipeline() throws Exception { final PipelineBuilder<Integer, Integer> builder = Funcs::identity; try (final Pipeline<Integer, Integer> step = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final PipelineBuilder<Integer, Integer> wrapped = p -> p.addStep(step); try (final Pipeline<Integer, Integer> pipeline = Pipeline.build(wrapped, PIPELINE_EXECUTOR)) { final Future<Integer> f = pipeline.execute(7); final int result = f.get(); Assert.assertEquals(7, result); } } } @org.junit.Test public void testOneStep() throws Exception { final PipelineBuilder<Integer, Long> builder = p -> p .addStep(IntToLongStep.INSTANCE); try (final Pipeline<Integer, Long> pipeline = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final Future<Long> f = pipeline.execute(7); final long result = f.get(); Assert.assertEquals(14L, result); } } @org.junit.Test public void testOneStepPipeline() throws Exception { final PipelineBuilder<Integer, Long> builder = p -> p .addStep(IntToLongStep.INSTANCE); try (final Pipeline<Integer, Long> step = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final PipelineBuilder<Integer, Long> wrapped = p -> p.addStep(step); try (final Pipeline<Integer, Long> pipeline = Pipeline.build(wrapped, PIPELINE_EXECUTOR)) { final Future<Long> f = pipeline.execute(7); final long result = f.get(); Assert.assertEquals(14L, result); } } } @org.junit.Test public void testOneStepFork() throws Exception { final PipelineBuilder<Integer, Long> builder = p -> p .addStep(IntToLongForkStep.INSTANCE); try (final Pipeline<Integer, Long> pipeline = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final Future<Long> f = pipeline.execute(7); final long result = f.get(); Assert.assertEquals(14L, result); } } @org.junit.Test public void testOneStepPipelineFork() throws Exception { final PipelineBuilder<Integer, Long> builder = p -> p .addStep(IntToLongForkStep.INSTANCE); try (final Pipeline<Integer, Long> step = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final PipelineBuilder<Integer, Long> wrapped = p -> p.addStep(step); try (final Pipeline<Integer, Long> pipeline = Pipeline.build(wrapped, PIPELINE_EXECUTOR)) { final Future<Long> f = pipeline.execute(7); final long result = f.get(); Assert.assertEquals(14L, result); } } } @org.junit.Test public void testTwoSteps() throws Exception { final PipelineBuilder<Integer, Double> builder = p -> p .addStep(IntToLongStep.INSTANCE) .addStep(LongToDoubleStep.INSTANCE); try (final Pipeline<Integer, Double> pipeline = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final Future<Double> f = pipeline.execute(7); final double result = f.get(); Assert.assertEquals(28.0, result, 0.00000001); } } @org.junit.Test public void testTwoStepsPipeline() throws Exception { final PipelineBuilder<Integer, Double> builder = p -> p .addStep(IntToLongStep.INSTANCE) .addStep(LongToDoubleStep.INSTANCE); try (final Pipeline<Integer, Double> step = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final PipelineBuilder<Integer, Double> wrapped = p -> p.addStep(step); try (final Pipeline<Integer, Double> pipeline = Pipeline.build(wrapped, PIPELINE_EXECUTOR)) { final Future<Double> f = pipeline.execute(7); final double result = f.get(); Assert.assertEquals(28.0, result, 0.00000001); } } } @org.junit.Test public void testTwoStepsFork() throws Exception { final PipelineBuilder<Integer, Double> builder = p -> p .addStep(IntToLongForkStep.INSTANCE) .addStep(LongToDoubleForkStep.INSTANCE); try (final Pipeline<Integer, Double> pipeline = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final Future<Double> f = pipeline.execute(7); final double result = f.get(); Assert.assertEquals(28.0, result, 0.00000001); } } @org.junit.Test public void testTwoStepsPipelineFork() throws Exception { final PipelineBuilder<Integer, Double> builder = p -> p .addStep(IntToLongForkStep.INSTANCE) .addStep(LongToDoubleForkStep.INSTANCE); try (final Pipeline<Integer, Double> step = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final PipelineBuilder<Integer, Double> wrapped = p -> p.addStep(step); try (final Pipeline<Integer, Double> pipeline = Pipeline.build(wrapped, PIPELINE_EXECUTOR)) { final Future<Double> f = pipeline.execute(7); final double result = f.get(); Assert.assertEquals(28.0, result, 0.00000001); } } } @org.junit.Test public void testParallel() throws Exception { final PipelineBuilder<Integer, Long> builder = p -> p .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .join(); try (final Pipeline<Integer, Long> pipeline = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final Future<Long> f = pipeline.execute(7); final long result = f.get(); Assert.assertEquals(119L, result); } } @org.junit.Test public void testParallelPipeline() throws Exception { final PipelineBuilder<Integer, Long> builder = p -> p .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .addParallelStep(IntToLongStep.INSTANCE, Long::sum) .join(); try (final Pipeline<Integer, Long> step = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final PipelineBuilder<Integer, Long> wrapped = p -> p.addStep(step); try (final Pipeline<Integer, Long> pipeline = Pipeline.build(wrapped, PIPELINE_EXECUTOR)) { final Future<Long> f = pipeline.execute(7); final long result = f.get(); Assert.assertEquals(119L, result); } } } @org.junit.Test public void testParallelFork() throws Exception { final PipelineBuilder<Integer, Long> builder = p -> p .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .join(); try (final Pipeline<Integer, Long> pipeline = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final Future<Long> f = pipeline.execute(7); final long result = f.get(); Assert.assertEquals(119L, result); } } @org.junit.Test public void testParallelPipelineFork() throws Exception { final PipelineBuilder<Integer, Long> builder = p -> p .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .addParallelStep(IntToLongForkStep.INSTANCE, Long::sum) .join(); try (final Pipeline<Integer, Long> step = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final PipelineBuilder<Integer, Long> wrapped = p -> p.addStep(step); try (final Pipeline<Integer, Long> pipeline = Pipeline.build(wrapped, PIPELINE_EXECUTOR)) { final Future<Long> f = pipeline.execute(7); final long result = f.get(); Assert.assertEquals(119L, result); } } } @org.junit.Test public void testIf() throws Exception { final PipelineBuilder<Integer, Integer> builder = p -> p .addIfStep(i -> i % 2 == 0, IncrementStep.INSTANCE); try (final Pipeline<Integer, Integer> pipeline = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final Future<Integer> f7 = pipeline.execute(7); final int seven = f7.get(); Assert.assertEquals(7, seven); final Future<Integer> f14 = pipeline.execute(14); final int fifteen = f14.get(); Assert.assertEquals(15, fifteen); } } @org.junit.Test public void testIfElse() throws Exception { final PipelineBuilder<Integer, Boolean> builder = p -> p .addIfElseStep(i -> i % 2 == 0, EvenStep.INSTANCE, OddStep.INSTANCE); try (final Pipeline<Integer, Boolean> pipeline = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final Future<Boolean> fOdd = pipeline.execute(7); final boolean isOddEven = fOdd.get(); Assert.assertFalse(isOddEven); final Future<Boolean> fEven = pipeline.execute(14); final boolean isEvenEven = fEven.get(); Assert.assertTrue(isEvenEven); } } @org.junit.Test public void testSwitch() throws Exception { final PipelineBuilder<Integer, String> builder = p -> p .addSwitchStep("switch", i -> Math.abs(i) % 3, Arrays.asList( step((i) -> "reminder 0"), step((i) -> "reminder 1"), step((i) -> "reminder 2"))).peek(System.out::println); try (final Pipeline<Integer, String> pipeline = Pipeline.build("testSwitch", builder, PIPELINE_EXECUTOR)) { final Future<String> f0 = pipeline.execute(9); final String r0 = f0.get(); Assert.assertEquals("reminder 0", r0); final Future<String> f1 = pipeline.execute(10); final String r1 = f1.get(); Assert.assertEquals("reminder 1", r1); final Future<String> f2 = pipeline.execute(11); final String r2 = f2.get(); Assert.assertEquals("reminder 2", r2); } } @SuppressWarnings("unchecked") @org.junit.Test public void testSwitchVarargs() throws Exception { final PipelineBuilder<Integer, String> builder = p -> p .addSwitchStep("switch", i -> Math.abs(i) % 3, step((i) -> "reminder 0"), step((i) -> "reminder 1"), step((i) -> "reminder 2")).peek(System.out::println); try (final Pipeline<Integer, String> pipeline = Pipeline.build("testSwitchVarargs", builder, PIPELINE_EXECUTOR)) { final Future<String> f0 = pipeline.execute(9); final String r0 = f0.get(); Assert.assertEquals("reminder 0", r0); final Future<String> f1 = pipeline.execute(10); final String r1 = f1.get(); Assert.assertEquals("reminder 1", r1); final Future<String> f2 = pipeline.execute(11); final String r2 = f2.get(); Assert.assertEquals("reminder 2", r2); } } @SuppressWarnings("unchecked") @org.junit.Test public void testSwitchVarargsPipeline() throws Exception { final PipelineBuilder<Integer, String> builder = p -> p .addSwitchStep("switch", i -> Math.abs(i) % 3, Pipeline.build("p0", r -> r.addStep("s0", step((i) -> "reminder 0")).peek(System.out::println), PIPELINE_EXECUTOR), Pipeline.build("p1", r -> r.addStep("s1", step((i) -> "reminder 1")).peek(System.out::println), PIPELINE_EXECUTOR), Pipeline.build("p2", r -> r.addStep("s2", step((i) -> "reminder 2")).peek(System.out::println), PIPELINE_EXECUTOR)); try (final Pipeline<Integer, String> pipeline = Pipeline.build("testSwitchVarargsPipeline", builder, PIPELINE_EXECUTOR)) { final Future<String> f0 = pipeline.execute(9); final String r0 = f0.get(); Assert.assertEquals("reminder 0", r0); final Future<String> f1 = pipeline.execute(10); final String r1 = f1.get(); Assert.assertEquals("reminder 1", r1); final Future<String> f2 = pipeline.execute(11); final String r2 = f2.get(); Assert.assertEquals("reminder 2", r2); } } @org.junit.Test public void testAvgCalc() throws Exception { final PipelineStep<Double, List<Integer>> initStep = step(i -> new ArrayList<>()); final BiFunction<Double, List<Integer>, List<Integer>> initMerger = merger(); final PipelineStep<Double, Integer> calcStep = step(PipelineTest::numOfSteps); final BiFunction<List<Integer>, Integer, List<Integer>> calcMerger = merger(List::add); final PipelineStep<Double, Double> resultStep = step(); final BiFunction<List<Integer>, Double, Double> resultMerger = PipelineTest::avg; final PipelineBuilder<Double, Double> builder = p -> p .addParallelStep(initStep, initMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(calcStep, calcMerger) .addParallelStep(resultStep, resultMerger) .join(); try (final Pipeline<Double, Double> pipeline = Pipeline.build(builder, PIPELINE_EXECUTOR)) { final Future<Double> f3 = pipeline.execute(1_000.0); final Double r3 = f3.get(); Assert.assertTrue(r3 > 0.4 && r3 < 0.6); final Future<Double> f6 = pipeline.execute(1_000_000.0); final Double r6 = f6.get(); Assert.assertTrue(r6 > 0.4 && r6 < 0.6); } } @org.junit.Test public void testNested() throws Exception { final PipelineStep<Integer, Integer> step = e -> e.accept(e.get() + 1); final PipelineBuilder<Integer, Integer> seqBuilder = p -> p.peek(System.out::println) .addStep("seq_1", step).peek(System.out::println) .addStep("seq_2", step).peek(System.out::println) .addStep("seq_3", step).peek(System.out::println); final PipelineBuilder<Integer, Integer> parBuilder = p -> p.peek(System.out::println) .addParallelStep("par_1", step, BuilderHelper.merger()).peek(System.out::println) .addParallelStep("par_2", step, BuilderHelper.merger()).peek(System.out::println) .addParallelStep("par_3", step, BuilderHelper.merger()).peek(System.out::println) .join(); final PipelineBuilder<Integer, Integer> seqSeqBuilder = p -> p.peek(System.out::println) .buildStep("seq_seq_1", seqBuilder).peek(System.out::println) .buildStep("seq_seq_2", seqBuilder).peek(System.out::println) .buildStep("seq_seq_3", seqBuilder).peek(System.out::println); final PipelineBuilder<Integer, Integer> seqParBuilder = p -> p.peek(System.out::println) .buildStep("seq_par_1", parBuilder).peek(System.out::println) .buildStep("seq_par_2", parBuilder).peek(System.out::println) .buildStep("seq_par_3", BuilderHelper.adapter(Funcs.identityFunc(), parBuilder, BuilderHelper.merger())).peek(System.out::println); final PipelineBuilder<Integer, Integer> parSeqBuilder = p -> p.peek(System.out::println) .buildParallelStep("par_seq_1", seqBuilder, BuilderHelper.merger()).peek(System.out::println) .buildParallelStep("par_seq_2", seqBuilder, BuilderHelper.merger()).peek(System.out::println) .buildParallelStep("par_seq_3", seqBuilder, BuilderHelper.merger()).peek(System.out::println) .join(); final PipelineBuilder<Integer, Integer> parParBuilder = p -> p.peek(System.out::println) .buildParallelStep("par_par_1", parBuilder, BuilderHelper.merger()).peek(System.out::println) .buildParallelStep("par_par_2", parBuilder, BuilderHelper.merger()).peek(System.out::println) .buildParallelStep("par_par_3", BuilderHelper.adapter(Funcs.identityFunc(), parBuilder, BuilderHelper.merger()), BuilderHelper.merger()).peek(System.out::println) .join(); final PipelineBuilder<Integer, Integer> builder = p -> p.peek(System.out::println) .buildStep("builder_1", seqSeqBuilder).peek(System.out::println) .buildStep("builder_2", seqParBuilder).peek(System.out::println) .buildStep("builder_3", parSeqBuilder).peek(System.out::println) .buildStep("builder_4", parParBuilder).peek(System.out::println); try (final Pipeline<Integer, Integer> pipeline = Pipeline.build("pipeline", builder, PIPELINE_EXECUTOR)) { final Future<Integer> f = pipeline.execute(1); final int r = f.get(); Assert.assertEquals("testNested", 17, r); } } @org.junit.Test public void testRetry() throws Exception { final PipelineStep<Integer, Integer> step = e -> { if (ThreadLocalRandom.current().nextDouble() < 0.9) { if (ThreadLocalRandom.current().nextBoolean()) { throw new RuntimeException("no go 1"); } else { e.stop(new RuntimeException("no go 2")); } } else { e.accept(e.get() + 1); } }; final PipelineBuilder<Integer, Integer> builder = p -> p.peek(System.out::println) .addStep("retryStep", retry(step, i -> 10L)).peek(System.out::println); try (final Pipeline<Integer, Integer> pipeline = Pipeline.build("testRetry", builder, PIPELINE_EXECUTOR)) { final Future<Integer> f = pipeline.execute(1); final int r = f.get(); Assert.assertEquals("testRetry", 2, r); } } @org.junit.Test public void testRetryPar() throws Exception { final PipelineStep<Integer, Integer> step = e -> { if (ThreadLocalRandom.current().nextDouble() < 0.9) { if (ThreadLocalRandom.current().nextBoolean()) { throw new RuntimeException("no go 1"); } else { e.stop(new RuntimeException("no go 2")); } } else { e.accept(e.get() + 1); } }; final PipelineBuilder<Integer, Integer> builder = p -> p.peek(System.out::println) .addParallelStep("retryStep_1", retry(step, i -> 10L), merger()).peek(System.out::println) .addParallelStep("retryStep_2", retry(step, i -> 10L), Integer::sum).peek(System.out::println) .addParallelStep("retryStep_3", retry(step, i -> 10L), Integer::sum).peek(System.out::println) .addParallelStep("retryStep_4", retry(step, i -> 10L), Integer::sum).peek(System.out::println) .addParallelStep("retryStep_5", retry(step, i -> 10L), Integer::sum).peek(System.out::println) .addParallelStep("retryStep_6", retry(step, i -> 10L), Integer::sum).peek(System.out::println) .addParallelStep("retryStep_7", retry(step, i -> 10L), Integer::sum).peek(System.out::println) .addParallelStep("retryStep_8", retry(step, i -> 10L), Integer::sum).peek(System.out::println) .addParallelStep("retryStep_9", retry(step, i -> 10L), Integer::sum).peek(System.out::println) .join().peek(System.out::println); try (final Pipeline<Integer, Integer> pipeline = Pipeline.build("testRetryPar", builder, PIPELINE_EXECUTOR)) { final Future<Integer> f = pipeline.execute(1); final int r = f.get(); Assert.assertEquals("testRetryPar", 18, r); } } @org.junit.Test public void testOrder() throws Exception { final PipelineBuilder<Integer, Integer> builder = p -> p.peek(System.out::println) .addOrderedStep("ordered", OrderStep.INSTANCE).peek(System.out::println); try (final Pipeline<Integer, Integer> pipeline = Pipeline.build("testOrder", builder, PIPELINE_EXECUTOR)) { final int count = 100; final List<Future<Integer>> fs = new ArrayList<>(); for (int i = 0; i < count; i++) { fs.add(pipeline.execute(i)); } for (int i = 0; i < count; i++) { final Future<Integer> f = fs.get(i); final int r = f.get(); Assert.assertEquals("testOrder", i, r); } } } @org.junit.Test public void testOrderBuilder() throws Exception { final PipelineBuilder<Integer, Integer> step = p -> p.peek(System.out::println) .addStep("step_1", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_2", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_3", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_4", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_5", OrderStep.INSTANCE).peek(System.out::println); final PipelineBuilder<Integer, Integer> builder = p -> p.peek(System.out::println) .buildOrderedStep("ordered", step).peek(System.out::println); try (final Pipeline<Integer, Integer> pipeline = Pipeline.build("testOrderBuilder", builder, PIPELINE_EXECUTOR)) { final int count = 100; final List<Future<Integer>> fs = new ArrayList<>(); for (int i = 0; i < count; i++) { fs.add(pipeline.execute(i)); } for (int i = 0; i < count; i++) { final Future<Integer> f = fs.get(i); final int r = f.get(); Assert.assertEquals("testOrderBuilder", i, r); } } } @org.junit.Test public void testOrderPartitionBuilder() throws Exception { final PipelineBuilder<Integer, Integer> step = p -> p.peek(System.out::println) .addStep("step_1", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_2", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_3", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_4", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_5", OrderStep.INSTANCE).peek(System.out::println); final int numOfPartitions = 20; final List<PipelineBuilder<Integer, Integer>> partitions = new ArrayList<>(numOfPartitions); for (int i = 0; i < numOfPartitions; i++) { final String name = "ordered_" + (i + 1); final PipelineBuilder<Integer, Integer> partition = p -> p.peek(System.out::println) .buildOrderedStep(name, step).peek(System.out::println); partitions.add(partition); } final PipelineBuilder<Integer, Integer> builder = p -> p.peek(System.out::println) .buildSwitchStep("switch", i -> Math.abs(i) % numOfPartitions, partitions).peek(System.out::println); try (final Pipeline<Integer, Integer> pipeline = Pipeline.build("testOrderPartitionBuilder", builder, PIPELINE_EXECUTOR)) { final int count = 100; final List<Future<Integer>> fs = new ArrayList<>(); for (int i = 0; i < count; i++) { fs.add(pipeline.execute(i)); } for (int i = 0; i < count; i++) { final Future<Integer> f = fs.get(i); final int r = f.get(); Assert.assertEquals("testOrderPartitionBuilder", i, r); } } } @org.junit.Test public void testUnorder() throws Exception { final PipelineBuilder<Integer, Integer> builder = p -> p.peek(System.out::println) .addStep("unordered", OrderStep.INSTANCE).peek(System.out::println); try (final Pipeline<Integer, Integer> pipeline = Pipeline.build("testUnorder", builder, PIPELINE_EXECUTOR)) { final int count = 100; final List<Future<Integer>> fs = new ArrayList<>(); for (int i = 0; i < count; i++) { fs.add(pipeline.execute(i)); } for (int i = 0; i < count; i++) { final Future<Integer> f = fs.get(i); final int r = f.get(); Assert.assertEquals("testUnorder", i, r); } } } @org.junit.Test public void testUnorderBuilder() throws Exception { final PipelineBuilder<Integer, Integer> step = p -> p.peek(System.out::println) .addStep("step_1", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_2", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_3", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_4", OrderStep.INSTANCE).peek(System.out::println) .addStep("step_5", OrderStep.INSTANCE).peek(System.out::println); final PipelineBuilder<Integer, Integer> builder = p -> p.peek(System.out::println) .buildStep("unordered", step).peek(System.out::println); try (final Pipeline<Integer, Integer> pipeline = Pipeline.build("testUnorderBuilder", builder, PIPELINE_EXECUTOR)) { final int count = 100; final List<Future<Integer>> fs = new ArrayList<>(); for (int i = 0; i < count; i++) { fs.add(pipeline.execute(i)); } for (int i = 0; i < count; i++) { final Future<Integer> f = fs.get(i); final int r = f.get(); Assert.assertEquals("testUnorderBuilder", i, r); } } } private static final class IntToLongStep implements PipelineStep<Integer, Long>, Runnable { private static final IntToLongStep INSTANCE = new IntToLongStep(); private final PipelineEntry<Integer, Long> entry; private IntToLongStep() { this(null); } private IntToLongStep(final PipelineEntry<Integer, Long> entry) { this.entry = entry; } private static void exec(final PipelineEntry<Integer, Long> entry) { final int input = entry.get(); final long result = input * 2L; entry.accept(result); } @Override public final void process(final PipelineEntry<Integer, Long> entry) { exec(entry); } @Override public final void run() { exec(this.entry); } } private static final class LongToDoubleStep implements PipelineStep<Long, Double> { private static final LongToDoubleStep INSTANCE = new LongToDoubleStep(); @Override public final void process(final PipelineEntry<Long, Double> entry) { final long input = entry.get(); final double result = input * 2.0; entry.accept(result); } } private static final class IntToLongForkStep implements PipelineStep<Integer, Long> { private static final IntToLongForkStep INSTANCE = new IntToLongForkStep(); @Override public final void process(final PipelineEntry<Integer, Long> entry) { AUX_EXECUTOR.execute(() -> IntToLongStep.INSTANCE.process(entry)); } } private static final class LongToDoubleForkStep implements PipelineStep<Long, Double> { private static final LongToDoubleForkStep INSTANCE = new LongToDoubleForkStep(); @Override public final void process(final PipelineEntry<Long, Double> entry) { AUX_EXECUTOR.execute(() -> LongToDoubleStep.INSTANCE.process(entry)); } } private static final class EvenStep implements PipelineStep<Integer, Boolean> { private static final EvenStep INSTANCE = new EvenStep(); @Override public final void process(final PipelineEntry<Integer, Boolean> entry) { AUX_EXECUTOR.execute(() -> { if (entry.get() % 2 != 0) { entry.stop(new AppException("Not even")); } else { entry.accept(true); } }); } } private static final class OddStep implements PipelineStep<Integer, Boolean> { private static final OddStep INSTANCE = new OddStep(); @Override public final void process(final PipelineEntry<Integer, Boolean> entry) { AUX_EXECUTOR.execute(() -> { if (entry.get() % 2 != 1) { entry.stop(new AppException("Not odd")); } else { entry.accept(false); } }); } } private static final class IncrementStep implements PipelineStep<Integer, Integer> { private static final IncrementStep INSTANCE = new IncrementStep(); @Override public final void process(final PipelineEntry<Integer, Integer> entry) { AUX_EXECUTOR.execute(() -> entry.accept(entry.get() + 1)); } } private static final class OrderStep implements PipelineStep<Integer, Integer> { private static final OrderStep INSTANCE = new OrderStep(); @Override public final void process(final PipelineEntry<Integer, Integer> entry) { if (ThreadLocalRandom.current().nextDouble() < 0.7) { if (ThreadLocalRandom.current().nextBoolean()) { entry.retry(100, TimeUnit.MILLISECONDS); } else { entry.accept(entry.get(), 100, TimeUnit.MILLISECONDS); } } else { entry.accept(entry.get()); } } } }
48.254821
178
0.597066
0a946f7741e8095592bb70785bcc3de28db399fc
1,511
package bg.bas.iinf.sinus.wicket.model.owl; import java.net.URI; import org.apache.wicket.model.LoadableDetachableModel; import org.semanticweb.owlapi.model.OWLNamedObject; import org.semanticweb.owlapi.model.OWLObject; import bg.bas.iinf.sinus.cache.CacheFactory; import bg.bas.iinf.sinus.cache.CacheWrapper; /** * LDM za OWLNamedObject * @author hok * */ public class OWLNamedObjectLDM<T extends OWLNamedObject> extends LoadableDetachableModel<T> { private static final long serialVersionUID = 5013539617348090497L; private URI uri; public OWLNamedObjectLDM(T object) { super(object); if (object != null) { this.uri = object.getIRI().toURI(); CacheWrapper<URI, OWLObject> cache = CacheFactory.getCache(); cache.put(uri, object); } } public OWLNamedObjectLDM(URI uri) { super(); this.uri = uri; } public OWLNamedObjectLDM() { super(); } @Override public void setObject(T object) { super.setObject(object); CacheWrapper<URI, OWLObject> cache = CacheFactory.getCache(); cache.put(uri, object); this.uri = object.getIRI().toURI(); } @SuppressWarnings("unchecked") @Override protected T load() { if (uri == null) { return null; } CacheWrapper<URI, OWLObject> cache = CacheFactory.getCache(); return (T) cache.get(uri); } public URI getUri() { return uri; } public void setUri(URI uri) { this.uri = uri; } }
21.898551
94
0.65321
f97105f320eeda63561103376ed472cb1da535c7
1,639
package de.team7.swt.checkout.presentation; import de.team7.swt.checkout.model.OrderCompletionFailure; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; /** * Middleware for catching exceptions and transforming them into meaningful HTTP responses. * * @author Vincent Nadoll */ @ControllerAdvice @Order(Ordered.HIGHEST_PRECEDENCE) class CheckoutHttpExceptionHandler extends ResponseEntityExceptionHandler { /** * Catches the {@link OrderCompletionFailure} and writes its underlying * {@link de.team7.swt.checkout.application.OrderCompletionReport} to the response body. * * @param ex caught {@link OrderCompletionFailure} * @param request current {@link WebRequest} * @return 409 Conflict - meaningful failed {@link de.team7.swt.checkout.application.OrderCompletionReport} */ @ExceptionHandler(OrderCompletionFailure.class) protected ResponseEntity<Object> handleFailedOrderCompletion(OrderCompletionFailure ex, WebRequest request) { HttpHeaders headers = new HttpHeaders(); HttpStatus status = HttpStatus.OK; return handleExceptionInternal(ex, ex.getReport(), headers, status, request); } }
43.131579
113
0.790116
895099d7311b59c33546705fb9dc7f3a467e8c39
7,341
/** */ package CIM15.IEC61970.Domain; import java.util.Date; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Date Time Interval</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link CIM15.IEC61970.Domain.DateTimeInterval#getStart <em>Start</em>}</li> * <li>{@link CIM15.IEC61970.Domain.DateTimeInterval#getEnd <em>End</em>}</li> * </ul> * </p> * * @generated */ public class DateTimeInterval extends MinimalEObjectImpl.Container implements EObject { /** * The default value of the '{@link #getStart() <em>Start</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStart() * @generated * @ordered */ protected static final Date START_EDEFAULT = null; /** * The cached value of the '{@link #getStart() <em>Start</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStart() * @generated * @ordered */ protected Date start = START_EDEFAULT; /** * This is true if the Start attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean startESet; /** * The default value of the '{@link #getEnd() <em>End</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEnd() * @generated * @ordered */ protected static final Date END_EDEFAULT = null; /** * The cached value of the '{@link #getEnd() <em>End</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEnd() * @generated * @ordered */ protected Date end = END_EDEFAULT; /** * This is true if the End attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean endESet; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DateTimeInterval() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return DomainPackage.Literals.DATE_TIME_INTERVAL; } /** * Returns the value of the '<em><b>Start</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Start</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Start</em>' attribute. * @see #isSetStart() * @see #unsetStart() * @see #setStart(Date) * @generated */ public Date getStart() { return start; } /** * Sets the value of the '{@link CIM15.IEC61970.Domain.DateTimeInterval#getStart <em>Start</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Start</em>' attribute. * @see #isSetStart() * @see #unsetStart() * @see #getStart() * @generated */ public void setStart(Date newStart) { start = newStart; startESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61970.Domain.DateTimeInterval#getStart <em>Start</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetStart() * @see #getStart() * @see #setStart(Date) * @generated */ public void unsetStart() { start = START_EDEFAULT; startESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61970.Domain.DateTimeInterval#getStart <em>Start</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Start</em>' attribute is set. * @see #unsetStart() * @see #getStart() * @see #setStart(Date) * @generated */ public boolean isSetStart() { return startESet; } /** * Returns the value of the '<em><b>End</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>End</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>End</em>' attribute. * @see #isSetEnd() * @see #unsetEnd() * @see #setEnd(Date) * @generated */ public Date getEnd() { return end; } /** * Sets the value of the '{@link CIM15.IEC61970.Domain.DateTimeInterval#getEnd <em>End</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>End</em>' attribute. * @see #isSetEnd() * @see #unsetEnd() * @see #getEnd() * @generated */ public void setEnd(Date newEnd) { end = newEnd; endESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61970.Domain.DateTimeInterval#getEnd <em>End</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetEnd() * @see #getEnd() * @see #setEnd(Date) * @generated */ public void unsetEnd() { end = END_EDEFAULT; endESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61970.Domain.DateTimeInterval#getEnd <em>End</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>End</em>' attribute is set. * @see #unsetEnd() * @see #getEnd() * @see #setEnd(Date) * @generated */ public boolean isSetEnd() { return endESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case DomainPackage.DATE_TIME_INTERVAL__START: return getStart(); case DomainPackage.DATE_TIME_INTERVAL__END: return getEnd(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case DomainPackage.DATE_TIME_INTERVAL__START: setStart((Date)newValue); return; case DomainPackage.DATE_TIME_INTERVAL__END: setEnd((Date)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case DomainPackage.DATE_TIME_INTERVAL__START: unsetStart(); return; case DomainPackage.DATE_TIME_INTERVAL__END: unsetEnd(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case DomainPackage.DATE_TIME_INTERVAL__START: return isSetStart(); case DomainPackage.DATE_TIME_INTERVAL__END: return isSetEnd(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (start: "); if (startESet) result.append(start); else result.append("<unset>"); result.append(", end: "); if (endESet) result.append(end); else result.append("<unset>"); result.append(')'); return result.toString(); } } // DateTimeInterval
23.378981
127
0.612723
5ad87a1987a1884d4cb0237a2db4b0e5eadf6203
126
package noppes.npcs.blocks.tiles; import net.minecraft.util.AxisAlignedBB; public class TileSign extends TileBanner { }
12.6
42
0.785714
939ef5724f3b79d992a66a509055ea2579a5157b
1,994
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.gradle.project.build.attribution; import com.intellij.execution.filters.Filter; import com.intellij.execution.filters.HyperlinkInfo; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.project.Project; import java.util.Collections; import org.jetbrains.annotations.NotNull; public class BuildAttributionOutputLinkFilter implements Filter { public static final String LINK_TEXT = "Build Analyzer"; public static final String INSIGHTS_AVAILABLE_LINE = "Build Analyzer results available"; @Override public Result applyFilter(@NotNull String line, int entireLength) { int lineStart = entireLength - line.length(); if (line.contains(INSIGHTS_AVAILABLE_LINE)) { int index = line.indexOf(LINK_TEXT); if (index != -1) { return new Result(Collections.singletonList(createLink(lineStart + index, lineStart + index + LINK_TEXT.length()))); } } return null; } @NotNull private static ResultItem createLink(int start, int end) { return new ResultItem(start, end, getHyperLinkInfo()); } @NotNull private static HyperlinkInfo getHyperLinkInfo() { return new HyperlinkInfo() { @Override public void navigate(Project project) { ServiceManager.getService(project, BuildAttributionManager.class).openResultsTab(); } }; } }
34.982456
124
0.740221
291e674a4468babba7e68ccecfb440c7457e4279
2,941
package org.commcare.adapters; import android.app.Activity; import org.commcare.cases.entity.Entity; import org.commcare.cases.entity.NodeEntityFactory; import org.javarosa.core.model.instance.TreeReference; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; /** * Filter (and order) entities by those whose 'extra key', most likely case id, * is present in the provided ordered key set * * @author Phillip Mates (pmates@dimagi.com). */ public class EntityKeyFilterer extends EntityFiltererBase { private final LinkedHashSet<String> orderedKeySet; /** * @param orderedKeySet Keys that are used to filter and order the Entity * list based on the entity's 'extra key' field */ public EntityKeyFilterer(EntityListAdapter adapter, NodeEntityFactory nodeFactory, List<Entity<TreeReference>> fullEntityList, Activity context, LinkedHashSet<String> orderedKeySet) { super(context, nodeFactory, adapter, fullEntityList); this.orderedKeySet = orderedKeySet; } @Override protected void filter() { if (isCancelled() || orderedKeySet.isEmpty()) { return; } // Add entities whose extra keys are in the key set, preserving key set // ordering. Don't assume one-to-one correspondence between entities // and keys: depending on the appliciation we might want to attach the // same data to multiple entities HashMap<String, List<Entity<TreeReference>>> keyToEntitiesMap = buildKeyToEntitiesMap(fullEntityList); for (String key : orderedKeySet) { if (keyToEntitiesMap.containsKey(key)) { matchList.addAll(keyToEntitiesMap.get(key)); } } } /** * Group entities by their 'extra key' field * * @return A map from 'extra key' values to a list of entities that have * that 'extra key' */ private static HashMap<String, List<Entity<TreeReference>>> buildKeyToEntitiesMap(List<Entity<TreeReference>> entityList) { // NOTE PLM: potentially expensive in presence of large entity set; // could build at entity load time or forgoe ordering or constrain the // key to entity mapping to be one-to-one HashMap<String, List<Entity<TreeReference>>> keyToEntitiesMap = new HashMap<>(); for (Entity<TreeReference> entity : entityList) { if (keyToEntitiesMap.containsKey(entity.extraKey)) { keyToEntitiesMap.get(entity.extraKey).add(entity); } else { ArrayList<Entity<TreeReference>> list = new ArrayList<>(); list.add(entity); keyToEntitiesMap.put(entity.extraKey, list); } } return keyToEntitiesMap; } }
37.705128
127
0.644679
b5367db24e652362a1981f18c2c146d23e5dfbe6
367
package io.quarkus.resteasy.reactive.server.test.multipart; import java.io.File; import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.PartType; import org.jboss.resteasy.reactive.RestForm; public class MultipartOutputFileResponse { @RestForm String name; @RestForm @PartType(MediaType.APPLICATION_OCTET_STREAM) File file; }
19.315789
59
0.773842
b0b49a9ad6775546d084d2d1c2d04f63c1a44b87
2,624
package com.mvc.timemachine.models; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="users") public class User extends BaseEntity<Long>{ @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "email", length = 100, nullable = false, unique = true) private String email; @Column(name = "user_name", length = 100, nullable = false) private String username; @Column(name = "password", length = 255) private String password; @Enumerated(EnumType.STRING) @Column(name = "sign_in_provider", length = 20) private SocialMediaService signInProvider; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user") private List<Comment> comments = new ArrayList<>(); @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user") private List<Post> posts = new ArrayList<>(); @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user") private List<Like> likes = new ArrayList<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } public List<Post> getPosts() { return posts; } public void setPosts(List<Post> posts) { this.posts = posts; } public List<Like> getLikes() { return likes; } public void setLikes(List<Like> likes) { this.likes = likes; } public String getEmail() { return email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public void setEmail(String email) { this.email = email; } public void setSignInProvider(SocialMediaService signInProvider) { this.signInProvider = signInProvider; } public String getPassword() { return password; } public void setPassword(String pass) { password = pass; } public SocialMediaService getSignInProvider() { return signInProvider; } @Override public String toString() { return "Post{" + "id=" + id + ", email='" + email + '\'' + ", username='" + username + '\'' + '}'; } }
20.661417
81
0.704268
0ba50b4dcbaa2a391d632319db14cde498eb88fc
3,903
package com.capstone.AninPringleOfori.dao; import com.capstone.AninPringleOfori.model.item.Item; import com.capstone.AninPringleOfori.model.item.TShirt; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; @Repository public class TShirtDaoImpl implements TShirtDao { private static final String ADD_TSHIRT_SQL = "insert into t_shirt(size, color, description, price, orderQuantity) values (?, ?, ?, ?, ?)"; private static final String DELETE_TSHIRT_SQL = "delete from t_shirt where t_shirt_id = ?"; private static final String FIND_TSHIRT_BY_ID_SQL = "select * from t_shirt where t_shirt_id = ?"; private static final String UPDATE_TSHIRT_SQL = "update t_shirt set size = ?, color = ?, description = ?, price =?, orderQuantity = ? where t_shirt_id = ?"; private static final String FIND_ALL_TSHIRTS_SQL = "select * from t_shirt"; private static final String FIND_BY_COLOR_SQL = "select * from t_shirt where color = ?"; private static final String FIND_BY_SIZE_SQL = "select * from t_shirt where size = ?"; JdbcTemplate jdbcTemplate; @Autowired public TShirtDaoImpl(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public TShirt addtShirt(TShirt tShirt) { jdbcTemplate.update(ADD_TSHIRT_SQL, tShirt.getSize(), tShirt.getColor(), tShirt.getDescription(), tShirt.getPrice(), tShirt.getOrderQuantity()); int id = jdbcTemplate.queryForObject("select last_insert_id()", Integer.class); tShirt.setId(id); return tShirt; } @Override public void deletetShirt(int id) { jdbcTemplate.update(DELETE_TSHIRT_SQL, id); } @Override public void updatetShirt(TShirt tShirt) { jdbcTemplate.update(UPDATE_TSHIRT_SQL, tShirt.getSize(), tShirt.getColor(), tShirt.getDescription(), tShirt.getPrice(), tShirt.getOrderQuantity(), tShirt.getId()); } @Override public List<TShirt> findAlltShirts() { return jdbcTemplate.query(FIND_ALL_TSHIRTS_SQL, this::mapRowTotShirt); } @Override public TShirt findById(int id) { try { return jdbcTemplate.queryForObject(FIND_TSHIRT_BY_ID_SQL, this::mapRowTotShirt, id); } catch (EmptyResultDataAccessException e) { throw new IllegalArgumentException("T-shirt with specified ID not found."); } } @Override public List<TShirt> findtShirtByColor(String color) { return jdbcTemplate.query(FIND_BY_COLOR_SQL, this::mapRowTotShirt, color); } @Override public List<TShirt> findtShirtBySize(String size) { return jdbcTemplate.query(FIND_BY_SIZE_SQL, this::mapRowTotShirt, size); } private TShirt mapRowTotShirt(ResultSet resultSet, int rowNum) throws SQLException { return new TShirt(resultSet.getInt("t_shirt_id"), resultSet.getString("size"), resultSet.getString("color"), resultSet.getString("description"), resultSet.getDouble("price"), resultSet.getInt("orderQuantity")); } @Override public void decrementQuantity(Item item, int orderQuantity) { if (orderQuantity > item.getOrderQuantity()) { throw new IllegalArgumentException(String.format("Order orderQuantity cannot be greater than %s", item.getOrderQuantity())); } item.setOrderQuantity(item.getOrderQuantity() - orderQuantity); updatetShirt((TShirt) item); } }
37.893204
160
0.674609
60cd300bd70b0505af3571ca24fb1e4700293c09
1,303
package com.clean.architecture.infra.factory; import com.clean.architecture.domain.factory.AbstractRepositoryFactory; import com.clean.architecture.domain.repository.CouponRepository; import com.clean.architecture.domain.repository.ItemRepository; import com.clean.architecture.domain.repository.OrderRepository; import com.clean.architecture.infra.database.DatabaseConnector; import com.clean.architecture.infra.repository.database.CouponRepositoryDatabase; import com.clean.architecture.infra.repository.database.ItemRepositoryDatabase; import com.clean.architecture.infra.repository.database.OrderRepositoryDatabase; public class DatabaseRepositoryFactory implements AbstractRepositoryFactory { private final DatabaseConnector databaseConnector; public DatabaseRepositoryFactory(DatabaseConnector databaseConnector) { this.databaseConnector = databaseConnector; } @Override public ItemRepository createItemRepository() { return new ItemRepositoryDatabase(databaseConnector); } @Override public CouponRepository createCuponRepository() { return new CouponRepositoryDatabase(databaseConnector); } @Override public OrderRepository createOrderRepository() { return new OrderRepositoryDatabase(databaseConnector); } }
37.228571
81
0.815042
8ba5cc75bd509043013c019e9282c8e89e13ab13
26,230
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2014 Edgar Espina * * 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.jooby.apitool.raml; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.inject.internal.MoreTypes; import io.swagger.converter.ModelConverters; import io.swagger.models.Model; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.PropertyBuilder; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; import io.swagger.models.properties.UUIDProperty; import org.jooby.MediaType; import org.jooby.apitool.RouteMethod; import org.jooby.apitool.RouteParameter; import org.jooby.apitool.RouteResponse; import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.EnumMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; /** * RAML objects for describing a RAML definition file. This is a partial representation of the RAML * specification. * * @since 1.2.0 * @author edgar */ public class Raml { private String title; private String version; private String baseUri; private List<String> mediaType; private List<String> protocols; private Map<String, RamlType> types; private Map<String, RamlPath> resources = new LinkedHashMap<>(); /** * RAML title. * * @return RAML title. */ public String getTitle() { return title; } /** * Set RAML title. * * @param title RAML title. */ public void setTitle(final String title) { this.title = title; } /** * RAML version. * * @return RAML version. */ public String getVersion() { return version; } /** * Set RAML version. * * @param version RAML version. */ public void setVersion(final String version) { this.version = version; } /** * RAML base uri. * * @return RAML base uri. */ public String getBaseUri() { return baseUri; } /** * Set base uri. * * @param baseUri Base uri. */ public void setBaseUri(final String baseUri) { this.baseUri = baseUri; } /** * Get media types. * * @return Media types. */ public List<String> getMediaType() { return mediaType; } /** * Set media types. * * @param mediaType Media types. */ public void setMediaType(final List<String> mediaType) { this.mediaType = mediaType; } /** * Get protocols. * * @return Protocols. */ public List<String> getProtocols() { return protocols; } /** * Set protocols. * * @param protocols Protocols. */ public void setProtocols(final List<String> protocols) { this.protocols = protocols; } /** * RAML types. * * @return RAML types. */ public Map<String, RamlType> getTypes() { return types; } /** * Get resources. * * @return Resources. */ @JsonAnyGetter public Map<String, RamlPath> getResources() { return resources; } /** * Get a path for the given pattern. If the path doesn't exist, a new path will be created. * * @param pattern Pattern. * @return Path for the given pattern. */ public RamlPath path(String pattern) { RamlPath path = resources.get(pattern); if (path == null) { path = new RamlPath(); resources.put(pattern, path); } return path; } /** * Define/map a custom Java type to RAML type. * * <pre> * RamlType uuid = raml.define(UUID.class, RamlType.STRING); * uuid.setPattern("..."); * </pre> * * @param javaType Java type. * @param baseType RAML base type. * @return New RAML type. */ public RamlType define(Type javaType, RamlType baseType) { Objects.requireNonNull(javaType, "Java type required."); Objects.requireNonNull(baseType, "Raml type required."); if (types == null) { types = new LinkedHashMap<>(); } String typeName = MoreTypes.getRawType(javaType).getSimpleName(); RamlType ramlType = new RamlType(baseType.getType(), typeName); types.put(typeName, ramlType); return ramlType; } /** * Register a Java type and produces an equivalent RAML type. It returns an existing RAML type if * the Java type was registered already. * * @param type Java type. * @return RAML type. */ public RamlType define(Type type) { if (types == null) { types = new LinkedHashMap<>(); } Type componentType = componentType(type); String typeName = MoreTypes.getRawType(componentType).getSimpleName(); RamlType ramlType = RamlType.valueOf(typeName); if (ramlType.isObject()) { RamlType existing = types.get(typeName); if (existing == null) { ModelConverters converter = ModelConverters.getInstance(); Property property = converter.readAsProperty(componentType); Map<PropertyBuilder.PropertyId, Object> args = new EnumMap<>( PropertyBuilder.PropertyId.class); for (Map.Entry<String, Model> entry : converter.readAll(componentType).entrySet()) { define(entry.getKey(), entry.getValue()); } ramlType = define(typeName, PropertyBuilder.toModel(PropertyBuilder.merge(property, args))); } else { ramlType = existing; } } return type != componentType ? ramlType.toArray() : ramlType; } private Type componentType(final Type type) { Class<?> rawType = MoreTypes.getRawType(type); if (rawType.isArray()) { return rawType.getComponentType(); } if (Collection.class.isAssignableFrom(rawType) && type instanceof ParameterizedType) { return ((ParameterizedType) type).getActualTypeArguments()[0]; } return type; } private RamlType define(final String type, final Model model) { RamlType definition = types.get(type); if (definition == null) { RamlType object = new RamlType("object", type); types.put(type, object); Map<String, Object> example = new LinkedHashMap<>(); Optional.ofNullable(model.getProperties()) .ifPresent(properties -> properties.forEach((name, property) -> { if (property instanceof RefProperty) { String propertyType = propertyType(property); object.newProperty(name, propertyType, false); } else if (property instanceof ArrayProperty) { String propertyType = propertyType(((ArrayProperty) property).getItems()) + "[]"; object.newProperty(name, propertyType, false); } else { String propertyType = propertyType(property); List<String> enums = null; if (property instanceof StringProperty) { enums = ((StringProperty) property).getEnum(); } RamlType ramlType = RamlType.valueOf(propertyType); // String propertyType = ramlType.isObject() ? property.getType() : ramlType.getType(); object.newProperty(name, propertyType, false, Optional.ofNullable(enums).map(it -> it.toArray(new String[it.size()])) .orElse(new String[0])); example.put(name, Optional.ofNullable(enums).<Object>map(it -> it.get(0)) .orElse(ramlType.getExample())); } })); definition = object; if (example.values().stream().filter(Objects::nonNull).count() > 0) { object.setExample(example); } } return definition; } private String propertyType(Property property) { if (property instanceof RefProperty) { return ((RefProperty) property).getSimpleRef(); } // Special handling for uuid type reported by Swagger converter String type = property.getType(); if (property instanceof UUIDProperty) { type = UUID.class.getSimpleName(); } RamlType ramlType = types.get(type); return ramlType == null ? property.getType() : ramlType.getRef().getType(); } /** * Set RAML paths. * * @param resources RAML paths. */ public void setResources(final Map<String, RamlPath> resources) { this.resources = resources; } /** * Convert this RAML object to Yaml. * * @return Yaml string. * @throws IOException If something goes wrong. */ public String toYaml() throws IOException { YAMLMapper mapper = new YAMLMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, false); mapper.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true); return "#%RAML 1.0\n" + mapper.writer().withDefaultPrettyPrinter().writeValueAsString(this); } /** * Build a {@link Raml} object from list of {@link RouteMethod}. * * @param base Base raml (might be null). * @param routes List of routes. * @return RAML object. */ public static Raml build(Raml base, List<RouteMethod> routes) { Raml raml = Optional.ofNullable(base).orElseGet(Raml::new); BiFunction<RamlPath, String, RamlPath> pathFactory = (path, segment) -> path == null ? raml.path(segment) : path.path(segment); BiConsumer<Function<String, RamlParameter>, RouteParameter> parameterFactory = (factory, parameter) -> { RamlParameter p = factory.apply(parameter.name()); p.setDescription(parameter.description() .map(Raml::yamlText) .orElse(null)); List<String> enums = parameter.enums(); if (enums.size() > 0) { p.setType(RamlType.STRING); p.setEnum(enums); } else { p.setType(raml.define(parameter.type())); } p.setRequired(!parameter.optional()); p.setDefault(parameter.defaultValue()); }; for (RouteMethod route : routes) { List<String> segments = Splitter.on("/") .trimResults() .omitEmptyStrings() .splitToList(route.pattern()); RamlPath path = null; for (String segment : segments) { RamlPath newPath = pathFactory.apply(path, "/" + segment); if (segment.startsWith("{") && segment.endsWith("}")) { String pathvar = segment.substring(1, segment.length() - 1); route.parameters().stream() .filter(it -> it.kind() == RouteParameter.Kind.PATH) .filter(it -> it.name().equals(pathvar)) .findFirst() .ifPresent(it -> parameterFactory.accept(newPath::uriParameter, it)); } path = newPath; } path = Optional.ofNullable(path).orElseGet(() -> raml.path("/")); path.setDescription(route.summary() .map(Raml::yamlText) .orElse(null)); RamlMethod method = path.method(route.method()); method.setDescription(route.description() .map(Raml::yamlText) .orElse(null)); /** Check for files, if we find one use multipart to render them: */ List<RouteParameter> files = route.parameters().stream() .filter(it -> it.kind() == RouteParameter.Kind.FILE) .collect(Collectors.toList()); if (files.size() > 0) { route.parameters().stream() .filter(it -> it.kind() == RouteParameter.Kind.QUERY) .forEach(it -> parameterFactory.accept(method::formParameter, it)); files.forEach(it -> { parameterFactory.accept(method::formParameter, it); method.setMediaType(ImmutableList.of(MediaType.multipart.name())); }); } else { route.parameters().stream() .filter(it -> it.kind() == RouteParameter.Kind.QUERY) .forEach(it -> parameterFactory.accept(method::queryParameter, it)); } /** Headers: */ route.parameters().stream() .filter(it -> it.kind() == RouteParameter.Kind.HEADER) .forEach(it -> parameterFactory.accept(method::headerParameter, it)); /** Body: */ route.parameters().stream() .filter(it -> it.kind() == RouteParameter.Kind.BODY) .forEach(it -> { method.setMediaType(route.consumes()); method.setBody(raml.define(it.type())); }); /** Response: */ RouteResponse returns = route.response(); Map<Integer, String> status = returns.status(); Integer statusCode = returns.statusCode(); RamlResponse response = method.response(statusCode); response.setDescription(yamlText(returns.description().orElse(status.get(statusCode)))); if (route.produces().size() > 0) { route.produces().forEach(type -> response.setMediaType(type, raml.define(returns.type()))); } else { response.setMediaType(null, raml.define(returns.type())); } status.entrySet().stream() .filter(it -> !statusCode.equals(it.getKey())) .forEach(it -> method.response(it.getKey()).setDescription(it.getValue())); } /** Default consumes/produces: */ Set<String> alltypes = new LinkedHashSet<>(); Consumer<Function<RouteMethod, List<String>>> mediaTypes = types -> routes.stream().forEach(r -> types.apply(r).forEach(alltypes::add)); mediaTypes.accept(RouteMethod::consumes); mediaTypes.accept(RouteMethod::produces); if (alltypes.size() == 0) { raml.setMediaType(ImmutableList.of(MediaType.json.name())); } else if (alltypes.size() == 1) { raml.setMediaType(ImmutableList.of(alltypes.iterator().next())); } return raml; } static String yamlText(String text) { return Optional.ofNullable(text).map(lines -> Splitter.on("\n") .trimResults() .omitEmptyStrings() .splitToList(lines) .stream() .collect(Collectors.joining("\n")) ).orElse(null); } }
39.802731
108
0.665498
dfbd1791d66e37ab2287ca598dc5e8fc0e6870a5
268
package com.gathermall.product.dao; import com.gathermall.product.entity.SpuInfoDesc; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; @Mapper public interface SpuInfoDescDao extends BaseMapper<SpuInfoDesc> { }
22.333333
65
0.828358
907fe0266008608f79e65d0c7f0e3733ae09a2b3
664
import java.util.Scanner; /** * * @author Bruno */ public class Main { public static void main(String[] args) { Scanner ler= new Scanner(System.in); //instancia Vendedor v= new Vendedor(); //valores System.out.println("Digite as vendas de Março: "); v.vendasMarco= ler.nextDouble(); System.out.println("Digite as vendas de Abril: "); v.vendasAbril= ler.nextDouble(); //saída System.out.println("Dados: "+v.verDados()); System.out.println("Média: "+v.calcularMedia()); System.out.println("Classificar: "+v.classificar()); } }
24.592593
60
0.563253
7579e72d96279ed6a928c58f11c0c195fe256f33
3,605
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; /** * This class reads bytes from a stream, creates consignments and * puts each consignment into a message * * Message Format (without in-between space) * RDT sequence_number payload CRLF, or * RDT sequence_number payload END_CRLF, or * * @author eekian */ public class MessageFactory { public static int CONSIGNMENT = 512; public static int HEX_PER_LINE = 512; public static byte[] RDT = new byte[] { 0x52, 0x44, 0x54 }; public static byte[] SEQ_0 = new byte[] { 0x0 }; public static byte[] END = new byte[] { 0x45, 0x4e, 0x44 }; public static byte[] CRLF = new byte[] { 0x0a, 0x0d }; byte count = 0; public String fileName; MessageFactory(String s) { fileName = s; } public byte[] doIt(int skipBytes) { FileInputStream myFIS = null; byte[] myData = new byte[CONSIGNMENT]; byte[] myLastData; byte[] myMsg = null; int bytesRead = 0; int i; // counter for copying bytes in array try { myFIS = new FileInputStream(fileName); myFIS.skip(skipBytes*512); bytesRead = myFIS.read(myData); //System.out.println("bytesRead : " + bytesRead); if (bytesRead > -1) { //printBytesAsHex(myData); //System.out.println("data consignment has " + bytesRead + " bytes"); if (bytesRead < CONSIGNMENT) { // last consignment // make a special byte array that exactly fits the number of bytes read // otherwise, the consignment may be padded with junk data myLastData = new byte[bytesRead]; for (i=0; i<bytesRead; i++) { myLastData[i] = myData[i]; } myMsg = concatenateByteArrays(RDT, SEQ_0, myLastData, END, CRLF); } else { myMsg = concatenateByteArrays(RDT, SEQ_0, myData, CRLF); } SEQ_0[0] += 0x1; // prepare to send, concat bytes //printBytesAsHex(myMsg); //System.out.println("message has " + myMsg.length + " bytes"); } } /*catch (FileNotFoundException ex1) { System.out.println(ex1.getMessage()); } */catch (IOException ex) { System.out.println(ex.getMessage()); }finally { /*try { myFIS.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); } */ return myMsg; } } public static byte[] concatenateByteArrays(byte[] a, byte[] b, byte[] c, byte[] d) { byte[] result = new byte[a.length + b.length + c.length + d.length]; System.arraycopy(a, 0, result, 0, a.length); System.arraycopy(b, 0, result, a.length, b.length); System.arraycopy(c, 0, result, a.length+b.length, c.length); System.arraycopy(d, 0, result, a.length+b.length+c.length, d.length); return result; } public static byte[] concatenateByteArrays(byte[] a, byte[] b, byte[] c, byte[] d, byte[] e) { byte[] result = new byte[a.length + b.length + c.length + d.length + e.length]; System.arraycopy(a, 0, result, 0, a.length); System.arraycopy(b, 0, result, a.length, b.length); System.arraycopy(c, 0, result, a.length+b.length, c.length); System.arraycopy(d, 0, result, a.length+b.length+c.length, d.length); System.arraycopy(e, 0, result, a.length+b.length+c.length+d.length, e.length); return result; } }
32.772727
98
0.595007
cf4671f62e8857502964c3c06861f6ab59caa65f
1,980
/* * Copyright (c) 2020-2021 Chuntung Ho. Some rights reserved. */ package com.chuntung.payment.dto; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class PayQueryResult implements Serializable { private static final long serialVersionUID = 8756471524183185831L; private PayStateEnum state; // 是否有退款 private Boolean refunded; // 第三方交易号 private String tradeNo; // 支付完成时间 private Date tradeTime; // 本地请求号 private String requestNo; // 支付金额 private BigDecimal amount; public PayStateEnum getState() { return state; } public void setState(PayStateEnum state) { this.state = state; } public Boolean getRefunded() { return refunded; } public void setRefunded(Boolean refunded) { this.refunded = refunded; } public String getTradeNo() { return tradeNo; } public void setTradeNo(String tradeNo) { this.tradeNo = tradeNo; } public Date getTradeTime() { return tradeTime; } public void setTradeTime(Date tradeTime) { this.tradeTime = tradeTime; } public String getRequestNo() { return requestNo; } public void setRequestNo(String requestNo) { this.requestNo = requestNo; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } @Override public String toString() { final StringBuilder sb = new StringBuilder("PayQueryResult{"); sb.append("state=").append(state); sb.append(", refunded=").append(refunded); sb.append(", tradeNo='").append(tradeNo).append('\''); sb.append(", tradeTime=").append(tradeTime); sb.append(", requestNo='").append(requestNo).append('\''); sb.append(", amount=").append(amount); sb.append('}'); return sb.toString(); } }
22.5
70
0.623232
89b108c5912b7e1285c43e9e053a8392b4addb37
1,256
/* * Copyright © 2015 - 2021 ReSys (info@dialob.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dialob.rule.parser.api; import org.jetbrains.annotations.NotNull; import java.util.function.UnaryOperator; public interface RuleExpressionCompiler { /** * * * @param expression * @param compilationResultListener * @return true is expression compilation was ok. * @deprecated @{see io.dialob.session.engine.program.ddrl.DDRLExpressionCompiler#compile} */ @Deprecated boolean compile(String expression, VariableFinder variableFinder, RuleExpressionCompilerCallback compilationResultListener); @NotNull UnaryOperator<String> createIdRenamer(String oldId, String newId); }
32.205128
128
0.73965
cb53494cf1a7b658d9344020ecb28aa0642fd93d
1,413
package utils; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; public class FileFilters { public static FileFilter directoryFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; public static FilenameFilter exceptionFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.equals("exception.json"); } }; public static FilenameFilter javaFilesFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".java"); } }; public static FilenameFilter annotatedScreenshotsFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return (name.contains("Annotated") && name.endsWith("png")); } }; public static FilenameFilter visualLocatorFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return (name.contains("visualLocator") && name.endsWith("png")); } }; public static FilenameFilter afterScreenshotsFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return (name.contains("2after") && name.endsWith("png")); } }; public static FilenameFilter beforeScreenshotsFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return (name.contains("1before") && name.endsWith("png")); } }; }
27.173077
81
0.721161
79fbbb22c3191757175b8f628e46e80a1b9a585d
1,014
public class Assignment { public static void main (String[] args){ double right = 6.0; double left = 10.0; double answer, a, b; System.out.println("A = " + left); System.out.println("B = " + right); // Assignment System.out.println("\nAssignment"); answer = left + right; System.out.println("A(" + left + ") + B(" + right + ") = " + answer); // Unary Operators System.out.println("\nUnary Operator"); a = left; b = right; System.out.println("A++ = " + a++); a = left; System.out.println("++A = " + ++a); System.out.println("B-- = " + b--); b = right; System.out.println("--B = " + --b); // Power function System.out.println("\nPower Function"); a = left; b = right; System.out.println("A^B = " + Math.pow(a, b)); } }
27.405405
55
0.431953
9081579158b9697aeb8c2f36c736a2fc8f6dc251
1,503
package edu.usfca.cs272; import java.nio.file.Path; import java.nio.file.PathMatcher; public class PathMatcherDemo { public static void main(String[] args) { Path hello = Path.of("hello.txt"); Path world = Path.of("txt.world"); PathMatcher anonClass = new PathMatcher() { @Override public boolean matches(Path p) { return p.toString().endsWith(".txt"); } }; System.out.println(hello + ": " + anonClass.matches(hello)); System.out.println(world + ": " + anonClass.matches(world)); System.out.println(); /* * * TODO * */ // PathMatcher verboseLambda = null; // System.out.println(hello + ": " + verboseLambda.matches(hello)); // System.out.println(world + ": " + verboseLambda.matches(world)); // System.out.println(); // PathMatcher compactLambda = null; // System.out.println(hello + ": " + compactLambda.matches(hello)); // System.out.println(world + ": " + compactLambda.matches(world)); // System.out.println(); // Predicate<Path> predicateLambda = null; // System.out.println(hello + ": " + predicateLambda.test(hello)); // System.out.println(world + ": " + predicateLambda.test(world)); // System.out.println(); // System.out.println(hello + ": " + varAnonClass.matches(hello)); // System.out.println(world + ": " + varAnonClass.matches(world)); // System.out.println(); // // System.out.println(hello + ": " + varLambda.test(hello)); // System.out.println(world + ": " + varLambda.test(world)); // System.out.println(); } }
27.327273
68
0.650699
dc44d8e4268cccd8394fb65f85315d6fd5b16e91
18,232
package us.ihmc.commonWalkingControlModules.trajectories; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Random; import org.junit.After; import org.junit.Test; import us.ihmc.continuousIntegration.ContinuousIntegrationAnnotations.ContinuousIntegrationTest; import us.ihmc.euclid.referenceFrame.FramePoint3D; import us.ihmc.euclid.referenceFrame.FramePose3D; import us.ihmc.euclid.referenceFrame.FrameQuaternion; import us.ihmc.euclid.referenceFrame.FrameVector3D; import us.ihmc.euclid.referenceFrame.ReferenceFrame; import us.ihmc.euclid.referenceFrame.tools.EuclidFrameRandomTools; import us.ihmc.euclid.referenceFrame.tools.ReferenceFrameTools; import us.ihmc.euclid.tools.EuclidCoreRandomTools; import us.ihmc.robotics.math.trajectories.OrientationInterpolationTrajectoryGenerator; import us.ihmc.robotics.math.trajectories.StraightLinePositionTrajectoryGenerator; import us.ihmc.robotics.trajectories.providers.ConstantDoubleProvider; import us.ihmc.robotics.trajectories.providers.ConstantOrientationProvider; import us.ihmc.robotics.trajectories.providers.ConstantPositionProvider; import us.ihmc.robotics.trajectories.providers.OrientationProvider; import us.ihmc.robotics.trajectories.providers.PositionProvider; import us.ihmc.yoVariables.providers.DoubleProvider; import us.ihmc.yoVariables.registry.YoVariableRegistry; public class StraightLinePoseTrajectoryGeneratorTest { private static final Random random = new Random(1516351L); private static final ReferenceFrame worldFrame = ReferenceFrame.getWorldFrame(); private static final ReferenceFrame frameA = ReferenceFrame.constructFrameWithUnchangingTransformToParent("frameA", worldFrame, EuclidCoreRandomTools.nextRigidBodyTransform(random)); private static final double EPSILON = 1.0e-10; @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testRuntimeExceptions() { YoVariableRegistry registry = new YoVariableRegistry("youpiloup"); StraightLinePoseTrajectoryGenerator trajToTest1 = new StraightLinePoseTrajectoryGenerator("blop1", worldFrame, registry); StraightLinePoseTrajectoryGenerator trajToTest2 = new StraightLinePoseTrajectoryGenerator("blop2", false, worldFrame, registry); try { trajToTest1.registerNewTrajectoryFrame(frameA); fail("Should have thrown an exception."); } catch (Exception e) { // Good } try { trajToTest1.switchTrajectoryFrame(worldFrame); fail("Should have thrown an exception."); } catch (Exception e) { // Good } try { trajToTest2.registerNewTrajectoryFrame(frameA); fail("Should have thrown an exception."); } catch (Exception e) { // Good } try { trajToTest2.switchTrajectoryFrame(worldFrame); fail("Should have thrown an exception."); } catch (Exception e) { // Good } } @ContinuousIntegrationTest(estimatedDuration = 0.2) @Test(timeout = 30000) public void testCompareWithSingleFrameTrajectoryGenerators() { YoVariableRegistry registry = new YoVariableRegistry("youpiloup"); StraightLinePoseTrajectoryGenerator trajToTest = new StraightLinePoseTrajectoryGenerator("blop", worldFrame, registry); DoubleProvider trajectoryTimeProvider = new ConstantDoubleProvider(10.0); FramePoint3D initialPosition = EuclidFrameRandomTools.nextFramePoint3D(random, worldFrame, 100.0, 100.0, 100.0); PositionProvider initialPositionProvider = new ConstantPositionProvider(initialPosition); FramePoint3D finalPosition = EuclidFrameRandomTools.nextFramePoint3D(random, worldFrame, 100.0, 100.0, 100.0); PositionProvider finalPositionProvider = new ConstantPositionProvider(finalPosition); FrameQuaternion initialOrientation = EuclidFrameRandomTools.nextFrameQuaternion(random, worldFrame); OrientationProvider initialOrientationProvider = new ConstantOrientationProvider(initialOrientation); FrameQuaternion finalOrientation = EuclidFrameRandomTools.nextFrameQuaternion(random, worldFrame); OrientationProvider finalOrientationProvider = new ConstantOrientationProvider(finalOrientation); StraightLinePositionTrajectoryGenerator originalPosition = new StraightLinePositionTrajectoryGenerator("position", worldFrame, trajectoryTimeProvider, initialPositionProvider, finalPositionProvider, registry); OrientationInterpolationTrajectoryGenerator originalOrientation = new OrientationInterpolationTrajectoryGenerator("orientation", worldFrame, trajectoryTimeProvider, initialOrientationProvider, finalOrientationProvider, registry); trajToTest.setInitialPose(initialPosition, initialOrientation); trajToTest.setFinalPose(new FramePose3D(finalPosition, finalOrientation)); trajToTest.setTrajectoryTime(trajectoryTimeProvider.getValue()); originalPosition.initialize(); originalOrientation.initialize(); trajToTest.initialize(); double dt = 1.0e-3; FramePoint3D position1 = new FramePoint3D(); FrameVector3D velocity1 = new FrameVector3D(); FrameVector3D acceleration1 = new FrameVector3D(); FrameQuaternion orientation1 = new FrameQuaternion(); FrameVector3D angularVelocity1 = new FrameVector3D(); FrameVector3D angularAcceleration1 = new FrameVector3D(); FramePoint3D position2 = new FramePoint3D(); FrameVector3D velocity2 = new FrameVector3D(); FrameVector3D acceleration2 = new FrameVector3D(); FrameQuaternion orientation2 = new FrameQuaternion(); FrameVector3D angularVelocity2 = new FrameVector3D(); FrameVector3D angularAcceleration2 = new FrameVector3D(); for (double t = 0.0; t <= trajectoryTimeProvider.getValue(); t += dt) { originalPosition.compute(t); originalOrientation.compute(t); trajToTest.compute(t); originalPosition.getLinearData(position1, velocity1, acceleration1); originalOrientation.getAngularData(orientation1, angularVelocity1, angularAcceleration1); trajToTest.getLinearData(position2, velocity2, acceleration2); trajToTest.getAngularData(orientation2, angularVelocity2, angularAcceleration2); assertTrue(position1.epsilonEquals(position2, EPSILON)); assertTrue(velocity1.epsilonEquals(velocity2, EPSILON)); assertTrue(acceleration1.epsilonEquals(acceleration2, EPSILON)); assertTrue(orientation1.epsilonEquals(orientation2, EPSILON)); assertTrue(angularVelocity1.epsilonEquals(angularVelocity2, EPSILON)); assertTrue(angularAcceleration1.epsilonEquals(angularAcceleration2, EPSILON)); } } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testNegativeTime() { YoVariableRegistry registry = new YoVariableRegistry("youpiloup"); StraightLinePoseTrajectoryGenerator trajToTest = new StraightLinePoseTrajectoryGenerator("blop", worldFrame, registry); DoubleProvider trajectoryTimeProvider = new ConstantDoubleProvider(10.0); FramePoint3D initialPosition = EuclidFrameRandomTools.nextFramePoint3D(random, worldFrame, 100.0, 100.0, 100.0); FramePoint3D finalPosition = EuclidFrameRandomTools.nextFramePoint3D(random, worldFrame, 100.0, 100.0, 100.0); FrameQuaternion initialOrientation = EuclidFrameRandomTools.nextFrameQuaternion(random, worldFrame); FrameQuaternion finalOrientation = EuclidFrameRandomTools.nextFrameQuaternion(random, worldFrame); trajToTest.setInitialPose(initialPosition, initialOrientation); trajToTest.setFinalPose(new FramePose3D(finalPosition, finalOrientation)); trajToTest.setTrajectoryTime(trajectoryTimeProvider.getValue()); trajToTest.initialize(); trajToTest.compute(-5.0); FramePoint3D position1 = new FramePoint3D(initialPosition); FrameVector3D velocity1 = new FrameVector3D(worldFrame); FrameVector3D acceleration1 = new FrameVector3D(worldFrame); FrameQuaternion orientation1 = new FrameQuaternion(initialOrientation); FrameVector3D angularVelocity1 = new FrameVector3D(worldFrame); FrameVector3D angularAcceleration1 = new FrameVector3D(worldFrame); FramePoint3D position2 = new FramePoint3D(); FrameVector3D velocity2 = new FrameVector3D(); FrameVector3D acceleration2 = new FrameVector3D(); FrameQuaternion orientation2 = new FrameQuaternion(); FrameVector3D angularVelocity2 = new FrameVector3D(); FrameVector3D angularAcceleration2 = new FrameVector3D(); trajToTest.getLinearData(position2, velocity2, acceleration2); trajToTest.getAngularData(orientation2, angularVelocity2, angularAcceleration2); assertTrue(position1.epsilonEquals(position2, EPSILON)); assertTrue(velocity1.epsilonEquals(velocity2, EPSILON)); assertTrue(acceleration1.epsilonEquals(acceleration2, EPSILON)); assertTrue(orientation1.epsilonEquals(orientation2, EPSILON)); assertTrue(angularVelocity1.epsilonEquals(angularVelocity2, EPSILON)); assertTrue(angularAcceleration1.epsilonEquals(angularAcceleration2, EPSILON)); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testTooBigTime() { YoVariableRegistry registry = new YoVariableRegistry("youpiloup"); StraightLinePoseTrajectoryGenerator trajToTest = new StraightLinePoseTrajectoryGenerator("blop", worldFrame, registry); DoubleProvider trajectoryTimeProvider = new ConstantDoubleProvider(10.0); FramePoint3D initialPosition = EuclidFrameRandomTools.nextFramePoint3D(random, worldFrame, 100.0, 100.0, 100.0); FramePoint3D finalPosition = EuclidFrameRandomTools.nextFramePoint3D(random, worldFrame, 100.0, 100.0, 100.0); FrameQuaternion initialOrientation = EuclidFrameRandomTools.nextFrameQuaternion(random, worldFrame); FrameQuaternion finalOrientation = EuclidFrameRandomTools.nextFrameQuaternion(random, worldFrame); trajToTest.setInitialPose(initialPosition, initialOrientation); trajToTest.setFinalPose(new FramePose3D(finalPosition, finalOrientation)); trajToTest.setTrajectoryTime(trajectoryTimeProvider.getValue()); trajToTest.initialize(); trajToTest.compute(15.0); FramePoint3D position1 = new FramePoint3D(finalPosition); FrameVector3D velocity1 = new FrameVector3D(worldFrame); FrameVector3D acceleration1 = new FrameVector3D(worldFrame); FrameQuaternion orientation1 = new FrameQuaternion(finalOrientation); FrameVector3D angularVelocity1 = new FrameVector3D(worldFrame); FrameVector3D angularAcceleration1 = new FrameVector3D(worldFrame); FramePoint3D position2 = new FramePoint3D(); FrameVector3D velocity2 = new FrameVector3D(); FrameVector3D acceleration2 = new FrameVector3D(); FrameQuaternion orientation2 = new FrameQuaternion(); FrameVector3D angularVelocity2 = new FrameVector3D(); FrameVector3D angularAcceleration2 = new FrameVector3D(); trajToTest.getLinearData(position2, velocity2, acceleration2); trajToTest.getAngularData(orientation2, angularVelocity2, angularAcceleration2); assertTrue(position1.epsilonEquals(position2, EPSILON)); assertTrue(velocity1.epsilonEquals(velocity2, EPSILON)); assertTrue(acceleration1.epsilonEquals(acceleration2, EPSILON)); assertTrue(orientation1.epsilonEquals(orientation2, EPSILON)); assertTrue(angularVelocity1.epsilonEquals(angularVelocity2, EPSILON)); assertTrue(angularAcceleration1.epsilonEquals(angularAcceleration2, EPSILON)); } @ContinuousIntegrationTest(estimatedDuration = 0.2) @Test(timeout = 30000) public void testMultipleFramesWithSingleFrameTrajectoryGenerators() { YoVariableRegistry registry = new YoVariableRegistry("youpiloup"); StraightLinePoseTrajectoryGenerator trajToTest = new StraightLinePoseTrajectoryGenerator("blop", true, worldFrame, registry); DoubleProvider trajectoryTimeProvider = new ConstantDoubleProvider(10.0); FramePoint3D initialPosition = EuclidFrameRandomTools.nextFramePoint3D(random, worldFrame, 100.0, 100.0, 100.0); PositionProvider initialPositionProvider = new ConstantPositionProvider(initialPosition); FramePoint3D finalPosition = EuclidFrameRandomTools.nextFramePoint3D(random, worldFrame, 100.0, 100.0, 100.0); PositionProvider finalPositionProvider = new ConstantPositionProvider(finalPosition); FrameQuaternion initialOrientation = EuclidFrameRandomTools.nextFrameQuaternion(random, worldFrame); OrientationProvider initialOrientationProvider = new ConstantOrientationProvider(initialOrientation); FrameQuaternion finalOrientation = EuclidFrameRandomTools.nextFrameQuaternion(random, worldFrame); OrientationProvider finalOrientationProvider = new ConstantOrientationProvider(finalOrientation); StraightLinePositionTrajectoryGenerator originalPosition = new StraightLinePositionTrajectoryGenerator("position1", worldFrame, trajectoryTimeProvider, initialPositionProvider, finalPositionProvider, registry); OrientationInterpolationTrajectoryGenerator originalOrientation = new OrientationInterpolationTrajectoryGenerator("orientation1", worldFrame, trajectoryTimeProvider, initialOrientationProvider, finalOrientationProvider, registry); trajToTest.setInitialPose(initialPosition, initialOrientation); trajToTest.setFinalPose(new FramePose3D(finalPosition, finalOrientation)); trajToTest.setTrajectoryTime(trajectoryTimeProvider.getValue()); originalPosition.initialize(); originalOrientation.initialize(); trajToTest.initialize(); double dt = 1.0e-3; FramePoint3D position1 = new FramePoint3D(); FrameVector3D velocity1 = new FrameVector3D(); FrameVector3D acceleration1 = new FrameVector3D(); FrameQuaternion orientation1 = new FrameQuaternion(); FrameVector3D angularVelocity1 = new FrameVector3D(); FrameVector3D angularAcceleration1 = new FrameVector3D(); FramePoint3D position2 = new FramePoint3D(); FrameVector3D velocity2 = new FrameVector3D(); FrameVector3D acceleration2 = new FrameVector3D(); FrameQuaternion orientation2 = new FrameQuaternion(); FrameVector3D angularVelocity2 = new FrameVector3D(); FrameVector3D angularAcceleration2 = new FrameVector3D(); for (double t = 0.0; t <= trajectoryTimeProvider.getValue(); t += dt) { originalPosition.compute(t); originalOrientation.compute(t); trajToTest.compute(t); originalPosition.getLinearData(position1, velocity1, acceleration1); originalOrientation.getAngularData(orientation1, angularVelocity1, angularAcceleration1); trajToTest.getLinearData(position2, velocity2, acceleration2); trajToTest.getAngularData(orientation2, angularVelocity2, angularAcceleration2); assertTrue(position1.epsilonEquals(position2, EPSILON)); assertTrue(velocity1.epsilonEquals(velocity2, EPSILON)); assertTrue(acceleration1.epsilonEquals(acceleration2, EPSILON)); assertTrue(orientation1.epsilonEquals(orientation2, EPSILON)); assertTrue(angularVelocity1.epsilonEquals(angularVelocity2, EPSILON)); assertTrue(angularAcceleration1.epsilonEquals(angularAcceleration2, EPSILON)); } // Do the same in another frame initialPosition = EuclidFrameRandomTools.nextFramePoint3D(random, frameA, 100.0, 100.0, 100.0); initialPositionProvider = new ConstantPositionProvider(initialPosition); finalPosition = EuclidFrameRandomTools.nextFramePoint3D(random, frameA, 100.0, 100.0, 100.0); finalPositionProvider = new ConstantPositionProvider(finalPosition); initialOrientation = EuclidFrameRandomTools.nextFrameQuaternion(random, frameA); initialOrientationProvider = new ConstantOrientationProvider(initialOrientation); finalOrientation = EuclidFrameRandomTools.nextFrameQuaternion(random, frameA); finalOrientationProvider = new ConstantOrientationProvider(finalOrientation); originalPosition = new StraightLinePositionTrajectoryGenerator("position2", frameA, trajectoryTimeProvider, initialPositionProvider, finalPositionProvider, registry); originalOrientation = new OrientationInterpolationTrajectoryGenerator("orientation2", frameA, trajectoryTimeProvider, initialOrientationProvider, finalOrientationProvider, registry); trajToTest.registerNewTrajectoryFrame(frameA); trajToTest.switchTrajectoryFrame(frameA); trajToTest.setInitialPose(initialPosition, initialOrientation); trajToTest.setFinalPose(new FramePose3D(finalPosition, finalOrientation)); trajToTest.setTrajectoryTime(trajectoryTimeProvider.getValue()); originalPosition.initialize(); originalOrientation.initialize(); trajToTest.initialize(); for (double t = 0.0; t <= trajectoryTimeProvider.getValue(); t += dt) { originalPosition.compute(t); originalOrientation.compute(t); trajToTest.compute(t); originalPosition.getLinearData(position1, velocity1, acceleration1); originalOrientation.getAngularData(orientation1, angularVelocity1, angularAcceleration1); trajToTest.getLinearData(position2, velocity2, acceleration2); trajToTest.getAngularData(orientation2, angularVelocity2, angularAcceleration2); assertTrue(position1.epsilonEquals(position2, EPSILON)); assertTrue(velocity1.epsilonEquals(velocity2, EPSILON)); assertTrue(acceleration1.epsilonEquals(acceleration2, EPSILON)); assertTrue(orientation1.epsilonEquals(orientation2, EPSILON)); assertTrue(angularVelocity1.epsilonEquals(angularVelocity2, EPSILON)); assertTrue(angularAcceleration1.epsilonEquals(angularAcceleration2, EPSILON)); } } }
50.504155
157
0.769471
94e0620a635d3c607ffa6fec186e8bc56dd75be0
5,764
/* * Copyright (C) 2019 Parrot Drones SAS * * 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 Parrot Company 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 * PARROT COMPANY 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.parrot.drone.groundsdk.arsdkengine.peripheral.anafi.wifi; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.SparseArray; import com.parrot.drone.groundsdk.device.peripheral.wifi.Channel; import com.parrot.drone.sdkcore.arsdk.ArsdkFeatureWifi; import com.parrot.drone.sdkcore.ulog.ULog; import static com.parrot.drone.groundsdk.arsdkengine.Logging.TAG_WIFI; /** * Channels Arsdk conversion utility class. * <p> * The {@code obtain} methods always return a Wifi {@link Channel} instance, based on the given information, possibly * using fallback policies when the information is erroneous or incomplete. * <p> * The {@code get} methods return a valid non-{@code null} {@code Channel} instance only if the provided information * allows to find exactly the requested channel. */ final class Channels { /** * Retrieves the wifi channel corresponding to a given frequency band/channel id pair. * * @param band frequency band where the channel operates. If {@code null}, search in all bands for the given * channel identifier * @param channelId identifier of the channel * * @return the corresponding wifi {@code Channel}, if known, otherwise {@link Channel#BAND_5_CHANNEL_34} if the * specified band is 5 GHz, otherwise {@link Channel#BAND_2_4_CHANNEL_1} */ @NonNull static Channel obtain(@Nullable ArsdkFeatureWifi.Band band, int channelId) { Channel channel = null; Channel defaultChannel = Channel.BAND_2_4_CHANNEL_1; if (band != null) { switch (band) { case E2_4_GHZ: channel = CHANNELS_2_4_GHZ.get(channelId); break; case E5_GHZ: channel = CHANNELS_5_GHZ.get(channelId); defaultChannel = Channel.BAND_5_CHANNEL_34; break; } } else { channel = CHANNELS_2_4_GHZ.get(channelId); if (channel == null) { channel = CHANNELS_5_GHZ.get(channelId); } } if (channel == null) { ULog.e(TAG_WIFI, "Unsupported channel [band: " + band + ", id: " + channelId + "]"); channel = defaultChannel; } return channel; } /** * Retrieves the wifi channel corresponding to a given frequency band/channel id pair. * * @param band frequency band where the channel operates * @param channelId identifier of the channel * * @return the corresponding wifi {@code Channel}, if known, otherwise {@code null} */ @Nullable static Channel get(@Nullable ArsdkFeatureWifi.Band band, int channelId) { Channel channel = null; if (band != null) { switch (band) { case E2_4_GHZ: channel = CHANNELS_2_4_GHZ.get(channelId); break; case E5_GHZ: channel = CHANNELS_5_GHZ.get(channelId); break; } if (channel == null) { ULog.e(TAG_WIFI, "Unsupported channel [band: " + band + ", id: " + channelId + "]"); } } return channel; } /** Map of 2.4 GHz band channels, by channel id. */ private static final SparseArray<Channel> CHANNELS_2_4_GHZ = new SparseArray<>(); /** Map of 5 GHz band channels, by channel id. */ private static final SparseArray<Channel> CHANNELS_5_GHZ = new SparseArray<>(); static { for (Channel channel : Channel.values()) { int channelId = channel.getChannelId(); switch (channel.getBand()) { case B_2_4_GHZ: CHANNELS_2_4_GHZ.put(channelId, channel); break; case B_5_GHZ: CHANNELS_5_GHZ.put(channelId, channel); break; } } } /** Private constructor for static utility class. */ private Channels() { } }
40.027778
117
0.629251
63146283f5d6d308b6a7d70997e99b6b1007e8a4
1,375
package ExamExercises_07.ExamJanuary72018; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Coins { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); double change = Double.parseDouble(reader.readLine()); int moneyRepInt = (int) (change * 100);// Money , change int counter = 0; while (moneyRepInt > 0){ if (moneyRepInt >= 200){ counter++; moneyRepInt -= 200; }else if (moneyRepInt >= 100){ counter++; moneyRepInt -= 100; }else if (moneyRepInt >= 50){ counter++; moneyRepInt -= 50; }else if (moneyRepInt >= 20){ counter++; moneyRepInt -= 20; }else if (moneyRepInt >= 10){ counter++; moneyRepInt -= 10; }else if (moneyRepInt >= 5){ counter++; moneyRepInt -= 5; }else if (moneyRepInt >= 2){ counter++; moneyRepInt -= 2; }else { counter++; moneyRepInt -= 1; } } System.out.print(counter); } }
25.943396
85
0.484364
7a22aa6d486a540ce918a7bba4b12aae8d0c4eb1
4,384
package com.jfinalshop.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.jfinalshop.model.base.BaseArticleCategory; /** * Dao - 文章分类 * * * */ @SuppressWarnings("serial") public class ArticleCategory extends BaseArticleCategory<ArticleCategory> { public static final ArticleCategory dao = new ArticleCategory(); /** 树路径分隔符 */ public static final String TREE_PATH_SEPARATOR = ","; /** 访问路径前缀 */ private static final String PATH_PREFIX = "/article/list"; /** 下级分类 */ private List<ArticleCategory> children = new ArrayList<ArticleCategory>(); /** 文章 */ private List<Article> articles = new ArrayList<Article>(); /** * 查找顶级文章分类 * * @param count * 数量 * @return 顶级文章分类 */ public List<ArticleCategory> findRoots(Integer count) { String sql = "SELECT * FROM article_category WHERE parent_id IS NULL ORDER BY orders ASC"; if (count != null) { sql += " LIMIT 0, " + count; } return find(sql); } /** * 查找上级文章分类 * * @param articleCategory * 文章分类 * @param count * 数量 * @return 上级文章分类 */ public List<ArticleCategory> findParents(ArticleCategory articleCategory, Integer count) { if (articleCategory == null || articleCategory.getParent() == null) { return Collections.<ArticleCategory> emptyList(); } String sql = "SELECT * FROM article_category WHERE id IN (?) ORDER BY grade ASC"; if (count != null) { sql += " LIMIT 0, " + count; } return find(sql, articleCategory.getTreePaths()); } /** * 查找下级文章分类 * * @param articleCategory * 文章分类 * @param count * 数量 * @return 下级文章分类 */ public List<ArticleCategory> findChildren(ArticleCategory articleCategory, Integer count) { String sql = ""; if (articleCategory != null) { sql = "SELECT * FROM `article_category` WHERE `tree_path` LIKE '%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId() + ArticleCategory.TREE_PATH_SEPARATOR +"%' ORDER BY orders ASC"; } else { sql = "SELECT * FROM `article_category` ORDER BY orders ASC"; } if (count != null) { sql += " LIMIT 0, " + count; } return sort(find(sql), articleCategory); } /** * 排序文章分类 * * @param articleCategories * 文章分类 * @param parent * 上级文章分类 * @return 文章分类 */ private List<ArticleCategory> sort(List<ArticleCategory> articleCategories, ArticleCategory parent) { List<ArticleCategory> result = new ArrayList<ArticleCategory>(); if (articleCategories != null) { for (ArticleCategory articleCategory : articleCategories) { if ((articleCategory.getParent() != null && articleCategory.getParent().equals(parent)) || (articleCategory.getParent() == null && parent == null)) { result.add(articleCategory); result.addAll(sort(articleCategories, articleCategory)); } } } return result; } /** * 获取上级分类 * * @return 上级分类 */ public ArticleCategory getParent() { return ArticleCategory.dao.findById(getParentId()); } /** * 获取下级分类 * * @return 下级分类 */ public List<ArticleCategory> getChildren() { String sql ="SELECT * FROM article_category WHERE `parent_id` = ?"; if (children.isEmpty()) { ArticleCategory.dao.find(sql, getParentId()); } return children; } /** * 设置下级分类 * * @param children * 下级分类 */ public void setChildren(List<ArticleCategory> children) { this.children = children; } /** * 获取文章 * * @return 文章 */ public List<Article> getArticles() { String sql = "SELECT * FROM article WHERE `article_category_id` = ?"; if (articles.isEmpty()) { articles = Article.dao.find(sql, getId()); } return articles; } /** * 设置文章 * * @param articles * 文章 */ public void setArticles(List<Article> articles) { this.articles = articles; } /** * 获取树路径 * * @return 树路径 */ public List<Long> getTreePaths() { List<Long> treePaths = new ArrayList<Long>(); String[] ids = StringUtils.split(getTreePath(), TREE_PATH_SEPARATOR); if (ids != null) { for (String id : ids) { treePaths.add(Long.valueOf(id)); } } return treePaths; } /** * 获取访问路径 * * @return 访问路径 */ public String getPath() { if (getId() != null) { return PATH_PREFIX + "/" + getId(); } return null; } }
22.030151
198
0.638686
72676f749791b7208a134e76ab1dda95e25d114d
10,459
package com.alibaba.datax.plugin.writer.clickhousereader; import com.alibaba.datax.common.element.*; import com.alibaba.datax.common.exception.DataXException; import com.alibaba.datax.common.plugin.RecordSender; import com.alibaba.datax.common.plugin.TaskPluginCollector; import com.alibaba.datax.common.statistics.PerfRecord; import com.alibaba.datax.common.statistics.PerfTrace; import com.alibaba.datax.common.util.Configuration; import com.alibaba.datax.plugin.rdbms.reader.CommonRdbmsReader; import com.alibaba.datax.plugin.rdbms.reader.Key; import com.alibaba.datax.plugin.rdbms.util.DBUtil; import com.alibaba.datax.plugin.rdbms.util.DBUtilErrorCode; import com.alibaba.datax.plugin.rdbms.util.DataBaseType; import com.alibaba.datax.plugin.rdbms.util.RdbmsException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Types; public class SubCommonClickhouseReader extends CommonRdbmsReader { public static class Job extends CommonRdbmsReader.Job { public Job(DataBaseType dataBaseType) { super(dataBaseType); } } public static class Task extends CommonRdbmsReader.Task { private static final Logger LOG = LoggerFactory.getLogger(Task.class); private static final boolean IS_DEBUG = LOG.isDebugEnabled(); public Task(DataBaseType dataBaseType) { super(dataBaseType); } public Task(DataBaseType dataBaseType,int taskGropuId, int taskId) { super(dataBaseType,taskGropuId,taskId); } @Override public void startRead(Configuration readerSliceConfig, RecordSender recordSender, TaskPluginCollector taskPluginCollector, int fetchSize) { int taskId = -1; int taskGroupId = -1; DataBaseType dataBaseType = super.getDataBaseType(); String jdbcUrl = super.getJdbcUrl(); String username = super.getUsername(); String password = super.getPassword(); String mandatoryEncoding = super.getMandatoryEncoding(); String socketTimeout = readerSliceConfig.getString("socket_timeout"); String basicMsg = super.getBasicMsg(); String querySql = readerSliceConfig.getString(Key.QUERY_SQL); String table = readerSliceConfig.getString(Key.TABLE); Connection conn = null; PerfTrace.getInstance().addTaskDetails(taskId, table + "," + basicMsg); LOG.info("Begin to read record by Sql: [{}\n] {}.", querySql, basicMsg); PerfRecord queryPerfRecord = new PerfRecord(taskGroupId,taskId, PerfRecord.PHASE.SQL_QUERY); queryPerfRecord.start(); if(StringUtils.isNotEmpty(socketTimeout)){ conn = DBUtil.getConnection(dataBaseType, jdbcUrl,username, password,socketTimeout); }else { conn = DBUtil.getConnection(dataBaseType, jdbcUrl,username, password); } // session config .etc related DBUtil.dealWithSessionConfig(conn, readerSliceConfig,dataBaseType, basicMsg); int columnNumber = 0; ResultSet rs = null; try { rs = DBUtil.query(conn, querySql, fetchSize); queryPerfRecord.end(); ResultSetMetaData metaData = rs.getMetaData(); columnNumber = metaData.getColumnCount(); //这个统计干净的result_Next时间 PerfRecord allResultPerfRecord = new PerfRecord(taskGroupId, taskId, PerfRecord.PHASE.RESULT_NEXT_ALL); allResultPerfRecord.start(); long rsNextUsedTime = 0; long lastTime = System.nanoTime(); while (rs.next()) { rsNextUsedTime += (System.nanoTime() - lastTime); this.transportOneRecord(recordSender, rs, metaData, columnNumber, mandatoryEncoding, taskPluginCollector); lastTime = System.nanoTime(); } allResultPerfRecord.end(rsNextUsedTime); //目前大盘是依赖这个打印,而之前这个Finish read record是包含了sql查询和result next的全部时间 LOG.info("Finished read record by Sql: [{}\n] {}.",querySql, basicMsg); }catch (Exception e) { throw RdbmsException.asQueryException(dataBaseType, e, querySql, table, username); } finally { DBUtil.closeDBResources(null, conn); } } @Override protected Record transportOneRecord(RecordSender recordSender, ResultSet rs, ResultSetMetaData metaData, int columnNumber, String mandatoryEncoding, TaskPluginCollector taskPluginCollector) { Record record = recordSender.createRecord(); try { for (int i = 1; i <= columnNumber; i++) { switch (metaData.getColumnType(i)) { case Types.CHAR: case Types.NCHAR: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.NVARCHAR: case Types.LONGNVARCHAR: String rawData; if (StringUtils.isBlank(mandatoryEncoding)) { rawData = rs.getString(i); } else { rawData = new String( (rs.getBytes(i) == null ? EMPTY_CHAR_ARRAY : rs.getBytes(i)), mandatoryEncoding); } record.addColumn(new StringColumn(rawData)); break; case Types.CLOB: case Types.NCLOB: record.addColumn(new StringColumn(rs.getString(i))); break; case Types.SMALLINT: case Types.TINYINT: case Types.INTEGER: case Types.BIGINT: record.addColumn(new LongColumn(rs.getString(i))); break; case Types.NUMERIC: case Types.DECIMAL: record.addColumn(new DoubleColumn(rs.getString(i))); break; case Types.FLOAT: case Types.REAL: case Types.DOUBLE: record.addColumn(new DoubleColumn(rs.getString(i))); break; case Types.TIME: record.addColumn(new DateColumn(rs.getTime(i))); break; // for mysql bug, see http://bugs.mysql.com/bug.php?id=35115 case Types.DATE: if (metaData.getColumnTypeName(i).equalsIgnoreCase( "year")) { record.addColumn(new LongColumn(rs.getInt(i))); } else { record.addColumn(new DateColumn(rs.getDate(i))); } break; case Types.TIMESTAMP: record.addColumn(new DateColumn(rs.getTimestamp(i))); break; case Types.BINARY: case Types.VARBINARY: case Types.BLOB: case Types.LONGVARBINARY: record.addColumn(new BytesColumn(rs.getBytes(i))); break; // warn: bit(1) -> Types.BIT 可使用BoolColumn // warn: bit(>1) -> Types.VARBINARY 可使用BytesColumn case Types.BOOLEAN: case Types.BIT: record.addColumn(new BoolColumn(rs.getBoolean(i))); break; case Types.NULL: String stringData = null; if (rs.getObject(i) != null) { stringData = rs.getObject(i).toString(); } record.addColumn(new StringColumn(stringData)); break; //case Types.TIME_WITH_TIMEZONE: //case Types.TIMESTAMP_WITH_TIMEZONE: // record.addColumn(new StringColumn(rs.getString(i))); // break; default: // warn:not support INTERVAL etc: Types.JAVA_OBJECT throw DataXException .asDataXException( DBUtilErrorCode.UNSUPPORTED_TYPE, String.format( "您的配置文件中的列配置信息有误. 因为DataX 不支持数据库读取这种字段类型. 字段名:[%s], 字段名称:[%s], 字段Java类型:[%s]. 请尝试使用数据库函数将其转换datax支持的类型 或者不同步该字段 .", metaData.getColumnName(i), metaData.getColumnType(i), metaData.getColumnClassName(i))); } } } catch (Exception e) { if (IS_DEBUG) { LOG.debug("read data " + record.toString() + " occur exception:", e); } // TODO 这里识别为脏数据靠谱吗? taskPluginCollector.collectDirtyRecord(record, e); if (e instanceof DataXException) { throw (DataXException) e; } } recordSender.sendToWriter(record); return record; } } }
43.579167
167
0.501769
35367bb3851017d8bcd610ce06446b30aa93fe91
1,205
/** * 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.network.v2020_05_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Network Virtual Appliance Sku Properties. */ public class Office365PolicyProperties { /** * Office 365 breakout categories. */ @JsonProperty(value = "breakOutCategories") private BreakOutCategoryPolicies breakOutCategories; /** * Get office 365 breakout categories. * * @return the breakOutCategories value */ public BreakOutCategoryPolicies breakOutCategories() { return this.breakOutCategories; } /** * Set office 365 breakout categories. * * @param breakOutCategories the breakOutCategories value to set * @return the Office365PolicyProperties object itself. */ public Office365PolicyProperties withBreakOutCategories(BreakOutCategoryPolicies breakOutCategories) { this.breakOutCategories = breakOutCategories; return this; } }
27.386364
106
0.717012
f37f3400ebe6137673fe41ff74ccb0ee853f3b9e
1,968
package de.unibi.agbi.biodwh2.core.etl; import com.fasterxml.jackson.databind.MappingIterator; import de.unibi.agbi.biodwh2.core.DataSource; import de.unibi.agbi.biodwh2.core.Workspace; import de.unibi.agbi.biodwh2.core.exceptions.ParserException; import de.unibi.agbi.biodwh2.core.exceptions.ParserFormatException; import de.unibi.agbi.biodwh2.core.io.FileUtils; import java.io.IOException; import java.util.List; public abstract class SingleFileCsvParser<D extends DataSource, T> extends Parser<D> { private final Class<T> typeVariableClass; private final boolean hasHeader; private final CsvType type; private final String fileName; protected SingleFileCsvParser(final D dataSource, final Class<T> typeVariableClass, final boolean hasHeader, final CsvType type, final String fileName) { super(dataSource); this.typeVariableClass = typeVariableClass; this.hasHeader = hasHeader; this.type = type; this.fileName = fileName; } @Override public final boolean parse(final Workspace workspace) throws ParserException { try (MappingIterator<T> iterator = getMappingIterator(workspace, dataSource)) { if (hasHeader) iterator.next(); storeResults(dataSource, iterator.readAll()); } catch (IOException e) { throw new ParserFormatException("Failed to parse the file '" + fileName + "'", e); } return true; } private MappingIterator<T> getMappingIterator(final Workspace workspace, final D dataSource) throws IOException { return type == CsvType.CSV ? FileUtils.openCsv(workspace, dataSource, fileName, typeVariableClass) : FileUtils.openTsv(workspace, dataSource, fileName, typeVariableClass); } protected abstract void storeResults(final D dataSource, final List<T> results); protected enum CsvType { CSV, TSV } }
37.846154
117
0.700203
cf49d53e2256e339f3b0fca37cbb9c8ef6a451b4
5,425
package me.megamichiel.animationlib.util.pipeline; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import java.util.function.*; public class Pipeline<E> extends AbstractPipeline<Predicate<? super E>> { public Pipeline(PipelineContext ctx) { super(ctx); } public void accept(E value) { _accept(p -> p.test(value)); } public Pipeline<E> filter(Predicate<? super E> predicate) { Pipeline<E> pipeline = new Pipeline<>(ctx); forEach(e -> { if (predicate.test(e)) pipeline.accept(e); }); return pipeline; } public Pipeline<E> nonNull() { return filter(Objects::nonNull); } public Pipeline<E> exclude(Predicate<? super E> predicate) { Pipeline<E> pipeline = new Pipeline<>(ctx); forEach(e -> { if (!predicate.test(e)) pipeline.accept(e); }); return pipeline; } public <R> Pipeline<R> map(Function<? super E, ? extends R> mapper) { Pipeline<R> pipeline = new Pipeline<>(ctx); forEach(e -> pipeline.accept(mapper.apply(e))); return pipeline; } public <R> Pipeline<R> cast(Class<R> type) { Pipeline<R> pipeline = new Pipeline<>(ctx); forEach(e -> { if (type.isInstance(e)) pipeline.accept(type.cast(e)); }); return pipeline; } public IntPipeline mapToInt(ToIntFunction<? super E> mapper) { IntPipeline pipeline = new IntPipeline(ctx); forEach(e -> pipeline.accept(mapper.applyAsInt(e))); return pipeline; } public LongPipeline mapToLong(ToLongFunction<? super E> mapper) { LongPipeline pipeline = new LongPipeline(ctx); forEach(e -> pipeline.accept(mapper.applyAsLong(e))); return pipeline; } public DoublePipeline mapToDouble(ToDoubleFunction<? super E> mapper) { DoublePipeline pipeline = new DoublePipeline(ctx); forEach(e -> pipeline.accept(mapper.applyAsDouble(e))); return pipeline; } public <R> Pipeline<R> flatMap(Function<? super E, ? extends Pipeline<? extends R>> mapper) { Pipeline<R> pipeline = new Pipeline<>(ctx); forEach(e -> mapper.apply(e).forEach(pipeline::accept)); return pipeline; } public IntPipeline flatMapToInt(Function<? super E, ? extends IntPipeline> mapper) { IntPipeline pipeline = new IntPipeline(ctx); forEach(e -> mapper.apply(e).forEach(pipeline::accept)); return pipeline; } public LongPipeline flatMapToLong(Function<? super E, ? extends LongPipeline> mapper) { LongPipeline pipeline = new LongPipeline(ctx); forEach(e -> mapper.apply(e).forEach(pipeline::accept)); return pipeline; } public DoublePipeline flatMapToDouble(Function<? super E, ? extends DoublePipeline> mapper) { DoublePipeline pipeline = new DoublePipeline(ctx); forEach(e -> mapper.apply(e).forEach(pipeline::accept)); return pipeline; } public Pipeline<E> acceptWhile(Predicate<E> predicate) { Pipeline<E> pipeline = new Pipeline<>(ctx); add(e -> { if (predicate.test(e)) { pipeline.accept(e); return false; } return true; }); return pipeline; } public Pipeline<E> acceptUntil(Predicate<E> predicate) { Pipeline<E> pipeline = new Pipeline<>(ctx); add(e -> { if (predicate.test(e)) return true; pipeline.accept(e); return false; }); return pipeline; } public Pipeline<E> acceptWhileBefore(long time) { return acceptWhile(e -> System.currentTimeMillis() < time); } public Pipeline<E> acceptUntil(long time) { return acceptUntil(e -> System.currentTimeMillis() >= time); } public Pipeline<E> skipUntil(Predicate<E> predicate) { Pipeline<E> pipeline = new Pipeline<>(ctx); add(e -> { if (predicate.test(e)) { forEach(pipeline::accept); return true; } return false; }); return pipeline; } public Pipeline<E> skipUntil(long time) { return skipUntil(e -> System.currentTimeMillis() >= time); } public Pipeline<E> skipWhile(Predicate<E> predicate) { Pipeline<E> pipeline = new Pipeline<>(ctx); add(e -> { if (predicate.test(e)) return false; forEach(pipeline::accept); return true; }); return pipeline; } public Pipeline<E> limit(long maxSize) { AtomicLong l = new AtomicLong(maxSize); return acceptUntil(e -> l.decrementAndGet() < 0); } public Pipeline<E> skip(long n) { AtomicLong l = new AtomicLong(n); return skipUntil(e -> l.decrementAndGet() < 0); } public Pipeline<E> post(boolean async) { Pipeline<E> pipeline = new Pipeline<>(ctx); forEach(e -> ctx.post(() -> pipeline.accept(e), async)); return pipeline; } public void forEach(Consumer<? super E> action) { add(e -> { action.accept(e); return false; }); } public Pipeline<E> peek(Consumer<? super E> action) { forEach(action); return this; } }
30.649718
97
0.581751
a5c5d08f71878148c90dcee76178b1e2011fc50c
1,568
package uk.co.codera.ci.tooling.api.bitbucket; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.codera.ci.tooling.api.bitbucket.dto.PushEventDto; import uk.co.codera.ci.tooling.git.GitEventListener; import uk.co.codera.ci.tooling.git.GitPushEvent; @Path("/bitbucket") @Consumes(MediaType.APPLICATION_JSON) public class BitBucketResource { @SuppressWarnings("squid:S1312") private final Logger logger; private final PushEventDtoAdapter gitPushEventAdapter; private final GitEventListener gitEventListener; public BitBucketResource(Logger logger, PushEventDtoAdapter gitPushEventAdapter, GitEventListener gitEventListener) { this.logger = logger; this.gitPushEventAdapter = gitPushEventAdapter; this.gitEventListener = gitEventListener; } public BitBucketResource(PushEventDtoAdapter gitPushEventAdapter, GitEventListener gitEventListener) { this(LoggerFactory.getLogger(BitBucketResource.class), gitPushEventAdapter, gitEventListener); } @POST public void push(PushEventDto pushEvent) { this.logger.info("Received push event [{}]", pushEvent); GitPushEvent gitPushEvent = this.gitPushEventAdapter.from(pushEvent); if (gitPushEvent.getReference().isTag()) { this.logger.info("Ignoring event because it is not related to a branch"); } else { this.gitEventListener.on(gitPushEvent); } } }
34.844444
121
0.744898
42b9c92095a043cc048e568f819da621f7e1d609
2,368
/* * Copyright 2019 lorislab.org. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lorislab.p6.service; import org.lorislab.p6.jpa.model.ProcessToken; import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; import javax.json.bind.JsonbConfig; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; public class ServerJsonService { private static final Jsonb JSON; static { JsonbConfig config = new JsonbConfig() .withFormatting(true); JSON = JsonbBuilder.create(config); } public static String toString(Object data) { if (data != null) { return JSON.toJson(data); } return null; } private static Map fromString(String data) { if (data != null) { return JSON.fromJson(data, Map.class); } return null; } public static Map fromToken(ProcessToken token) { Map data = new HashMap<>(); if (token != null && token.getData() != null) { String tmp = new String(token.getData(), StandardCharsets.UTF_8); data = fromString(tmp); } return data; } @SuppressWarnings("unchecked") public static ProcessToken mergeData(ProcessToken token, Map newData) { if (newData != null && token != null) { Map data = fromToken(token); data.putAll(newData); String tmp = toString(data); token.setData(tmp.getBytes(StandardCharsets.UTF_8)); } return token; } public static ProcessToken mergeData(ProcessToken token, String json) { return mergeData(token, fromString(json)); } public static ProcessToken mergeData(ProcessToken token, ProcessToken from) { return mergeData(token, fromToken(from)); } }
29.234568
81
0.651182
ffeada836511e72b2ef73bfd673a40266525d27f
1,334
package us.aaronweiss.pixalia.server.packets; import io.netty.channel.Channel; import us.aaronweiss.pixalia.server.tools.Utils; public class VHostChangeRequestPacket extends Packet { public static final byte OPCODE = 0x04; private VHostChangeRequestPacket(Channel channel, boolean status) { super(channel, OPCODE); this.packetType = PacketType.OUTBOUND; this.buffer.writeBoolean(status); trim(); } private VHostChangeRequestPacket(Channel channel, String desiredVHost) { super(channel, OPCODE); this.packetType = PacketType.INBOUND; this.buffer.writeByte(desiredVHost.getBytes().length); this.buffer.writeBytes(desiredVHost.getBytes()); trim(); } public boolean status() { this.ready(); if (this.packetType.is(PacketType.INBOUND)) { return this.buffer.readBoolean(); } return false; } public String virtualHost() { this.ready(); if (this.packetType.is(PacketType.OUTBOUND)) { return Utils.readString(this.buffer.readByte(), this.buffer); } return null; } public static VHostChangeRequestPacket newOutboundPacket(Channel channel, boolean status) { return new VHostChangeRequestPacket(channel, status); } public static VHostChangeRequestPacket newInboundPacket(Channel channel, String desiredVHost) { return new VHostChangeRequestPacket(channel, desiredVHost); } }
27.791667
96
0.762369
51c6a83a026610790bbd3c1fda145768028c8921
349
package org.ecjug.hackday.repository; import org.ecjug.hackday.domain.model.Group; import java.util.List; import java.util.Optional; public interface GroupRepository { Group add(Group group); List<Group> list(); Optional<Group> byId(String groupId); void update(Group group); Optional<Group> byUrlname(String urlname); }
17.45
46
0.730659
0907e3ac79d85998ccc1efe1de20083e37b23f21
397
import java.util.Scanner; class Palindrome { public static void main(String args[]) { String a; String b=""; Scanner src = new Scanner(System.in); a = src.nextLine(); for (int i = a.length() - 1;i >=0;i--) { b = b+a.charAt(i); } if (b.equals(a)) { System.out.println("This is a palindrome"); } else { System.out.println("This is not a palindrome"); } } }
15.88
50
0.581864
8b0c7d96d7e61a25c6a21819c1c589b6ade833d7
112
package com.ygmpkk.marketdata.agent.service.marketapi.command; public abstract class CommandRequestWrapper { }
22.4
62
0.839286
2a7bd53c822e3cdf7f23126dc595268070cf5f9c
5,831
package com.example.findacar.adapters; import android.app.Activity; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import com.example.findacar.R; import com.example.findacar.fragments.ServiceRatingFragment; import com.example.findacar.mockupData.Reservations; import com.example.findacar.model.Reservation; import com.example.findacar.service.ServiceUtils; import com.squareup.picasso.Picasso; import org.w3c.dom.Text; import java.text.SimpleDateFormat; import java.util.List; public class PreviousReservationAdapter extends BaseAdapter implements PreviousReservationsHelper { private List<Reservation> mDataset; public Activity activity; private String email; public PreviousReservationAdapter(Activity activity, List<Reservation> mDataset, String email) { this.activity = activity; this.mDataset = mDataset; this.email = email; } @Override public int getCount() { return mDataset.size(); } @Override public Object getItem(int position) { return mDataset.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View vi = convertView; final Reservation reservation = this.mDataset.get(position); if(convertView==null){ vi = activity.getLayoutInflater().inflate(R.layout.fragment_reservation, null); } TextView vehicleServiceName = (TextView)vi.findViewById(R.id.textViewVehicleName); TextView datePickUp = (TextView)vi.findViewById(R.id.textViewReservationDatePickUp); TextView datReturn = (TextView)vi.findViewById(R.id.textViewReservationDateReturn); TextView price = (TextView)vi.findViewById(R.id.textViewReservationPrice); TextView comment = (TextView)vi.findViewById(R.id.textView5); ImageView carPhoto = (ImageView) vi.findViewById(R.id.car_photo); Picasso.get().load(ServiceUtils.SERVICE_API_PATH + "search/getImage/" + reservation.getVehicle().getImageFile()) .resize(300,300).into(carPhoto); //carPhoto.setImageResource(R.drawable.dacia_logan); vehicleServiceName.setText(reservation.getVehicle().getName()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); datePickUp.setText(dateFormat.format(reservation.getPickUpDate())); datReturn.setText(dateFormat.format(reservation.getReturnDate())); Button buttonRate = (Button) vi.findViewById(R.id.button5); Button buttonCancel = (Button) vi.findViewById(R.id.button2); buttonCancel.setVisibility(View.GONE); RatingBar ratingBar = vi.findViewById(R.id.ratingBar3); Drawable drawable = ratingBar.getProgressDrawable(); drawable.setColorFilter(Color.parseColor("#DAA520"), PorterDuff.Mode.SRC_ATOP); if (reservation.getReview() != null){ ratingBar.setVisibility(View.VISIBLE); ratingBar.setRating(reservation.getReview().getRating()); buttonRate.setVisibility(View.GONE); comment.setVisibility(View.VISIBLE); comment.setText(reservation.getReview().getComment()); }else { ratingBar.setVisibility(View.GONE); comment.setVisibility(View.GONE); buttonRate.setVisibility(View.VISIBLE); final View finalVi = vi; buttonRate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FragmentTransaction ft =((AppCompatActivity)activity).getSupportFragmentManager().beginTransaction(); Fragment prev =((AppCompatActivity)activity).getSupportFragmentManager().findFragmentByTag("dialog"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); // Create and show the dialog. DialogFragment newFragment = new ServiceRatingFragment(reservation, email, PreviousReservationAdapter.this, position, finalVi); newFragment.show(ft, "dialog"); } }); } return vi; } @Override public void closeButton(int position, View view, String comment, String rating) { View v = getView(position, view, null); System.out.println(position); Button b = (Button) v.findViewById(R.id.button5); b.setVisibility(View.GONE); System.out.println(comment); RatingBar ratingBar = (RatingBar) v.findViewById(R.id.ratingBar3); ratingBar.setVisibility(View.VISIBLE); Drawable drawable = ratingBar.getProgressDrawable(); drawable.setColorFilter(Color.parseColor("#DAA520"), PorterDuff.Mode.SRC_ATOP); ratingBar.setRating(Float.parseFloat(rating)); TextView commentText = (TextView) v.findViewById(R.id.textView5); commentText.setText(comment); commentText.setVisibility(View.VISIBLE); } public void setmDataset(List<Reservation> mDataset) { if (mDataset != null){ this.mDataset = mDataset; } } }
38.111111
147
0.686332
1cc50116bc925fdd8961cb023bc52bdf6938fcea
848
package com.googlecode.aviator.runtime.function.string; import java.util.Map; import com.googlecode.aviator.runtime.function.AbstractFunction; import com.googlecode.aviator.runtime.function.FunctionUtils; import com.googlecode.aviator.runtime.type.AviatorLong; import com.googlecode.aviator.runtime.type.AviatorObject; /** * String.indexOf function * * @author boyan * @Date 2011-7-13 * */ public class StringIndexOfFunction extends AbstractFunction { public String getName() { return "string.indexOf"; } @Override public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) { String target = FunctionUtils.getStringValue(arg1, env); String param = FunctionUtils.getStringValue(arg2, env); return AviatorLong.valueOf(target.indexOf(param)); } }
26.5
95
0.738208
dcdd7d687a1f65410d599282217efa3e8d910733
1,391
package com.xxyp.xxyp.user.contract; import com.xxyp.xxyp.common.base.IBasePresenter; import com.xxyp.xxyp.common.base.IBaseView; import com.xxyp.xxyp.common.bean.UserInfo; import com.xxyp.xxyp.user.bean.UserShotListBean; import rx.Observable; /** * Description : 个人中心contract Created by sunpengfei on 2017/8/2. Person in * charge : sunpengfei */ public interface PersonalCenterContract { /** * 个人中心view */ interface View extends IBaseView<Presenter> { void showUserInfo(UserInfo userInfo); void showFansCount(int fansCount, int followCount); } /** * 个人中心presenter */ interface Presenter extends IBasePresenter<View> { /** * 获取我的粉丝关注数 */ void getFansCount(); /** * 获取我的信息 */ void getMyUserInfo(); /** * 打开用户信息 */ void openPersonalInfo(); /** * 打开我的约拍 */ void openMyDatingShot(); /** * 打开我的全部粉丝 */ void openMyFans(); /** * 打开我的全部关注 */ void openMyFocus(); void openSetting(); void openMyPhoto(); } /** * 个人中心model */ interface Model { /** * 获取我的信息 * * @return Observable */ Observable<UserInfo> getMyUserInfo(); } }
16.963415
74
0.531991
7e7fbc62e1cbd853425c9066232b646790fe03fe
4,403
package ca.ubc.ece.salt.pangor.analysis.argumentorder; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.stream.Collectors; import org.mozilla.javascript.Node; import org.mozilla.javascript.ast.Assignment; import org.mozilla.javascript.ast.AstNode; import org.mozilla.javascript.ast.ExpressionStatement; import org.mozilla.javascript.ast.FunctionNode; import org.mozilla.javascript.ast.IfStatement; import org.mozilla.javascript.ast.Name; import ca.ubc.ece.salt.gumtree.ast.ClassifiedASTNode.ChangeType; import ca.ubc.ece.salt.pangor.analysis.classify.ClassifierDataSet; import ca.ubc.ece.salt.pangor.analysis.meta.MetaAnalysis; import ca.ubc.ece.salt.pangor.batch.AnalysisMetaInformation; import ca.ubc.ece.salt.pangor.classify.alert.ArgumentOrderAlert; import ca.ubc.ece.salt.pangor.classify.alert.ClassifierAlert; import ca.ubc.ece.salt.pangor.js.analysis.AnalysisUtilities; /** * Checker to find inserted if statements in a function where the "then part" of * the if statement has at least 2 assignments in which the LHS is a function * argument and 1 assignment in which the RHS is a function argument. In * practice, people do that to check if some argument is null and change the * order of them. They try somehow to simulate method overloading. */ public class ArgumentOrderAnalysis extends MetaAnalysis<ClassifierAlert, ClassifierDataSet, ArgumentOrderScopeAnalysis, ArgumentOrderScopeAnalysis> { public ArgumentOrderAnalysis(ClassifierDataSet dataSet, AnalysisMetaInformation ami) { super(dataSet, ami, new ArgumentOrderScopeAnalysis(dataSet, ami), new ArgumentOrderScopeAnalysis(dataSet, ami)); } /** * Synthesized alerts by inspecting the results of the scope analysis on the * source file and the not defined analysis on the destination file. * * @throws Exception */ @Override protected void synthesizeAlerts() throws Exception { /* * Take all inserted if statements and check which ones have assignments * with one of function arguments on the LHS */ for (IfStatement statement : this.dstAnalysis.visitor.storedNodes) { // Get enclosing function FunctionNode enclosingFunction = statement.getEnclosingFunction(); if (enclosingFunction == null || enclosingFunction.getChangeType() == ChangeType.INSERTED || enclosingFunction.getChangeType() == ChangeType.MOVED) { continue; } // Get parameters which are Names and store identifiers Set<String> parameters = enclosingFunction.getParams().stream() .filter(p -> p instanceof Name) .map(p -> ((Name) p).getIdentifier()) .collect(Collectors.toSet()); // Get modified variables from if block Set<String> modifiedVariablesLHS = variablesOnSideAssignmentsOfBlock(statement.getThenPart(), true); Set<String> modifiedVariablesRHS = variablesOnSideAssignmentsOfBlock(statement.getThenPart(), false); // See if there is any intersection between modified variables and // parameters // WARNING: retainAll is destructive Set<String> parametersClone = new HashSet<>(parameters); parameters.retainAll(modifiedVariablesLHS); parametersClone.retainAll(modifiedVariablesRHS); // We look for 2 modified parameters (LHS) and 1 used (RHS) if (parameters.size() >= 2 && parametersClone.size() >= 1) { this.registerAlert(new ArgumentOrderAlert(ami, AnalysisUtilities.getFunctionName(statement.getEnclosingFunction()), "TODO")); } } return; } /* * Using normal iterator over children. I think having a visitor for that is * an overkill. */ private static Set<String> variablesOnSideAssignmentsOfBlock(AstNode block, boolean leftHandSide) { Set<String> output = new HashSet<>(); Iterator<Node> blockIterator = block.iterator(); while (blockIterator.hasNext()) { Node node = blockIterator.next(); if (!(node instanceof ExpressionStatement)) continue; ExpressionStatement expression = (ExpressionStatement) node; if (!(expression.getExpression() instanceof Assignment)) continue; Assignment assignment = (Assignment) expression.getExpression(); if (leftHandSide) { if (assignment.getLeft() instanceof Name) output.add(((Name) assignment.getLeft()).getIdentifier()); } else { if (assignment.getRight() instanceof Name) output.add(((Name) assignment.getRight()).getIdentifier()); } } return output; } }
35.796748
114
0.756757
30f89bf0503728a7a176fd3c806c0217d46e5610
3,143
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.eql.session; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.common.Strings; import org.elasticsearch.core.Nullable; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.fetch.subphase.FieldAndFormat; import org.elasticsearch.tasks.TaskId; import org.elasticsearch.xpack.eql.action.EqlSearchTask; import java.time.ZoneId; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Function; public class EqlConfiguration extends org.elasticsearch.xpack.ql.session.Configuration { private final String[] indices; private final TimeValue requestTimeout; private final String clientId; private final IndicesOptions indicesOptions; private final TaskId taskId; private final EqlSearchTask task; private final int fetchSize; @Nullable private final QueryBuilder filter; @Nullable private final List<FieldAndFormat> fetchFields; @Nullable private Map<String, Object> runtimeMappings; public EqlConfiguration( String[] indices, ZoneId zi, String username, String clusterName, QueryBuilder filter, Map<String, Object> runtimeMappings, List<FieldAndFormat> fetchFields, TimeValue requestTimeout, IndicesOptions indicesOptions, int fetchSize, String clientId, TaskId taskId, EqlSearchTask task, Function<String, Collection<String>> versionIncompatibleClusters ) { super(zi, username, clusterName, versionIncompatibleClusters); this.indices = indices; this.filter = filter; this.runtimeMappings = runtimeMappings; this.fetchFields = fetchFields; this.requestTimeout = requestTimeout; this.clientId = clientId; this.indicesOptions = indicesOptions; this.taskId = taskId; this.task = task; this.fetchSize = fetchSize; } public String[] indices() { return indices; } public String indexAsWildcard() { return Strings.arrayToCommaDelimitedString(indices); } public TimeValue requestTimeout() { return requestTimeout; } public int fetchSize() { return fetchSize; } public QueryBuilder filter() { return filter; } public Map<String, Object> runtimeMappings() { return runtimeMappings; } public List<FieldAndFormat> fetchFields() { return fetchFields; } public String clientId() { return clientId; } public IndicesOptions indicesOptions() { return indicesOptions; } public boolean isCancelled() { return task.isCancelled(); } public TaskId getTaskId() { return taskId; } }
27.094828
88
0.692332
4a2793857f73737012448f5c10fd364ba45bf45c
358
package zdream.nsfplayer.mpeg; /** * <p>Mpeg 格式的音频数据帧 * * @author Zdream * @since v0.1 * @date 2018-01-16 */ public class MpegFrame { MpegFrame(MpegAudio audio, int seq) { this.audio = audio; this.seq = seq; } /** * 序号 */ public final int seq; /** * 属于哪个 audio 的 */ public final MpegAudio audio; int offset; int length; }
11.548387
38
0.603352
1c797b20b0dd086caf66c62f0315a01e31543fe8
842
package SearchStateAI; import Puzzle.ListKR; import Puzzle.PuzzleKR; import java.util.*; public class BreathFirstSearch { Queue<ListKR> puzzleKRQueue = new LinkedList<>(); public BreathFirstSearch(ListKR firstQueue) { puzzleKRQueue.add(firstQueue); } public String getSolution(){ while(!puzzleKRQueue.isEmpty()){ ListKR puzzle = puzzleKRQueue.remove(); if(puzzle.isPuzzleComplete()) { System.out.println("Solution found"); return puzzle.getMoveHistory(); } for (PuzzleKR puzzleToAdd:puzzle.getAllMovesForAllVehicles()) { puzzleKRQueue.add((ListKR) puzzleToAdd); } } System.out.println("Solution Not found"); return "No Solution"; } }
25.515152
76
0.586698
06500c0d6123a0de5a9b7fa39788be29c5e02637
705
package jp.gr.java_conf.spica.plugin.gradle.jacoco.test.assertions; import jp.gr.java_conf.spica.plugin.gradle.jacoco.internal.domain.coverage.model.CoverageReport; import org.assertj.core.api.AbstractAssert; public class CoverageReportAssert extends AbstractAssert<CoverageReportAssert, CoverageReport> { public CoverageReportAssert( CoverageReport coverageReport) { super(coverageReport, CoverageReportAssert.class); } public CoverageReportAssert isEqualTo(CoverageReport expected) { new CoverageSummaryAssert(actual.summary()).isEqualTo(expected.summary()); new ClassToCoverageAssert(actual.classToCoverages()).isEqualTo(expected.classToCoverages()); return this; } }
37.105263
96
0.805674
9065288dcf312506f7e588e6ad227e0671334f36
846
/* * @lc app=leetcode id=201 lang=java * * [201] Bitwise AND of Numbers Range * * https://leetcode.com/problems/bitwise-and-of-numbers-range/description/ * * algorithms * Medium (39.09%) * Likes: 955 * Dislikes: 120 * Total Accepted: 148.4K * Total Submissions: 379.6K * Testcase Example: '5\n7' * * Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND * of all numbers in this range, inclusive. * * Example 1: * * * Input: [5,7] * Output: 4 * * * Example 2: * * * Input: [0,1] * Output: 0 */ // @lc code=start public class Solution { public int rangeBitwiseAnd(int m, int n) { int result = m; m++; while(m <= n){ result&=m; m++; } return result; } } // @lc code=end
16.92
79
0.523641
13e8d93b4d25a86138960c4641df62c36dceba88
1,076
package org.calvin.String; import java.util.HashMap; import java.util.Map; public class FirstRecurring { public static Character findFirstRecurring(String input) { if (input == null || input.length() < 2) return null; Map<Character, Integer> tracker = new HashMap<>(); for (char c : input.toCharArray()) tracker.put(c, tracker.getOrDefault(c, 0) + 1); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (tracker.get(c) > 1) { return c; } } return null; } public static Character findFirstRecurringAllLowercase(String input) { input = input.toLowerCase(); int[] visited = new int[26]; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); visited[c - 'a']++; } for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (visited[c - 'a'] > 1) { return c; } } return null; } }
29.081081
90
0.506506
5b97bf6ebd628cd6c5eb86b8535cdab2569aa593
890
package com.miausoft.miaups.controllers; import com.miausoft.miaups.persistence.ParcelDimensionsRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/parceldimensions") @CrossOrigin("*") public class ParcelDimensionsController { @Autowired ParcelDimensionsRepository parcelDimensionsRepository; @RequestMapping(method = RequestMethod.GET) public ResponseEntity getAll() { return new ResponseEntity(parcelDimensionsRepository.findAll(), HttpStatus.OK); } }
37.083333
87
0.824719
ede88592a8f8b35ccd7e3608089553aad229df7a
1,843
public class TNode<E extends Comparable<E>> { protected E key; protected TNode<E> left = null; protected TNode<E> right = null; protected int size = 1; protected int height = 0; protected int freq = 1; // increment when duplicate keys are inserted protected int access = 0; // increment when TNode is probed during search/find operation public TNode() { this.key = null; this.size = 0; } public TNode( E key) { this.key = key; } public TNode<E> Left() { return this.left; } public TNode<E> Right() { return this.right; } public E Key() { return this.key; } public void setLeft(TNode<E> left) { this.left = left; } public void setRight(TNode<E> right) { this.right = right; } public void setKey(E key) { this.key = key; } public int size() { return this.size; } public void setSize() { this.size = setSize(this); } protected int setSize( TNode<E> curr) { if (curr == null) return 0; return 1 + setSize(curr.left) + setSize(curr.right); } public int height() { return this.height; } public void setHeight() { this.height = setHeight(this); } protected int setHeight( TNode<E> curr) { if (curr == null) return -1; return 1 + Math.max(setHeight(curr.left), setHeight(curr.right)); } public int compareTo( TNode<E> that) { if (this.Key().compareTo(that.Key()) < 0) return -1; if (this.Key().compareTo(that.Key()) > 0) return +1; else return 0; } public int Freq() { return this.freq; } public void incrementFreq() { this.freq++; } public void resetFreq() { this.freq = 1; } public int Access() { return this.access; } public void incrementAccess() { this.access++; } public void resetAccess() { this.access = 0; } }
18.806122
94
0.604449
63b155300f5894d76917d8d9525fa00626fc46eb
5,515
/** * Copyright 2014 Internet2 * * 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. */ /* Copyright (C) 2004-2007 University Corporation for Advanced Internet Development, Inc. Copyright (C) 2004-2007 The University Of Chicago 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 edu.internet2.middleware.grouper.group; import edu.internet2.middleware.grouper.Group; import edu.internet2.middleware.grouper.GrouperSession; import edu.internet2.middleware.grouper.RegistrySubject; import edu.internet2.middleware.grouper.Stem; import edu.internet2.middleware.grouper.StemFinder; import edu.internet2.middleware.grouper.SubjectFinder; import edu.internet2.middleware.grouper.exception.GroupDeleteException; import edu.internet2.middleware.grouper.exception.GrouperException; import edu.internet2.middleware.grouper.exception.InsufficientPrivilegeException; import edu.internet2.middleware.grouper.exception.MemberAddException; import edu.internet2.middleware.grouper.helper.GrouperTest; import edu.internet2.middleware.subject.SourceUnavailableException; import edu.internet2.middleware.subject.Subject; import edu.internet2.middleware.subject.SubjectNotFoundException; import edu.internet2.middleware.subject.SubjectNotUniqueException; /** * Test <code>Group.delete()</code>. * @author blair christensen. * @version $Id: Test_I_API_Group_delete.java,v 1.1 2009-03-20 19:56:41 mchyzer Exp $ * @since 1.2.0 */ public class Test_I_API_Group_delete extends GrouperTest { // PRIVATE INSTANCE VARIABLES // private Group gA, gB; private Stem parent; private RegistrySubject rSubjX; private GrouperSession s; private Subject subjX; // TESTING INFRASTRUCTURE // public void setUp() { super.setUp(); try { s = GrouperSession.start( SubjectFinder.findRootSubject() ); parent = StemFinder.findRootStem(s).addChildStem("parent", "parent"); gA = parent.addChildGroup("child group a", "child group a"); gB = parent.addChildGroup("child group b", "child group b"); rSubjX = RegistrySubject.add(s, "subjX", "person", "subjX"); subjX = SubjectFinder.findById( rSubjX.getId(), true ); } catch (Exception eShouldNotHappen) { throw new GrouperException( eShouldNotHappen.getMessage(), eShouldNotHappen ); } } public void tearDown() { try { s.stop(); } catch (Exception eShouldNotHappen) { throw new GrouperException( eShouldNotHappen.getMessage(), eShouldNotHappen ); } super.tearDown(); } // TESTS // /** * Delete group with a <i>Subject</i> that can no longer be resolved. * @since 1.2.0 */ public void test_delete_withSubjectThatCanNoLongerBeResolved() throws GroupDeleteException, GrouperException, InsufficientPrivilegeException, MemberAddException, SourceUnavailableException, SubjectNotFoundException, SubjectNotUniqueException { // SETUP gA.addMember(subjX); rSubjX.delete(s); // TEST gA.delete(); assertTrue(true); } /** * Delete group that causes an effective <i>Subject</i> when the <i>Subject</i> no longer exists. * @since 1.2.0 */ public void test_delete_causesAnEffectiveSubjectWhenSubjectNoLongerExists() throws GroupDeleteException, GrouperException, InsufficientPrivilegeException, MemberAddException, SubjectNotFoundException, SubjectNotUniqueException { // SETUP gA.addMember(subjX); gB.addMember( gA.toSubject() ); rSubjX.delete(s); // TEST gA.delete(); assertTrue("no exceptions thrown", true); } /** * Delete group with an effective <i>Subject</i> when the <i>Subject</i> no longer exists. * @since 1.2.0 */ public void test_delete_withAnEffectiveSubjectWhenSubjectNoLongerExists() throws GroupDeleteException, GrouperException, InsufficientPrivilegeException, MemberAddException, SubjectNotFoundException, SubjectNotUniqueException { // SETUP gA.addMember(subjX); gB.addMember( gA.toSubject() ); rSubjX.delete(s); // TEST gB.delete(); assertTrue("no exceptions thrown", true); } }
33.424242
100
0.683772
9d1ab631b62b587a5006071ce0fd4df1bf5acd69
2,555
/* * Copyright (c) 2020 Thomas Neidhart. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.netomi.bat.dexfile; import com.github.netomi.bat.dexfile.io.DexDataInput; import com.github.netomi.bat.dexfile.io.DexDataOutput; import org.junit.jupiter.api.Test; import java.util.EnumSet; import java.util.function.Consumer; import java.util.function.Function; import static org.junit.jupiter.api.Assertions.*; public class EncodedFieldTest extends DexContentTest<EncodedField> { @Override public EncodedField[] getTestInstances() { return new EncodedField[] { EncodedField.of(1, Visibility.PUBLIC, FieldModifier.FINAL), EncodedField.of(2, Visibility.PRIVATE), EncodedField.of(65535, Visibility.PACKAGE_PRIVATE, FieldModifier.VOLATILE, FieldModifier.SYNTHETIC), }; } @Override public Function<DexDataInput, EncodedField> getFactoryMethod() { return (input) -> EncodedField.readContent(input, 0); } @Override public Consumer<DexDataOutput> getWriteMethod(EncodedField data) { return (output) -> data.write(output, 0); } @Test public void inputChecking() { assertThrows(IllegalArgumentException.class, () -> { EncodedField.of(-1, Visibility.PUBLIC, FieldModifier.FINAL); }); } @Test public void getter() { EncodedField[] data = getTestInstances(); assertEquals(1, data[0].getFieldIndex()); assertEquals(Visibility.PUBLIC, data[0].getVisibility()); assertEquals(EnumSet.of(FieldModifier.FINAL), data[0].getModifiers()); } @Test public void equals() { EncodedField e1 = EncodedField.of(1, Visibility.PUBLIC, FieldModifier.FINAL); EncodedField e2 = EncodedField.of(2, Visibility.PRIVATE, FieldModifier.STATIC); EncodedField e3 = EncodedField.of(1, Visibility.PUBLIC, FieldModifier.FINAL); assertEquals(e1, e1); assertNotEquals(e1, e2); assertEquals(e1, e3); } }
33.181818
112
0.691194
bcc6a58d91a390febbf714777fe704425158dff5
1,519
package seedu.address.logic.commands.mark; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.mark.Mark; /** * Mark "and" subcommand */ public class MarkAndCommand extends MarkCommand { public static final String MESSAGE_SUCCESS = "%d students were added to %s from (%s intersect %s)"; private final String alias1; private final String alias2; private final String alias3; public MarkAndCommand(String alias1, String alias2, String alias3) { this.alias1 = alias1; this.alias2 = alias2; this.alias3 = alias3; } @Override public CommandResult execute(Model model, CommandHistory history) throws CommandException { Mark mark1 = model.getMark(alias2); Mark result = mark1.intersect(model.getMark(alias3)); model.setMark(alias1, result); return new CommandResult(String.format(MESSAGE_SUCCESS, result.count(), alias1, alias2, alias3)); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof MarkAndCommand)) { return false; } MarkAndCommand command = (MarkAndCommand) other; return alias1.equals(command.alias1) && alias2.equals(command.alias2) && alias3.equals(command.alias3); } }
31
105
0.673469
d4025127f710fb188d1651845e59e0a5d6522a68
1,288
package core.string; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class EqualityTest { @Test public void checkReferenceEquality() { String s1 = "Firefly"; String s2 = "Firefly"; assertTrue(s1 == s2); String s3 = "Fire" + "fly"; assertTrue(s1 == s3); String s4 = new String("Firefly"); assertFalse(s1 == s4); assertFalse(s2 == s4); String s5 = new String(s1); assertFalse(s1 == s5); assertFalse(s2 == s5); assertFalse(s4 == s5); } @Test public void checkValueEquality() { String s1 = "Firefly"; String s2 = "Firefly"; assertTrue(s1.equals(s2)); String s3 = new String("Firefly"); assertTrue(s1.equals(s3)); assertTrue(s2.equals(s3)); String s4 = new String(s1); assertTrue(s1.equals(s4)); assertTrue(s2.equals(s4)); assertTrue(s3.equals(s4)); } @Test public void checkValueEqualityIgnoreCase() { String s1 = "firefly"; String s2 = "FIREFLY"; assertTrue(s1.equalsIgnoreCase(s2)); String s3 = new String("Firefly"); assertTrue(s1.equalsIgnoreCase(s3)); assertTrue(s2.equalsIgnoreCase(s3)); String s4 = new String(s1); assertTrue(s1.equalsIgnoreCase(s4)); assertTrue(s2.equalsIgnoreCase(s4)); assertTrue(s3.equalsIgnoreCase(s4)); } }
21.114754
45
0.681677
b3b0cf4bd709a5a4f957edf33fc80f033ef768d0
3,801
import org.junit.Test; import java.util.Arrays; import java.util.NoSuchElementException; import static org.junit.Assert.*; public class AddressBookTest { private static AddressBook createDictionary() { return new AddressBook( new Pair("Krivitskii", new Address("Komendantskii", "1", "1")), new Pair("Shadaev", new Address("Komendantskii", "22", "269")), new Pair("Galieva", new Address("Nevskiy", "35", "3")), new Pair("Shomov", new Address("Komendantskii", "35", "5")), new Pair("Kuznecova", new Address("Nevskiy", "35", "3")), new Pair("Sergeev", new Address("Primorskaya", "19", "2")), new Pair("Petryaeva", new Address("Lesnaya", "22", "269"))); } @Test public void add() { assertEquals(8, createDictionary() .add("Sidorov", new Address("Lesnaya", "52", "24")) .size()); assertEquals(1, new AddressBook() .add("Krivitskii", new Address("Komendantskii", "1", "1")) .size()); } @Test public void remove() { assertEquals(6, createDictionary() .remove("Galieva") .size()); } @Test(expected = NoSuchElementException.class) public void removeNull() { new AddressBook() .remove("Test"); } @Test public void changeAddress() { assertEquals("Komendantskii", createDictionary() .changeAddress("Galieva", new Address("Komendantskii", "35", "3")) .getAddress("Galieva").getStreet()); } @Test(expected = NoSuchElementException.class) public void changeAddressNull() { new AddressBook() .changeAddress("Krivitskii", new Address("Nevskiy", "35", "3")); } @Test public void getAdds() { assertEquals(new AddressBook( new Pair("Shadaev", new Address("Komendantskii", "22", "269"))) .getAddress("Shadaev"), new Address("Komendantskii", "22", "269")); } @Test(expected = NoSuchElementException.class) public void getAddressNull() { new AddressBook() .getAddress("Krivitskii"); } @Test public void filterStreet() { assertTrue(Arrays.asList("Krivitskii", "Shadaev", "Shomov") .containsAll(createDictionary().filterStreet("Komendantskii"))); assertTrue(createDictionary() .filterStreet("Spasskaya") .isEmpty()); } @Test public void filterBuilding() { assertTrue(Arrays.asList("Galieva", "Kuznecova") .containsAll(createDictionary().filterBuilding("Nevskiy", "35"))); assertTrue(createDictionary().filterBuilding("Komendantskii", "228") .isEmpty()); } @Test public void size() { assertEquals(8, createDictionary() .add("Orlov", new Address("Nevskiy", "35", "222")) .size()); assertEquals(0, new AddressBook() .size()); } @Test public void getStreet() { assertEquals("Nevskiy", new Address("Nevskiy", "35", "261") .getStreet()); } @Test public void getBuilding() { assertEquals("35", new Address("Nevskiy", "35", "261") .getBuilding()); } @Test public void getApartment() { assertEquals("261", new Address("Nevskiy", "35", "261") .getApartment()); } @Test public void testEquals() { assertEquals(new Address("Primorskaya", "24", "118"), new Address("Primorskaya", "24", "118")); assertNotEquals(new Address("Shavrova", "54", "32"), new Address("Shavrova", "54", "87")); } }
31.941176
103
0.548014
d6cb4442f3eb6a3167fef8e2c39a0b734043d41a
5,272
package com.kodstar.backend.service.impl; import com.kodstar.backend.model.dto.Label; import com.kodstar.backend.model.entity.LabelEntity; import com.kodstar.backend.repository.LabelRepository; import com.kodstar.backend.service.LabelService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import javax.persistence.EntityNotFoundException; import java.util.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @SpringBootTest class LabelServiceImplTest { @Autowired private LabelService labelService; @MockBean private LabelRepository labelRepository; private Label label; @BeforeEach void setUp() { this.label = new Label(); label.setId(1L); label.setName("backend"); label.setColor("fe642e"); } @Test @DisplayName("Test saveLabelEntity Success") void saveLabelEntity() { // Setup our mock repository LabelEntity labelEntity = labelService.convertToEntity(label); when(labelRepository.save(labelEntity)).thenReturn(labelEntity); // Execute the service call Label savedLabel = labelService.saveLabelEntity(label); // Assert the response assertNotNull(savedLabel); assertEquals(labelEntity.getColor(),savedLabel.getColor()); } @Test @DisplayName("Test findById Success") void findById() { // Setup our mock repository LabelEntity labelEntity = labelService.convertToEntity(label); when(labelRepository.findById(1L)).thenReturn(Optional.of(labelEntity)); // Execute the service call Label returnedLabel = labelService.findById(1L); // Assert the response assertEquals(labelEntity.getColor(),returnedLabel.getColor()); } @Test @DisplayName("Test findById_NotFound") void findByIdNotFound() { // Setup our mock repository when(labelRepository.findById(1L)).thenReturn(Optional.empty()); // Assert the response assertThrows(EntityNotFoundException.class,()->labelService.findById(1L)); } @Test @DisplayName("Test findByName Success") void findByName() { // Setup our mock repository LabelEntity labelEntity = labelService.convertToEntity(label); when(labelRepository.findByName("backend")).thenReturn(Optional.of(labelEntity)); // Execute the service call Optional<LabelEntity> returnedLabelEntity = labelService.findByName("backend"); // Assert the response assertTrue(returnedLabelEntity.isPresent()); } @Test @DisplayName("Test getAllLabels Success") void getAllLabels() { // Setup our mock repository LabelEntity labelEntity = labelService.convertToEntity(label); List<LabelEntity> labels = new ArrayList<>(); labels.add(labelEntity); when(labelRepository.findAll()).thenReturn(labels); // Execute the service call Collection<Label> returnedLabels = labelService.getAllLabels(); // Assert the response assertEquals(returnedLabels.size(),1); } @Test @DisplayName("Test updateLabelEntity Success") void updateLabelEntity() { // Setup our mock repository LabelEntity labelEntity = labelService.convertToEntity(label); when(labelRepository.findById(1L)).thenReturn(Optional.of(labelEntity)); when(labelRepository.save(labelEntity)).thenReturn(labelEntity); // Execute the service call Label updatedLabel = labelService.updateLabelEntity(1L,label); // Assert the response assertNotNull(updatedLabel); assertEquals(labelEntity.getColor(),updatedLabel.getColor()); } @Test @DisplayName("Test deleteLabel Success") void deleteLabel() { // Setup our mock repository LabelEntity labelEntity = labelService.convertToEntity(label); when(labelRepository.findById(1L)).thenReturn(Optional.of(labelEntity)); // Execute the service call labelService.deleteLabel(1L); // Assert the response verify(labelRepository,times(1)).delete(labelEntity); } @Test @DisplayName("Test saveAll Success") void saveAll() { // Setup our mock repository LabelEntity labelEntity = labelService.convertToEntity(label); Set<LabelEntity> labelEntities = new HashSet<>(); labelEntities.add(labelEntity); List<LabelEntity> labels = new ArrayList<>(); labels.add(labelEntity); when(labelRepository.saveAll(labelEntities)).thenReturn(labels); // Execute the service call labelService.saveAll(labelEntities); // Assert the response assertEquals(labels.size(),1); verify(labelRepository,times(1)).saveAll(labelEntities); } @Test @DisplayName("Test findAll Success") void findAll() { // Setup our mock repository LabelEntity labelEntity = labelService.convertToEntity(label); List<LabelEntity> labels = new ArrayList<>(); labels.add(labelEntity); labels.add(labelEntity); when(labelRepository.findAll()).thenReturn(labels); // Execute the service call Collection<LabelEntity> returnedLabels = labelService.findAll(); // Assert the response assertEquals(returnedLabels.size(),2); } }
28.344086
85
0.735205
8e3cdfadf447190bb9bc923b135a74c5db9257e6
420
package io.metadew.iesi.metadata.definition.action.result.key; import io.metadew.iesi.metadata.definition.key.MetadataKey; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = true) public class ActionResultOutputKey extends MetadataKey { private final String runId; private final Long processId; private final String actionId; private final String outputName; }
24.705882
62
0.797619
c8877110c1f65beae0cfc26f0e165f9be9ab2c5f
5,001
/*PLEASE DO NOT EDIT THIS CODE*/ /*This code was generated using the UMPLE 1.31.1.5860.78bb27cc6 modeling language!*/ package cruise.umple.parser; import java.nio.file.*; /** * Used to indicate the coordinates of a position when parsing. This is done by keeping track of the * filename, the line number and the corresponding offset on that line number. */ // line 108 "../../../../src/ParseUtilities.ump" // line 346 "../../../../src/ParseUtilities_Code.ump" public class Position { //------------------------ // MEMBER VARIABLES //------------------------ //Position Attributes private String filename; private int lineNumber; private int characterOffset; private int offset; //Helper Variables private int cachedHashCode; private boolean canSetFilename; private boolean canSetLineNumber; private boolean canSetCharacterOffset; private boolean canSetOffset; //------------------------ // CONSTRUCTOR //------------------------ public Position(String aFilename, int aLineNumber, int aCharacterOffset, int aOffset) { cachedHashCode = -1; canSetFilename = true; canSetLineNumber = true; canSetCharacterOffset = true; canSetOffset = true; filename = aFilename; lineNumber = aLineNumber; characterOffset = aCharacterOffset; offset = aOffset; } //------------------------ // INTERFACE //------------------------ public boolean setFilename(String aFilename) { boolean wasSet = false; if (!canSetFilename) { return false; } filename = aFilename; wasSet = true; return wasSet; } public boolean setLineNumber(int aLineNumber) { boolean wasSet = false; if (!canSetLineNumber) { return false; } lineNumber = aLineNumber; wasSet = true; return wasSet; } public boolean setCharacterOffset(int aCharacterOffset) { boolean wasSet = false; if (!canSetCharacterOffset) { return false; } characterOffset = aCharacterOffset; wasSet = true; return wasSet; } public boolean setOffset(int aOffset) { boolean wasSet = false; if (!canSetOffset) { return false; } offset = aOffset; wasSet = true; return wasSet; } /** * The filename of the position. */ public String getFilename() { return filename; } /** * The line number of the position. */ public int getLineNumber() { return lineNumber; } /** * The character offset of the position. */ public int getCharacterOffset() { return characterOffset; } /** * The offset of the position. */ public int getOffset() { return offset; } public boolean equals(Object obj) { if (obj == null) { return false; } if (!getClass().equals(obj.getClass())) { return false; } Position compareTo = (Position)obj; if (getFilename() == null && compareTo.getFilename() != null) { return false; } else if (getFilename() != null && !getFilename().equals(compareTo.getFilename())) { return false; } if (getLineNumber() != compareTo.getLineNumber()) { return false; } if (getCharacterOffset() != compareTo.getCharacterOffset()) { return false; } if (getOffset() != compareTo.getOffset()) { return false; } return true; } public int hashCode() { if (cachedHashCode != -1) { return cachedHashCode; } cachedHashCode = 17; if (getFilename() != null) { cachedHashCode = cachedHashCode * 23 + getFilename().hashCode(); } else { cachedHashCode = cachedHashCode * 23; } cachedHashCode = cachedHashCode * 23 + getLineNumber(); cachedHashCode = cachedHashCode * 23 + getCharacterOffset(); cachedHashCode = cachedHashCode * 23 + getOffset(); canSetFilename = false; canSetLineNumber = false; canSetCharacterOffset = false; canSetOffset = false; return cachedHashCode; } public void delete() {} // line 352 "../../../../src/ParseUtilities_Code.ump" public Position(int aLineNumber, int aCharacterOffset, int aOffset){ this(null, aLineNumber, aCharacterOffset, aOffset); } // line 357 "../../../../src/ParseUtilities_Code.ump" public Position copy(){ return new Position(filename,lineNumber,characterOffset,offset); } // line 362 "../../../../src/ParseUtilities_Code.ump" public Position add(Position more){ String tfile = filename == null ? more.getFilename() : filename; return new Position(filename, getLineNumber() + more.getLineNumber() - 1, getCharacterOffset() + more.getCharacterOffset(), getOffset() + more.getOffset()); } /** * extract the line number of the position */ // line 368 "../../../../src/ParseUtilities_Code.ump" public int getLineNum(){ return getLineNumber(); } // line 373 "../../../../src/ParseUtilities_Code.ump" public String toString(){ return "[" + getLineNumber() + "," + getCharacterOffset() + "]"; } }
22.940367
160
0.625475
598e8c16803225ba110412f8c5265d1a7552be8c
2,264
package com.yi.swagger.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ParameterBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.schema.ModelRef; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.service.Parameter; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.List; /** * Swagger2 配置 * @author YI * @date 2018-8-17 09:45:57 */ @Configuration @EnableSwagger2 public class Swagger2 { /** * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包 * @return */ @Bean public Docket createRestApi() { // 为swagger添加header参数可供输入,此配置可选 ParameterBuilder userTokenHeader = new ParameterBuilder(); ParameterBuilder userIdHeader = new ParameterBuilder(); List<Parameter> pars = new ArrayList<Parameter>(); userTokenHeader.name("headerUserToken").description("userToken") .modelRef(new ModelRef("string")).parameterType("header") .required(false).build(); userIdHeader.name("headerUserId").description("userId") .modelRef(new ModelRef("string")).parameterType("header") .required(false).build(); pars.add(userTokenHeader.build()); pars.add(userIdHeader.build()); return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select() .apis(RequestHandlerSelectors.basePackage("com.yi.swagger.controller")) .paths(PathSelectors.any()).build() .globalOperationParameters(pars); } /** * 构建 api文档的信息 * @return ApiInfo */ private ApiInfo apiInfo() { return new ApiInfoBuilder() // 设置页面标题 .title("使用swagger2构建短视频后端api接口文档") // 设置联系人 .contact(new Contact("懿", "http://www.hwy.ac.com", "ilovey_hwy@163.com")) // 描述 .description("欢迎访问短视频接口文档") // 定义版本号 .version("1.0").build(); } }
31.444444
77
0.738516
97c5461ab2d03957f8789d43fb9fde5ce348bdd4
842
package com.example.helloworld.model; public class VareforbrugElement { private String varenavn = ""; private String opkoeb = ""; private String koebsPris = ""; private String vareforbrug = ""; public String getVarenavn() { return varenavn; } public void setVarenavn(String varenavn) { this.varenavn = varenavn; } public String getOpkoeb() { return opkoeb; } public void setOpkoeb(String opkoeb) { this.opkoeb = opkoeb; } public String getKoebsPris() { return koebsPris; } public void setKoebsPris(String koebsPris) { this.koebsPris = koebsPris; } public String getVareforbrug() { return vareforbrug; } public void setVareforbrug(String vareforbrug) { this.vareforbrug = vareforbrug; } }
20.047619
52
0.625891
161217c39b67aa9ff14d3537c3287dfdb6ba50cf
140
package com.moemoe.lalala.utils; /** * Created by yi on 2017/1/12. */ public interface MoeMoeCallback { void onSuccess(Object o); }
14
33
0.685714
298d97f363f937a211409d9335c424c1bc9cadb9
7,783
/******************************************************************************* * Copyright (c) 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Zend Technologies *******************************************************************************/ package org.eclipse.php.core.tests.typeinference; import java.io.ByteArrayInputStream; import java.io.File; import java.util.LinkedHashMap; import java.util.Map; import junit.extensions.TestSetup; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.dltk.ast.ASTNode; import org.eclipse.dltk.ast.declarations.ModuleDeclaration; import org.eclipse.dltk.ast.expressions.CallExpression; import org.eclipse.dltk.ast.expressions.Expression; import org.eclipse.dltk.core.DLTKCore; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.core.SourceParserUtil; import org.eclipse.dltk.ti.IContext; import org.eclipse.dltk.ti.goals.ExpressionTypeGoal; import org.eclipse.dltk.ti.types.IEvaluatedType; import org.eclipse.php.core.tests.AbstractPDTTTest; import org.eclipse.php.core.tests.PHPCoreTests; import org.eclipse.php.core.tests.PdttFile; import org.eclipse.php.internal.core.PHPVersion; import org.eclipse.php.internal.core.project.PHPNature; import org.eclipse.php.internal.core.typeinference.PHPTypeInferencer; import org.eclipse.php.internal.core.typeinference.context.ContextFinder; public class TypeInferenceTests extends AbstractPDTTTest { protected static final int ENGINE_TIMEOUT = 100000; protected static final Map<PHPVersion, String[]> TESTS = new LinkedHashMap<PHPVersion, String[]>(); static { TESTS.put(PHPVersion.PHP5, new String[] { "/workspace/typeinference/php5" }); TESTS.put(PHPVersion.PHP5_3, new String[] { "/workspace/typeinference/php5" }); TESTS.put(PHPVersion.PHP5_4, new String[] { "/workspace/typeinference/php5", "/workspace/typeinference/php54" }); }; private static PHPTypeInferencer typeInferenceEngine; private static IProject project; public static void setUpSuite() throws Exception { project = ResourcesPlugin.getWorkspace().getRoot() .getProject("TypeInferenceTests"); if (project.exists()) { return; } project.create(null); project.open(null); // configure nature IProjectDescription desc = project.getDescription(); desc.setNatureIds(new String[] { PHPNature.ID }); project.setDescription(desc, null); typeInferenceEngine = new PHPTypeInferencer(); } public static void tearDownSuite() throws Exception { project.close(null); project.delete(true, true, null); project = null; typeInferenceEngine = null; } public TypeInferenceTests(String description) { super(description); } public static Test suite() { TestSuite suite = new TestSuite("Type Inference Tests"); for (final PHPVersion phpVersion : TESTS.keySet()) { TestSuite phpVerSuite = new TestSuite(phpVersion.getAlias()); for (String testsDirectory : TESTS.get(phpVersion)) { for (final String fileName : getPDTTFiles(testsDirectory)) { try { final PdttFile pdttFile = new PdttFile(fileName); final String pruner = getPrunerType(pdttFile); phpVerSuite.addTest(new TypeInferenceTests(phpVersion .getAlias() + " - /" + fileName) { protected void setUp() throws Exception { PHPCoreTests.setProjectPhpVersion(project, phpVersion); } protected void tearDown() throws Exception { } protected void runTest() throws Throwable { String criteriaFunction = new File(fileName) .getName().replaceAll("\\.pdtt", ""); String code = pdttFile.getFile(); IEvaluatedType evaluatedType = findEvaluatedType( code, criteriaFunction, pruner); Assert.assertNotNull( "Can't evaluate type for: " + code, evaluatedType); Assert.assertEquals(pdttFile.getExpected() .trim(), evaluatedType.getTypeName() .trim()); } }); } catch (final Exception e) { phpVerSuite.addTest(new TestCase(fileName) { // dummy // test // indicating // PDTT // file // parsing // failure protected void runTest() throws Throwable { throw e; } }); } } } suite.addTest(phpVerSuite); } // Create a setup wrapper TestSetup setup = new TestSetup(suite) { protected void setUp() throws Exception { setUpSuite(); } protected void tearDown() throws Exception { tearDownSuite(); } }; return setup; } private static String getPrunerType(PdttFile pdttFile) { Map<String, String> config = pdttFile.getConfig(); return config.get("prune"); } class ASTNodeSearcher extends ContextFinder { private IContext context; private ASTNode result; private String criteriaFunction; public ASTNodeSearcher(ISourceModule sourceModule, String criteriaFunction) { super(sourceModule); this.criteriaFunction = criteriaFunction; } public boolean visit(Expression node) throws Exception { if (node instanceof CallExpression) { CallExpression callExpression = (CallExpression) node; if (criteriaFunction.equals(callExpression.getName())) { result = (ASTNode) callExpression.getArgs().getChilds() .get(0); context = contextStack.peek(); return false; } } return true; } public ASTNode getResult() { return result; } public IContext getContext() { return context; } } protected IEvaluatedType findEvaluatedType(String code, String criteriaFunction, String pruner) throws Exception { IFile file = project.getFile("dummy.php"); if (file.exists()) { file.setContents(new ByteArrayInputStream(code.getBytes()), true, false, null); } else { file.create(new ByteArrayInputStream(code.getBytes()), true, null); } try { project.build(IncrementalProjectBuilder.FULL_BUILD, null); PHPCoreTests.waitForIndexer(); PHPCoreTests.waitForAutoBuild(); ISourceModule sourceModule = DLTKCore.createSourceModuleFrom(file); ModuleDeclaration moduleDecl = SourceParserUtil .getModuleDeclaration(sourceModule); ASTNodeSearcher searcher = new ASTNodeSearcher(sourceModule, criteriaFunction); moduleDecl.traverse(searcher); Assert.assertNotNull("Method call " + criteriaFunction + "() in code: " + code, searcher.getResult()); Assert.assertNotNull("Can't find context for " + criteriaFunction + "() in code: " + code, searcher.getContext()); ExpressionTypeGoal goal = new ExpressionTypeGoal( searcher.getContext(), searcher.getResult()); if ("phpdocGoals".equals(pruner)) { return typeInferenceEngine.evaluateTypeHeavy(goal, ENGINE_TIMEOUT); } if ("heavyGoals".equals(pruner)) { return typeInferenceEngine.evaluateTypePHPDoc(goal, ENGINE_TIMEOUT); } return typeInferenceEngine.evaluateType(goal, ENGINE_TIMEOUT); } finally { try { file.delete(true, null); } catch (Exception e) { // do not handle - may be it's currently in use } } } }
30.521569
100
0.694976
e49c797661811d91efe1c5bc9179eddac73f1c25
536
package com.gps.db.service; import com.baomidou.mybatisplus.extension.service.IService; import com.gps.common.model.CommandType; import com.gps.db.dbutils.MyPage; import com.gps.db.entity.CommandTypeEntity; import java.util.List; import java.util.Map; /** * * * @author zb * @email zb@gmail.com * @date 2019-06-30 11:13:45 */ public interface CommandTypeService extends IService<CommandTypeEntity> { MyPage<CommandTypeEntity> queryPage(Map<String, Object> params); List<CommandTypeEntity> getByImei(String imei); }
21.44
73
0.757463
9126fb6745be35f660b1d1b5730c2973096269d9
2,728
/** * Created by egor_hm on 7/3/15. */ import edu.princeton.cs.algs4.WeightedQuickUnionUF; public class Percolation { private int gridSize = 0; private boolean [] grid = null; private WeightedQuickUnionUF qu = null; private WeightedQuickUnionUF backwashQu = null; private int virtualTop = 0; private int virtualBottom = 0; public Percolation(int N) { this.qu = new WeightedQuickUnionUF(N * N + 2); this.backwashQu = new WeightedQuickUnionUF(N * N + 2); this.virtualBottom = N * N + 1; this.virtualTop = 0; this.gridSize = N; if (N <= 0) { throw new java.lang.IllegalArgumentException("Index is less than 0"); } grid = new boolean[N * N + 1]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { grid[xyTo1D(i, j)] = false; } } } private boolean isIndexOut(int i, int j) { if ((i < 1) || (i > gridSize) || (j < 1) || (j > gridSize)) { return true; } return false; } private int xyTo1D(int i, int j) { return (i - 1) * this.gridSize + j; } private void union(int i, int j, int i1, int j1) { if (!isIndexOut(i1, j1) && isOpen(i1, j1)) { int p = xyTo1D(i1, j1); int q = xyTo1D(i, j); this.qu.union(p, q); this.backwashQu.union(p, q); } } public void open(int i, int j) { if (isIndexOut(i, j)) throw new IndexOutOfBoundsException("Out of bounds :("); grid[xyTo1D(i, j)] = true; //union with neighbors union(i, j, i - 1, j); union(i, j, i, j - 1); union(i, j, i + 1, j); union(i, j, i, j + 1); if (i == 1) { this.qu.union(virtualTop, xyTo1D(i, j)); this.backwashQu.union(virtualTop, xyTo1D(i, j)); } if (i == this.gridSize) this.qu.union(virtualBottom, xyTo1D(i, j)); } public boolean isOpen(int i, int j) { if (isIndexOut(i, j)) throw new IndexOutOfBoundsException("Out of bounds :("); return grid[xyTo1D(i, j)]; } public boolean isFull(int i, int j) { if (isIndexOut(i, j)) throw new IndexOutOfBoundsException("Out of bounds :("); return this.backwashQu.connected(xyTo1D(i, j), virtualTop); } public boolean percolates() { return this.qu.connected(virtualBottom, virtualTop); } public static void main(String[] args) { Percolation p = new Percolation(10); p.open(1, 1); p.open(1, 2); boolean a = p.isFull(1, 2); System.out.print(a); } }
25.027523
81
0.522361
d41506b5a8fc8b9617dc93bc592e057d1b2dd97d
8,633
/* * Copyright 2010-2022 Jan de Jongh <jfcmdejongh@gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.javajdj.jinstrument.swing.instrument.hp3325b; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; import org.javajdj.jinstrument.Instrument; import org.javajdj.jinstrument.InstrumentListener; import org.javajdj.jinstrument.InstrumentReading; import org.javajdj.jinstrument.InstrumentSettings; import org.javajdj.jinstrument.InstrumentStatus; import org.javajdj.jinstrument.InstrumentView; import org.javajdj.jinstrument.InstrumentViewType; import org.javajdj.jinstrument.FunctionGenerator; import org.javajdj.jinstrument.gpib.fg.hp3325b.HP3325B_GPIB_Instrument; import org.javajdj.jinstrument.gpib.fg.hp3325b.HP3325B_GPIB_Settings; import org.javajdj.jinstrument.swing.base.JInstrumentPanel; import org.javajdj.jinstrument.swing.base.JFunctionGeneratorPanel; import org.javajdj.jswing.jsevensegment.JSevenSegmentNumber; /** A Swing panel for the Frequency Sweep Time setting of a {@link HP3325B_GPIB_Instrument} Function Generator. * * @author Jan de Jongh {@literal <jfcmdejongh@gmail.com>} * */ public class JHP3325B_GPIB_FrequencySweepTime extends JFunctionGeneratorPanel implements InstrumentView { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // LOGGER // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private static final Logger LOG = Logger.getLogger (JHP3325B_GPIB_FrequencySweepTime.class.getName ()); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // CONSTRUCTOR(S) / FACTORY / CLONING // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public JHP3325B_GPIB_FrequencySweepTime ( final FunctionGenerator functionGenerator, final String title, final int level, final Color panelColor) { super (functionGenerator, title, level, panelColor); if (! (functionGenerator instanceof HP3325B_GPIB_Instrument)) throw new IllegalArgumentException (); final HP3325B_GPIB_Instrument hp3325b = (HP3325B_GPIB_Instrument) functionGenerator; removeAll (); setLayout (new GridLayout (1, 1)); this.jTime = new JSevenSegmentNumber (JInstrumentPanel.getGuiPreferencesTimeColor (), false, 7, 3); this.jTime.addMouseListener (this.jTimeMouseListener); add (this.jTime); getFunctionGenerator ().addInstrumentListener (this.instrumentListener); } public JHP3325B_GPIB_FrequencySweepTime (final HP3325B_GPIB_Instrument functionGenerator, final int level) { this (functionGenerator, null, level, null); } public JHP3325B_GPIB_FrequencySweepTime (final HP3325B_GPIB_Instrument functionGenerator) { this (functionGenerator, 0); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // INSTRUMENT VIEW TYPE // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public final static InstrumentViewType INSTRUMENT_VIEW_TYPE = new InstrumentViewType () { @Override public final String getInstrumentViewTypeUrl () { return "HP-3325B [GPIB] Frequency Sweep Time Setting"; } @Override public final InstrumentView openInstrumentView (final Instrument instrument) { if (instrument != null && (instrument instanceof HP3325B_GPIB_Instrument)) return new JHP3325B_GPIB_FrequencySweepTime ((HP3325B_GPIB_Instrument) instrument); else return null; } }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // InstrumentView // URL / NAME / toString // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Override public String getInstrumentViewUrl () { return JHP3325B_GPIB_FrequencySweepTime.INSTRUMENT_VIEW_TYPE.getInstrumentViewTypeUrl () + "<>" + getInstrument ().getInstrumentUrl (); } @Override public String toString () { return getInstrumentViewUrl (); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // SWING // FREQUENCY // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private final JSevenSegmentNumber jTime; private final MouseListener jTimeMouseListener = new MouseAdapter () { @Override public void mouseClicked (final MouseEvent me) { final Double newTime_s = getPeriodFromDialog_s ("Enter Sweep Time [s]", null); if (newTime_s != null) try { ((HP3325B_GPIB_Instrument) JHP3325B_GPIB_FrequencySweepTime.this.getFunctionGenerator ()).setSweepTime_s ( newTime_s); } catch (InterruptedException ie) { LOG.log (Level.INFO, "Caught InterruptedException while setting frequency sweep time on instrument: {0}.", ie.getStackTrace ()); } catch (IOException ioe) { LOG.log (Level.INFO, "Caught IOException while setting frequency sweep time on instrument: {0}.", ioe.getStackTrace ()); } } }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // INSTRUMENT LISTENER // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private final InstrumentListener instrumentListener = new InstrumentListener () { @Override public void newInstrumentStatus (final Instrument instrument, final InstrumentStatus instrumentStatus) { // EMPTY } @Override public void newInstrumentSettings (final Instrument instrument, final InstrumentSettings instrumentSettings) { if (instrument != JHP3325B_GPIB_FrequencySweepTime.this.getFunctionGenerator ()|| instrumentSettings == null) throw new IllegalArgumentException (); if (! (instrumentSettings instanceof HP3325B_GPIB_Settings)) throw new IllegalArgumentException (); final HP3325B_GPIB_Settings settings = (HP3325B_GPIB_Settings) instrumentSettings; SwingUtilities.invokeLater (() -> { JHP3325B_GPIB_FrequencySweepTime.this.inhibitInstrumentControl = true; // try { final double rem_s = settings.getSweepTime_s (); final int reading_s = (int) Math.floor (rem_s); final double rem_ms = rem_s - reading_s; final int reading_ms = (int) Math.floor (rem_ms * 1.0e3); JHP3325B_GPIB_FrequencySweepTime.this.jTime.setNumber (reading_s + 1.0e-3 * reading_ms); } finally { JHP3325B_GPIB_FrequencySweepTime.this.inhibitInstrumentControl = false; } }); } @Override public void newInstrumentReading (final Instrument instrument, final InstrumentReading instrumentReading) { // EMPTY } }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // END OF FILE // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }
36.42616
132
0.556817
0f77d9a1e592a24639a10ed94b6e79c9acc315b0
714
package com.concordium.sdk.responses.transactionstatus; import com.concordium.sdk.transactions.AccountAddress; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.ToString; /** * Account is not a delegation account. */ @ToString @Getter public class RejectReasonNotADelegator extends RejectReason { private final AccountAddress accountAddress; @JsonCreator RejectReasonNotADelegator(@JsonProperty("contents") AccountAddress accountAddress) { this.accountAddress = accountAddress; } @Override public RejectReasonType getType() { return RejectReasonType.NOT_A_DELEGATOR; } }
26.444444
88
0.780112
1c99f268dda42c3e74135305225b271db782d6d7
451
package com.g10.ssm.po; public class Permission { private Integer permissionId; private String name; public Integer getPermissionId() { return permissionId; } public void setPermissionId(Integer permissionId) { this.permissionId = permissionId; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } }
19.608696
55
0.629712
90da4d0f781d68218fb9f514137e98b9355f49c8
84,905
/* * @(#)MmeIuIf.java 1.0 09/12/14 * * This file has been auto-generated by JNC, the * Java output format plug-in of pyang. * Origin: module "hcta-epc", revision: "2014-09-18". */ package hctaEpc.mmeSgsn.interface_.iu; import .ietfInetTypes.IpAddress; import Element; import Epc; import JNCException; import com.tailf.jnc.YangElement; import com.tailf.jnc.YangEnumeration; import com.tailf.jnc.YangString; import com.tailf.jnc.YangUInt16; import com.tailf.jnc.YangUInt8; /** * This class represents an element from * the namespace http://hitachi-cta.com/ns/epc * generated to "src/hctaEpc/mmeSgsn/interface_/iu/mme-iu-if" * <p> * See line 45 in * rncConfig.yang * * @version 1.0 2014-12-09 * @author Auto Generated */ public class MmeIuIf extends YangElement { private static final long serialVersionUID = 1L; /** * Constructor for an empty MmeIuIf object. */ public MmeIuIf() { super(Epc.NAMESPACE, "mme-iu-if"); } /** * Clones this object, returning an exact copy. * @return A clone of the object. */ public MmeIuIf clone() { return (MmeIuIf)cloneContent(new MmeIuIf()); } /** * Clones this object, returning a shallow copy. * @return A clone of the object. Children are not included. */ public MmeIuIf cloneShallow() { return (MmeIuIf)cloneShallowContent(new MmeIuIf()); } /** * @return An array with the identifiers of any key children */ public String[] keyNames() { return null; } /** * @return An array with the identifiers of any children, in order. */ public String[] childrenNames() { return new String[] { "reset-ack-timer-tratr", "reset-timer-trafr", "reset-retry-trafr", "sccp-class-of-service", "sccp-connection-establish-timer", "sccp-inactivity-test-timer", "sccp-inactivity-receive-timer", "sccp-timer-release", "sccp-timer-repeat-release", "sccp-pause-delay-timer", "trab-assgt-timer", "trab-assgt-retry", "reloc-alloc-timer", "reloc-complete-timer", "iu-release-timer", "iu-signaling-act-timer", "security-mode-timer", "security-mode-retry", "srns-rau-timer", "inter-rat-indirect-forwarding", "indirect-data-fwd-ip-address", "indirect-tunnel-hold-timer", "version", "reloc-resource-release-timer", "dscp-mark", "csg-expiration-release-timer", "signaling-variant", }; } /* Access methods for optional leaf child: "reset-ack-timer-tratr". */ /** * Gets the value for child leaf "reset-ack-timer-tratr". * @return The value of the leaf. */ public YangUInt8 getResetAckTimerTratrValue() throws JNCException { YangUInt8 resetAckTimerTratr = (YangUInt8)getValue("reset-ack-timer-tratr"); if (resetAckTimerTratr == null) { resetAckTimerTratr = new YangUInt8("60"); // default } return resetAckTimerTratr; } /** * Sets the value for child leaf "reset-ack-timer-tratr", * using instance of generated typedef class. * @param resetAckTimerTratrValue The value to set. * @param resetAckTimerTratrValue used during instantiation. */ public void setResetAckTimerTratrValue(YangUInt8 resetAckTimerTratrValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "reset-ack-timer-tratr", resetAckTimerTratrValue, childrenNames()); } /** * Sets the value for child leaf "reset-ack-timer-tratr", * using Java primitive values. * @param resetAckTimerTratrValue used during instantiation. */ public void setResetAckTimerTratrValue(short resetAckTimerTratrValue) throws JNCException { setResetAckTimerTratrValue(new YangUInt8(resetAckTimerTratrValue)); } /** * Sets the value for child leaf "reset-ack-timer-tratr", * using a String value. * @param resetAckTimerTratrValue used during instantiation. */ public void setResetAckTimerTratrValue(String resetAckTimerTratrValue) throws JNCException { setResetAckTimerTratrValue(new YangUInt8(resetAckTimerTratrValue)); } /** * Unsets the value for child leaf "reset-ack-timer-tratr". */ public void unsetResetAckTimerTratrValue() throws JNCException { delete("reset-ack-timer-tratr"); } /** * This method is used for creating a subtree filter. * The added "reset-ack-timer-tratr" leaf will not have a value. */ public void addResetAckTimerTratr() throws JNCException { setLeafValue(Epc.NAMESPACE, "reset-ack-timer-tratr", null, childrenNames()); } /** * Marks the leaf "reset-ack-timer-tratr" with operation "replace". */ public void markResetAckTimerTratrReplace() throws JNCException { markLeafReplace("resetAckTimerTratr"); } /** * Marks the leaf "reset-ack-timer-tratr" with operation "merge". */ public void markResetAckTimerTratrMerge() throws JNCException { markLeafMerge("resetAckTimerTratr"); } /** * Marks the leaf "reset-ack-timer-tratr" with operation "create". */ public void markResetAckTimerTratrCreate() throws JNCException { markLeafCreate("resetAckTimerTratr"); } /** * Marks the leaf "reset-ack-timer-tratr" with operation "delete". */ public void markResetAckTimerTratrDelete() throws JNCException { markLeafDelete("resetAckTimerTratr"); } /* Access methods for optional leaf child: "reset-timer-trafr". */ /** * Gets the value for child leaf "reset-timer-trafr". * @return The value of the leaf. */ public YangUInt8 getResetTimerTrafrValue() throws JNCException { YangUInt8 resetTimerTrafr = (YangUInt8)getValue("reset-timer-trafr"); if (resetTimerTrafr == null) { resetTimerTrafr = new YangUInt8("90"); // default } return resetTimerTrafr; } /** * Sets the value for child leaf "reset-timer-trafr", * using instance of generated typedef class. * @param resetTimerTrafrValue The value to set. * @param resetTimerTrafrValue used during instantiation. */ public void setResetTimerTrafrValue(YangUInt8 resetTimerTrafrValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "reset-timer-trafr", resetTimerTrafrValue, childrenNames()); } /** * Sets the value for child leaf "reset-timer-trafr", * using Java primitive values. * @param resetTimerTrafrValue used during instantiation. */ public void setResetTimerTrafrValue(short resetTimerTrafrValue) throws JNCException { setResetTimerTrafrValue(new YangUInt8(resetTimerTrafrValue)); } /** * Sets the value for child leaf "reset-timer-trafr", * using a String value. * @param resetTimerTrafrValue used during instantiation. */ public void setResetTimerTrafrValue(String resetTimerTrafrValue) throws JNCException { setResetTimerTrafrValue(new YangUInt8(resetTimerTrafrValue)); } /** * Unsets the value for child leaf "reset-timer-trafr". */ public void unsetResetTimerTrafrValue() throws JNCException { delete("reset-timer-trafr"); } /** * This method is used for creating a subtree filter. * The added "reset-timer-trafr" leaf will not have a value. */ public void addResetTimerTrafr() throws JNCException { setLeafValue(Epc.NAMESPACE, "reset-timer-trafr", null, childrenNames()); } /** * Marks the leaf "reset-timer-trafr" with operation "replace". */ public void markResetTimerTrafrReplace() throws JNCException { markLeafReplace("resetTimerTrafr"); } /** * Marks the leaf "reset-timer-trafr" with operation "merge". */ public void markResetTimerTrafrMerge() throws JNCException { markLeafMerge("resetTimerTrafr"); } /** * Marks the leaf "reset-timer-trafr" with operation "create". */ public void markResetTimerTrafrCreate() throws JNCException { markLeafCreate("resetTimerTrafr"); } /** * Marks the leaf "reset-timer-trafr" with operation "delete". */ public void markResetTimerTrafrDelete() throws JNCException { markLeafDelete("resetTimerTrafr"); } /* Access methods for optional leaf child: "reset-retry-trafr". */ /** * Gets the value for child leaf "reset-retry-trafr". * @return The value of the leaf. */ public YangUInt8 getResetRetryTrafrValue() throws JNCException { YangUInt8 resetRetryTrafr = (YangUInt8)getValue("reset-retry-trafr"); if (resetRetryTrafr == null) { resetRetryTrafr = new YangUInt8("1"); // default } return resetRetryTrafr; } /** * Sets the value for child leaf "reset-retry-trafr", * using instance of generated typedef class. * @param resetRetryTrafrValue The value to set. * @param resetRetryTrafrValue used during instantiation. */ public void setResetRetryTrafrValue(YangUInt8 resetRetryTrafrValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "reset-retry-trafr", resetRetryTrafrValue, childrenNames()); } /** * Sets the value for child leaf "reset-retry-trafr", * using Java primitive values. * @param resetRetryTrafrValue used during instantiation. */ public void setResetRetryTrafrValue(short resetRetryTrafrValue) throws JNCException { setResetRetryTrafrValue(new YangUInt8(resetRetryTrafrValue)); } /** * Sets the value for child leaf "reset-retry-trafr", * using a String value. * @param resetRetryTrafrValue used during instantiation. */ public void setResetRetryTrafrValue(String resetRetryTrafrValue) throws JNCException { setResetRetryTrafrValue(new YangUInt8(resetRetryTrafrValue)); } /** * Unsets the value for child leaf "reset-retry-trafr". */ public void unsetResetRetryTrafrValue() throws JNCException { delete("reset-retry-trafr"); } /** * This method is used for creating a subtree filter. * The added "reset-retry-trafr" leaf will not have a value. */ public void addResetRetryTrafr() throws JNCException { setLeafValue(Epc.NAMESPACE, "reset-retry-trafr", null, childrenNames()); } /** * Marks the leaf "reset-retry-trafr" with operation "replace". */ public void markResetRetryTrafrReplace() throws JNCException { markLeafReplace("resetRetryTrafr"); } /** * Marks the leaf "reset-retry-trafr" with operation "merge". */ public void markResetRetryTrafrMerge() throws JNCException { markLeafMerge("resetRetryTrafr"); } /** * Marks the leaf "reset-retry-trafr" with operation "create". */ public void markResetRetryTrafrCreate() throws JNCException { markLeafCreate("resetRetryTrafr"); } /** * Marks the leaf "reset-retry-trafr" with operation "delete". */ public void markResetRetryTrafrDelete() throws JNCException { markLeafDelete("resetRetryTrafr"); } /* Access methods for optional leaf child: "sccp-class-of-service". */ /** * Gets the value for child leaf "sccp-class-of-service". * @return The value of the leaf. */ public YangEnumeration getSccpClassOfServiceValue() throws JNCException { return (YangEnumeration)getValue("sccp-class-of-service"); } /** * Sets the value for child leaf "sccp-class-of-service", * using instance of generated typedef class. * @param sccpClassOfServiceValue The value to set. * @param sccpClassOfServiceValue used during instantiation. */ public void setSccpClassOfServiceValue(YangEnumeration sccpClassOfServiceValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-class-of-service", sccpClassOfServiceValue, childrenNames()); } /** * Sets the value for child leaf "sccp-class-of-service", * using a String value. * @param sccpClassOfServiceValue used during instantiation. */ public void setSccpClassOfServiceValue(String sccpClassOfServiceValue) throws JNCException { setSccpClassOfServiceValue(new YangEnumeration(sccpClassOfServiceValue, new String[] { "connection-less", "connection-oriented", "connection-less,connection-oriented", })); } /** * Unsets the value for child leaf "sccp-class-of-service". */ public void unsetSccpClassOfServiceValue() throws JNCException { delete("sccp-class-of-service"); } /** * This method is used for creating a subtree filter. * The added "sccp-class-of-service" leaf will not have a value. */ public void addSccpClassOfService() throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-class-of-service", null, childrenNames()); } /** * Marks the leaf "sccp-class-of-service" with operation "replace". */ public void markSccpClassOfServiceReplace() throws JNCException { markLeafReplace("sccpClassOfService"); } /** * Marks the leaf "sccp-class-of-service" with operation "merge". */ public void markSccpClassOfServiceMerge() throws JNCException { markLeafMerge("sccpClassOfService"); } /** * Marks the leaf "sccp-class-of-service" with operation "create". */ public void markSccpClassOfServiceCreate() throws JNCException { markLeafCreate("sccpClassOfService"); } /** * Marks the leaf "sccp-class-of-service" with operation "delete". */ public void markSccpClassOfServiceDelete() throws JNCException { markLeafDelete("sccpClassOfService"); } /* Access methods for optional leaf child: "sccp-connection-establish-timer". */ /** * Gets the value for child leaf "sccp-connection-establish-timer". * @return The value of the leaf. */ public YangUInt8 getSccpConnectionEstablishTimerValue() throws JNCException { YangUInt8 sccpConnectionEstablishTimer = (YangUInt8)getValue("sccp-connection-establish-timer"); if (sccpConnectionEstablishTimer == null) { sccpConnectionEstablishTimer = new YangUInt8("60"); // default } return sccpConnectionEstablishTimer; } /** * Sets the value for child leaf "sccp-connection-establish-timer", * using instance of generated typedef class. * @param sccpConnectionEstablishTimerValue The value to set. * @param sccpConnectionEstablishTimerValue used during instantiation. */ public void setSccpConnectionEstablishTimerValue(YangUInt8 sccpConnectionEstablishTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-connection-establish-timer", sccpConnectionEstablishTimerValue, childrenNames()); } /** * Sets the value for child leaf "sccp-connection-establish-timer", * using Java primitive values. * @param sccpConnectionEstablishTimerValue used during instantiation. */ public void setSccpConnectionEstablishTimerValue(short sccpConnectionEstablishTimerValue) throws JNCException { setSccpConnectionEstablishTimerValue(new YangUInt8(sccpConnectionEstablishTimerValue)); } /** * Sets the value for child leaf "sccp-connection-establish-timer", * using a String value. * @param sccpConnectionEstablishTimerValue used during instantiation. */ public void setSccpConnectionEstablishTimerValue(String sccpConnectionEstablishTimerValue) throws JNCException { setSccpConnectionEstablishTimerValue(new YangUInt8(sccpConnectionEstablishTimerValue)); } /** * Unsets the value for child leaf "sccp-connection-establish-timer". */ public void unsetSccpConnectionEstablishTimerValue() throws JNCException { delete("sccp-connection-establish-timer"); } /** * This method is used for creating a subtree filter. * The added "sccp-connection-establish-timer" leaf will not have a value. */ public void addSccpConnectionEstablishTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-connection-establish-timer", null, childrenNames()); } /** * Marks the leaf "sccp-connection-establish-timer" with operation "replace". */ public void markSccpConnectionEstablishTimerReplace() throws JNCException { markLeafReplace("sccpConnectionEstablishTimer"); } /** * Marks the leaf "sccp-connection-establish-timer" with operation "merge". */ public void markSccpConnectionEstablishTimerMerge() throws JNCException { markLeafMerge("sccpConnectionEstablishTimer"); } /** * Marks the leaf "sccp-connection-establish-timer" with operation "create". */ public void markSccpConnectionEstablishTimerCreate() throws JNCException { markLeafCreate("sccpConnectionEstablishTimer"); } /** * Marks the leaf "sccp-connection-establish-timer" with operation "delete". */ public void markSccpConnectionEstablishTimerDelete() throws JNCException { markLeafDelete("sccpConnectionEstablishTimer"); } /* Access methods for optional leaf child: "sccp-inactivity-test-timer". */ /** * Gets the value for child leaf "sccp-inactivity-test-timer". * @return The value of the leaf. */ public YangUInt16 getSccpInactivityTestTimerValue() throws JNCException { YangUInt16 sccpInactivityTestTimer = (YangUInt16)getValue("sccp-inactivity-test-timer"); if (sccpInactivityTestTimer == null) { sccpInactivityTestTimer = new YangUInt16("300"); // default } return sccpInactivityTestTimer; } /** * Sets the value for child leaf "sccp-inactivity-test-timer", * using instance of generated typedef class. * @param sccpInactivityTestTimerValue The value to set. * @param sccpInactivityTestTimerValue used during instantiation. */ public void setSccpInactivityTestTimerValue(YangUInt16 sccpInactivityTestTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-inactivity-test-timer", sccpInactivityTestTimerValue, childrenNames()); } /** * Sets the value for child leaf "sccp-inactivity-test-timer", * using Java primitive values. * @param sccpInactivityTestTimerValue used during instantiation. */ public void setSccpInactivityTestTimerValue(int sccpInactivityTestTimerValue) throws JNCException { setSccpInactivityTestTimerValue(new YangUInt16(sccpInactivityTestTimerValue)); } /** * Sets the value for child leaf "sccp-inactivity-test-timer", * using a String value. * @param sccpInactivityTestTimerValue used during instantiation. */ public void setSccpInactivityTestTimerValue(String sccpInactivityTestTimerValue) throws JNCException { setSccpInactivityTestTimerValue(new YangUInt16(sccpInactivityTestTimerValue)); } /** * Unsets the value for child leaf "sccp-inactivity-test-timer". */ public void unsetSccpInactivityTestTimerValue() throws JNCException { delete("sccp-inactivity-test-timer"); } /** * This method is used for creating a subtree filter. * The added "sccp-inactivity-test-timer" leaf will not have a value. */ public void addSccpInactivityTestTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-inactivity-test-timer", null, childrenNames()); } /** * Marks the leaf "sccp-inactivity-test-timer" with operation "replace". */ public void markSccpInactivityTestTimerReplace() throws JNCException { markLeafReplace("sccpInactivityTestTimer"); } /** * Marks the leaf "sccp-inactivity-test-timer" with operation "merge". */ public void markSccpInactivityTestTimerMerge() throws JNCException { markLeafMerge("sccpInactivityTestTimer"); } /** * Marks the leaf "sccp-inactivity-test-timer" with operation "create". */ public void markSccpInactivityTestTimerCreate() throws JNCException { markLeafCreate("sccpInactivityTestTimer"); } /** * Marks the leaf "sccp-inactivity-test-timer" with operation "delete". */ public void markSccpInactivityTestTimerDelete() throws JNCException { markLeafDelete("sccpInactivityTestTimer"); } /* Access methods for optional leaf child: "sccp-inactivity-receive-timer". */ /** * Gets the value for child leaf "sccp-inactivity-receive-timer". * @return The value of the leaf. */ public YangUInt16 getSccpInactivityReceiveTimerValue() throws JNCException { YangUInt16 sccpInactivityReceiveTimer = (YangUInt16)getValue("sccp-inactivity-receive-timer"); if (sccpInactivityReceiveTimer == null) { sccpInactivityReceiveTimer = new YangUInt16("660"); // default } return sccpInactivityReceiveTimer; } /** * Sets the value for child leaf "sccp-inactivity-receive-timer", * using instance of generated typedef class. * @param sccpInactivityReceiveTimerValue The value to set. * @param sccpInactivityReceiveTimerValue used during instantiation. */ public void setSccpInactivityReceiveTimerValue(YangUInt16 sccpInactivityReceiveTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-inactivity-receive-timer", sccpInactivityReceiveTimerValue, childrenNames()); } /** * Sets the value for child leaf "sccp-inactivity-receive-timer", * using Java primitive values. * @param sccpInactivityReceiveTimerValue used during instantiation. */ public void setSccpInactivityReceiveTimerValue(int sccpInactivityReceiveTimerValue) throws JNCException { setSccpInactivityReceiveTimerValue(new YangUInt16(sccpInactivityReceiveTimerValue)); } /** * Sets the value for child leaf "sccp-inactivity-receive-timer", * using a String value. * @param sccpInactivityReceiveTimerValue used during instantiation. */ public void setSccpInactivityReceiveTimerValue(String sccpInactivityReceiveTimerValue) throws JNCException { setSccpInactivityReceiveTimerValue(new YangUInt16(sccpInactivityReceiveTimerValue)); } /** * Unsets the value for child leaf "sccp-inactivity-receive-timer". */ public void unsetSccpInactivityReceiveTimerValue() throws JNCException { delete("sccp-inactivity-receive-timer"); } /** * This method is used for creating a subtree filter. * The added "sccp-inactivity-receive-timer" leaf will not have a value. */ public void addSccpInactivityReceiveTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-inactivity-receive-timer", null, childrenNames()); } /** * Marks the leaf "sccp-inactivity-receive-timer" with operation "replace". */ public void markSccpInactivityReceiveTimerReplace() throws JNCException { markLeafReplace("sccpInactivityReceiveTimer"); } /** * Marks the leaf "sccp-inactivity-receive-timer" with operation "merge". */ public void markSccpInactivityReceiveTimerMerge() throws JNCException { markLeafMerge("sccpInactivityReceiveTimer"); } /** * Marks the leaf "sccp-inactivity-receive-timer" with operation "create". */ public void markSccpInactivityReceiveTimerCreate() throws JNCException { markLeafCreate("sccpInactivityReceiveTimer"); } /** * Marks the leaf "sccp-inactivity-receive-timer" with operation "delete". */ public void markSccpInactivityReceiveTimerDelete() throws JNCException { markLeafDelete("sccpInactivityReceiveTimer"); } /* Access methods for optional leaf child: "sccp-timer-release". */ /** * Gets the value for child leaf "sccp-timer-release". * @return The value of the leaf. */ public YangUInt8 getSccpTimerReleaseValue() throws JNCException { YangUInt8 sccpTimerRelease = (YangUInt8)getValue("sccp-timer-release"); if (sccpTimerRelease == null) { sccpTimerRelease = new YangUInt8("10"); // default } return sccpTimerRelease; } /** * Sets the value for child leaf "sccp-timer-release", * using instance of generated typedef class. * @param sccpTimerReleaseValue The value to set. * @param sccpTimerReleaseValue used during instantiation. */ public void setSccpTimerReleaseValue(YangUInt8 sccpTimerReleaseValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-timer-release", sccpTimerReleaseValue, childrenNames()); } /** * Sets the value for child leaf "sccp-timer-release", * using Java primitive values. * @param sccpTimerReleaseValue used during instantiation. */ public void setSccpTimerReleaseValue(short sccpTimerReleaseValue) throws JNCException { setSccpTimerReleaseValue(new YangUInt8(sccpTimerReleaseValue)); } /** * Sets the value for child leaf "sccp-timer-release", * using a String value. * @param sccpTimerReleaseValue used during instantiation. */ public void setSccpTimerReleaseValue(String sccpTimerReleaseValue) throws JNCException { setSccpTimerReleaseValue(new YangUInt8(sccpTimerReleaseValue)); } /** * Unsets the value for child leaf "sccp-timer-release". */ public void unsetSccpTimerReleaseValue() throws JNCException { delete("sccp-timer-release"); } /** * This method is used for creating a subtree filter. * The added "sccp-timer-release" leaf will not have a value. */ public void addSccpTimerRelease() throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-timer-release", null, childrenNames()); } /** * Marks the leaf "sccp-timer-release" with operation "replace". */ public void markSccpTimerReleaseReplace() throws JNCException { markLeafReplace("sccpTimerRelease"); } /** * Marks the leaf "sccp-timer-release" with operation "merge". */ public void markSccpTimerReleaseMerge() throws JNCException { markLeafMerge("sccpTimerRelease"); } /** * Marks the leaf "sccp-timer-release" with operation "create". */ public void markSccpTimerReleaseCreate() throws JNCException { markLeafCreate("sccpTimerRelease"); } /** * Marks the leaf "sccp-timer-release" with operation "delete". */ public void markSccpTimerReleaseDelete() throws JNCException { markLeafDelete("sccpTimerRelease"); } /* Access methods for optional leaf child: "sccp-timer-repeat-release". */ /** * Gets the value for child leaf "sccp-timer-repeat-release". * @return The value of the leaf. */ public YangUInt8 getSccpTimerRepeatReleaseValue() throws JNCException { YangUInt8 sccpTimerRepeatRelease = (YangUInt8)getValue("sccp-timer-repeat-release"); if (sccpTimerRepeatRelease == null) { sccpTimerRepeatRelease = new YangUInt8("20"); // default } return sccpTimerRepeatRelease; } /** * Sets the value for child leaf "sccp-timer-repeat-release", * using instance of generated typedef class. * @param sccpTimerRepeatReleaseValue The value to set. * @param sccpTimerRepeatReleaseValue used during instantiation. */ public void setSccpTimerRepeatReleaseValue(YangUInt8 sccpTimerRepeatReleaseValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-timer-repeat-release", sccpTimerRepeatReleaseValue, childrenNames()); } /** * Sets the value for child leaf "sccp-timer-repeat-release", * using Java primitive values. * @param sccpTimerRepeatReleaseValue used during instantiation. */ public void setSccpTimerRepeatReleaseValue(short sccpTimerRepeatReleaseValue) throws JNCException { setSccpTimerRepeatReleaseValue(new YangUInt8(sccpTimerRepeatReleaseValue)); } /** * Sets the value for child leaf "sccp-timer-repeat-release", * using a String value. * @param sccpTimerRepeatReleaseValue used during instantiation. */ public void setSccpTimerRepeatReleaseValue(String sccpTimerRepeatReleaseValue) throws JNCException { setSccpTimerRepeatReleaseValue(new YangUInt8(sccpTimerRepeatReleaseValue)); } /** * Unsets the value for child leaf "sccp-timer-repeat-release". */ public void unsetSccpTimerRepeatReleaseValue() throws JNCException { delete("sccp-timer-repeat-release"); } /** * This method is used for creating a subtree filter. * The added "sccp-timer-repeat-release" leaf will not have a value. */ public void addSccpTimerRepeatRelease() throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-timer-repeat-release", null, childrenNames()); } /** * Marks the leaf "sccp-timer-repeat-release" with operation "replace". */ public void markSccpTimerRepeatReleaseReplace() throws JNCException { markLeafReplace("sccpTimerRepeatRelease"); } /** * Marks the leaf "sccp-timer-repeat-release" with operation "merge". */ public void markSccpTimerRepeatReleaseMerge() throws JNCException { markLeafMerge("sccpTimerRepeatRelease"); } /** * Marks the leaf "sccp-timer-repeat-release" with operation "create". */ public void markSccpTimerRepeatReleaseCreate() throws JNCException { markLeafCreate("sccpTimerRepeatRelease"); } /** * Marks the leaf "sccp-timer-repeat-release" with operation "delete". */ public void markSccpTimerRepeatReleaseDelete() throws JNCException { markLeafDelete("sccpTimerRepeatRelease"); } /* Access methods for optional leaf child: "sccp-pause-delay-timer". */ /** * Gets the value for child leaf "sccp-pause-delay-timer". * @return The value of the leaf. */ public YangString getSccpPauseDelayTimerValue() throws JNCException { YangString sccpPauseDelayTimer = (YangString)getValue("sccp-pause-delay-timer"); if (sccpPauseDelayTimer == null) { sccpPauseDelayTimer = new YangString("120"); // default } return sccpPauseDelayTimer; } /** * Sets the value for child leaf "sccp-pause-delay-timer", * using instance of generated typedef class. * @param sccpPauseDelayTimerValue The value to set. * @param sccpPauseDelayTimerValue used during instantiation. */ public void setSccpPauseDelayTimerValue(YangString sccpPauseDelayTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-pause-delay-timer", sccpPauseDelayTimerValue, childrenNames()); } /** * Sets the value for child leaf "sccp-pause-delay-timer", * using a String value. * @param sccpPauseDelayTimerValue used during instantiation. */ public void setSccpPauseDelayTimerValue(String sccpPauseDelayTimerValue) throws JNCException { setSccpPauseDelayTimerValue(new YangString(sccpPauseDelayTimerValue)); } /** * Unsets the value for child leaf "sccp-pause-delay-timer". */ public void unsetSccpPauseDelayTimerValue() throws JNCException { delete("sccp-pause-delay-timer"); } /** * This method is used for creating a subtree filter. * The added "sccp-pause-delay-timer" leaf will not have a value. */ public void addSccpPauseDelayTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "sccp-pause-delay-timer", null, childrenNames()); } /** * Marks the leaf "sccp-pause-delay-timer" with operation "replace". */ public void markSccpPauseDelayTimerReplace() throws JNCException { markLeafReplace("sccpPauseDelayTimer"); } /** * Marks the leaf "sccp-pause-delay-timer" with operation "merge". */ public void markSccpPauseDelayTimerMerge() throws JNCException { markLeafMerge("sccpPauseDelayTimer"); } /** * Marks the leaf "sccp-pause-delay-timer" with operation "create". */ public void markSccpPauseDelayTimerCreate() throws JNCException { markLeafCreate("sccpPauseDelayTimer"); } /** * Marks the leaf "sccp-pause-delay-timer" with operation "delete". */ public void markSccpPauseDelayTimerDelete() throws JNCException { markLeafDelete("sccpPauseDelayTimer"); } /* Access methods for optional leaf child: "trab-assgt-timer". */ /** * Gets the value for child leaf "trab-assgt-timer". * @return The value of the leaf. */ public YangUInt8 getTrabAssgtTimerValue() throws JNCException { YangUInt8 trabAssgtTimer = (YangUInt8)getValue("trab-assgt-timer"); if (trabAssgtTimer == null) { trabAssgtTimer = new YangUInt8("4"); // default } return trabAssgtTimer; } /** * Sets the value for child leaf "trab-assgt-timer", * using instance of generated typedef class. * @param trabAssgtTimerValue The value to set. * @param trabAssgtTimerValue used during instantiation. */ public void setTrabAssgtTimerValue(YangUInt8 trabAssgtTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "trab-assgt-timer", trabAssgtTimerValue, childrenNames()); } /** * Sets the value for child leaf "trab-assgt-timer", * using Java primitive values. * @param trabAssgtTimerValue used during instantiation. */ public void setTrabAssgtTimerValue(short trabAssgtTimerValue) throws JNCException { setTrabAssgtTimerValue(new YangUInt8(trabAssgtTimerValue)); } /** * Sets the value for child leaf "trab-assgt-timer", * using a String value. * @param trabAssgtTimerValue used during instantiation. */ public void setTrabAssgtTimerValue(String trabAssgtTimerValue) throws JNCException { setTrabAssgtTimerValue(new YangUInt8(trabAssgtTimerValue)); } /** * Unsets the value for child leaf "trab-assgt-timer". */ public void unsetTrabAssgtTimerValue() throws JNCException { delete("trab-assgt-timer"); } /** * This method is used for creating a subtree filter. * The added "trab-assgt-timer" leaf will not have a value. */ public void addTrabAssgtTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "trab-assgt-timer", null, childrenNames()); } /** * Marks the leaf "trab-assgt-timer" with operation "replace". */ public void markTrabAssgtTimerReplace() throws JNCException { markLeafReplace("trabAssgtTimer"); } /** * Marks the leaf "trab-assgt-timer" with operation "merge". */ public void markTrabAssgtTimerMerge() throws JNCException { markLeafMerge("trabAssgtTimer"); } /** * Marks the leaf "trab-assgt-timer" with operation "create". */ public void markTrabAssgtTimerCreate() throws JNCException { markLeafCreate("trabAssgtTimer"); } /** * Marks the leaf "trab-assgt-timer" with operation "delete". */ public void markTrabAssgtTimerDelete() throws JNCException { markLeafDelete("trabAssgtTimer"); } /* Access methods for optional leaf child: "trab-assgt-retry". */ /** * Gets the value for child leaf "trab-assgt-retry". * @return The value of the leaf. */ public YangUInt8 getTrabAssgtRetryValue() throws JNCException { YangUInt8 trabAssgtRetry = (YangUInt8)getValue("trab-assgt-retry"); if (trabAssgtRetry == null) { trabAssgtRetry = new YangUInt8("4"); // default } return trabAssgtRetry; } /** * Sets the value for child leaf "trab-assgt-retry", * using instance of generated typedef class. * @param trabAssgtRetryValue The value to set. * @param trabAssgtRetryValue used during instantiation. */ public void setTrabAssgtRetryValue(YangUInt8 trabAssgtRetryValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "trab-assgt-retry", trabAssgtRetryValue, childrenNames()); } /** * Sets the value for child leaf "trab-assgt-retry", * using Java primitive values. * @param trabAssgtRetryValue used during instantiation. */ public void setTrabAssgtRetryValue(short trabAssgtRetryValue) throws JNCException { setTrabAssgtRetryValue(new YangUInt8(trabAssgtRetryValue)); } /** * Sets the value for child leaf "trab-assgt-retry", * using a String value. * @param trabAssgtRetryValue used during instantiation. */ public void setTrabAssgtRetryValue(String trabAssgtRetryValue) throws JNCException { setTrabAssgtRetryValue(new YangUInt8(trabAssgtRetryValue)); } /** * Unsets the value for child leaf "trab-assgt-retry". */ public void unsetTrabAssgtRetryValue() throws JNCException { delete("trab-assgt-retry"); } /** * This method is used for creating a subtree filter. * The added "trab-assgt-retry" leaf will not have a value. */ public void addTrabAssgtRetry() throws JNCException { setLeafValue(Epc.NAMESPACE, "trab-assgt-retry", null, childrenNames()); } /** * Marks the leaf "trab-assgt-retry" with operation "replace". */ public void markTrabAssgtRetryReplace() throws JNCException { markLeafReplace("trabAssgtRetry"); } /** * Marks the leaf "trab-assgt-retry" with operation "merge". */ public void markTrabAssgtRetryMerge() throws JNCException { markLeafMerge("trabAssgtRetry"); } /** * Marks the leaf "trab-assgt-retry" with operation "create". */ public void markTrabAssgtRetryCreate() throws JNCException { markLeafCreate("trabAssgtRetry"); } /** * Marks the leaf "trab-assgt-retry" with operation "delete". */ public void markTrabAssgtRetryDelete() throws JNCException { markLeafDelete("trabAssgtRetry"); } /* Access methods for optional leaf child: "reloc-alloc-timer". */ /** * Gets the value for child leaf "reloc-alloc-timer". * @return The value of the leaf. */ public YangUInt8 getRelocAllocTimerValue() throws JNCException { YangUInt8 relocAllocTimer = (YangUInt8)getValue("reloc-alloc-timer"); if (relocAllocTimer == null) { relocAllocTimer = new YangUInt8("10"); // default } return relocAllocTimer; } /** * Sets the value for child leaf "reloc-alloc-timer", * using instance of generated typedef class. * @param relocAllocTimerValue The value to set. * @param relocAllocTimerValue used during instantiation. */ public void setRelocAllocTimerValue(YangUInt8 relocAllocTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "reloc-alloc-timer", relocAllocTimerValue, childrenNames()); } /** * Sets the value for child leaf "reloc-alloc-timer", * using Java primitive values. * @param relocAllocTimerValue used during instantiation. */ public void setRelocAllocTimerValue(short relocAllocTimerValue) throws JNCException { setRelocAllocTimerValue(new YangUInt8(relocAllocTimerValue)); } /** * Sets the value for child leaf "reloc-alloc-timer", * using a String value. * @param relocAllocTimerValue used during instantiation. */ public void setRelocAllocTimerValue(String relocAllocTimerValue) throws JNCException { setRelocAllocTimerValue(new YangUInt8(relocAllocTimerValue)); } /** * Unsets the value for child leaf "reloc-alloc-timer". */ public void unsetRelocAllocTimerValue() throws JNCException { delete("reloc-alloc-timer"); } /** * This method is used for creating a subtree filter. * The added "reloc-alloc-timer" leaf will not have a value. */ public void addRelocAllocTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "reloc-alloc-timer", null, childrenNames()); } /** * Marks the leaf "reloc-alloc-timer" with operation "replace". */ public void markRelocAllocTimerReplace() throws JNCException { markLeafReplace("relocAllocTimer"); } /** * Marks the leaf "reloc-alloc-timer" with operation "merge". */ public void markRelocAllocTimerMerge() throws JNCException { markLeafMerge("relocAllocTimer"); } /** * Marks the leaf "reloc-alloc-timer" with operation "create". */ public void markRelocAllocTimerCreate() throws JNCException { markLeafCreate("relocAllocTimer"); } /** * Marks the leaf "reloc-alloc-timer" with operation "delete". */ public void markRelocAllocTimerDelete() throws JNCException { markLeafDelete("relocAllocTimer"); } /* Access methods for optional leaf child: "reloc-complete-timer". */ /** * Gets the value for child leaf "reloc-complete-timer". * @return The value of the leaf. */ public YangUInt8 getRelocCompleteTimerValue() throws JNCException { YangUInt8 relocCompleteTimer = (YangUInt8)getValue("reloc-complete-timer"); if (relocCompleteTimer == null) { relocCompleteTimer = new YangUInt8("25"); // default } return relocCompleteTimer; } /** * Sets the value for child leaf "reloc-complete-timer", * using instance of generated typedef class. * @param relocCompleteTimerValue The value to set. * @param relocCompleteTimerValue used during instantiation. */ public void setRelocCompleteTimerValue(YangUInt8 relocCompleteTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "reloc-complete-timer", relocCompleteTimerValue, childrenNames()); } /** * Sets the value for child leaf "reloc-complete-timer", * using Java primitive values. * @param relocCompleteTimerValue used during instantiation. */ public void setRelocCompleteTimerValue(short relocCompleteTimerValue) throws JNCException { setRelocCompleteTimerValue(new YangUInt8(relocCompleteTimerValue)); } /** * Sets the value for child leaf "reloc-complete-timer", * using a String value. * @param relocCompleteTimerValue used during instantiation. */ public void setRelocCompleteTimerValue(String relocCompleteTimerValue) throws JNCException { setRelocCompleteTimerValue(new YangUInt8(relocCompleteTimerValue)); } /** * Unsets the value for child leaf "reloc-complete-timer". */ public void unsetRelocCompleteTimerValue() throws JNCException { delete("reloc-complete-timer"); } /** * This method is used for creating a subtree filter. * The added "reloc-complete-timer" leaf will not have a value. */ public void addRelocCompleteTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "reloc-complete-timer", null, childrenNames()); } /** * Marks the leaf "reloc-complete-timer" with operation "replace". */ public void markRelocCompleteTimerReplace() throws JNCException { markLeafReplace("relocCompleteTimer"); } /** * Marks the leaf "reloc-complete-timer" with operation "merge". */ public void markRelocCompleteTimerMerge() throws JNCException { markLeafMerge("relocCompleteTimer"); } /** * Marks the leaf "reloc-complete-timer" with operation "create". */ public void markRelocCompleteTimerCreate() throws JNCException { markLeafCreate("relocCompleteTimer"); } /** * Marks the leaf "reloc-complete-timer" with operation "delete". */ public void markRelocCompleteTimerDelete() throws JNCException { markLeafDelete("relocCompleteTimer"); } /* Access methods for optional leaf child: "iu-release-timer". */ /** * Gets the value for child leaf "iu-release-timer". * @return The value of the leaf. */ public YangUInt8 getIuReleaseTimerValue() throws JNCException { YangUInt8 iuReleaseTimer = (YangUInt8)getValue("iu-release-timer"); if (iuReleaseTimer == null) { iuReleaseTimer = new YangUInt8("5"); // default } return iuReleaseTimer; } /** * Sets the value for child leaf "iu-release-timer", * using instance of generated typedef class. * @param iuReleaseTimerValue The value to set. * @param iuReleaseTimerValue used during instantiation. */ public void setIuReleaseTimerValue(YangUInt8 iuReleaseTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "iu-release-timer", iuReleaseTimerValue, childrenNames()); } /** * Sets the value for child leaf "iu-release-timer", * using Java primitive values. * @param iuReleaseTimerValue used during instantiation. */ public void setIuReleaseTimerValue(short iuReleaseTimerValue) throws JNCException { setIuReleaseTimerValue(new YangUInt8(iuReleaseTimerValue)); } /** * Sets the value for child leaf "iu-release-timer", * using a String value. * @param iuReleaseTimerValue used during instantiation. */ public void setIuReleaseTimerValue(String iuReleaseTimerValue) throws JNCException { setIuReleaseTimerValue(new YangUInt8(iuReleaseTimerValue)); } /** * Unsets the value for child leaf "iu-release-timer". */ public void unsetIuReleaseTimerValue() throws JNCException { delete("iu-release-timer"); } /** * This method is used for creating a subtree filter. * The added "iu-release-timer" leaf will not have a value. */ public void addIuReleaseTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "iu-release-timer", null, childrenNames()); } /** * Marks the leaf "iu-release-timer" with operation "replace". */ public void markIuReleaseTimerReplace() throws JNCException { markLeafReplace("iuReleaseTimer"); } /** * Marks the leaf "iu-release-timer" with operation "merge". */ public void markIuReleaseTimerMerge() throws JNCException { markLeafMerge("iuReleaseTimer"); } /** * Marks the leaf "iu-release-timer" with operation "create". */ public void markIuReleaseTimerCreate() throws JNCException { markLeafCreate("iuReleaseTimer"); } /** * Marks the leaf "iu-release-timer" with operation "delete". */ public void markIuReleaseTimerDelete() throws JNCException { markLeafDelete("iuReleaseTimer"); } /* Access methods for optional leaf child: "iu-signaling-act-timer". */ /** * Gets the value for child leaf "iu-signaling-act-timer". * @return The value of the leaf. */ public YangString getIuSignalingActTimerValue() throws JNCException { YangString iuSignalingActTimer = (YangString)getValue("iu-signaling-act-timer"); if (iuSignalingActTimer == null) { iuSignalingActTimer = new YangString("5"); // default } return iuSignalingActTimer; } /** * Sets the value for child leaf "iu-signaling-act-timer", * using instance of generated typedef class. * @param iuSignalingActTimerValue The value to set. * @param iuSignalingActTimerValue used during instantiation. */ public void setIuSignalingActTimerValue(YangString iuSignalingActTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "iu-signaling-act-timer", iuSignalingActTimerValue, childrenNames()); } /** * Sets the value for child leaf "iu-signaling-act-timer", * using a String value. * @param iuSignalingActTimerValue used during instantiation. */ public void setIuSignalingActTimerValue(String iuSignalingActTimerValue) throws JNCException { setIuSignalingActTimerValue(new YangString(iuSignalingActTimerValue)); } /** * Unsets the value for child leaf "iu-signaling-act-timer". */ public void unsetIuSignalingActTimerValue() throws JNCException { delete("iu-signaling-act-timer"); } /** * This method is used for creating a subtree filter. * The added "iu-signaling-act-timer" leaf will not have a value. */ public void addIuSignalingActTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "iu-signaling-act-timer", null, childrenNames()); } /** * Marks the leaf "iu-signaling-act-timer" with operation "replace". */ public void markIuSignalingActTimerReplace() throws JNCException { markLeafReplace("iuSignalingActTimer"); } /** * Marks the leaf "iu-signaling-act-timer" with operation "merge". */ public void markIuSignalingActTimerMerge() throws JNCException { markLeafMerge("iuSignalingActTimer"); } /** * Marks the leaf "iu-signaling-act-timer" with operation "create". */ public void markIuSignalingActTimerCreate() throws JNCException { markLeafCreate("iuSignalingActTimer"); } /** * Marks the leaf "iu-signaling-act-timer" with operation "delete". */ public void markIuSignalingActTimerDelete() throws JNCException { markLeafDelete("iuSignalingActTimer"); } /* Access methods for optional leaf child: "security-mode-timer". */ /** * Gets the value for child leaf "security-mode-timer". * @return The value of the leaf. */ public YangUInt8 getSecurityModeTimerValue() throws JNCException { YangUInt8 securityModeTimer = (YangUInt8)getValue("security-mode-timer"); if (securityModeTimer == null) { securityModeTimer = new YangUInt8("5"); // default } return securityModeTimer; } /** * Sets the value for child leaf "security-mode-timer", * using instance of generated typedef class. * @param securityModeTimerValue The value to set. * @param securityModeTimerValue used during instantiation. */ public void setSecurityModeTimerValue(YangUInt8 securityModeTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "security-mode-timer", securityModeTimerValue, childrenNames()); } /** * Sets the value for child leaf "security-mode-timer", * using Java primitive values. * @param securityModeTimerValue used during instantiation. */ public void setSecurityModeTimerValue(short securityModeTimerValue) throws JNCException { setSecurityModeTimerValue(new YangUInt8(securityModeTimerValue)); } /** * Sets the value for child leaf "security-mode-timer", * using a String value. * @param securityModeTimerValue used during instantiation. */ public void setSecurityModeTimerValue(String securityModeTimerValue) throws JNCException { setSecurityModeTimerValue(new YangUInt8(securityModeTimerValue)); } /** * Unsets the value for child leaf "security-mode-timer". */ public void unsetSecurityModeTimerValue() throws JNCException { delete("security-mode-timer"); } /** * This method is used for creating a subtree filter. * The added "security-mode-timer" leaf will not have a value. */ public void addSecurityModeTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "security-mode-timer", null, childrenNames()); } /** * Marks the leaf "security-mode-timer" with operation "replace". */ public void markSecurityModeTimerReplace() throws JNCException { markLeafReplace("securityModeTimer"); } /** * Marks the leaf "security-mode-timer" with operation "merge". */ public void markSecurityModeTimerMerge() throws JNCException { markLeafMerge("securityModeTimer"); } /** * Marks the leaf "security-mode-timer" with operation "create". */ public void markSecurityModeTimerCreate() throws JNCException { markLeafCreate("securityModeTimer"); } /** * Marks the leaf "security-mode-timer" with operation "delete". */ public void markSecurityModeTimerDelete() throws JNCException { markLeafDelete("securityModeTimer"); } /* Access methods for optional leaf child: "security-mode-retry". */ /** * Gets the value for child leaf "security-mode-retry". * @return The value of the leaf. */ public YangUInt8 getSecurityModeRetryValue() throws JNCException { YangUInt8 securityModeRetry = (YangUInt8)getValue("security-mode-retry"); if (securityModeRetry == null) { securityModeRetry = new YangUInt8("2"); // default } return securityModeRetry; } /** * Sets the value for child leaf "security-mode-retry", * using instance of generated typedef class. * @param securityModeRetryValue The value to set. * @param securityModeRetryValue used during instantiation. */ public void setSecurityModeRetryValue(YangUInt8 securityModeRetryValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "security-mode-retry", securityModeRetryValue, childrenNames()); } /** * Sets the value for child leaf "security-mode-retry", * using Java primitive values. * @param securityModeRetryValue used during instantiation. */ public void setSecurityModeRetryValue(short securityModeRetryValue) throws JNCException { setSecurityModeRetryValue(new YangUInt8(securityModeRetryValue)); } /** * Sets the value for child leaf "security-mode-retry", * using a String value. * @param securityModeRetryValue used during instantiation. */ public void setSecurityModeRetryValue(String securityModeRetryValue) throws JNCException { setSecurityModeRetryValue(new YangUInt8(securityModeRetryValue)); } /** * Unsets the value for child leaf "security-mode-retry". */ public void unsetSecurityModeRetryValue() throws JNCException { delete("security-mode-retry"); } /** * This method is used for creating a subtree filter. * The added "security-mode-retry" leaf will not have a value. */ public void addSecurityModeRetry() throws JNCException { setLeafValue(Epc.NAMESPACE, "security-mode-retry", null, childrenNames()); } /** * Marks the leaf "security-mode-retry" with operation "replace". */ public void markSecurityModeRetryReplace() throws JNCException { markLeafReplace("securityModeRetry"); } /** * Marks the leaf "security-mode-retry" with operation "merge". */ public void markSecurityModeRetryMerge() throws JNCException { markLeafMerge("securityModeRetry"); } /** * Marks the leaf "security-mode-retry" with operation "create". */ public void markSecurityModeRetryCreate() throws JNCException { markLeafCreate("securityModeRetry"); } /** * Marks the leaf "security-mode-retry" with operation "delete". */ public void markSecurityModeRetryDelete() throws JNCException { markLeafDelete("securityModeRetry"); } /* Access methods for optional leaf child: "srns-rau-timer". */ /** * Gets the value for child leaf "srns-rau-timer". * @return The value of the leaf. */ public YangUInt8 getSrnsRauTimerValue() throws JNCException { YangUInt8 srnsRauTimer = (YangUInt8)getValue("srns-rau-timer"); if (srnsRauTimer == null) { srnsRauTimer = new YangUInt8("5"); // default } return srnsRauTimer; } /** * Sets the value for child leaf "srns-rau-timer", * using instance of generated typedef class. * @param srnsRauTimerValue The value to set. * @param srnsRauTimerValue used during instantiation. */ public void setSrnsRauTimerValue(YangUInt8 srnsRauTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "srns-rau-timer", srnsRauTimerValue, childrenNames()); } /** * Sets the value for child leaf "srns-rau-timer", * using Java primitive values. * @param srnsRauTimerValue used during instantiation. */ public void setSrnsRauTimerValue(short srnsRauTimerValue) throws JNCException { setSrnsRauTimerValue(new YangUInt8(srnsRauTimerValue)); } /** * Sets the value for child leaf "srns-rau-timer", * using a String value. * @param srnsRauTimerValue used during instantiation. */ public void setSrnsRauTimerValue(String srnsRauTimerValue) throws JNCException { setSrnsRauTimerValue(new YangUInt8(srnsRauTimerValue)); } /** * Unsets the value for child leaf "srns-rau-timer". */ public void unsetSrnsRauTimerValue() throws JNCException { delete("srns-rau-timer"); } /** * This method is used for creating a subtree filter. * The added "srns-rau-timer" leaf will not have a value. */ public void addSrnsRauTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "srns-rau-timer", null, childrenNames()); } /** * Marks the leaf "srns-rau-timer" with operation "replace". */ public void markSrnsRauTimerReplace() throws JNCException { markLeafReplace("srnsRauTimer"); } /** * Marks the leaf "srns-rau-timer" with operation "merge". */ public void markSrnsRauTimerMerge() throws JNCException { markLeafMerge("srnsRauTimer"); } /** * Marks the leaf "srns-rau-timer" with operation "create". */ public void markSrnsRauTimerCreate() throws JNCException { markLeafCreate("srnsRauTimer"); } /** * Marks the leaf "srns-rau-timer" with operation "delete". */ public void markSrnsRauTimerDelete() throws JNCException { markLeafDelete("srnsRauTimer"); } /* Access methods for optional leaf child: "inter-rat-indirect-forwarding". */ /** * Gets the value for child leaf "inter-rat-indirect-forwarding". * @return The value of the leaf. */ public YangEnumeration getInterRatIndirectForwardingValue() throws JNCException { YangEnumeration interRatIndirectForwarding = (YangEnumeration)getValue("inter-rat-indirect-forwarding"); if (interRatIndirectForwarding == null) { interRatIndirectForwarding = new YangEnumeration("never", new String[] { // default "never", "always", "inter-plmn-inter-rat", }); } return interRatIndirectForwarding; } /** * Sets the value for child leaf "inter-rat-indirect-forwarding", * using instance of generated typedef class. * @param interRatIndirectForwardingValue The value to set. * @param interRatIndirectForwardingValue used during instantiation. */ public void setInterRatIndirectForwardingValue(YangEnumeration interRatIndirectForwardingValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "inter-rat-indirect-forwarding", interRatIndirectForwardingValue, childrenNames()); } /** * Sets the value for child leaf "inter-rat-indirect-forwarding", * using a String value. * @param interRatIndirectForwardingValue used during instantiation. */ public void setInterRatIndirectForwardingValue(String interRatIndirectForwardingValue) throws JNCException { setInterRatIndirectForwardingValue(new YangEnumeration(interRatIndirectForwardingValue, new String[] { "never", "always", "inter-plmn-inter-rat", })); } /** * Unsets the value for child leaf "inter-rat-indirect-forwarding". */ public void unsetInterRatIndirectForwardingValue() throws JNCException { delete("inter-rat-indirect-forwarding"); } /** * This method is used for creating a subtree filter. * The added "inter-rat-indirect-forwarding" leaf will not have a value. */ public void addInterRatIndirectForwarding() throws JNCException { setLeafValue(Epc.NAMESPACE, "inter-rat-indirect-forwarding", null, childrenNames()); } /** * Marks the leaf "inter-rat-indirect-forwarding" with operation "replace". */ public void markInterRatIndirectForwardingReplace() throws JNCException { markLeafReplace("interRatIndirectForwarding"); } /** * Marks the leaf "inter-rat-indirect-forwarding" with operation "merge". */ public void markInterRatIndirectForwardingMerge() throws JNCException { markLeafMerge("interRatIndirectForwarding"); } /** * Marks the leaf "inter-rat-indirect-forwarding" with operation "create". */ public void markInterRatIndirectForwardingCreate() throws JNCException { markLeafCreate("interRatIndirectForwarding"); } /** * Marks the leaf "inter-rat-indirect-forwarding" with operation "delete". */ public void markInterRatIndirectForwardingDelete() throws JNCException { markLeafDelete("interRatIndirectForwarding"); } /* Access methods for optional leaf child: "indirect-data-fwd-ip-address". */ /** * Gets the value for child leaf "indirect-data-fwd-ip-address". * @return The value of the leaf. */ public IpAddress getIndirectDataFwdIpAddressValue() throws JNCException { IpAddress indirectDataFwdIpAddress = (IpAddress)getValue("indirect-data-fwd-ip-address"); if (indirectDataFwdIpAddress == null) { indirectDataFwdIpAddress = new IpAddress("0.0.0.0"); // default } return indirectDataFwdIpAddress; } /** * Sets the value for child leaf "indirect-data-fwd-ip-address", * using a JNC type value. * @param indirectDataFwdIpAddressValue The value to set. * @param indirectDataFwdIpAddressValue used during instantiation. */ public void setIndirectDataFwdIpAddressValue(IpAddress indirectDataFwdIpAddressValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "indirect-data-fwd-ip-address", indirectDataFwdIpAddressValue, childrenNames()); } /** * Sets the value for child leaf "indirect-data-fwd-ip-address", * using a String value. * @param indirectDataFwdIpAddressValue used during instantiation. */ public void setIndirectDataFwdIpAddressValue(String indirectDataFwdIpAddressValue) throws JNCException { setIndirectDataFwdIpAddressValue(new IpAddress(indirectDataFwdIpAddressValue)); } /** * Unsets the value for child leaf "indirect-data-fwd-ip-address". */ public void unsetIndirectDataFwdIpAddressValue() throws JNCException { delete("indirect-data-fwd-ip-address"); } /** * This method is used for creating a subtree filter. * The added "indirect-data-fwd-ip-address" leaf will not have a value. */ public void addIndirectDataFwdIpAddress() throws JNCException { setLeafValue(Epc.NAMESPACE, "indirect-data-fwd-ip-address", null, childrenNames()); } /** * Marks the leaf "indirect-data-fwd-ip-address" with operation "replace". */ public void markIndirectDataFwdIpAddressReplace() throws JNCException { markLeafReplace("indirectDataFwdIpAddress"); } /** * Marks the leaf "indirect-data-fwd-ip-address" with operation "merge". */ public void markIndirectDataFwdIpAddressMerge() throws JNCException { markLeafMerge("indirectDataFwdIpAddress"); } /** * Marks the leaf "indirect-data-fwd-ip-address" with operation "create". */ public void markIndirectDataFwdIpAddressCreate() throws JNCException { markLeafCreate("indirectDataFwdIpAddress"); } /** * Marks the leaf "indirect-data-fwd-ip-address" with operation "delete". */ public void markIndirectDataFwdIpAddressDelete() throws JNCException { markLeafDelete("indirectDataFwdIpAddress"); } /* Access methods for optional leaf child: "indirect-tunnel-hold-timer". */ /** * Gets the value for child leaf "indirect-tunnel-hold-timer". * @return The value of the leaf. */ public YangUInt8 getIndirectTunnelHoldTimerValue() throws JNCException { YangUInt8 indirectTunnelHoldTimer = (YangUInt8)getValue("indirect-tunnel-hold-timer"); if (indirectTunnelHoldTimer == null) { indirectTunnelHoldTimer = new YangUInt8("5"); // default } return indirectTunnelHoldTimer; } /** * Sets the value for child leaf "indirect-tunnel-hold-timer", * using instance of generated typedef class. * @param indirectTunnelHoldTimerValue The value to set. * @param indirectTunnelHoldTimerValue used during instantiation. */ public void setIndirectTunnelHoldTimerValue(YangUInt8 indirectTunnelHoldTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "indirect-tunnel-hold-timer", indirectTunnelHoldTimerValue, childrenNames()); } /** * Sets the value for child leaf "indirect-tunnel-hold-timer", * using Java primitive values. * @param indirectTunnelHoldTimerValue used during instantiation. */ public void setIndirectTunnelHoldTimerValue(short indirectTunnelHoldTimerValue) throws JNCException { setIndirectTunnelHoldTimerValue(new YangUInt8(indirectTunnelHoldTimerValue)); } /** * Sets the value for child leaf "indirect-tunnel-hold-timer", * using a String value. * @param indirectTunnelHoldTimerValue used during instantiation. */ public void setIndirectTunnelHoldTimerValue(String indirectTunnelHoldTimerValue) throws JNCException { setIndirectTunnelHoldTimerValue(new YangUInt8(indirectTunnelHoldTimerValue)); } /** * Unsets the value for child leaf "indirect-tunnel-hold-timer". */ public void unsetIndirectTunnelHoldTimerValue() throws JNCException { delete("indirect-tunnel-hold-timer"); } /** * This method is used for creating a subtree filter. * The added "indirect-tunnel-hold-timer" leaf will not have a value. */ public void addIndirectTunnelHoldTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "indirect-tunnel-hold-timer", null, childrenNames()); } /** * Marks the leaf "indirect-tunnel-hold-timer" with operation "replace". */ public void markIndirectTunnelHoldTimerReplace() throws JNCException { markLeafReplace("indirectTunnelHoldTimer"); } /** * Marks the leaf "indirect-tunnel-hold-timer" with operation "merge". */ public void markIndirectTunnelHoldTimerMerge() throws JNCException { markLeafMerge("indirectTunnelHoldTimer"); } /** * Marks the leaf "indirect-tunnel-hold-timer" with operation "create". */ public void markIndirectTunnelHoldTimerCreate() throws JNCException { markLeafCreate("indirectTunnelHoldTimer"); } /** * Marks the leaf "indirect-tunnel-hold-timer" with operation "delete". */ public void markIndirectTunnelHoldTimerDelete() throws JNCException { markLeafDelete("indirectTunnelHoldTimer"); } /* Access methods for optional leaf child: "version". */ /** * Gets the value for child leaf "version". * @return The value of the leaf. */ public YangEnumeration getVersionValue() throws JNCException { YangEnumeration version = (YangEnumeration)getValue("version"); if (version == null) { version = new YangEnumeration("10.9.0", new String[] { // default "9.5.0", "10.9.0", }); } return version; } /** * Sets the value for child leaf "version", * using instance of generated typedef class. * @param versionValue The value to set. * @param versionValue used during instantiation. */ public void setVersionValue(YangEnumeration versionValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "version", versionValue, childrenNames()); } /** * Sets the value for child leaf "version", * using a String value. * @param versionValue used during instantiation. */ public void setVersionValue(String versionValue) throws JNCException { setVersionValue(new YangEnumeration(versionValue, new String[] { "9.5.0", "10.9.0", })); } /** * Unsets the value for child leaf "version". */ public void unsetVersionValue() throws JNCException { delete("version"); } /** * This method is used for creating a subtree filter. * The added "version" leaf will not have a value. */ public void addVersion() throws JNCException { setLeafValue(Epc.NAMESPACE, "version", null, childrenNames()); } /** * Marks the leaf "version" with operation "replace". */ public void markVersionReplace() throws JNCException { markLeafReplace("version"); } /** * Marks the leaf "version" with operation "merge". */ public void markVersionMerge() throws JNCException { markLeafMerge("version"); } /** * Marks the leaf "version" with operation "create". */ public void markVersionCreate() throws JNCException { markLeafCreate("version"); } /** * Marks the leaf "version" with operation "delete". */ public void markVersionDelete() throws JNCException { markLeafDelete("version"); } /* Access methods for optional leaf child: "reloc-resource-release-timer". */ /** * Gets the value for child leaf "reloc-resource-release-timer". * @return The value of the leaf. */ public YangUInt8 getRelocResourceReleaseTimerValue() throws JNCException { YangUInt8 relocResourceReleaseTimer = (YangUInt8)getValue("reloc-resource-release-timer"); if (relocResourceReleaseTimer == null) { relocResourceReleaseTimer = new YangUInt8("5"); // default } return relocResourceReleaseTimer; } /** * Sets the value for child leaf "reloc-resource-release-timer", * using instance of generated typedef class. * @param relocResourceReleaseTimerValue The value to set. * @param relocResourceReleaseTimerValue used during instantiation. */ public void setRelocResourceReleaseTimerValue(YangUInt8 relocResourceReleaseTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "reloc-resource-release-timer", relocResourceReleaseTimerValue, childrenNames()); } /** * Sets the value for child leaf "reloc-resource-release-timer", * using Java primitive values. * @param relocResourceReleaseTimerValue used during instantiation. */ public void setRelocResourceReleaseTimerValue(short relocResourceReleaseTimerValue) throws JNCException { setRelocResourceReleaseTimerValue(new YangUInt8(relocResourceReleaseTimerValue)); } /** * Sets the value for child leaf "reloc-resource-release-timer", * using a String value. * @param relocResourceReleaseTimerValue used during instantiation. */ public void setRelocResourceReleaseTimerValue(String relocResourceReleaseTimerValue) throws JNCException { setRelocResourceReleaseTimerValue(new YangUInt8(relocResourceReleaseTimerValue)); } /** * Unsets the value for child leaf "reloc-resource-release-timer". */ public void unsetRelocResourceReleaseTimerValue() throws JNCException { delete("reloc-resource-release-timer"); } /** * This method is used for creating a subtree filter. * The added "reloc-resource-release-timer" leaf will not have a value. */ public void addRelocResourceReleaseTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "reloc-resource-release-timer", null, childrenNames()); } /** * Marks the leaf "reloc-resource-release-timer" with operation "replace". */ public void markRelocResourceReleaseTimerReplace() throws JNCException { markLeafReplace("relocResourceReleaseTimer"); } /** * Marks the leaf "reloc-resource-release-timer" with operation "merge". */ public void markRelocResourceReleaseTimerMerge() throws JNCException { markLeafMerge("relocResourceReleaseTimer"); } /** * Marks the leaf "reloc-resource-release-timer" with operation "create". */ public void markRelocResourceReleaseTimerCreate() throws JNCException { markLeafCreate("relocResourceReleaseTimer"); } /** * Marks the leaf "reloc-resource-release-timer" with operation "delete". */ public void markRelocResourceReleaseTimerDelete() throws JNCException { markLeafDelete("relocResourceReleaseTimer"); } /* Access methods for optional leaf child: "dscp-mark". */ /** * Gets the value for child leaf "dscp-mark". * @return The value of the leaf. */ public YangString getDscpMarkValue() throws JNCException { YangString dscpMark = (YangString)getValue("dscp-mark"); if (dscpMark == null) { dscpMark = new YangString("de"); // default } return dscpMark; } /** * Sets the value for child leaf "dscp-mark", * using instance of generated typedef class. * @param dscpMarkValue The value to set. * @param dscpMarkValue used during instantiation. */ public void setDscpMarkValue(YangString dscpMarkValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "dscp-mark", dscpMarkValue, childrenNames()); } /** * Sets the value for child leaf "dscp-mark", * using a String value. * @param dscpMarkValue used during instantiation. */ public void setDscpMarkValue(String dscpMarkValue) throws JNCException { setDscpMarkValue(new YangString(dscpMarkValue)); } /** * Unsets the value for child leaf "dscp-mark". */ public void unsetDscpMarkValue() throws JNCException { delete("dscp-mark"); } /** * This method is used for creating a subtree filter. * The added "dscp-mark" leaf will not have a value. */ public void addDscpMark() throws JNCException { setLeafValue(Epc.NAMESPACE, "dscp-mark", null, childrenNames()); } /** * Marks the leaf "dscp-mark" with operation "replace". */ public void markDscpMarkReplace() throws JNCException { markLeafReplace("dscpMark"); } /** * Marks the leaf "dscp-mark" with operation "merge". */ public void markDscpMarkMerge() throws JNCException { markLeafMerge("dscpMark"); } /** * Marks the leaf "dscp-mark" with operation "create". */ public void markDscpMarkCreate() throws JNCException { markLeafCreate("dscpMark"); } /** * Marks the leaf "dscp-mark" with operation "delete". */ public void markDscpMarkDelete() throws JNCException { markLeafDelete("dscpMark"); } /* Access methods for optional leaf child: "csg-expiration-release-timer". */ /** * Gets the value for child leaf "csg-expiration-release-timer". * @return The value of the leaf. */ public YangUInt8 getCsgExpirationReleaseTimerValue() throws JNCException { YangUInt8 csgExpirationReleaseTimer = (YangUInt8)getValue("csg-expiration-release-timer"); if (csgExpirationReleaseTimer == null) { csgExpirationReleaseTimer = new YangUInt8("5"); // default } return csgExpirationReleaseTimer; } /** * Sets the value for child leaf "csg-expiration-release-timer", * using instance of generated typedef class. * @param csgExpirationReleaseTimerValue The value to set. * @param csgExpirationReleaseTimerValue used during instantiation. */ public void setCsgExpirationReleaseTimerValue(YangUInt8 csgExpirationReleaseTimerValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "csg-expiration-release-timer", csgExpirationReleaseTimerValue, childrenNames()); } /** * Sets the value for child leaf "csg-expiration-release-timer", * using Java primitive values. * @param csgExpirationReleaseTimerValue used during instantiation. */ public void setCsgExpirationReleaseTimerValue(short csgExpirationReleaseTimerValue) throws JNCException { setCsgExpirationReleaseTimerValue(new YangUInt8(csgExpirationReleaseTimerValue)); } /** * Sets the value for child leaf "csg-expiration-release-timer", * using a String value. * @param csgExpirationReleaseTimerValue used during instantiation. */ public void setCsgExpirationReleaseTimerValue(String csgExpirationReleaseTimerValue) throws JNCException { setCsgExpirationReleaseTimerValue(new YangUInt8(csgExpirationReleaseTimerValue)); } /** * Unsets the value for child leaf "csg-expiration-release-timer". */ public void unsetCsgExpirationReleaseTimerValue() throws JNCException { delete("csg-expiration-release-timer"); } /** * This method is used for creating a subtree filter. * The added "csg-expiration-release-timer" leaf will not have a value. */ public void addCsgExpirationReleaseTimer() throws JNCException { setLeafValue(Epc.NAMESPACE, "csg-expiration-release-timer", null, childrenNames()); } /** * Marks the leaf "csg-expiration-release-timer" with operation "replace". */ public void markCsgExpirationReleaseTimerReplace() throws JNCException { markLeafReplace("csgExpirationReleaseTimer"); } /** * Marks the leaf "csg-expiration-release-timer" with operation "merge". */ public void markCsgExpirationReleaseTimerMerge() throws JNCException { markLeafMerge("csgExpirationReleaseTimer"); } /** * Marks the leaf "csg-expiration-release-timer" with operation "create". */ public void markCsgExpirationReleaseTimerCreate() throws JNCException { markLeafCreate("csgExpirationReleaseTimer"); } /** * Marks the leaf "csg-expiration-release-timer" with operation "delete". */ public void markCsgExpirationReleaseTimerDelete() throws JNCException { markLeafDelete("csgExpirationReleaseTimer"); } /* Access methods for optional leaf child: "signaling-variant". */ /** * Gets the value for child leaf "signaling-variant". * @return The value of the leaf. */ public YangEnumeration getSignalingVariantValue() throws JNCException { YangEnumeration signalingVariant = (YangEnumeration)getValue("signaling-variant"); if (signalingVariant == null) { signalingVariant = new YangEnumeration("itu", new String[] { // default "itu", "ansi", }); } return signalingVariant; } /** * Sets the value for child leaf "signaling-variant", * using instance of generated typedef class. * @param signalingVariantValue The value to set. * @param signalingVariantValue used during instantiation. */ public void setSignalingVariantValue(YangEnumeration signalingVariantValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "signaling-variant", signalingVariantValue, childrenNames()); } /** * Sets the value for child leaf "signaling-variant", * using a String value. * @param signalingVariantValue used during instantiation. */ public void setSignalingVariantValue(String signalingVariantValue) throws JNCException { setSignalingVariantValue(new YangEnumeration(signalingVariantValue, new String[] { "itu", "ansi", })); } /** * Unsets the value for child leaf "signaling-variant". */ public void unsetSignalingVariantValue() throws JNCException { delete("signaling-variant"); } /** * This method is used for creating a subtree filter. * The added "signaling-variant" leaf will not have a value. */ public void addSignalingVariant() throws JNCException { setLeafValue(Epc.NAMESPACE, "signaling-variant", null, childrenNames()); } /** * Marks the leaf "signaling-variant" with operation "replace". */ public void markSignalingVariantReplace() throws JNCException { markLeafReplace("signalingVariant"); } /** * Marks the leaf "signaling-variant" with operation "merge". */ public void markSignalingVariantMerge() throws JNCException { markLeafMerge("signalingVariant"); } /** * Marks the leaf "signaling-variant" with operation "create". */ public void markSignalingVariantCreate() throws JNCException { markLeafCreate("signalingVariant"); } /** * Marks the leaf "signaling-variant" with operation "delete". */ public void markSignalingVariantDelete() throws JNCException { markLeafDelete("signalingVariant"); } /** * Support method for addChild. * Adds a child to this object. * * @param child The child to add */ public void addChild(Element child) { super.addChild(child); } }
32.769201
112
0.652117
8c7b963697cd4187b8607cd4591eced51840ae5c
4,730
package org.succlz123.blueboard.view.adapter.recyclerview.other; import com.facebook.drawee.view.SimpleDraweeView; import org.succlz123.blueboard.MyApplication; import org.succlz123.blueboard.R; import org.succlz123.blueboard.base.BaseRvViewHolder; import org.succlz123.blueboard.model.bean.acfun.AcReOther; import org.succlz123.blueboard.model.utils.common.OkUtils; import android.graphics.Canvas; import android.graphics.Rect; import android.net.Uri; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by succlz123 on 15/8/17. */ public class AcRankingRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private AcReOther mAcReOther; private List<AcReOther.DataEntity.PageEntity.ListEntity> mAcReOtherList = new ArrayList(); public AcReOther getmAcReOther() { return mAcReOther; } public void setmAcReOther(AcReOther acReOther) { this.mAcReOther = acReOther; mAcReOtherList.clear(); mAcReOtherList.addAll(acReOther.getData().getPage().getList()); notifyDataSetChanged(); } public void addAcReOtherDate(AcReOther acReOther) { mAcReOtherList.addAll(acReOther.getData().getPage().getList()); notifyItemInserted(getItemCount()); } private OnClickListener mOnClickListener; public interface OnClickListener { void onClick(View view, int position, String contentId); } public void setOnClickListener(OnClickListener onClickListener) { this.mOnClickListener = onClickListener; } public class RankingVH extends BaseRvViewHolder { private TextView tvTitleHot; private TextView tvClickHot; private TextView tvReplyHot; private SimpleDraweeView imgCoverHot; private CardView cvVerticalWithClickInfo; public RankingVH(View itemView) { super(itemView); tvTitleHot = f(itemView, R.id.cv_vertical_with_click_info_tv_title); tvClickHot = f(itemView, R.id.cv_vertical_with_click_info_tv_click); tvReplyHot = f(itemView, R.id.cv_vertical_with_click_info_tv_reply); imgCoverHot = f(itemView, R.id.cv_vertical_with_click_info_img); cvVerticalWithClickInfo = f(itemView, R.id.cv_vertical_with_click_info); } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ac_rv_cardview_vertical_with_click_info, parent, false); return new RankingVH(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { if (holder instanceof RankingVH && mAcReOtherList.size() != 0) { final AcReOther.DataEntity.PageEntity.ListEntity entity = mAcReOtherList.get(position); ((RankingVH) holder).imgCoverHot .setImageURI(Uri.parse(entity.getCover())); ((RankingVH) holder).tvTitleHot .setText(entity.getTitle()); ((RankingVH) holder).tvClickHot .setText(MyApplication.getInstance().getApplicationContext().getString(R.string.click) + " " + entity.getViews()); ((RankingVH) holder).tvReplyHot .setText(MyApplication.getInstance().getApplicationContext().getString(R.string.reply) + " " + entity.getComments()); ((RankingVH) holder).cvVerticalWithClickInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mOnClickListener.onClick(v, position, entity.getContentId()); } }); } } @Override public int getItemCount() { return mAcReOtherList.size(); } //处理cardView中间的margin public static class MyDecoration extends RecyclerView.ItemDecoration { @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDraw(c, parent, state); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition(); int marginRight = OkUtils.dp2px(parent.getContext(), 8); if (position % 2 == 0) { outRect.set(0, 0, marginRight, 0); } } } }
36.666667
137
0.682452
635b8758d1064d91f80ffdf5fab98a75ae72be74
2,628
package com.happy; import java.util.Stack; /** * 第32题 最长有效括号 * 给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。 * * @author qgl * @date 2019/06/02 */ public class LongestValidParentheses32 { /** * 解法一:利用栈 * 时间复杂度:O(n),空间复杂度:O(n) * * @param s * @return */ public int longestValidParentheses(String s) { if (s == null || s.length() <= 1) { return 0; } int maxLength = 0; Stack<Integer> stack = new Stack<>(); stack.push(-1); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { stack.push(i); } else { stack.pop(); if (stack.empty()) { stack.push(i); } else { maxLength = Math.max(maxLength, i - stack.peek()); } } } return maxLength; } /** * 解法二:双指针法 * 时间复杂度:O(n),空间复杂度:O(1) * * @param s * @return */ public int longestValidParentheses2(String s) { int left = 0, right = 0, maxLength = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { left++; } else { right++; } if (left == right) { maxLength = Math.max(maxLength, 2 * right); } else if (right >= left) { left = right = 0; } } left = right = 0; for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) == '(') { left++; } else { right++; } if (left == right) { maxLength = Math.max(maxLength, 2 * left); } else if (left >= right) { left = right = 0; } } return maxLength; } /** * 解法三:动态规划 * 时间复杂度:O(n),空间复杂度:O(n) * * @param s * @return */ public int longestValidParentheses3(String s) { int maxLength = 0; int dp[] = new int[s.length()]; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == ')') { if (s.charAt(i - 1) == '(') { dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2; } else if (i - dp[i - 1] > 0 && s.charAt(i - dp[i - 1] - 1) == '(') { dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2; } maxLength = Math.max(maxLength, dp[i]); } } return maxLength; } }
25.269231
95
0.371385
4ce7974dd55d481294553fd9df6d0cd6c8f4d064
2,093
package com.lamfire.utils; import java.io.Serializable; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * 带标识的多线程执行器 */ public class IdentityExecutor { private final Set<Serializable> taskIds = Sets.newHashSet(); private ExecutorService service; public IdentityExecutor(ExecutorService service) { this.service = service; } public Set<Serializable> getWaitingTaskIds() { return taskIds; } /** * 提交任务 * * @param id * @param task * @return * @throws TaskExistsException 当该任务ID还存在于队列中,则抛出异常 */ public synchronized Future<?> submit(Serializable id, Runnable task) throws TaskExistsException { if (taskIds.contains(id)) { throw new TaskExistsException("Failed submit task,identity exists - " + id.toString()); } taskIds.add(id); return service.submit(new Task(id, task)); } public void shutdown() { service.shutdown(); } public List<Runnable> shutdownNow() { return service.shutdownNow(); } public void awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { service.awaitTermination(timeout, unit); } public class TaskExistsException extends Exception { private static final long serialVersionUID = 3792731443027168307L; public TaskExistsException(String message) { super(message); } } private class Task implements Runnable { private Serializable id; private Runnable realTask; public Task(Serializable id, Runnable runTask) { this.id = id; this.realTask = runTask; } @Override public void run() { try { this.realTask.run(); } finally { taskIds.remove(id); } } } }
25.216867
102
0.593884
f91c0788c5d6844b65f46cb96a3a5723769399d5
3,289
package net.violet.platform.datamodel.factories.implementations; import java.sql.SQLException; import java.util.Collections; import net.violet.db.records.factories.RecordFactoryImpl; import net.violet.platform.datamodel.Messenger; import net.violet.platform.datamodel.MessengerImpl; import net.violet.platform.datamodel.User; import net.violet.platform.datamodel.VObject; import net.violet.platform.datamodel.factories.Factories; import net.violet.platform.datamodel.factories.MessengerFactory; import org.apache.log4j.Logger; public class MessengerFactoryImpl extends RecordFactoryImpl<Messenger, MessengerImpl> implements MessengerFactory { private static final Logger LOGGER = Logger.getLogger(MessengerFactoryImpl.class); public MessengerFactoryImpl() { super(MessengerImpl.SPECIFICATION); } public Messenger getByObject(VObject inObject) { if (inObject != null) { return getByObjectId(inObject.getId()); } return null; } public Messenger getByObjectId(long inId) { Messenger theMessenger = findByObjectId(inId); if (theMessenger == null) { try { final VObject theVObject = Factories.VOBJECT.find(inId); if (theVObject != null) { theMessenger = new MessengerImpl(theVObject, theVObject.getObject_login()); } } catch (final SQLException e) { theMessenger = findByObjectId(inId); if (theMessenger == null) { MessengerFactoryImpl.LOGGER.fatal(e, e); } } } return theMessenger; } public Messenger getByUser(User inUser) { if (inUser != null) { return getByUserId(inUser.getId()); } return null; } public Messenger getByUserId(long inId) { Messenger theMessenger = findByUserId(inId); if (theMessenger == null) { try { final User theUser = Factories.USER.find(inId); if (theUser != null) { theMessenger = new MessengerImpl(theUser, theUser.getUser_email()); } } catch (final SQLException e) { theMessenger = findByUserId(inId); if (theMessenger == null) { MessengerFactoryImpl.LOGGER.fatal(e, e); } } } return theMessenger; } /** * Finds a messenger from the given VObjectImpl id * * @param inId * @return */ private Messenger findByObjectId(long inId) { return findByKey(1, inId); } /** * Finds the only messenger associated with the given user id * * @param inUser * @return null if it could not be found, the messenger otherwise */ private Messenger findByUserId(long inId) { return findByKey(2, inId); } public Messenger findByUser(User inUser) { return findByUserId(inUser.getId()); } /** * Find a MessengerImpl from the given MessageImpl id * * @param inVObject * @return */ public Messenger findSenderByMessageId(long inId) { final Messenger theMessenger = find(new String[] { "message_received" }, "message_received.message_id = ? and message_received.sender_id = messenger.id", Collections.singletonList((Object) inId)); if (theMessenger == null) { return find(new String[] { "message_sent" }, "message_sent.message_id = ? and message_sent.sender_id = messenger.id", Collections.singletonList((Object) inId)); } return theMessenger; } public Messenger findByObject(VObject theObject) { return (theObject != null) ? findByObjectId(theObject.getId()) : null; } }
26.739837
198
0.723016
61e06b786421a23488301d19ce68e05aa89762c6
1,005
package net.ttk1.hideme.command; import net.ttk1.hideme.HideMeManager; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Set; public class ShowCommand extends AbstractCommand { public ShowCommand(HideMeManager manager) { super(manager, "show", "hideme.show", 0, true); } @Override protected void executeImpl(CommandSender sender, String[] args) { Player player = (Player) sender; if (manager.isHidden(player)) { manager.showPlayer(player); player.sendMessage("You are now visible."); } else { player.sendMessage("You are already visible."); } } @Override protected void tabCompleteImpl(CommandSender sender, String[] args, Set<String> candidates) { if (args.length == 0) { candidates.add(commandName); } else if (args.length == 1 && commandName.startsWith(args[0])) { candidates.add(commandName); } } }
29.558824
97
0.639801