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
2cc73e0f73f99beb4fe9da1d76dcd9af06039f9b
249
package com.pisces.core.exception; public class LicenseException extends BaseException { private static final long serialVersionUID = 2982990613157147413L; public LicenseException(Enum<?> key, Object... args) { super(key, args); } }
24.9
68
0.742972
6a7fc148e70a3323ce4c95db94eb76c36f3138bb
625
//Criando im programa que calcula o IMC package aulas; import java.util.Scanner; public class AULA010 { public static void main(String[]args){ Scanner input = new Scanner (System.in); System.out.println(" IMC\n"); System.out.println("Informe sua altura: "); double altura = input.nextDouble(); System.out.println("Informe seu peso: "); double peso = input.nextDouble(); double imc = peso /( altura * altura); System.out.print("Seu IMC é: " + imc + "\n"); } }
18.382353
51
0.5216
0fac32292784e5f86dac4f4a0370699e88a8aa29
1,858
package com.up.libraryBookingSystem.pojo; import com.up.libraryBookingSystem.ENUMS.Nationality; import java.util.Objects; public class Authors { private Integer AuthorId; private String name; private Nationality nationality; private String image; public Authors(Integer authorId, String name, Nationality nationality, String image) { AuthorId = authorId; this.name = name; this.nationality = nationality; this.image = image; } public Integer getAuthorId() { return AuthorId; } public void setAuthorId(Integer authorId) { AuthorId = authorId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Nationality getNationality() { return nationality; } public void setNationality(Nationality nationality) { this.nationality = nationality; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Authors authors = (Authors) o; return Objects.equals(AuthorId, authors.AuthorId) && Objects.equals(name, authors.name) && nationality == authors.nationality && Objects.equals(image, authors.image); } @Override public int hashCode() { return Objects.hash(AuthorId, name, nationality, image); } @Override public String toString() { return "Authors{" + "AuthorId=" + AuthorId + ", name='" + name + '\'' + ", nationality=" + nationality + ", image='" + image + '\'' + '}'; } }
24.447368
174
0.593649
14002bc681e22912fbb12277c743d0e05090b021
5,443
/* * 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.sling.security.impl; import static org.mockito.Mockito.*; import java.util.Dictionary; import java.util.Hashtable; import javax.servlet.http.HttpServletRequest; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; public class ReferrerFilterTest { protected ReferrerFilter filter; @Before public void setup() { filter = new ReferrerFilter(); final ComponentContext ctx = mock(ComponentContext.class); final BundleContext bundleCtx = mock(BundleContext.class); final ServiceRegistration reg = mock(ServiceRegistration.class); final Dictionary<String, Object> props = new Hashtable<String, Object>(){{ put("allow.hosts", new String[]{"relhost"}); put("allow.hosts.regexp", new String[]{"http://([^.]*.)?abshost:80"}); }}; doReturn(props).when(ctx).getProperties(); doReturn(bundleCtx).when(ctx).getBundleContext(); doReturn(reg).when(bundleCtx).registerService(any(String[].class), any(), any(Dictionary.class)); doNothing().when(reg).unregister(); filter.activate(ctx); } @Test public void testHostName() { Assert.assertEquals("somehost", filter.getHost("http://somehost").host); Assert.assertEquals("somehost", filter.getHost("http://somehost/somewhere").host); Assert.assertEquals("somehost", filter.getHost("http://somehost:4242/somewhere").host); Assert.assertEquals("somehost", filter.getHost("http://admin@somehost/somewhere").host); Assert.assertEquals("somehost", filter.getHost("http://admin@somehost/somewhere?invald=@gagga").host); Assert.assertEquals("somehost", filter.getHost("http://admin@somehost:1/somewhere").host); Assert.assertEquals("somehost", filter.getHost("http://admin:admin@somehost/somewhere").host); Assert.assertEquals("somehost", filter.getHost("http://admin:admin@somehost:4343/somewhere").host); Assert.assertEquals("localhost", filter.getHost("http://localhost").host); Assert.assertEquals("127.0.0.1", filter.getHost("http://127.0.0.1").host); Assert.assertEquals("localhost", filter.getHost("http://localhost:535").host); Assert.assertEquals("127.0.0.1", filter.getHost("http://127.0.0.1:242").host); Assert.assertEquals("localhost", filter.getHost("http://localhost:256235/etewteq.ff").host); Assert.assertEquals("127.0.0.1", filter.getHost("http://127.0.0.1/wetew.qerq").host); Assert.assertEquals(null, filter.getHost("http:/admin:admin@somehost:4343/somewhere")); } private HttpServletRequest getRequest(final String referrer) { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getMethod()).thenReturn("POST"); when(request.getRequestURI()).thenReturn("http://somehost/somewhere"); when(request.getHeader("referer")).thenReturn(referrer); return request; } @Test public void testValidRequest() { Assert.assertEquals(false, filter.isValidRequest(getRequest(null))); Assert.assertEquals(true, filter.isValidRequest(getRequest("relative"))); Assert.assertEquals(true, filter.isValidRequest(getRequest("/relative/too"))); Assert.assertEquals(true, filter.isValidRequest(getRequest("/relative/but/[illegal]"))); Assert.assertEquals(false, filter.isValidRequest(getRequest("http://somehost"))); Assert.assertEquals(true, filter.isValidRequest(getRequest("http://localhost"))); Assert.assertEquals(true, filter.isValidRequest(getRequest("http://127.0.0.1"))); Assert.assertEquals(false, filter.isValidRequest(getRequest("http://somehost/but/[illegal]"))); Assert.assertEquals(true, filter.isValidRequest(getRequest("http://relhost"))); Assert.assertEquals(true, filter.isValidRequest(getRequest("http://relhost:9001"))); Assert.assertEquals(false, filter.isValidRequest(getRequest("http://abshost:9001"))); Assert.assertEquals(false, filter.isValidRequest(getRequest("https://abshost:80"))); Assert.assertEquals(true, filter.isValidRequest(getRequest("http://abshost:80"))); Assert.assertEquals(false, filter.isValidRequest(getRequest("http://abshost:9001"))); Assert.assertEquals(true, filter.isValidRequest(getRequest("http://another.abshost:80"))); Assert.assertEquals(false, filter.isValidRequest(getRequest("http://yet.another.abshost:80"))); } }
55.540816
110
0.710086
c89f8fe990d677dfd6b33568beb1f5f8edb01b41
820
package org.loomdev.loom.entity.monster.skeleton; import org.jetbrains.annotations.NotNull; import org.loomdev.api.entity.EntityType; import org.loomdev.api.entity.monster.skeleton.WitherSkeleton; import org.loomdev.loom.entity.monster.skeleton.AbstractSkeletonImpl; public class WitherSkeletonImpl extends AbstractSkeletonImpl implements WitherSkeleton { public WitherSkeletonImpl(net.minecraft.world.entity.monster.WitherSkeleton entity) { super(entity); } @Override @NotNull public EntityType<WitherSkeleton> getType() { return EntityType.WITHER_SKELETON; } @Override @NotNull public net.minecraft.world.entity.monster.WitherSkeleton getMinecraftEntity() { return (net.minecraft.world.entity.monster.WitherSkeleton) super.getMinecraftEntity(); } }
31.538462
94
0.770732
93d292a8342fb84ad4ab9c4ab305adcdd60b3539
1,229
/* * @test /nodynamiccopyright/ * @summary smoke test for inference of throws type variables * @compile/fail/ref=TargetType63.out -XDrawDiagnostics TargetType63.java */ class TargetType63 { interface F<T extends Throwable> { void m() throws T; } void g1() { } void g2() throws ClassNotFoundException { } void g3() throws Exception { } <Z extends Throwable> void m1(F<Z> fz) throws Z { } <Z extends ClassNotFoundException> void m2(F<Z> fz) throws Z { } void test1() { m1(()->{ }); //ok (Z = RuntimeException) m1(this::g1); //ok (Z = RuntimeException) } void test2() { m2(()->{ }); //fail (Z = ClassNotFoundException) m2(this::g1); //fail (Z = ClassNotFoundException) } void test3() { m1(()->{ throw new ClassNotFoundException(); }); //fail (Z = ClassNotFoundException) m1(this::g2); //fail (Z = ClassNotFoundException) m2(()->{ throw new ClassNotFoundException(); }); //fail (Z = ClassNotFoundException) m2(this::g2); //fail (Z = ClassNotFoundException) } void test4() { m1(()->{ throw new Exception(); }); //fail (Z = Exception) m1(this::g3); //fail (Z = Exception) } }
29.97561
92
0.586656
63c09332560c38a724c2b6f1e2efb474fc41282b
1,571
package com.productandcousmer02; /** * 线程间通信 : * 1.使用生产者 消费者 * 2.通知等待唤醒机制 * * 判断,干活,通知 * 使用synchronized实现 * */ public class NotifyWaitDemo { public static void main(String[] args) { Products products = new Products(); new Thread(()-> { for (int i = 0; i < 10; i++) { try { products.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } },"A").start(); new Thread(()-> { for (int i = 0; i < 10; i++) { try { products.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } },"B").start(); } } /** * 资源类 */ class Products { private int num = 0; public synchronized void increment() throws InterruptedException { //1.判断 if (num != 0) { //有产品 不需要生产 等待 this.wait(); } //2.干活 ++num; System.out.println(Thread.currentThread().getName() + "\t" + num); //3.通知 this.notifyAll(); } public synchronized void decrement() throws InterruptedException { //1.判断 if (num == 0) { //没有产品 不能消费 等待 this.wait(); } //2.干活 --num; System.out.println(Thread.currentThread().getName() + "\t" + num); //3.通知 this.notifyAll(); } }
20.671053
74
0.425207
29cd0189f17f4a0807555fc8d1fe6ea8a7d64eea
4,263
/* * Copyright (C) 2022 The SINOBU Development Team * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT */ package kiss.signal; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import kiss.Disposable; import kiss.I; import kiss.Observer; import kiss.Signal; class SignalCreationTest extends SignalTester { @Test void single() { monitor(() -> signal(1)); assert main.value(1); assert main.isCompleted(); assert main.isNotError(); assert main.isDisposed(); } @Test void multi() { monitor(() -> signal(1, 2, 3)); assert main.value(1, 2, 3); assert main.isCompleted(); assert main.isNotError(); assert main.isDisposed(); } @Test void empty() { monitor(() -> I.signal()); assert main.value(); assert main.isCompleted(); assert main.isNotError(); assert main.isDisposed(); } @Test void never() { monitor(() -> Signal.never()); assert main.value(); assert main.isNotCompleted(); assert main.isNotError(); assert main.isNotDisposed(); } @Test void singleNull() { monitor(() -> signal((String) null)); assert main.value((String) null); assert main.isCompleted(); assert main.isNotError(); assert main.isDisposed(); } @Test void multiNull() { monitor(() -> signal(null, null, null)); assert main.value(null, null, null); assert main.isCompleted(); assert main.isNotError(); assert main.isDisposed(); } @Test void arrayNull() { monitor(() -> signal((String[]) null)); assert main.value(); assert main.isCompleted(); assert main.isNotError(); assert main.isDisposed(); } @Test void iterable() { monitor(() -> signal(list(1, 2))); assert main.value(1, 2); assert main.isCompleted(); assert main.isNotError(); assert main.isDisposed(); } @Test void iterableNull() { monitor(() -> signal((Iterable) null)); assert main.value(); assert main.isCompleted(); assert main.isNotError(); assert main.isDisposed(); } @Test void supplier() { monitor(() -> signal(() -> 1)); assert main.value(1); assert main.isCompleted(); assert main.isNotError(); assert main.isDisposed(); } @Test void supplierNull() { monitor(() -> signal((Supplier) null)); assert main.value(); assert main.isCompleted(); assert main.isNotError(); assert main.isDisposed(); } @Test void interval() { monitor(() -> I.schedule(0, 30, ms, false, scheduler) .take(4) .map(e -> System.currentTimeMillis()) .pair() .map(values -> 30 <= values.get(1) - values.get(0))); assert main.isNotCompleted(); assert main.isNotDisposed(); scheduler.await(200, ms); assert main.value(true, true, true); assert main.isCompleted(); assert main.isDisposed(); } @Test void constructWithObserverCollection() { List<Observer<String>> observers = new ArrayList(); List<String> results = new ArrayList(); Disposable disposer = new Signal<String>(observers).map(String::toUpperCase).to(results::add); observers.forEach(e -> e.accept("one")); assert results.get(0).equals("ONE"); observers.forEach(e -> e.accept("two")); assert results.get(1).equals("TWO"); // dispose disposer.dispose(); observers.forEach(e -> e.accept("Disposed signal doesn't propagate event.")); assert results.size() == 2; } }
25.076471
103
0.541872
9706f56c0c65c58a0835c24e7be3ace369cbf18c
10,380
/* * 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 * * 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.streams.s3; import org.apache.streams.config.ComponentConfigurator; import org.apache.streams.config.StreamsConfigurator; import org.apache.streams.converter.LineReadWriteUtil; import org.apache.streams.core.DatumStatus; import org.apache.streams.core.DatumStatusCountable; import org.apache.streams.core.DatumStatusCounter; import org.apache.streams.core.StreamsDatum; import org.apache.streams.core.StreamsPersistWriter; import org.apache.streams.jackson.StreamsJacksonMapper; import com.amazonaws.ClientConfiguration; import com.amazonaws.Protocol; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.S3ClientOptions; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Preconditions; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Flushable; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * S3PersistWriter writes documents to s3. */ public class S3PersistWriter implements StreamsPersistWriter, DatumStatusCountable { public static final String STREAMS_ID = "S3PersistWriter"; private static final Logger LOGGER = LoggerFactory.getLogger(S3PersistWriter.class); private static final char DELIMITER = '\t'; private ObjectMapper objectMapper; private AmazonS3Client amazonS3Client; private S3WriterConfiguration s3WriterConfiguration; private final List<String> writtenFiles = new ArrayList<>(); protected LineReadWriteUtil lineWriterUtil; private final AtomicLong totalBytesWritten = new AtomicLong(); private AtomicLong bytesWrittenThisFile = new AtomicLong(); private final AtomicInteger totalRecordsWritten = new AtomicInteger(); private AtomicInteger fileLineCounter = new AtomicInteger(); private static Map<String, String> objectMetaData = new HashMap<>(); static { objectMetaData.put("line[0]", "id"); objectMetaData.put("line[1]", "timeStamp"); objectMetaData.put("line[2]", "metaData"); objectMetaData.put("line[3]", "document"); } private OutputStreamWriter currentWriter = null; public AmazonS3Client getAmazonS3Client() { return this.amazonS3Client; } public S3WriterConfiguration getS3WriterConfiguration() { return this.s3WriterConfiguration; } public List<String> getWrittenFiles() { return this.writtenFiles; } public Map<String, String> getObjectMetaData() { return objectMetaData; } public ObjectMapper getObjectMapper() { return this.objectMapper; } public void setObjectMapper(ObjectMapper mapper) { this.objectMapper = mapper; } public void setObjectMetaData(Map<String, String> val) { objectMetaData = val; } public S3PersistWriter() { this(new ComponentConfigurator<>(S3WriterConfiguration.class).detectConfiguration()); } public S3PersistWriter(S3WriterConfiguration s3WriterConfiguration) { this.s3WriterConfiguration = s3WriterConfiguration; } /** * Instantiator with a pre-existing amazonS3Client, this is used to help with re-use. * @param amazonS3Client * If you have an existing amazonS3Client, it wont' bother to create another one * @param s3WriterConfiguration * Configuration of the write paths and instructions are still required. */ public S3PersistWriter(AmazonS3Client amazonS3Client, S3WriterConfiguration s3WriterConfiguration) { this.amazonS3Client = amazonS3Client; this.s3WriterConfiguration = s3WriterConfiguration; } @Override public String getId() { return STREAMS_ID; } @Override public void write(StreamsDatum streamsDatum) { synchronized (this) { // Check to see if we need to reset the file that we are currently working with if (this.currentWriter == null || ( this.bytesWrittenThisFile.get() >= (this.s3WriterConfiguration.getMaxFileSize() * 1024 * 1024))) { try { LOGGER.info("Resetting the file"); this.currentWriter = resetFile(); } catch (Exception ex) { ex.printStackTrace(); } } String line = lineWriterUtil.convertResultToString(streamsDatum); try { this.currentWriter.write(line); } catch (IOException ex) { ex.printStackTrace(); } // add the bytes we've written int recordSize = line.getBytes().length; this.totalBytesWritten.addAndGet(recordSize); this.bytesWrittenThisFile.addAndGet(recordSize); // increment the record count this.totalRecordsWritten.incrementAndGet(); this.fileLineCounter.incrementAndGet(); } } /** * Reset File when it's time to create a new file. * @return OutputStreamWriter * @throws Exception Exception */ public synchronized OutputStreamWriter resetFile() throws Exception { // this will keep it thread safe, so we don't create too many files if (this.fileLineCounter.get() == 0 && this.currentWriter != null) { return this.currentWriter; } closeAndDestroyWriter(); // Create the path for where the file is going to live. try { // generate a file name String fileName = this.s3WriterConfiguration.getWriterFilePrefix() + (this.s3WriterConfiguration.getChunk() ? "/" : "-") + new Date().getTime() + ".tsv"; // create the output stream OutputStream outputStream = new S3OutputStreamWrapper(this.amazonS3Client, this.s3WriterConfiguration.getBucket(), this.s3WriterConfiguration.getWriterPath(), fileName, objectMetaData); // reset the counter this.fileLineCounter = new AtomicInteger(); this.bytesWrittenThisFile = new AtomicLong(); // add this to the list of written files writtenFiles.add(this.s3WriterConfiguration.getWriterPath() + fileName); // Log that we are creating this file LOGGER.info("File Created: Bucket[{}] - {}", this.s3WriterConfiguration.getBucket(), this.s3WriterConfiguration.getWriterPath() + fileName); // return the output stream return new OutputStreamWriter(outputStream); } catch (Exception ex) { LOGGER.error(ex.getMessage()); throw ex; } } private synchronized void closeAndDestroyWriter() { // if there is a current writer, we must close it first. if (this.currentWriter != null) { this.safeFlush(this.currentWriter); this.closeSafely(this.currentWriter); this.currentWriter = null; // Logging of information to alert the user to the activities of this class LOGGER.debug("File Closed: Records[{}] Bytes[{}] {} ", this.fileLineCounter.get(), this.bytesWrittenThisFile.get(), this.writtenFiles.get(this.writtenFiles.size() - 1)); } } private synchronized void closeSafely(Writer writer) { if (writer != null) { try { writer.flush(); writer.close(); } catch (Exception ex) { LOGGER.trace("closeSafely", ex); } LOGGER.debug("File Closed"); } } private void safeFlush(Flushable flushable) { // This is wrapped with a ByteArrayOutputStream, so this is really safe. if (flushable != null) { try { flushable.flush(); } catch (IOException ex) { LOGGER.trace("safeFlush", ex); } } } @Override public void prepare(Object configurationObject) { lineWriterUtil = LineReadWriteUtil.getInstance(s3WriterConfiguration); // Connect to S3 synchronized (this) { try { // if the user has chosen to not set the object mapper, then set a default object mapper for them. if (this.objectMapper == null) { this.objectMapper = StreamsJacksonMapper.getInstance(); } // Create the credentials Object if (this.amazonS3Client == null) { AWSCredentials credentials = new BasicAWSCredentials(s3WriterConfiguration.getKey(), s3WriterConfiguration.getSecretKey()); ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setProtocol(Protocol.valueOf(s3WriterConfiguration.getProtocol().toString())); // We do not want path style access S3ClientOptions clientOptions = new S3ClientOptions(); clientOptions.setPathStyleAccess(false); this.amazonS3Client = new AmazonS3Client(credentials, clientConfig); if (StringUtils.isNotEmpty(s3WriterConfiguration.getRegion())) { this.amazonS3Client.setRegion(Region.getRegion(Regions.fromName(s3WriterConfiguration.getRegion()))); } this.amazonS3Client.setS3ClientOptions(clientOptions); } } catch (Exception ex) { LOGGER.error("Exception while preparing the S3 client: {}", ex); } Preconditions.checkArgument(this.amazonS3Client != null); } } public void cleanUp() { closeAndDestroyWriter(); } @Override public DatumStatusCounter getDatumStatusCounter() { DatumStatusCounter counters = new DatumStatusCounter(); counters.incrementAttempt(this.totalRecordsWritten.get()); counters.incrementStatus(DatumStatus.SUCCESS, this.totalRecordsWritten.get()); return counters; } }
33.376206
175
0.715318
beceb1bd7d6d0688d54f96aa0f6c7c45d98485d4
1,055
package server.push; import io.netty.channel.ChannelHandlerContext; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.util.concurrent.ConcurrentHashMap; /** * Created by huoyijie on 18/10/25. */ public class UniqueIdCtxMap { private static final InternalLogger log = InternalLoggerFactory.getInstance(UniqueIdCtxMap.class); private static final ConcurrentHashMap<Long, ChannelHandlerContext> uniqueId2Ctx = new ConcurrentHashMap<>(); public static void add(long uniqueId, ChannelHandlerContext ctx) { log.debug("server.push.UniqueIdCtxMap.bind " + uniqueId); if(!uniqueId2Ctx.containsKey(uniqueId)) { uniqueId2Ctx.putIfAbsent(uniqueId, ctx); } } public static void remove(long uniqueId) { log.debug("server.push.UniqueIdCtxMap.unbind " + uniqueId); uniqueId2Ctx.remove(uniqueId); } public static ChannelHandlerContext get(long uniqueId) { return uniqueId2Ctx.get(uniqueId); } }
32.96875
113
0.734597
25e9ba0f60c35413c5b4d8523371c1f9497fae53
707
package ada.domain.dvc.values; import ada.domain.dvc.protocol.api.ValueObject; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = RoleAuthorization.class, name = "role"), @JsonSubTypes.Type(value = UserAuthorization.class, name = "user"), @JsonSubTypes.Type(value = WildcardAuthorization.class, name = "wildcard") }) public interface Authorization extends ValueObject { @JsonIgnore boolean hasAuthorization(User user); }
30.73913
78
0.760962
80527bbd4b946462c80aba743ea7051229975cc1
1,234
package qp.dataflow; import com.google.common.base.MoreObjects; import java.util.Objects; /** * * @author tperrotta */ public class Transformation extends DataflowObject implements Comparable<Transformation> { private String tag; public Transformation() { } public Transformation(String tag) { this.tag = tag; } @Override public int hashCode() { return Objects.hash(this.tag); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Transformation other = (Transformation) obj; return Objects.equals(this.tag, other.tag); } @Override public String toString() { return MoreObjects.toStringHelper(this.getClass()) .add("tag", tag) .toString(); } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } @Override public int compareTo(Transformation o) { return this.tag.compareTo(o.tag); } }
19.587302
90
0.560778
147db5a61641dd4c3271bba001339bd38960d7f4
1,135
package PersonalFolder; import java.util.ArrayList; import java.util.Arrays; public class EmployeeDetails { private static ArrayList<Employee> employees = new ArrayList<>(); public void addNamesToList() { employees.add(new Employee("Addams", " Gomez"," Accounting")); employees.add(new Employee("Taylor", " Andy", " Public Admin")); employees.add(new Employee("Kirk", " James", " Marketing")); } public void changeName(){ employees.add(3,(new Employee("presh", "lois", " Management"))); employees.add(4,(new Employee("Eric", "lois", " Logistics"))); employees.add(5,(new Employee("Ama", "lois", " Banking"))); employees.add(6,(new Employee("kindy", "lois", " Finance"))); employees.add(7,(new Employee("Ruth", "lois", " DevOps"))); employees.add(8,(new Employee("Amaka", "lois", " Pharmacy"))); System.out.println(employees); } public static void main(String[] args) { EmployeeDetails employeeDetails = new EmployeeDetails(); employeeDetails.addNamesToList(); employeeDetails.changeName(); } }
32.428571
72
0.627313
11549ba3819480fcb546f5d97bab45ada5e4e8d3
883
/** * MuleSoft Examples * Copyright 2014 MuleSoft, Inc. * * This product includes software developed at * MuleSoft, Inc. (http://www.mulesoft.com/). */ package org.mule.examples; import org.codehaus.jackson.annotate.JsonAutoDetect; @JsonAutoDetect public class Address { private String streetAddress; private String city; private String state; private String zipCode; public String getStreetAddress() { return streetAddress; } public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } }
18.395833
53
0.722537
52e25be258e4ed23b9053ad9eac35f77038cefd9
2,284
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LeafNode.java * Copyright (C) 2013 University of Waikato, Hamilton, New Zealand * */ package weka.classifiers.trees.ht; import java.io.Serializable; import weka.core.Instance; /** * Leaf node in a HoeffdingTree * * @author Richard Kirkby ([email protected]) * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class LeafNode extends HNode implements Serializable { /** * For serialization */ private static final long serialVersionUID = -3359429731894384404L; /** The actual node for this leaf */ public HNode m_theNode; /** Parent split node */ public SplitNode m_parentNode; /** Parent branch leading to this node */ public String m_parentBranch; /** * Construct an empty leaf node */ public LeafNode() { } /** * Construct a leaf node with the given actual node, parent and parent branch * * @param node the actual node at this leaf * @param parentNode the parent split node * @param parentBranch the branch leading to this node */ public LeafNode(HNode node, SplitNode parentNode, String parentBranch) { m_theNode = node; m_parentNode = parentNode; m_parentBranch = parentBranch; } @Override public void updateNode(Instance inst) throws Exception { if (m_theNode != null) { m_theNode.updateDistribution(inst); } else { super.updateDistribution(inst); } } }
28.911392
82
0.640981
0e606fd5b1357b306d86b9ba9450925ee8af90c3
27,510
// Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.cf_segments; import com.google.classlib.events.InstructionHandler; import com.google.classlib.model.ClassInfo; import com.google.classlib.model.ConstantPoolTag; import com.google.classlib.model.FieldrefInfo; import com.google.classlib.model.InterfaceMethodrefInfo; import com.google.classlib.model.Item; import com.google.classlib.model.KnownAttribute; import com.google.classlib.model.MethodrefInfo; import com.google.classlib.model.NameAndTypeInfo; import com.google.classlib.model.StringInfo; import com.google.classlib.model.VerificationTypeInfo; import com.google.classlib.pool.ResolvingClassEventHandler; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Callable; public class MeasureClassEventHandler extends ResolvingClassEventHandler { private final Metrics metrics; public MeasureClassEventHandler(Metrics metrics) { super(new InstHandler(metrics)); this.metrics = metrics; // ClassFile { // u4 magic; // u2 minor_version; // u2 major_version; // u2 constant_pool_count; // cp_info constant_pool[constant_pool_count-1]; // u2 access_flags; // u2 this_class; // u2 super_class; // u2 interfaces_count; // u2 interfaces[interfaces_count]; // u2 fields_count; // field_info fields[fields_count]; // u2 methods_count; // method_info methods[methods_count]; // u2 attributes_count; // attribute_info attributes[attributes_count]; // } metrics.classFile.increment(1, 24); } @Override public void handleInterfaces(int[] interfaces) { super.handleInterfaces(interfaces); this.metrics.interfaces.increment(interfaces.length, interfaces.length * 2); } @Override public void handleAttributeInfo(int attributeNameIndex, Callable<byte[]> info) { super.handleAttributeInfo(attributeNameIndex, info); // attribute_info { // u2 attribute_name_index; // u4 attribute_length; // u1 info[attribute_length]; // } try { String type = getPool()[attributeNameIndex].toString(); int size = info.call().length + 6; switch (type) { case "SourceFile": metrics.otherClassAttributes.increment(1, size); break; case "BootstrapMethods": metrics.bootstrapMethodAttributes.increment(1, size); break; case "InnerClasses": metrics.innerClasses.increment(1, size); break; case "LineNumberTable": metrics.lineNumberTableEntries.increment(1, size); break; case "LocalVariableTable": metrics.localVariableTable.increment(1, size); break; case "StackMap": // StackMapEntries are counted separately. metrics.stackMapTable.increment(0, size); break; default: metrics.otherClassAttributes.increment(1, size); break; } } catch (Exception e) { throw new RuntimeException(e); } } @Override public void endConstantPool() { super.endConstantPool(); for (int i = 1; i < getPool().length; i++) { Object object = getPool()[i]; if (object instanceof ClassInfo || object instanceof StringInfo) { metrics.constantPool.increment(1, 3); } else if (object instanceof FieldrefInfo || object instanceof MethodrefInfo || object instanceof InterfaceMethodrefInfo || object instanceof Integer || object instanceof Float || object instanceof NameAndTypeInfo) { metrics.constantPool.increment(1, 5); } else if (object instanceof Long || object instanceof Double) { metrics.constantPool.increment(1, 9); // Skip next entry. i++; } else { // This is either a String, or object is null, constituting Constant_MethodHandle, // Constant_MethodType or InvokeDynamic. All handled below in other handlers. assert object instanceof String || object == null; } } } @Override public void handleConstant(ConstantPoolTag tag, int index, int length, String utf8) { super.handleConstant(tag, index, length, utf8); metrics.constantPool.increment(1, length + 3); } @Override public void handleConstantMethodHandle( ConstantPoolTag tag, int index, int referenceKind, int referenceIndex) { super.handleConstantMethodHandle(tag, index, referenceKind, referenceIndex); metrics.constantPool.increment(1, 4); } @Override public void handleConstantMethodType(ConstantPoolTag tag, int index, int descriptorIndex) { super.handleConstantMethodType(tag, index, descriptorIndex); metrics.constantPool.increment(1, 3); } @Override public void handleConstantInvokeDynamic( ConstantPoolTag tag, int index, int bootstrapMethodAttributeIndex, int nameAndTypeIndex) { super.handleConstantInvokeDynamic(tag, index, bootstrapMethodAttributeIndex, nameAndTypeIndex); metrics.constantPool.increment(1, 5); } @Override public void beginFieldInfo( int accessFlags, int nameIndex, int descriptorIndex, int attributesCount) { // field_info { // u2 access_flags; // u2 name_index; // u2 descriptor_index; // u2 attributes_count; // attribute_info attributes[attributes_count]; // } long infoSize = 2 + 2 + 2 + 2; metrics.fieldInfo.increment(1, infoSize); } @Override public void beginMethodInfo( int accessFlags, int nameIndex, int descriptorIndex, int attributesCount) { // method_info { // u2 access_flags; // u2 name_index; // u2 descriptor_index; // u2 attributes_count; // attribute_info attributes[attributes_count]; // } long infoSize = 2 + 2 + 2 + 2; metrics.methodInfo.increment(1, infoSize); } @Override public Set<KnownAttribute> getHandledAttributes() { Set<KnownAttribute> known = new HashSet<>(); known.add(KnownAttribute.Code); known.add(KnownAttribute.StackMapTable); return known; } @Override public void beginCodeAttribute(int maxStack, int maxLocals, long codeLength) { super.beginCodeAttribute(maxStack, maxLocals, codeLength); // Code_attribute { // u2 attribute_name_index; // u4 attribute_length; // u2 max_stack; // u2 max_locals; // u4 code_length; // u1 code[code_length]; // u2 exception_table_length; // { u2 start_pc; // u2 end_pc; // u2 handler_pc; // u2 catch_type; // } exception_table[exception_table_length]; // u2 attributes_count; // attribute_info attributes[attributes_count]; // } long codeSize = 2 + 4 + 2 + 2 + 4 + codeLength + 2 + 2; metrics.code.increment(1, codeSize); metrics.maxLocals.increment(1, maxLocals); metrics.maxStacks.increment(1, maxStack); } @Override public void handleExceptionTableEntry(int startPc, int endPc, int handlerPc, int catchType) { super.handleExceptionTableEntry(startPc, endPc, handlerPc, catchType); metrics.exceptionTable.increment(1, 8); } @Override public void beginStackMapTableAttribute(int numberOfEntries) { super.beginStackMapTableAttribute(numberOfEntries); metrics.stackMapTable.increment(1, 2 + 4 + 2); } private int sizeOfVerificationTypeInfo(VerificationTypeInfo info) { if (info.getItem() == Item.ITEM_Object || info.getItem() == Item.ITEM_Uninitialized) { return 3; } else { return 1; } } @Override public void handleSameFrame(int offsetDelta) { super.handleSameFrame(offsetDelta); metrics.stackmapTableOtherEntries.increment(1, 1); } @Override public void handleSameLocals1StackItemFrame(int offsetDelta, VerificationTypeInfo stack) { super.handleSameLocals1StackItemFrame(offsetDelta, stack); metrics.stackmapTableOtherEntries.increment(1, 1 + sizeOfVerificationTypeInfo(stack)); } @Override public void handleSameLocals1StackItemFrameExtended(int offsetDelta, VerificationTypeInfo stack) { super.handleSameLocals1StackItemFrameExtended(offsetDelta, stack); metrics.stackmapTableOtherEntries.increment(1, 3 + sizeOfVerificationTypeInfo(stack)); } @Override public void handleChopFrame(int offsetDelta, int chopLocals) { super.handleChopFrame(offsetDelta, chopLocals); metrics.stackmapTableOtherEntries.increment(1, 3); } @Override public void handleSameFrameExtended(int offsetDelta) { super.handleSameFrameExtended(offsetDelta); metrics.stackmapTableOtherEntries.increment(1, 3); } @Override public void handleAppendFrame(int offsetDelta, VerificationTypeInfo[] locals) { super.handleAppendFrame(offsetDelta, locals); int size = 3; for (VerificationTypeInfo type : locals) { size += sizeOfVerificationTypeInfo(type); } metrics.stackmapTableOtherEntries.increment(1, size); } @Override public void handleFullFrame( int offsetDelta, VerificationTypeInfo[] locals, VerificationTypeInfo[] stack) { super.handleFullFrame(offsetDelta, locals, stack); // full_frame { // u1 frame_type = FULL_FRAME; /* 255 */ // u2 offset_delta; // u2 number_of_locals; // verification_type_info locals[number_of_locals]; // u2 number_of_stack_items; // verification_type_info stack[number_of_stack_items]; // } int size = 7; for (VerificationTypeInfo type : locals) { size += sizeOfVerificationTypeInfo(type); } for (VerificationTypeInfo type : stack) { size += sizeOfVerificationTypeInfo(type); } metrics.stackMapTableFullFrameEntries.increment(1, size); } // The instruction handler allows for measuring size on the instruction level. At this point we // are calculating the entire code size in beginCodeAttribute. However, to keep track of our how // well our load-store insertion works we are tracking the number of loads and stores inserted. private static class InstHandler implements InstructionHandler<Integer> { private final Metrics metrics; public InstHandler(Metrics metrics) { this.metrics = metrics; } @Override public Integer aaload() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.loads.increment(1, 2); return null; } @Override public Integer aastore() throws NullPointerException, ArrayIndexOutOfBoundsException, ArrayStoreException { metrics.stores.increment(1, 2); return null; } @Override public Integer aconstNull() { return null; } @Override public Integer aload(int index) { metrics.loads.increment(1, 3); return null; } @Override public Integer aloadN(int opcode) { metrics.loads.increment(1, 2); return null; } @Override public Integer anewarray(int index) throws NegativeArraySizeException { return null; } @Override public Integer areturn() throws IllegalMonitorStateException { return null; } @Override public Integer arraylength() throws NullPointerException { return null; } @Override public Integer astore(int index) { metrics.stores.increment(1, 3); return null; } @Override public Integer astoreN(int opcode) { metrics.stores.increment(1, 2); return null; } @Override public Integer athrow() throws NullPointerException, IllegalMonitorStateException { return null; } @Override public Integer baload() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.loads.increment(1, 2); return null; } @Override public Integer bastore() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.stores.increment(1, 2); return null; } @Override public Integer bipush(byte byteValue) { return null; } @Override public Integer caload() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.loads.increment(1, 2); return null; } @Override public Integer castore() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.stores.increment(1, 2); return null; } @Override public Integer checkcast(int index) throws ClassCastException { return null; } @Override public Integer d2f() { return null; } @Override public Integer d2i() { return null; } @Override public Integer d2l() { return null; } @Override public Integer dadd() { return null; } @Override public Integer daload() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.loads.increment(1, 2); return null; } @Override public Integer dastore() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.stores.increment(1, 2); return null; } @Override public Integer dcmp(int opcode) { return null; } @Override public Integer dconstD(int opcode) { return null; } @Override public Integer ddiv() { return null; } @Override public Integer dload(int index) { metrics.loads.increment(1, 3); return null; } @Override public Integer dloadN(int opcode) { metrics.loads.increment(1, 2); return null; } @Override public Integer dmul() { return null; } @Override public Integer dneg() { return null; } @Override public Integer drem() { return null; } @Override public Integer dreturn() throws IllegalMonitorStateException { return null; } @Override public Integer dstore(int index) { metrics.stores.increment(1, 3); return null; } @Override public Integer dstoreN(int opcode) { metrics.stores.increment(1, 2); return null; } @Override public Integer dsub() { return null; } @Override public Integer dup() { return null; } @Override public Integer dupX1() { return null; } @Override public Integer dupX2() { return null; } @Override public Integer dup2() { return null; } @Override public Integer dup2X1() { return null; } @Override public Integer dup2X2() { return null; } @Override public Integer f2d() { return null; } @Override public Integer f2i() { return null; } @Override public Integer f2l() { return null; } @Override public Integer fadd() { return null; } @Override public Integer faload() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.loads.increment(1, 2); return null; } @Override public Integer fastore() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.stores.increment(1, 2); return null; } @Override public Integer fcmp(int opcode) { return null; } @Override public Integer fconstF(int opcode) { return null; } @Override public Integer fdiv() { return null; } @Override public Integer fload(int index) { metrics.loads.increment(1, 3); return null; } @Override public Integer floadN(int opcode) { metrics.loads.increment(1, 2); return null; } @Override public Integer fmul() { return null; } @Override public Integer fneg() { return null; } @Override public Integer frem() { return null; } @Override public Integer freturn() throws IllegalMonitorStateException { return null; } @Override public Integer fstore(int index) { metrics.stores.increment(1, 3); return null; } @Override public Integer fstoreN(int opcode) { metrics.stores.increment(1, 2); return null; } @Override public Integer fsub() { return null; } @Override public Integer getfield(int index) throws IncompatibleClassChangeError, NullPointerException { return null; } @Override public Integer getstatic(int index) throws IncompatibleClassChangeError, Error { return null; } @Override public Integer gotoInstruction(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer gotoW(int branch) { metrics.jumps.increment(1, 6); return null; } @Override public Integer i2b() { return null; } @Override public Integer i2c() { return null; } @Override public Integer i2d() { return null; } @Override public Integer i2f() { return null; } @Override public Integer i2l() { return null; } @Override public Integer i2s() { return null; } @Override public Integer iadd() { return null; } @Override public Integer iaload() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.loads.increment(1, 2); return null; } @Override public Integer iand() { return null; } @Override public Integer iastore() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.stores.increment(1, 2); return null; } @Override public Integer iconstI(int opcode) { return null; } @Override public Integer idiv() throws ArithmeticException { return null; } @Override public Integer ifAcmpeq(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifAcmpne(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifIcmpeq(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifIcmpne(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifIcmplt(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifIcmpge(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifIcmpgt(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifIcmple(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifeq(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifne(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer iflt(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifge(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifgt(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifle(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifnonnull(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer ifnull(short branch) { metrics.jumps.increment(1, 4); return null; } @Override public Integer iinc(int index, short constValue) { return null; } @Override public Integer iload(int index) { metrics.loads.increment(1, 3); return null; } @Override public Integer iloadN(int opcode) { metrics.loads.increment(1, 2); return null; } @Override public Integer imul() { return null; } @Override public Integer ineg() { return null; } @Override public Integer instanceofInstruction(int index) { return null; } @Override public Integer invokedynamic(int index, short zero0, short zero1) { return null; } @Override public Integer invokeinterface(int index, short count, short zero) throws AbstractMethodError, NullPointerException, IncompatibleClassChangeError, IllegalAccessError, UnsatisfiedLinkError { return null; } @Override public Integer invokespecial(int index) throws AbstractMethodError, NullPointerException, UnsatisfiedLinkError { return null; } @Override public Integer invokestatic(int index) throws Error, UnsatisfiedLinkError { return null; } @Override public Integer invokevirtual(int index) throws NullPointerException, AbstractMethodError, UnsatisfiedLinkError { return null; } @Override public Integer ior() { return null; } @Override public Integer irem() throws ArithmeticException { return null; } @Override public Integer ireturn() throws IllegalMonitorStateException { return null; } @Override public Integer ishl() { return null; } @Override public Integer ishr() { return null; } @Override public Integer istore(int index) { metrics.stores.increment(1, 3); return null; } @Override public Integer istoreN(int opcode) { metrics.stores.increment(1, 2); return null; } @Override public Integer isub() { return null; } @Override public Integer iushr() { return null; } @Override public Integer ixor() { return null; } @Override public Integer jsr(short branch) { return null; } @Override public Integer jsrW(int branch) { return null; } @Override public Integer l2d() { return null; } @Override public Integer l2f() { return null; } @Override public Integer l2i() { return null; } @Override public Integer ladd() { return null; } @Override public Integer laload() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.loads.increment(1, 2); return null; } @Override public Integer land() { return null; } @Override public Integer lastore() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.stores.increment(1, 2); return null; } @Override public Integer lcmp() { return null; } @Override public Integer lconstL(int opcode) { return null; } @Override public Integer ldc(short index) { return null; } @Override public Integer ldcW(int index) { return null; } @Override public Integer ldc2W(int index) { return null; } @Override public Integer ldiv() throws ArithmeticException { return null; } @Override public Integer lload(int index) { metrics.loads.increment(1, 3); return null; } @Override public Integer lloadN(int opcode) { metrics.loads.increment(1, 2); return null; } @Override public Integer lmul() { return null; } @Override public Integer lneg() { return null; } @Override public Integer lookupswitch(int defaultValue, int npairs, int... matchOffsetPairs) { metrics.jumps.increment(1, 2 + 8 + matchOffsetPairs.length * 8); return null; } @Override public Integer lor() { return null; } @Override public Integer lrem() throws ArithmeticException { return null; } @Override public Integer lreturn() throws IllegalMonitorStateException { return null; } @Override public Integer lshl() { return null; } @Override public Integer lshr() { return null; } @Override public Integer lstore(int index) { metrics.stores.increment(1, 3); return null; } @Override public Integer lstoreN(int opcode) { metrics.stores.increment(1, 2); return null; } @Override public Integer lsub() { return null; } @Override public Integer lushr() { return null; } @Override public Integer lxor() { return null; } @Override public Integer monitorenter() throws NullPointerException { return null; } @Override public Integer monitorexit() throws NullPointerException, IllegalMonitorStateException { return null; } @Override public Integer multianewarray(int index, short dimensions) throws NegativeArraySizeException { return null; } @Override public Integer newInstruction(int index) throws Error { return null; } @Override public Integer newarray(short atype) throws NegativeArraySizeException { return null; } @Override public Integer nop() { return null; } @Override public Integer pop() { return null; } @Override public Integer pop2() { return null; } @Override public Integer putfield(int index) throws NullPointerException { return null; } @Override public Integer putstatic(int index) throws Error { return null; } @Override public Integer ret(int index) { return null; } @Override public Integer returnInstruction() throws IllegalMonitorStateException { return null; } @Override public Integer saload() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.loads.increment(1, 2); return null; } @Override public Integer sastore() throws NullPointerException, ArrayIndexOutOfBoundsException { metrics.stores.increment(1, 2); return null; } @Override public Integer sipush(short value) { return null; } @Override public Integer swap() { return null; } @Override public Integer tableswitch(int defaultValue, int low, int high, int... jumpoffsets) { metrics.jumps.increment(1, 2 + 16 + jumpoffsets.length * 4); return null; } @Override public Integer wide() { return null; } @Override public Integer impdep1() { return null; } @Override public Integer impdep2() { return null; } @Override public Integer breakpoint() { return null; } @Override public Integer unknown(int opcode) { return null; } @Override public void setPc(long pc) {} @Override public void handleParseError(String message) {} } }
23.098237
100
0.634533
5bf07b4a7c9f45b51dcd952f4095d2d098e08619
2,332
package engine.graphics; import java.awt.Graphics; import java.awt.Image; import java.util.ArrayList; import engine.core.MarioGame; import engine.helper.TileFeature; public class MarioTilemap extends MarioGraphics { public Image[][] sheet; public int[][] currentIndeces; public int[][] indexShift; public float[][] moveShift; public int animationIndex; public MarioTilemap(Image[][] sheet, int[][] currentIndeces) { this.sheet = sheet; this.currentIndeces = currentIndeces; this.indexShift = new int[currentIndeces.length][currentIndeces[0].length]; this.moveShift = new float[currentIndeces.length][currentIndeces[0].length]; this.animationIndex = 0; } @Override public void render(Graphics og, int x, int y) { this.animationIndex = (this.animationIndex + 1) % 5; int xMin = (x / 16) - 1; int yMin = (y / 16) - 1; int xMax = (x + MarioGame.width) / 16 + 1; int yMax = (y + MarioGame.height) / 16 + 1; for (int xTile = xMin; xTile <= xMax; xTile++) { for (int yTile = yMin; yTile <= yMax; yTile++) { if (xTile < 0 || yTile < 0 || xTile >= currentIndeces.length || yTile >= currentIndeces[0].length) { continue; } if (this.moveShift[xTile][yTile] > 0) { this.moveShift[xTile][yTile] -= 1; if (this.moveShift[xTile][yTile] < 0) { this.moveShift[xTile][yTile] = 0; } } ArrayList<TileFeature> features = TileFeature.getTileType(this.currentIndeces[xTile][yTile]); if (features.contains(TileFeature.ANIMATED)) { if (this.animationIndex == 0) { this.indexShift[xTile][yTile] = (this.indexShift[xTile][yTile] + 1) % 3; } } else { this.indexShift[xTile][yTile] = 0; } int index = currentIndeces[xTile][yTile] + indexShift[xTile][yTile]; int move = (int) moveShift[xTile][yTile]; Image img = sheet[index % 8][index / 8]; og.drawImage(img, xTile * 16 - x, yTile * 16 - y - move, null); } } } }
37.612903
116
0.539022
e53f150b49dae4ed077673ffe956c2d21e840879
2,174
/* * Copyright (C) 2022-2022 Huawei Technologies Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huaweicloud.integration.controller; import com.huaweicloud.integration.service.BarService; import com.alibaba.dubbo.rpc.service.GenericService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * 测试接口 * * @author provenceee * @since 2022-04-28 */ @RestController @RequestMapping("/consumer") public class ConsumerBarController { @Resource(name = "barService") private BarService barService; @Resource(name = "bar2Service") private BarService bar2Service; @Resource(name = "barGenericService") private GenericService barGenericService; /** * 测试接口 * * @param str 参数 * @return 测试信息 */ @GetMapping("/testBar") public String testBar(@RequestParam String str) { return barService.bar(str); } /** * 测试接口 * * @param str 参数 * @return 测试信息 */ @GetMapping("/testBar2") public String testBar2(@RequestParam String str) { return bar2Service.bar(str); } /** * 测试泛化接口 * * @param str 参数 * @return 测试信息 */ @GetMapping("/testBarGeneric") public String testBarGeneric(@RequestParam String str) { return barGenericService.$invoke("bar", new String[]{"java.lang.String"}, new Object[]{str}) .toString(); } }
26.839506
100
0.690432
2efec914843c4bc4eb433a39da20c9af674dbc8f
580
package dev.ursinn.schule.m120; import javax.swing.*; import java.awt.*; import java.awt.geom.Line2D; public class First2Ddemo extends JFrame { @Override public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.draw(new Line2D.Double(10, 40, getWidth() - 10, 70)); } public static void main(String[] args) { JFrame f = new First2Ddemo(); f.setSize(200, 100); f.setVisible(true); } }
23.2
96
0.648276
a2240b9e8af99b56180f9f9a7079bcbe0de1931c
247
package com.ibeetl.admin.console.handler; import com.ibeetl.admin.console.domain.ResultDO; /** * Created by lwen on 2018/9/15 */ public abstract class ExceptionHandler { public abstract void handle(Exception exception, ResultDO result); }
22.454545
70
0.765182
20161a1e97721c348c0999779424182e6abf88ad
420
package ru.gravo.boxes.work_place_list; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import ru.gravo.boxes.BpoA; /** * Created by Алексей on 02.11.2017. */ public class LcCfgWorkPlace { @SerializedName("CFG.WP") @Expose private BpoA<APlace>[] cfgWorkPlaceList; public BpoA<APlace>[] getCfgWorkPlaceList() { return cfgWorkPlaceList; } }
20
50
0.719048
6750d1ffa29d44954696d2baf73fbb1256c1a868
508
public class dupArray { public static void main(String[] args) { int [] array = {1 , 2 ,3 ,4 ,5}; int [] newArray = new int[array.length]; for (int i = 0 ; i < array.length; i ++){ newArray[i] = array[i]; System.out.println("old array " + array[i]); System.out.println("new array " + newArray[i]); } //This is another way on how to duplicate an array System.arraycopy(array, 0, newArray, 0, array.length); } }
25.4
62
0.529528
10e97b12403af8cdaa056356137ff09ba40bde3b
11,703
package io.nuls.chain; import io.nuls.base.basic.AddressTool; import io.nuls.base.protocol.CommonAdvice; import io.nuls.base.protocol.ProtocolGroupManager; import io.nuls.base.protocol.ProtocolLoader; import io.nuls.base.protocol.RegisterHelper; import io.nuls.base.protocol.cmd.TransactionDispatcher; import io.nuls.chain.config.NulsChainConfig; import io.nuls.chain.info.CmConstants; import io.nuls.chain.info.CmRuntimeInfo; import io.nuls.chain.model.po.BlockChain; import io.nuls.chain.rpc.call.RpcService; import io.nuls.chain.rpc.call.impl.RpcServiceImpl; import io.nuls.chain.service.CacheDataService; import io.nuls.chain.service.ChainService; import io.nuls.chain.service.impl.ChainServiceImpl; import io.nuls.chain.service.impl.CmTaskManager; import io.nuls.chain.service.tx.v1.ChainAssetCommitAdvice; import io.nuls.chain.service.tx.v1.ChainAssetRollbackAdvice; import io.nuls.chain.storage.InitDB; import io.nuls.chain.storage.impl.*; import io.nuls.chain.util.LoggerUtil; import io.nuls.core.core.annotation.Autowired; import io.nuls.core.core.annotation.Component; import io.nuls.core.core.ioc.SpringLiteContext; import io.nuls.core.model.BigIntegerUtils; import io.nuls.core.rockdb.service.RocksDBService; import io.nuls.core.rpc.info.HostInfo; import io.nuls.core.rpc.model.ModuleE; import io.nuls.core.rpc.modulebootstrap.Module; import io.nuls.core.rpc.modulebootstrap.NulsRpcModuleBootstrap; import io.nuls.core.rpc.modulebootstrap.RpcModule; import io.nuls.core.rpc.modulebootstrap.RpcModuleState; import io.nuls.core.rpc.util.AddressPrefixDatas; import io.nuls.core.rpc.util.NulsDateUtils; import java.io.File; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 链管理模块启动类 * Main class of BlockChain module * * @author tangyi * @date 2018/11/7 */ @Component public class ChainManagerBootstrap extends RpcModule { @Autowired private NulsChainConfig nulsChainConfig; @Autowired private AddressPrefixDatas addressPrefixDatas; @Autowired private RpcService rpcService; @Autowired private ChainService chainService; public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[]{"ws://" + HostInfo.getLocalIP() + ":7771"}; } NulsRpcModuleBootstrap.run("io.nuls", args); } /** * 读取resources/module.ini,初始化配置 * Read resources/module.ini to initialize the configuration */ private void initCfg() throws Exception { CmRuntimeInfo.nulsAssetId = nulsChainConfig.getMainAssetId(); CmRuntimeInfo.nulsChainId = nulsChainConfig.getMainChainId(); long decimal = (long) Math.pow(10, Integer.valueOf(nulsChainConfig.getDefaultDecimalPlaces())); BigInteger initNumber = BigIntegerUtils.stringToBigInteger(nulsChainConfig.getNulsAssetInitNumberMax()).multiply( BigInteger.valueOf(decimal)); nulsChainConfig.setNulsAssetInitNumberMax(BigIntegerUtils.bigIntegerToString(initNumber)); BigInteger assetDepositNuls = BigIntegerUtils.stringToBigInteger(nulsChainConfig.getAssetDepositNuls()).multiply( BigInteger.valueOf(decimal)); nulsChainConfig.setAssetDepositNuls(BigIntegerUtils.bigIntegerToString(assetDepositNuls)); nulsChainConfig.setAssetDepositNulsLockRate(String.valueOf(1-Double.valueOf(nulsChainConfig.getAssetDepositNulsDestroyRate()))); BigInteger assetInitNumberMin = BigIntegerUtils.stringToBigInteger(nulsChainConfig.getAssetInitNumberMin()).multiply( BigInteger.valueOf(decimal)); nulsChainConfig.setAssetInitNumberMin(BigIntegerUtils.bigIntegerToString(assetInitNumberMin)); BigInteger assetInitNumberMax = BigIntegerUtils.stringToBigInteger(nulsChainConfig.getAssetInitNumberMax()).multiply( BigInteger.valueOf(decimal)); nulsChainConfig.setAssetInitNumberMax(BigIntegerUtils.bigIntegerToString(assetInitNumberMax)); nulsChainConfig.setNulsFeeMainNetPercent((int) (Double.valueOf(nulsChainConfig.getNulsFeeMainNetRate()) * 100)); nulsChainConfig.setNulsFeeOtherNetPercent(100-nulsChainConfig.getNulsFeeMainNetPercent()); CmConstants.BLACK_HOLE_ADDRESS = AddressTool.getAddressByPubKeyStr(nulsChainConfig.getBlackHolePublicKey(), CmRuntimeInfo.getMainIntChainId()); LoggerUtil.defaultLogInit(CmRuntimeInfo.getMainIntChainId()); } /** * 如果数据库中有相同的配置,则以数据库为准 * If the database has the same configuration, use the database entity * * @throws Exception Any error will throw an exception */ private void initWithDatabase() throws Exception { /* 打开数据库连接 (Open database connection) */ RocksDBService.init(nulsChainConfig.getDataPath() + File.separator + ModuleE.CM.name); InitDB assetStorage = SpringLiteContext.getBean(AssetStorageImpl.class); assetStorage.initTableName(); LoggerUtil.logger().info("assetStorage.init complete....."); InitDB blockHeightStorage = SpringLiteContext.getBean(BlockHeightStorageImpl.class); blockHeightStorage.initTableName(); LoggerUtil.logger().info("blockHeightStorage.init complete....."); InitDB cacheDatasStorage = SpringLiteContext.getBean(CacheDatasStorageImpl.class); cacheDatasStorage.initTableName(); LoggerUtil.logger().info("cacheDatasStorage.init complete....."); InitDB chainAssetStorage = SpringLiteContext.getBean(ChainAssetStorageImpl.class); chainAssetStorage.initTableName(); LoggerUtil.logger().info("chainAssetStorage.init complete....."); InitDB chainStorage = SpringLiteContext.getBean(ChainStorageImpl.class); chainStorage.initTableName(); LoggerUtil.logger().info("chainStorage.init complete....."); InitDB chainCirculateStorage = SpringLiteContext.getBean(ChainCirculateStorageImpl.class); chainCirculateStorage.initTableName(); LoggerUtil.logger().info("chainCirculateStorage.init complete....."); } /** * 把Nuls2.0主网信息存入数据库中 * Store the Nuls2.0 main network information into the database * * @throws Exception Any error will throw an exception */ private void initMainChain() throws Exception { SpringLiteContext.getBean(ChainService.class).initMainChain(); } private void initChainDatas() throws Exception { SpringLiteContext.getBean(CacheDataService.class).initBlockDatas(); ChainServiceImpl chainService = SpringLiteContext.getBean(ChainServiceImpl.class); RpcServiceImpl rpcService = SpringLiteContext.getBean(RpcServiceImpl.class); long mainNetMagicNumber = rpcService.getMainNetMagicNumber(); chainService.initRegChainDatas(mainNetMagicNumber); LoggerUtil.logger().info("initChainDatas complete...."); } @Override public Module[] declareDependent() { return new Module[]{ Module.build(ModuleE.TX), Module.build(ModuleE.LG), Module.build(ModuleE.NW), Module.build(ModuleE.AC), Module.build(ModuleE.CS) }; } @Override public Module moduleInfo() { return new Module(ModuleE.CM.abbr, "1.0"); } /** * 初始化模块信息,比如初始化RockDB等,在此处初始化后,可在其他bean的afterPropertiesSet中使用 */ @Override public void init() { super.init(); try { /* Read resources/module.ini to initialize the configuration */ initCfg(); /** * 地址工具初始化 */ AddressTool.init(addressPrefixDatas); LoggerUtil.logger().info("initCfg complete....."); /*storage info*/ initWithDatabase(); LoggerUtil.logger().info("initWithDatabase complete....."); /* 把Nuls2.0主网信息存入数据库中 (Store the Nuls2.0 main network information into the database) */ initMainChain(); LoggerUtil.logger().info("initMainChain complete....."); } catch (Exception e) { LoggerUtil.logger().error(e); LoggerUtil.logger().error("初始化异常退出...."); System.exit(-1); } } @Override public boolean doStart() { TransactionDispatcher transactionDispatcher = SpringLiteContext.getBean(TransactionDispatcher.class); CommonAdvice commitAdvice = SpringLiteContext.getBean(ChainAssetCommitAdvice.class); CommonAdvice rollbackAdvice = SpringLiteContext.getBean(ChainAssetRollbackAdvice.class); transactionDispatcher.register(commitAdvice, rollbackAdvice); LoggerUtil.logger().info("doStart ok...."); return true; } @Override public void onDependenciesReady(Module module) { try { ProtocolLoader.load(CmRuntimeInfo.getMainIntChainId()); /*注册交易处理器*/ if (ModuleE.TX.abbr.equals(module.getName())) { int chainId = CmRuntimeInfo.getMainIntChainId(); boolean regSuccess = RegisterHelper.registerTx(chainId, ProtocolGroupManager.getCurrentProtocol(chainId)); if (!regSuccess) { LoggerUtil.logger().error("RegisterHelper.registerTx fail.."); System.exit(-1); } LoggerUtil.logger().info("regTxRpc complete....."); } if (ModuleE.PU.abbr.equals(module.getName())) { //注册相关交易 boolean regSuccess = RegisterHelper.registerProtocol(CmRuntimeInfo.getMainIntChainId()); if (!regSuccess) { LoggerUtil.logger().error("RegisterHelper.registerProtocol fail.."); System.exit(-1); } LoggerUtil.logger().info("register protocol ..."); } if (ModuleE.AC.abbr.equals(module.getName())) { //取跨链注册地址前缀数据给AC try { List<BlockChain> blockChains = chainService.getBlockList(); List<Map<String, Object>> list = new ArrayList<>(); for (BlockChain blockChain : blockChains) { if (blockChain.getChainId() == Integer.valueOf(nulsChainConfig.getMainChainId())) { continue; } Map<String, Object> prefix = new HashMap<>(); prefix.put("chainId", blockChain.getChainId()); prefix.put("addressPrefix", blockChain.getAddressPrefix()); list.add(prefix); } rpcService.addAcAddressPrefix(list); } catch (Exception e) { LoggerUtil.logger().error(e); } } } catch (Exception e) { LoggerUtil.logger().error(e); System.exit(-1); } } @Override public RpcModuleState onDependenciesReady() { try { /* 进行数据库数据初始化(避免异常关闭造成的事务不一致) */ initChainDatas(); } catch (Exception e) { LoggerUtil.logger().error(e); LoggerUtil.logger().error("启动异常退出...."); System.exit(-1); } CmTaskManager cmTaskManager = SpringLiteContext.getBean(CmTaskManager.class); cmTaskManager.start(); NulsDateUtils.getInstance().start(5 * 60 * 1000); LoggerUtil.logger().info("onDependenciesReady ok...."); return RpcModuleState.Running; } @Override public RpcModuleState onDependenciesLoss(Module dependenciesModule) { return RpcModuleState.Start; } }
43.025735
151
0.669657
a76e31d520b8405645ac016fce26361b96e8157d
1,386
/* * Copyright 2019 Patriot 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 io.patriot_framework.hub; import io.patriot_framework.network.simulator.api.model.devices.application.Application; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class ApplicationRegistry { private Map<String, Application> deployedApplications = new HashMap<>(); public boolean putDevice(Application a) { if (deployedApplications.containsKey(a.getName())) { return false; } deployedApplications.put(a.getName(), a); return true; } public Application getDevice(String name) { return deployedApplications.get(name); } public void putDevices(Collection<Application> apps) { apps.forEach(app -> this.putDevice(app)); } }
29.489362
88
0.700577
f52413a6cbdc7ab3cccb381725a8e1c2b4de28ad
280
package example.repo; import example.model.Customer786; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer786Repository extends CrudRepository<Customer786, Long> { List<Customer786> findByLastName(String lastName); }
21.538462
82
0.828571
0522ef643c8502d3d0ca0c4197515d3c16fde421
1,594
package chara; import java.util.ArrayList; import java.util.List; import Item.*; public abstract class Player extends Character { private int level; private Weapon weapon; private List<Item> inventory;//プレイヤーのインベントリ,サイズは5こ public int getLevel() { return this.level; } public void setLevel(int level) { this.level = level; } public Weapon getWeapon() { return this.weapon; } public void setWeapon(Weapon weapon) { this.weapon = weapon; } public Item getInventory(int index) { return inventory.get(index); } public void removeItem(int index) { inventory.remove(index); } public void removeItem(Item item) { inventory.remove(item); } public void setInventory(Item item) { if(item!=null&&inventory.size()<6)this.inventory.add(item); } @Override public void attack(Character chara) { chara.setMaxHitPoint(chara.getHitPoint()-(this.getAttackPoint())+this.weapon.getDamage()); } @Override public int getId() { return 1000; } @Override public String getName() { return "キャラ"; } @Override public void action(){ app.ShortDungeon.playerAction(); } Player(int maxhp,int maxsp,int ap,int mp,int dp,int x,int y){ super(maxhp, maxsp, ap, mp, dp,x,y); this.level=1; this.weapon = new Fist(); this.inventory=new ArrayList<>(); } public abstract void levelUp(); }
23.791045
99
0.584693
b071d739a0042b1f9715eef72aef43a4c23d156d
2,168
/* * The MIT License * * Copyright 2017 Olimpia Popica, Benone Aligica * * Contact: contact[a(t)]annotate[(d){o}t]zone * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package gui.support; import java.awt.Point; import java.awt.Color; /** * Encapsulate the needed information to be able to display scribbles. They will * not be used in the algorithms; just for display purposes. * * @author Olimpia Popica */ public class DisplayScribbles { private final Color color; // the color of the scribble private final Point panelPos; // the position of the pixel in the panel /** * Instantiates a new Display scribbles. * * @param color the color * @param panelPos the panel pos */ public DisplayScribbles(Color color, Point panelPos) { this.color = color; this.panelPos = panelPos; } /** * Gets color. * * @return the color */ public Color getColor() { return color; } /** * Gets panel pos. * * @return the panel pos */ public Point getPanelPos() { return panelPos; } }
30.535211
80
0.686808
bddbc71e24c519e57544b5fb66206e1bcba83ff9
325
package com.garowing.gameexp.game.rts.ai.behaviac.constants; /** * 过滤器类型 * @author seg * 2017年1月5日 */ public enum TargetFilterType { /** * 最近的敌人 */ NEAREST_ENEMY(1); /** * 代码 */ private int code; private TargetFilterType(int code) { this.code = code; } public int getCode() { return code; } }
10.833333
60
0.624615
031db795a4cec93a3d1da99e0ff550155f418e80
5,190
/* * Copyright 2015 Alexandr Evstigneev * * 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.perl5.lang.perl.idea.project; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.PlatformUtils; import com.intellij.util.containers.ContainerUtil; import com.perl5.lang.perl.idea.modules.JpsPerlLibrarySourceRootType; import com.perl5.lang.perl.idea.sdk.PerlSdkType; import com.perl5.lang.perl.idea.settings.Perl5Settings; import org.jetbrains.annotations.NotNull; import java.io.File; import java.util.Comparator; import java.util.HashSet; import java.util.Set; /** * Created by hurricup on 30.08.2015. */ public class PerlMicroIdeSettingsLoader implements ProjectComponent { protected Project myProject; protected Perl5Settings perl5Settings; public PerlMicroIdeSettingsLoader(Project project) { myProject = project; perl5Settings = Perl5Settings.getInstance(project); } // fixme make this non-static and request it from manager public static void applyClassPaths(ModifiableRootModel rootModel) { for (OrderEntry entry : rootModel.getOrderEntries()) { // System.err.println("Checking " + entry + " of " + entry.getClass()); if (entry instanceof LibraryOrderEntry) { // System.err.println("Removing " + entry); rootModel.removeOrderEntry(entry); } } LibraryTable table = rootModel.getModuleLibraryTable(); for (VirtualFile entry : rootModel.getSourceRoots(JpsPerlLibrarySourceRootType.INSTANCE)) { // System.err.println("Adding " + entry); Library tableLibrary = table.createLibrary(); Library.ModifiableModel modifiableModel = tableLibrary.getModifiableModel(); modifiableModel.addRoot(entry, OrderRootType.CLASSES); modifiableModel.commit(); } OrderEntry[] entries = rootModel.getOrderEntries(); ContainerUtil.sort(entries, new Comparator<OrderEntry>() { @Override public int compare(OrderEntry orderEntry, OrderEntry t1) { int i1 = orderEntry instanceof LibraryOrderEntry ? 1 : 0; int i2 = t1 instanceof LibraryOrderEntry ? 1 : 0; return i2 - i1; } }); rootModel.rearrangeOrderEntries(entries); if (!PlatformUtils.isIntelliJ()) { // add perl @inc to the end of libs Perl5Settings settings = Perl5Settings.getInstance(rootModel.getProject()); if (!settings.perlPath.isEmpty()) { for (String incPath : PerlSdkType.getInstance().getINCPaths(settings.perlPath)) { VirtualFile incFile = LocalFileSystem.getInstance().findFileByIoFile(new File(incPath)); if (incFile != null) { Library tableLibrary = table.createLibrary(); Library.ModifiableModel modifiableModel = tableLibrary.getModifiableModel(); modifiableModel.addRoot(incFile, OrderRootType.CLASSES); modifiableModel.addRoot(incFile, OrderRootType.SOURCES); modifiableModel.commit(); } } } } } public void initComponent() { // TODO: insert component initialization logic here } public void disposeComponent() { // TODO: insert component disposal logic here } @NotNull public String getComponentName() { return "PerlMicroIdeSettingsLoader"; } public void projectOpened() { // called when project is opened if (!PlatformUtils.isIntelliJ()) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { ModifiableRootModel rootModel = ModuleRootManager.getInstance(ModuleManager.getInstance(myProject).getModules()[0]).getModifiableModel(); ContentEntry entry = rootModel.getContentEntries()[0]; Set<String> libPaths = new HashSet<String>(perl5Settings.libRoots); for (SourceFolder folder : entry.getSourceFolders()) { // System.err.println("Before " + folder + " of " + folder.getRootType()); if (libPaths.contains(folder.getUrl())) entry.removeSourceFolder(folder); } for (String path : libPaths) entry.addSourceFolder(path, JpsPerlLibrarySourceRootType.INSTANCE); // for(SourceFolder folder: entry.getSourceFolders()) // System.err.println("After " + folder + " of " + folder.getRootType()); applyClassPaths(rootModel); rootModel.commit(); } }); } } public void projectClosed() { // called when project is being closed } }
30.174419
142
0.737187
6e6486d5838b91a89ffe2873de28595a26be82ca
9,750
package polimesa; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.swing.*; import java.awt.BorderLayout; import java.io.File; import net.bramp.ffmpeg.FFmpeg; import net.bramp.ffmpeg.FFmpegExecutor; import net.bramp.ffmpeg.FFprobe; import net.bramp.ffmpeg.builder.FFmpegBuilder; public class TestFFMpeg { //initialize some arguments that we will use and want every listener on some buttons to see public static String input_name="skoupidia"; public static String input_choice; public static String input_rate; public static void main(String[] args) { //about gui ( creating an instanse of jframe, sizing it and putting it in the middle of the screen ) JFrame f=new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(400,400); f.setVisible(true); f.setLocationRelativeTo(null); f.setTitle("Streaming Director"); //when we press the button to choose file( implemented later on the code ), it will open in a specific directory JFileChooser j = new JFileChooser("E:\\eclipse-workspace\\polimesa\\raw_videos\\"); //create the button to choose file JButton btn = new JButton("choose file"); btn.setSize(100,100); btn.setVisible(true); //add a listener to the button so when we click on it it will get the name of the file btn.addActionListener(e ->{ j.showSaveDialog(null); input_name = j.getSelectedFile().getName(); }); //dropdown options to choose the format JLabel ltype = new JLabel("select type"); String choices[]= { "avi", "mp4", "mkv" }; JComboBox cb = new JComboBox(choices); cb.setSize(100,100); cb.setVisible(true); //dropdown options to choose the Mbps JLabel lmbps = new JLabel("select type"); String choices2[]= { "0.2Mbps", "0.5Mbps", "1Mbps", "3Mbps" }; JComboBox cb2 = new JComboBox(choices2); cb.setSize(100,100); cb.setVisible(true); //button to click and convert the original file to the liking of the user depended by his options ( implemented later on the code ) JButton btn2 = new JButton("convert"); btn2.setSize(100,100); btn2.setVisible(true); //we put all this(buttons and dropdown lists) to the frame JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(100, 10, 10, 10)); f.add(panel); panel.add(btn); panel.add(cb); panel.add(cb2); panel.add(btn2); //listener for the "on click" of the CONVERT button ( btn2 ) //we get the parameters ( format, bitrate ) the user selected and we apply them to the ffmpegbuilder btn2.addActionListener(e -> { input_choice = String.valueOf(cb.getSelectedItem()); input_rate = String.valueOf((cb2).getSelectedItem()); //if no file is selected, an alert windows shows up if(input_name.equals("skoupidia")) { JOptionPane.showMessageDialog(null, "Error...\n Select a file."); } //setting up the directories for the input and output of ffmpeg etc. String inputDir = "E:\\eclipse-workspace\\polimesa\\raw_videos\\"; String outDir = "E:\\eclipse-workspace\\polimesa\\videos\\"; FFmpeg ffmpeg = null; FFprobe ffprobe = null; try { ffmpeg = new FFmpeg("E:\\ffmpeg\\bin\\ffmpeg.exe"); ffprobe = new FFprobe("E:\\ffmpeg\\bin\\ffprobe.exe"); } catch (IOException ex) { ex.printStackTrace(); } // as mentioned in the .doc file //for the avi format we change the resolution to match the bitrate //tested on the ffmpeg program in cmd first //quaranted the desired bitrate ( +- 10% deviation ) //if the user wants 200Kbps and .avi format. really simple using ffmpegbuilder //we also change the output name to match the user options if(input_rate.equals("0.2Mbps") && (input_choice.equals("avi")) ) { FFmpegBuilder builder = new FFmpegBuilder() .setInput(inputDir + input_name) .overrideOutputFiles(true) .addOutput(outDir + input_name.replaceAll("\\..+", "")+ input_rate+ "."+ input_choice) //.setVideoBitRate(200000) .setVideoResolution(400, 200) .done(); FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe); executor.createJob(builder).run(); } //as before we follow the same steps if(input_rate.equals("0.5Mbps") && (input_choice.equals("avi")) ) { FFmpegBuilder builder = new FFmpegBuilder() .setInput(inputDir + input_name) .overrideOutputFiles(true) .addOutput(outDir + input_name.replaceAll("\\..+", "")+ input_rate+ "."+ input_choice) .setVideoResolution(720, 500) .done(); FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe); executor.createJob(builder).run(); } if(input_rate.equals("1Mbps") && (input_choice.equals("avi")) ) { FFmpegBuilder builder = new FFmpegBuilder() .setInput(inputDir + input_name) .overrideOutputFiles(true) .addOutput(outDir + input_name.replaceAll("\\..+", "")+ input_rate+ "."+ input_choice) .setVideoResolution(1024, 768) .done(); FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe); executor.createJob(builder).run(); } if(input_rate.equals("3Mbps") && (input_choice.equals("avi")) ) { FFmpegBuilder builder = new FFmpegBuilder() .setInput(inputDir + input_name) .overrideOutputFiles(true) .addOutput(outDir + input_name.replaceAll("\\..+", "")+ input_rate+ "."+ input_choice) .setVideoResolution(1920, 1080) //.setVideoBitRate(bit_rate) .done(); FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe); executor.createJob(builder).run(); } // as mentioned in the .doc file //for the .mp4 and .mkv //we change the bitrate using the .setVideoBitRate not using the .setVideoResolution as we used before //same procedure. we take the users options and convert the files if(input_rate.equals("0.2Mbps") && ( (input_choice.equals("mp4") || (input_choice.equals("mkv")) ) ) ) { FFmpegBuilder builder = new FFmpegBuilder() .setInput(inputDir + input_name) .overrideOutputFiles(true) .addOutput(outDir + input_name.replaceAll("\\..+", "")+ input_rate+ "."+ input_choice) .setVideoBitRate(200000) .done(); FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe); executor.createJob(builder).run(); } if(input_rate.equals("0.5Mbps") && ( (input_choice.equals("mp4") || (input_choice.equals("mkv")) ) ) ) { FFmpegBuilder builder = new FFmpegBuilder() .setInput(inputDir + input_name) .overrideOutputFiles(true) .addOutput(outDir + input_name.replaceAll("\\..+", "")+ input_rate+ "."+ input_choice) .setVideoBitRate(500000) .done(); FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe); executor.createJob(builder).run(); } if(input_rate.equals("1Mbps") && ( (input_choice.equals("mp4") || (input_choice.equals("mkv")) ) ) ) { FFmpegBuilder builder = new FFmpegBuilder() .setInput(inputDir + input_name) .overrideOutputFiles(true) .addOutput(outDir + input_name.replaceAll("\\..+", "")+ input_rate+ "."+ input_choice) .setVideoBitRate(1000000) .done(); FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe); executor.createJob(builder).run(); } if(input_rate.equals("3Mbps") && ( (input_choice.equals("mp4") || (input_choice.equals("mkv")) ) ) ) { FFmpegBuilder builder = new FFmpegBuilder() .setInput(inputDir + input_name) .overrideOutputFiles(true) .addOutput(outDir + input_name.replaceAll("\\..+", "")+ input_rate+ "."+ input_choice) .setVideoBitRate(3000000) .done(); FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe); executor.createJob(builder).run(); } }); //last button to close the application after deleting the video we used from raw_videos JButton btn3 = new JButton("end"); btn3.setSize(100,100); btn3.setVisible(true); panel.add(btn3); btn3.addActionListener(exx ->{ Path path = Paths.get("E:\\eclipse-workspace\\polimesa\\raw_videos\\"+input_name); try { Files.delete(path); } catch (IOException e1) { e1.printStackTrace(); } System.exit(0); }); } }
37.356322
136
0.573538
53a32ea381dd39b42a477f95894cd25e2780b3a4
691
package mobi.tarantino.stub.auto.di; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import mobi.tarantino.stub.auto.SchedulerProvider; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; @Module public class SchedulersModule { @Provides @Singleton SchedulerProvider providesSchedulers() { return new SchedulerProvider() { @Override public Scheduler network() { return Schedulers.io(); } @Override public Scheduler ui() { return AndroidSchedulers.mainThread(); } }; } }
21.59375
54
0.639653
cb7ee27ebbd568b1935cb7f050fe43de667ddbc1
4,641
/* *AVISO LEGAL © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.contabilidad.util.report; import java.util.Set; import java.util.HashSet; import java.util.ArrayList; import java.util.List; import java.io.Serializable; import java.util.Date; import java.sql.Timestamp; import org.hibernate.validator.*; import com.bydan.framework.erp.business.entity.GeneralEntity; import com.bydan.framework.erp.business.entity.GeneralEntityParameterReturnGeneral; import com.bydan.framework.erp.business.entity.GeneralEntityReturnGeneral; import com.bydan.framework.erp.business.entity.Classe; import com.bydan.framework.erp.business.dataaccess.ConstantesSql; //import com.bydan.framework.erp.business.entity.Mensajes; import com.bydan.framework.erp.util.Constantes; import com.bydan.framework.erp.util.DeepLoadType; import com.bydan.erp.contabilidad.util.report.RetencionesPorPagarPorCuentasConstantesFunciones; import com.bydan.erp.contabilidad.business.entity.report.*;//RetencionesPorPagarPorCuentas import com.bydan.erp.seguridad.business.entity.*; import com.bydan.erp.contabilidad.business.entity.*; @SuppressWarnings("unused") public class RetencionesPorPagarPorCuentasParameterReturnGeneral extends GeneralEntityParameterReturnGeneral implements Serializable { private static final long serialVersionUID=1L; protected RetencionesPorPagarPorCuentas retencionesporpagarporcuentas; protected List<RetencionesPorPagarPorCuentas> retencionesporpagarporcuentass; public List<Empresa> empresasForeignKey; public List<Sucursal> sucursalsForeignKey; public List<Ejercicio> ejerciciosForeignKey; public List<Periodo> periodosForeignKey; public List<TipoRetencion> tiporetencionsForeignKey; public RetencionesPorPagarPorCuentasParameterReturnGeneral () throws Exception { super(); this.retencionesporpagarporcuentass= new ArrayList<RetencionesPorPagarPorCuentas>(); this.retencionesporpagarporcuentas= new RetencionesPorPagarPorCuentas(); this.empresasForeignKey=new ArrayList<Empresa>(); this.sucursalsForeignKey=new ArrayList<Sucursal>(); this.ejerciciosForeignKey=new ArrayList<Ejercicio>(); this.periodosForeignKey=new ArrayList<Periodo>(); this.tiporetencionsForeignKey=new ArrayList<TipoRetencion>(); } public RetencionesPorPagarPorCuentas getRetencionesPorPagarPorCuentas() throws Exception { return retencionesporpagarporcuentas; } public void setRetencionesPorPagarPorCuentas(RetencionesPorPagarPorCuentas newRetencionesPorPagarPorCuentas) { this.retencionesporpagarporcuentas = newRetencionesPorPagarPorCuentas; } public List<RetencionesPorPagarPorCuentas> getRetencionesPorPagarPorCuentass() throws Exception { return retencionesporpagarporcuentass; } public void setRetencionesPorPagarPorCuentass(List<RetencionesPorPagarPorCuentas> newRetencionesPorPagarPorCuentass) { this.retencionesporpagarporcuentass = newRetencionesPorPagarPorCuentass; } public List<Empresa> getempresasForeignKey() { return this.empresasForeignKey; } public List<Sucursal> getsucursalsForeignKey() { return this.sucursalsForeignKey; } public List<Ejercicio> getejerciciosForeignKey() { return this.ejerciciosForeignKey; } public List<Periodo> getperiodosForeignKey() { return this.periodosForeignKey; } public List<TipoRetencion> gettiporetencionsForeignKey() { return this.tiporetencionsForeignKey; } public void setempresasForeignKey(List<Empresa> empresasForeignKey) { this.empresasForeignKey=empresasForeignKey; } public void setsucursalsForeignKey(List<Sucursal> sucursalsForeignKey) { this.sucursalsForeignKey=sucursalsForeignKey; } public void setejerciciosForeignKey(List<Ejercicio> ejerciciosForeignKey) { this.ejerciciosForeignKey=ejerciciosForeignKey; } public void setperiodosForeignKey(List<Periodo> periodosForeignKey) { this.periodosForeignKey=periodosForeignKey; } public void settiporetencionsForeignKey(List<TipoRetencion> tiporetencionsForeignKey) { this.tiporetencionsForeignKey=tiporetencionsForeignKey; } }
35.7
135
0.805645
e8bc72aa2b772f4031f624bec1df71216b053dd6
306
package messenger.dispatch; import org.springframework.stereotype.*; import messenger.data.*; @Service public class MailGunMessageProvider implements MessageProvider { @Override public void send(Message message) { throw new MessageProviderException("mailgun", "Not Implemented"); } }
23.538462
73
0.754902
f28711115eb0523627d013aadc6f2a77302be85c
2,979
package com.jmtad.jftt.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.view.PagerAdapter; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import com.jmtad.jftt.R; /** * @description:个人中心卡片列表适配器 * @author: luweiming * @create: 2018-10-17 14:06 **/ public class CardAdapter extends PagerAdapter { Context context; private boolean hasCard = false; private ClickBindCallback bindCallback; public CardAdapter(Context context) { this.context = context; } private String cardBalance; private String cardNo; @Override public int getCount() { return 1; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { View view = LayoutInflater.from(context).inflate(R.layout.item_mine_card, null); RelativeLayout bindCard = view.findViewById(R.id.rl_card_no_bind); if (hasCard) { bindCard.setVisibility(View.GONE); TextView tvBalance = view.findViewById(R.id.tv_card_balance); TextView tvCardNo = view.findViewById(R.id.card_no); if (!TextUtils.isEmpty(cardNo)) { tvCardNo.setText(cardNo); } if (!TextUtils.isEmpty(cardBalance)) { tvBalance.setText(cardBalance); } } else { bindCard.setVisibility(View.VISIBLE); TextView tvBind = view.findViewById(R.id.tv_card_bind_now); tvBind.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (null != bindCallback) { bindCallback.goBind(); } } }); } container.addView(view); return view; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { } @Override public int getItemPosition(@NonNull Object object) { return POSITION_NONE; } public void setNoCard() { hasCard = false; notifyDataSetChanged(); } public void showCard(String cardNo) { this.cardNo = cardNo; hasCard = true; notifyDataSetChanged(); } public boolean isHasCard() { return hasCard; } public void setBalance(String balance) { this.cardBalance = balance; notifyDataSetChanged(); } public void setClickBindCallBack(ClickBindCallback callBack) { this.bindCallback = callBack; } public interface ClickBindCallback { void goBind(); } }
26.598214
97
0.627056
68006ca79974ef7833a3ea921597658ec0007c88
865
package com.wukj.utils; import android.util.Log; import com.wukj.lib.tools.EnvironmentVariable; import com.orhanobut.logger.Logger; /** * 项目名称: * 类名称:com.jonyker.common.utils * 类描述: * 创建人:Jonyker * 创建时间:2017/2/30 0030 上午 10:34 * 修改人:Jonyker * 联系方式:QQ/534098845 * 修改时间:2017/2/30 0030 上午 10:34 * 修改备注: * 版本:V.1.0 */ public class LogUtils { private static final String DEFAULT_TAG = "LogUtils"; public static boolean isDebug = true; public static void d(Class clazz,String printMsg){ if (isDebug){ StackTraceElement[] stacks = new Throwable().getStackTrace(); String sampleName = clazz.getSimpleName(); Log.e(DEFAULT_TAG,"["+sampleName+"]---: "+printMsg); } } public static void json(String printMsg){ if (isDebug){ Logger.json(printMsg); } } }
21.097561
73
0.628902
221e828005a63ace238e0d1ff22343969bb90776
224
package com.fr.swift.cloud.jdbc.adaptor; import com.fr.swift.cloud.jdbc.adaptor.bean.InsertionBean; /** * Created by lyon on 2018/12/10. */ public interface InsertionBeanParser { InsertionBean getInsertionBean(); }
18.666667
58
0.75
d062bfd6a231ad614e01b542364119988780123a
245
package net.minidev.ovh.api.coretypes; /** * Ip versions */ public enum OvhIpVersionEnum { v4("v4"), v6("v6"); final String value; OvhIpVersionEnum(String s) { this.value = s; } public String toString() { return this.value; } }
12.25
38
0.653061
6469f6abd6fa6d963cf999e4a84d1b1f1e1aaa27
1,905
/** * Copyright 2005-2016 hdiv.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.hdiv.context; import java.util.Map; public interface RequestContextDataValueProcessor { /** * Invoked when a new form action is rendered. * @param request the current request * @param action the form action * @param httpMethod the form HTTP method * @return the action to use, possibly modified */ String processAction(RequestContextHolder request, String action, String httpMethod); /** * Invoked when a form field value is rendered. * @param request the current request * @param name the form field name * @param value the form field value * @param type the form field type ("text", "hidden", etc.) * @return the form field value to use, possibly modified */ String processFormFieldValue(RequestContextHolder request, String name, String value, String type); /** * Invoked after all form fields have been rendered. * @param request the current request * @return additional hidden form fields to be added, or {@code null} */ Map<String, String> getExtraHiddenFields(RequestContextHolder request); /** * Invoked when a URL is about to be rendered or redirected to. * @param request the current request * @param url the URL value * @return the URL to use, possibly modified */ String processUrl(RequestContextHolder request, String url); }
33.421053
100
0.736483
65272d1c2ec73ccc32ead60d881bcdd4652f9314
214
package org.bumble.test.model; /** * @author : shenxiangyu * @date : */ public class SimpleCat { public void say() { System.out.println("I am a simple cat, can only say this one sentence"); } }
17.833333
80
0.621495
fb10377a90ec55273f83ca6e7b3ed8e819d6458a
1,154
package pt.up.fe.els2021.functions; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import pt.up.fe.els2021.Table; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "function") @JsonSubTypes({ @JsonSubTypes.Type(value = ExcludeFunction.class, name = "exclude"), @JsonSubTypes.Type(value = OrderByFunction.class, name = "sort"), @JsonSubTypes.Type(value = RenameFunction.class, name = "rename"), @JsonSubTypes.Type(value = SelectFunction.class, name = "select"), @JsonSubTypes.Type(value = TrimFunction.class, name = "trim"), @JsonSubTypes.Type(value = MoveColumnFunction.class, name = "move") }) public sealed interface TableFunction permits AddColumnFunction, AggregatesFunction, ExcludeFunction, GroupByFunction, MoveColumnFunction, OrderByFunction, RenameFunction, SelectFunction, TrimFunction { Table apply(Table table) throws Exception; sealed abstract class Builder permits ExcludeFunction.Builder, OrderByFunction.Builder, SelectFunction.Builder, TrimFunction.Builder { public abstract TableFunction build(); } }
50.173913
202
0.753899
1a19ca381eeefac7aad7b4b4e631dcfc62001899
396
package me.gabu.gabazar.livros.core.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.UNAUTHORIZED) public class AccessException extends RuntimeException{ public AccessException(String mensagem) { super(mensagem); } private static final long serialVersionUID = 1L; }
24.75
62
0.785354
b787bb84f153477db8ced8344b94cf523edeb3ba
2,384
package com.rozsa.crow.screen; import com.rozsa.crow.screen.attributes.Color; import com.rozsa.crow.screen.attributes.Size; import javax.swing.*; import java.util.HashMap; import java.util.Map; public abstract class BaseScreen<TKey, TKeyGroup> extends JPanel { private Map<TKey, BaseView> views; private Map<TKeyGroup, TKey[]> viewGroup; private TKeyGroup lastViewGroupSet; public BaseScreen(Size size) { this(size, Color.blue()); } public BaseScreen(Size size, Color bgColor) { views = new HashMap<>(); viewGroup = new HashMap<>(); setup(size, bgColor); } private void setup(Size size, Color color) { setSize(size.getWidth(), size.getHeight()); setBackground(color.getJColor()); setLayout(null); updateScreenSize(size); setIgnoreRepaint(true); } protected void addView(TKey key, BaseView view) { views.put(key, view); add(view); } protected void removeView(TKey key) { views.remove(key); } protected BaseView getView(TKey key) { if (!views.containsKey(key)) { return null; } return views.get(key); } protected void addViewGroup(TKeyGroup key, TKey...viewKeys) { viewGroup.put(key, viewKeys); } protected void removeViewGroup(Integer key) { viewGroup.remove(key); } protected void displayViewGroup(TKeyGroup key) { if (!viewGroup.containsKey(key)) { return; } if (lastViewGroupSet == key) { return; } views.values().forEach(this::remove); for (TKey viewKey : viewGroup.get(key)) { BaseView targetView = getView(viewKey); if (targetView != null) { add(targetView); } } lastViewGroupSet = key; draw(); } public void updateScreenSize(Size parentSize) { setSize(parentSize.getWidth(), parentSize.getHeight()); views.values().forEach(v -> v.updateScreenSize(parentSize)); } protected TKeyGroup getLastViewGroupSet() { return lastViewGroupSet; } protected void draw() { repaint(); views.values().forEach(BaseView::draw); } }
24.326531
69
0.574664
c97bcdebb016e2f95ac223d202a547e4c8ef8e87
1,360
package net.nemerosa.ontrack.jenkins.dsl.v4; import net.nemerosa.ontrack.dsl.v4.ChangeLog; import net.nemerosa.ontrack.jenkins.dsl.facade.*; import java.util.List; import java.util.stream.Collectors; public class ChangeLogV4Facade implements ChangeLogFacade { private final ChangeLog changeLog; public ChangeLogV4Facade(ChangeLog changeLog) { this.changeLog = changeLog; } @Override public BuildFacade getFrom() { return new BuildV4Facade(changeLog.getFrom()); } @Override public BuildFacade getTo() { return new BuildV4Facade(changeLog.getTo()); } @Override public List<ChangeLogCommitFacade> getCommits() { return changeLog.getCommits().stream() .map(ChangeLogCommitV4Facade::new) .collect(Collectors.toList()); } @Override public List<ChangeLogIssueFacade> getIssues() { return changeLog.getIssues().stream() .map(ChangeLogIssueV4Facade::new) .collect(Collectors.toList()); } @Override public List<ChangeLogFileFacade> getFiles() { return changeLog.getFiles().stream() .map(ChangeLogFileV4Facade::new) .collect(Collectors.toList()); } @Override public String getPageLink() { return changeLog.link("page"); } }
25.660377
59
0.649265
baa6a4b5789de3f91bebb6441c78afbaaff90f72
1,335
package org.jetbrains.research.kotlinrminer.cli.decomposition.replacement; import org.jetbrains.research.kotlinrminer.common.replacement.Replacement; import org.jetbrains.research.kotlinrminer.cli.decomposition.ObjectCreation; import org.jetbrains.research.kotlinrminer.cli.decomposition.OperationInvocation; public class MethodInvocationWithClassInstanceCreationReplacement extends Replacement { private final OperationInvocation invokedOperationBefore; private final ObjectCreation objectCreationAfter; public MethodInvocationWithClassInstanceCreationReplacement(String before, String after, ReplacementType type, OperationInvocation invokedOperationBefore, ObjectCreation objectCreationAfter) { super(before, after, type); this.invokedOperationBefore = invokedOperationBefore; this.objectCreationAfter = objectCreationAfter; } public OperationInvocation getInvokedOperationBefore() { return invokedOperationBefore; } public ObjectCreation getObjectCreationAfter() { return objectCreationAfter; } }
44.5
107
0.659925
2116c43687db173cf414b1ec5e83cb30fd746809
2,433
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org> */ package com.github.liachmodded.mcptiny; import org.gradle.api.Project; import org.gradle.api.artifacts.Dependency; public class McpTinyExtension { private final Project project; private final McpTiny plugin; public McpTinyExtension(Project project, McpTiny plugin) { this.project = project; this.plugin = plugin; } /** * Creates a dependency on a specified MCP mapping. * * @param mcVersion the target Minecraft version * @param mcpVersion the target MCP snapshot version * @return the created dependency */ public Dependency mcp(String mcVersion, String mcpVersion) { return plugin.makeMapping(project, mcVersion, mcpVersion); } // http://export.mcpbot.bspk.rs/mcp_snapshot_nodoc/20191108-1.14.3/mcp_snapshot_nodoc-20191108-1.14.3.zip // http://export.mcpbot.bspk.rs/mcp_snapshot/20191108-1.14.3/mcp_snapshot-20191108-1.14.3.zip // // http://files.minecraftforge.net/maven/de/oceanlabs/mcp/mcp_snapshot/20191108-1.14.3/mcp_snapshot-20191108-1.14.3.zip // https://files.minecraftforge.net/maven/de/oceanlabs/mcp/mcp_config/1.14.4-20190829.143755/mcp_config-1.14.4-20190829.143755.zip }
41.237288
133
0.753802
44553e240f740a97f81e9867c894c3683c984c0d
881
package io.digdag.core.database.migrate; import org.skife.jdbi.v2.Handle; public class Migration_20161110112233_AddStartedAtColumnAndIndexToTasks implements Migration { @Override public void migrate(Handle handle, MigrationContext context) { if (context.isPostgres()) { handle.update("alter table tasks" + " add column started_at timestamp with time zone"); } else { handle.update("alter table tasks" + " add column started_at timestamp"); } if (context.isPostgres()) { handle.update("create index tasks_on_state_and_started_at on tasks (state, started_at, id asc) where started_at is not null"); } else { handle.update("create index tasks_on_state_and_started_at on tasks (state, started_at, id asc)"); } } }
32.62963
138
0.633371
26837f7bf01c9c92b5a28231bce562235e3e5f9b
8,183
package ca.thurn.jgail.connect4; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import ca.thurn.jgail.core.Copyable; import ca.thurn.jgail.core.Player; import ca.thurn.jgail.core.State; /** * State class for a game of Connect4. */ public class C4State implements State { private static final int BOARD_HEIGHT = 6; private static final int BOARD_WIDTH = 7; private static final List<Long> p1Actions; private static final List<Long> p2Actions; static { p1Actions = new ArrayList<Long>(); for (int i = 0; i < BOARD_WIDTH; ++i) { p1Actions.add(C4Action.create(Player.PLAYER_ONE, i)); } p2Actions = new ArrayList<Long>(); for (int i = 0; i < BOARD_WIDTH; ++i) { p2Actions.add(C4Action.create(Player.PLAYER_TWO, i)); } } /** * Direction on the game board. */ private static enum Direction { N, NE, E, SE, S, SW, W, NW } // Indexed as board[column][row] with the origin being in the bottom left, // null represents an empty space. private int[][] board; private List<Long> actions; private int currentPlayer; private int winner; private Random random = new Random(); /** * Null-initializes this state. The state will not be usable until one of * initialize() or setToStartingConditions() is called on the result; */ public C4State() { } private C4State(int[][] board, List<Long> actions, int currentPlayer, int winner) { this.board = board; this.actions = actions; this.currentPlayer = currentPlayer; this.winner = winner; } /** * {@inheritDoc} */ @Override public State.ActionIterator getActionIterator() { return new State.ActionIteratorFromIterable(actions); } /** * {@inheritDoc} */ @Override public long getRandomAction() { return actions.get(random.nextInt(actions.size())); } /** * {@inheritDoc} */ @Override public long perform(long action) { int freeSpace = 0; while (board[C4Action.getColumnNumber(action)][freeSpace] != 0) { freeSpace++; } board[C4Action.getColumnNumber(action)][freeSpace] = currentPlayer; winner = computeWinner(currentPlayer, C4Action.getColumnNumber(action), freeSpace); currentPlayer = playerAfter(currentPlayer); actions = actionsForCurrentPlayer(); return 0; } /** * {@inheritDoc} */ @Override public void undo(long action, long undoToken) { int freeCell = BOARD_HEIGHT - 1; while (board[C4Action.getColumnNumber(action)][freeCell] == 0) { freeCell--; } board[C4Action.getColumnNumber(action)][freeCell] = 0; winner = 0; currentPlayer = playerBefore(currentPlayer); actions = actionsForCurrentPlayer(); } /** * {@inheritDoc} */ @Override public C4State setToStartingConditions() { board = new int[BOARD_WIDTH][BOARD_HEIGHT]; winner = 0; currentPlayer = Player.PLAYER_ONE; actions = actionsForCurrentPlayer(); return this; } /** * {@inheritDoc} */ @Override public State copy() { if (actions == null && board == null) { return new C4State(); } return new C4State(copyBoard(), new ArrayList<Long>(actions), currentPlayer, winner); } /** * {@inheritDoc} */ @Override public C4State initializeFrom(Copyable state) { C4State temp = (C4State)state.copy(); this.board = temp.board; this.winner = temp.winner; this.currentPlayer = temp.currentPlayer; this.actions = temp.actions; return this; } /** * {@inheritDoc} */ @Override public boolean isTerminal() { if (actions.size() == 0) return true; // Draw return winner != 0; } /** * {@inheritDoc} */ @Override public int getWinner() { return winner; } /** * {@inheritDoc} */ @Override public int getCurrentPlayer() { return currentPlayer; } /** * {@inheritDoc} */ @Override public int playerAfter(int player) { return player == Player.PLAYER_ONE ? Player.PLAYER_TWO : Player.PLAYER_ONE; } /** * {@inheritDoc} */ @Override public int playerBefore(int player) { return playerAfter(player); } /** * {@inheritDoc} */ @Override public String actionToString(long action) { return "[" + C4Action.getColumnNumber(action) + "]"; } @Override public String toString() { StringBuilder result = new StringBuilder(); for (int row = 5; row >= 0; --row) { for (int column = 0; column < 7; ++column) { int p = board[column][row]; if (p == 0) { result.append("-"); } else { result.append(p == Player.PLAYER_TWO ? "X" : "O"); } } result.append("\n"); } return result.toString(); } /** * @return A list of actions the current player could legally take from * the current state. */ private List<Long> actionsForCurrentPlayer() { List<Long> actions = currentPlayer == Player.PLAYER_TWO ? p2Actions : p1Actions; List<Long> result = new ArrayList<Long>(); for (int i = 0; i < actions.size(); ++i) { long action = actions.get(i); if (board[C4Action.getColumnNumber(action)][BOARD_HEIGHT - 1] == 0) { result.add(action); } } return result; } /** * Checks whether the provided player has won by making the provided move. * * @param player Player to check. * @param moveColumn Column number of player's move. * @param moveRow Row number of player's move. * @return The provided player if this move was a winning move for that * player, otherwise null. */ private int computeWinner(int player, int moveColumn, int moveRow) { // Vertical win? if (countGroupSize(moveColumn, moveRow - 1, Direction.S, player) >= 3) { return player; } // Horizontal win? if (countGroupSize(moveColumn + 1, moveRow, Direction.E, player) + countGroupSize(moveColumn - 1, moveRow, Direction.W, player) >= 3) { return player; } // Diagonal win? if (countGroupSize(moveColumn + 1, moveRow + 1, Direction.NE, player) + countGroupSize(moveColumn - 1, moveRow - 1, Direction.SW, player) >= 3) { return player; } if (countGroupSize(moveColumn - 1, moveRow + 1, Direction.NW, player) + countGroupSize(moveColumn + 1, moveRow - 1, Direction.SE, player) >=3) { return player; } // No win return 0; } /** * Counts consecutive pieces from the same player. * * @param col Column number to start counting from. * @param row Row number to start counting from. * @param dir Direction in which to count. * @param player Player whose pieces we are counting. * @return The number of pieces belonging to this player, not counting the * provided column and row, which can be found in a line in the provided * direction. */ private int countGroupSize(int col, int row, Direction dir, int player) { if (row < 6 && row >= 0 && col < 7 && col >= 0 && board[col][row] == player) { switch (dir) { case N: return 1 + countGroupSize(col, row + 1, dir, player); case S: return 1 + countGroupSize(col, row - 1, dir, player); case E: return 1 + countGroupSize(col + 1, row, dir, player); case W: return 1 + countGroupSize(col - 1, row, dir, player); case NE: return 1 + countGroupSize(col + 1, row + 1, dir, player); case NW: return 1 + countGroupSize(col - 1, row + 1, dir, player); case SE: return 1 + countGroupSize(col + 1, row - 1, dir, player); case SW: return 1 + countGroupSize(col - 1, row - 1, dir, player); default: return 0; } } else { return 0; } } /** * @return A copy of the game's current board. */ private int[][] copyBoard() { int[][] result = new int[BOARD_WIDTH][BOARD_HEIGHT]; for (int i = 0; i < BOARD_WIDTH; ++i) { result[i] = Arrays.copyOf(board[i], BOARD_HEIGHT); } return result; } }
26.06051
89
0.610901
821acac4abb5bfd7e5704ad8dbe50e41d524f420
15,310
package ai.clipper.rpc; import java.io.IOException; import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.LongBuffer; import java.util.*; import ai.clipper.container.data.*; import ai.clipper.container.ClipperModel; import ai.clipper.rpc.logging.*; import org.zeromq.ZMQ; public class RPC<I extends DataVector<?>> { private static String CONNECTION_ADDRESS = "tcp://%s:%s"; private static final long RPC_VERSION = 3; private static final long SOCKET_POLLING_TIMEOUT_MILLIS = 5000; private static final long SOCKET_ACTIVITY_TIMEOUT_MILLIS = 30000; private static final int EVENT_HISTORY_BUFFER_SIZE = 30; private final DataVectorParser<?, I> inputVectorParser; private final RPCEventHistory eventHistory; private Thread servingThread; private ByteBuffer outputHeaderBuffer; private ByteBuffer outputContentBuffer; private int outputHeaderBufferSize; private int outputContentBufferSize; public RPC(DataVectorParser<?, I> inputVectorParser) { this.inputVectorParser = inputVectorParser; this.eventHistory = new RPCEventHistory(EVENT_HISTORY_BUFFER_SIZE); } /** * This method blocks until the RPC connection is ended */ public void start(final ClipperModel<I> model, final String modelName, int modelVersion, final String host, final int port) throws UnknownHostException { InetAddress address = InetAddress.getByName(host); try { File file = new File("/model_is_ready.check"); file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } String ip = address.getHostAddress(); final ZMQ.Context context = ZMQ.context(1); servingThread = new Thread(() -> { // Initialize ZMQ try { serveModel(model, modelName, modelVersion, context, ip, port); } catch (NoSuchFieldException | IllegalArgumentException e) { e.printStackTrace(); } }); servingThread.start(); try { servingThread.join(); } catch (InterruptedException e) { System.out.println("RPC thread interrupted: " + e.getMessage()); } } public void stop() { if (servingThread != null) { servingThread.interrupt(); servingThread = null; } } public RPCEvent[] getEventHistory() { return eventHistory.getEvents(); } private void validateRpcVersion(long receivedVersion) throws Exception { if (receivedVersion != RPC_VERSION) { System.out.println(String.format( "ERROR: Received a message with RPC version: %d that does not match container version: %d", receivedVersion, RPC_VERSION)); } } private void serveModel(ClipperModel<I> model, String modelName, int modelVersion, final ZMQ.Context context, String ip, int port) throws NoSuchFieldException, IllegalArgumentException { int inputHeaderBufferSize = 0; int inputContentBufferSize = 0; ByteBuffer inputHeaderBuffer = null; ByteBuffer inputContentBuffer = null; boolean connected = false; long lastActivityTimeMillis = 0; String clipperAddress = String.format(CONNECTION_ADDRESS, ip, port); ZMQ.Poller poller = new ZMQ.Poller(1); while (true) { ZMQ.Socket socket = context.socket(ZMQ.DEALER); poller.register(socket, ZMQ.Poller.POLLIN); socket.connect(clipperAddress); sendHeartbeat(socket); while (true) { poller.poll(SOCKET_POLLING_TIMEOUT_MILLIS); if (!poller.pollin(0)) { // Failed to receive a message prior to the polling timeout if (connected) { if (System.currentTimeMillis() - lastActivityTimeMillis >= SOCKET_ACTIVITY_TIMEOUT_MILLIS) { // Terminate the session System.out.println("Connection timed out. Reconnecting..."); connected = false; poller.unregister(socket); socket.close(); break; } else { sendHeartbeat(socket); } } continue; } // Received a message prior to the polling timeout if (!connected) { connected = true; } lastActivityTimeMillis = System.currentTimeMillis(); PerformanceTimer.startTiming(); // Receive delimiter between routing identity and content socket.recv(); byte[] rpcVersionMessage = socket.recv(); byte[] typeMessage = socket.recv(); List<Long> parsedVersionMessage = DataUtils.getUnsignedIntsFromBytes(rpcVersionMessage); long rpcVersion = parsedVersionMessage.get(0); try { validateRpcVersion(rpcVersion); } catch (Exception e) { e.printStackTrace(); System.exit(1); } List<Long> parsedTypeMessage = DataUtils.getUnsignedIntsFromBytes(typeMessage); ContainerMessageType messageType = ContainerMessageType.fromCode(parsedTypeMessage.get(0).intValue()); switch (messageType) { case Heartbeat: System.out.println("Received heartbeat!"); eventHistory.insert(RPCEventType.ReceivedHeartbeat); byte[] heartbeatTypeMessage = socket.recv(); List<Long> parsedHeartbeatTypeMessage = DataUtils.getUnsignedIntsFromBytes(heartbeatTypeMessage); HeartbeatType heartbeatType = HeartbeatType.fromCode(parsedHeartbeatTypeMessage.get(0).intValue()); if (heartbeatType == HeartbeatType.RequestContainerMetadata) { sendContainerMetadata(socket, model, modelName, modelVersion); } break; case ContainerContent: eventHistory.insert(RPCEventType.ReceivedContainerContent); byte[] idMessage = socket.recv(); List<Long> parsedIdMessage = DataUtils.getUnsignedIntsFromBytes(idMessage); if (parsedIdMessage.size() < 1) { throw new NoSuchFieldException("Field \"message_id\" is missing from RPC message"); } long msgId = parsedIdMessage.get(0); System.out.println("Message ID: " + msgId); byte[] requestHeaderMessage = socket.recv(); List<Integer> requestHeader = DataUtils.getSignedIntsFromBytes(requestHeaderMessage); if (requestHeader.size() < 1) { throw new NoSuchFieldException("Request header is missing from RPC message"); } RequestType requestType = RequestType.fromCode(requestHeader.get(0)); if (requestType == RequestType.Predict) { byte[] inputHeaderSizeMessage = socket.recv(); List<Long> parsedInputHeaderSizeMessage = DataUtils.getLongsFromBytes(inputHeaderSizeMessage); if (parsedInputHeaderSizeMessage.size() < 1) { throw new NoSuchFieldException( "Input header size is missing from RPC predict request message"); } int inputHeaderSize = (int) ((long) parsedInputHeaderSizeMessage.get(0)); if (inputHeaderBuffer == null || inputHeaderBufferSize < inputHeaderSize) { inputHeaderBufferSize = inputHeaderSize * 2; inputHeaderBuffer = ByteBuffer.allocateDirect(inputHeaderBufferSize); inputHeaderBuffer.order(ByteOrder.LITTLE_ENDIAN); } inputHeaderBuffer.rewind(); inputHeaderBuffer.limit(inputHeaderBufferSize); int inputHeaderBytesRead = socket.recvZeroCopy(inputHeaderBuffer, inputHeaderSize, -1); inputHeaderBuffer.rewind(); inputHeaderBuffer.limit(inputHeaderBytesRead); LongBuffer inputHeader = inputHeaderBuffer.slice().order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); DataType inputType = DataType.fromCode((int) inputHeader.get(0)); long numInputs = inputHeader.get(1); int inputContentSizeBytes = 0; for (int i = 0; i < numInputs; ++i) { inputContentSizeBytes += inputHeader.get(i + 2); } if (inputContentBufferSize < inputContentSizeBytes) { inputContentBufferSize = inputContentSizeBytes * 2; inputContentBuffer = ByteBuffer.allocateDirect(inputContentBufferSize); inputContentBuffer.order(ByteOrder.LITTLE_ENDIAN); } inputContentBuffer.rewind(); ArrayList<I> inputs = new ArrayList<>(); int bufferPosition = 0; for (int i = 0; i < numInputs; ++i) { inputContentBuffer.position(bufferPosition); int inputSizeBytes = (int) inputHeader.get(i + 2); ByteBuffer inputBuffer = sliceOrdered(inputContentBuffer); socket.recvZeroCopy(inputBuffer, inputSizeBytes, -1); inputBuffer.position(0); inputBuffer.limit(inputSizeBytes); I input = inputVectorParser.constructDataVector(inputBuffer, inputSizeBytes); inputs.add(input); bufferPosition += inputSizeBytes; } PerformanceTimer.logElapsed("Recv and Parse"); try { handlePredictRequest(msgId, inputs, model, socket); } catch (IOException e) { e.printStackTrace(); } PerformanceTimer.logElapsed("Handle"); System.out.println(PerformanceTimer.getLog()); } else { // Handle Feedback request } break; case NewContainer: // We should never receive a new container message from Clipper eventHistory.insert(RPCEventType.ReceivedContainerMetadata); System.out.println("Received erroneous new container message from Clipper!"); break; default: break; } } } } private ByteBuffer sliceOrdered(ByteBuffer buffer) { return buffer.slice().order(ByteOrder.LITTLE_ENDIAN); } private void validateRequestInputType(ClipperModel<I> model, DataType inputType) throws IllegalArgumentException { if (model.getInputType() != inputType) { throw new IllegalArgumentException( String.format("RPC message has input of incorrect type \"%s\". Expected type: \"%s\"", inputType.toString(), model.getInputType().toString())); } } private void handlePredictRequest(long msgId, ArrayList<I> inputs, ClipperModel<I> model, ZMQ.Socket socket) throws IOException { List<SerializableString> predictions = model.predict(inputs); if (predictions.size() != inputs.size()) { String message = String.format("Attempting to send %d outputs for a request containg %d inputs!", predictions.size(), inputs.size()); throw new IllegalStateException(message); } long numOutputs = predictions.size(); int outputHeaderSizeBytes = (int) (numOutputs + 1) * Long.BYTES; int outputContentMaxSizeBytes = 0; for (SerializableString p : predictions) { // Add the maximum size of the string // with utf-8 encoding to the maximum buffer size. // The actual output length will be determined // when the string predictions are serialized outputContentMaxSizeBytes += p.maxSizeBytes(); } if (outputHeaderBuffer == null || outputHeaderBufferSize < outputHeaderSizeBytes) { outputHeaderBufferSize = outputHeaderSizeBytes * 2; outputHeaderBuffer = ByteBuffer.allocateDirect(outputHeaderBufferSize); outputHeaderBuffer.order(ByteOrder.LITTLE_ENDIAN); } outputHeaderBuffer.rewind(); outputHeaderBuffer.limit(outputHeaderSizeBytes); if (outputContentBuffer == null || outputContentBufferSize < outputContentMaxSizeBytes) { outputContentBufferSize = outputContentMaxSizeBytes * 2; outputContentBuffer = ByteBuffer.allocateDirect(outputContentBufferSize); outputContentBuffer.order(ByteOrder.LITTLE_ENDIAN); } outputContentBuffer.rewind(); LongBuffer longHeader = outputHeaderBuffer.asLongBuffer(); longHeader.put(numOutputs); // Create a list of buffers for individual outputs. // These buffers will all be backed by `outputContentBuffer` ByteBuffer[] outputBuffers = new ByteBuffer[(int) numOutputs]; int[] outputLengths = new int[(int) numOutputs]; int outputContentBufferPosition = 0; for (int i = 0; i < predictions.size(); i++) { outputContentBuffer.position(outputContentBufferPosition); SerializableString prediction = predictions.get(i); long outputLength = prediction.encodeUTF8ToBuffer(outputContentBuffer); outputContentBuffer.position(outputContentBufferPosition); ByteBuffer outputBuffer = outputContentBuffer.slice(); outputBuffer.order(ByteOrder.LITTLE_ENDIAN); outputBuffer.limit((int) outputLength); outputBuffers[i] = outputBuffer; outputLengths[i] = (int) outputLength; longHeader.put(outputLength); outputContentBufferPosition += outputLength; } longHeader.rewind(); socket.send("", ZMQ.SNDMORE); socket.send( DataUtils.getBytesFromInts(ContainerMessageType.ContainerContent.getCode()), ZMQ.SNDMORE); ByteBuffer msgIdBuf = ByteBuffer.allocate(Integer.BYTES); msgIdBuf.order(ByteOrder.LITTLE_ENDIAN); msgIdBuf.putInt((int) msgId); byte[] msgIdByteArr = msgIdBuf.array(); ByteBuffer headerSizeBuf = ByteBuffer.allocate(Long.BYTES); headerSizeBuf.order(ByteOrder.LITTLE_ENDIAN); headerSizeBuf.putLong(outputHeaderSizeBytes); byte[] headerSizeByteArr = headerSizeBuf.array(); socket.send(msgIdByteArr, ZMQ.SNDMORE); socket.send(headerSizeByteArr, ZMQ.SNDMORE); socket.sendZeroCopy(outputHeaderBuffer, outputHeaderSizeBytes, ZMQ.SNDMORE); int lastOutputMsgNum = predictions.size() - 1; for (int i = 0; i < predictions.size(); i++) { if (i < lastOutputMsgNum) { socket.sendZeroCopy(outputBuffers[i], outputLengths[i], ZMQ.SNDMORE); } else { socket.sendZeroCopy(outputBuffers[i], outputLengths[i], 0); } } eventHistory.insert(RPCEventType.SentContainerContent); } private void sendHeartbeat(ZMQ.Socket socket) { socket.send("", ZMQ.SNDMORE); socket.send(DataUtils.getBytesFromInts(ContainerMessageType.Heartbeat.getCode()), 0); eventHistory.insert(RPCEventType.SentHeartbeat); System.out.println("Sent heartbeat!"); } private void sendContainerMetadata( ZMQ.Socket socket, ClipperModel<I> model, String modelName, int modelVersion) { socket.send("", ZMQ.SNDMORE); socket.send( DataUtils.getBytesFromInts(ContainerMessageType.NewContainer.getCode()), ZMQ.SNDMORE); socket.send(modelName, ZMQ.SNDMORE); socket.send(String.valueOf(modelVersion), ZMQ.SNDMORE); socket.send(String.valueOf(model.getInputType().getCode()), ZMQ.SNDMORE); socket.send(DataUtils.getBytesFromLongs(RPC_VERSION), 0); eventHistory.insert(RPCEventType.SentContainerMetadata); System.out.println("Sent container metadata!"); } }
40.826667
101
0.662443
26f4703292d27394580676d20bbf63352da45c63
2,663
/* * Copyright 2012 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * 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.kuali.ole.coa.document.validation.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.kuali.ole.coa.businessobject.OleStewardship; import org.kuali.ole.sys.OLEKeyConstants; import org.kuali.rice.kns.document.MaintenanceDocument; import org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase; public class OleStewardShipRule extends MaintenanceDocumentRuleBase{ @Override protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) { boolean isValid = true; isValid &= validateStewardShipTypeName(document); return isValid; } /** * This method validates duplicate stewardShipTypeName and return boolean value. * @param oleStewardship * @return boolean */ private boolean validateStewardShipTypeName(MaintenanceDocument document) { OleStewardship oleStewardship = (OleStewardship) document.getNewMaintainableObject().getBusinessObject(); if (!document.isEdit() && oleStewardship.getStewardshipTypeName() != null) { Map<String, String> criteria = new HashMap<String, String>(); criteria.put(OLEKeyConstants.STWRDSHIP_TYPE_NAME, oleStewardship.getStewardshipTypeName()); List<OleStewardship> oleStewardshipList = (List<OleStewardship>) getBoService().findMatching(OleStewardship.class, criteria); if ((oleStewardshipList.size() > 0)) { for(OleStewardship oleStewardshipObj:oleStewardshipList){ String stewardShipTypeName=oleStewardshipObj.getStewardshipTypeName(); if(null==oleStewardship.getStewardshipTypeName()|| oleStewardship.getStewardshipTypeName().equalsIgnoreCase(stewardShipTypeName)) { putFieldError(OLEKeyConstants.STWRDSHIP_TYPE_NAME, OLEKeyConstants.ERROR_DUP_FOUND_STWRD_TYP_NAME); return false; } } } } return true; } }
42.269841
151
0.711603
05086423e06255445f4b57190f7ef7f5982e7e20
338
package com.lizy.myglide.load; /** * Created by lizy on 16-5-4. */ public enum MemoryCategory { LOW(0.5f), NORMAL(1.0f), HIGHT(1.5f); private float multiplier; MemoryCategory(float multiplier) { this.multiplier = multiplier; } public float getMultiplier() { return multiplier; } }
14.083333
38
0.609467
15e1e96c4f72b0a64fe69a168a46ec50e4d7eb4e
6,317
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Project.Product.Cart; import Project.DAO.ProductDAO; import Project.Sample.Product; import Project.Sample.User; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author TrungHuy */ @WebServlet(name = "AddToCart", urlPatterns = {"/Cart"}) public class AddToCart extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ private HashMap<Product, Integer> products; void addToCart(Product p, int num) { boolean exist = false; for (Map.Entry<Product, Integer> entry : this.products.entrySet()) { Product key = entry.getKey(); Integer value = entry.getValue(); if (key.getProID().equals(p.getProID())) { value += num; this.products.put(key, value); exist = true; if (value == 0) { removeFromCart(p); } break; } } if (!exist) { this.products.put(p, num); } } void removeFromCart(Product p) { for (Map.Entry<Product, Integer> entry : this.products.entrySet()) { Product key = entry.getKey(); Integer value = entry.getValue(); if (key.getProID().equals(p.getProID())) { this.products.remove(key); break; } } } float getTotal() { float total = 0; for (Map.Entry<Product, Integer> entry : this.products.entrySet()) { Product key = entry.getKey(); Integer value = entry.getValue(); total += key.getProPrice() * value; } return total; } int getNumberOfPro() { int total = 0; for (Map.Entry<Product, Integer> entry : this.products.entrySet()) { Integer value = entry.getValue(); total += value; } return total; } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ HttpSession session = request.getSession(); ProductDAO dao = new ProductDAO(); this.products = (HashMap<Product, Integer>) session.getAttribute("cart"); if (this.products == null) { this.products = new HashMap<Product, Integer>(); } String code = request.getParameter("id"); if (code != null) { String status = request.getParameter("add"); Product product = dao.getProduct(code); if (status != null) { String quantity = request.getParameter("num"); addToCart(product, Integer.parseInt(quantity)); } else { removeFromCart(product); } } float totalmoney = getTotal() ; String coupon = request.getParameter("coupon_code"); float coupon_value = dao.getCoupon(coupon); float discount = coupon_value / 100 * totalmoney; if (coupon != null) { session.setAttribute("finaltotal", totalmoney - discount); } else { request.setAttribute("message", "NOT VALID!"); if (this.products != null) { session.setAttribute("finaltotal", totalmoney); } } User u = (User) session.getAttribute("UI"); if (u != null) { u.setCoupon(coupon); u.setCoupon_value(coupon_value); u.setTotal(totalmoney - discount); u.setTotal(totalmoney); u.setCart(this.products); } session.setAttribute("coupon", coupon_value); session.setAttribute("cart", this.products); session.setAttribute("subtotalcart", totalmoney); session.setAttribute("numberofpro", getNumberOfPro()); response.sendRedirect(request.getParameter("from")); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
32.561856
123
0.585721
243a97c7774ccdba60ccfe1f370973cd01d53dbd
379
package je.techtribes.component.newsfeedconnector; import com.structurizr.annotation.Component; import je.techtribes.domain.NewsFeed; import je.techtribes.domain.NewsFeedEntry; import java.util.List; /** * Retrieves news feed entries from RSS and Atom feeds. */ @Component public interface NewsFeedConnector { List<NewsFeedEntry> loadNewsFeedEntries(NewsFeed feed); }
21.055556
59
0.799472
22185fe83232054031c42ee8809cfe256d3e81b4
690
/* * Copyright 2021, Yahoo Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE file in project root for terms. */ package com.yahoo.elide.datastores.aggregation.queryengines.sql.expression; import com.yahoo.elide.datastores.aggregation.query.Queryable; import lombok.Builder; import lombok.NonNull; import lombok.Value; /** * A reference to a column in the database: "$revenue". */ @Value @Builder public class PhysicalReference implements Reference { @NonNull private Queryable source; @NonNull private String name; @Override public <T> T accept(ReferenceVisitor<T> visitor) { return visitor.visitPhysicalReference(this); } }
22.258065
75
0.731884
daf7332a37c863cbc93b6ee4016508018ca84fad
2,002
package org.firstinspires.ftc.teamcode.localizers; public class IMUlocalizer { double x = 0; double y = 0; double z = 0; double xvelo = 0; double yvelo = 0; double zvelo = 0; double angleRad = 0; double last_xaccel_measurement = 0; double last_yaccel_measurement = 0; double last_zaccel_measurement = 0; double last_xvelo_measurement = 0; double last_yvelo_measurement = 0; double last_zvelo_measurement = 0; double time_of_last_measurement = 0; public IMUlocalizer(double startX, double startY, double startZ, double startRadians) { this.x = startX; this.y = startY; this.z = startZ; this.angleRad = startRadians; } public void updatePoseEstimate(double xaccel_robot, double yaccel_robot, double radians) { double cosA = Math.cos(radians); double sinA = Math.sin(radians); double xaccel = xaccel_robot * cosA - yaccel_robot * sinA; double yaccel = xaccel_robot * sinA + yaccel_robot * cosA; double time_of_current_measurement = (double) System.currentTimeMillis() / 1000; double time_delta = time_of_current_measurement - time_of_last_measurement; xvelo += ((xaccel + last_xaccel_measurement) / 2 ) * time_delta; yvelo += ((yaccel + last_yaccel_measurement) / 2 ) * time_delta; x += ((xvelo + last_xvelo_measurement) / 2 ) * time_delta; y += ((yvelo + last_yvelo_measurement) / 2 ) * time_delta; last_xaccel_measurement = xaccel; last_yaccel_measurement = yaccel; last_xvelo_measurement = xvelo; last_yvelo_measurement = yvelo; last_zvelo_measurement = zvelo; time_of_last_measurement = time_of_current_measurement; } public double getX() { return x; } public double getY() { return y; } public double getZ() { return z; } public double getAngleRad() { return angleRad; } }
23.833333
94
0.643856
0e4e86b5cf30c5a4ac54009cbaef45050d19e4b8
4,223
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.skyframe; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; /** * {@link WalkableGraph} that looks nodes up in a {@link QueryableGraph}. */ public class DelegatingWalkableGraph implements WalkableGraph { private final QueryableGraph graph; public DelegatingWalkableGraph(QueryableGraph graph) { this.graph = graph; } private NodeEntry getEntry(SkyKey key) { NodeEntry entry = Preconditions.checkNotNull(graph.get(key), key); Preconditions.checkState(entry.isDone(), "%s %s", key, entry); return entry; } private Map<SkyKey, NodeEntry> getEntries(Iterable<SkyKey> keys) { Map<SkyKey, NodeEntry> result = graph.getBatch(keys); Preconditions.checkState(result.size() == Iterables.size(keys), "%s %s", keys, result); for (Map.Entry<SkyKey, NodeEntry> entry : result.entrySet()) { Preconditions.checkState(entry.getValue().isDone(), entry); } return result; } @Override public boolean exists(SkyKey key) { NodeEntry entry = graph.get(key); return entry != null && entry.isDone(); } @Nullable @Override public SkyValue getValue(SkyKey key) { return getEntry(key).getValue(); } private static final Function<NodeEntry, SkyValue> GET_SKY_VALUE_FUNCTION = new Function<NodeEntry, SkyValue>() { @Nullable @Override public SkyValue apply(NodeEntry entry) { return entry.isDone() ? entry.getValue() : null; } }; @Override public Map<SkyKey, SkyValue> getDoneValues(Iterable<SkyKey> keys) { return Maps.filterValues(Maps.transformValues(graph.getBatch(keys), GET_SKY_VALUE_FUNCTION), Predicates.notNull()); } @Override public Map<SkyKey, Exception> getMissingAndExceptions(Iterable<SkyKey> keys) { Map<SkyKey, Exception> result = new HashMap<>(); Map<SkyKey, NodeEntry> graphResult = graph.getBatch(keys); for (SkyKey key : keys) { NodeEntry nodeEntry = graphResult.get(key); if (nodeEntry == null || !nodeEntry.isDone()) { result.put(key, null); } else { ErrorInfo errorInfo = nodeEntry.getErrorInfo(); if (errorInfo != null) { result.put(key, errorInfo.getException()); } } } return result; } @Nullable @Override public Exception getException(SkyKey key) { ErrorInfo errorInfo = getEntry(key).getErrorInfo(); return errorInfo == null ? null : errorInfo.getException(); } private static final Function<NodeEntry, Iterable<SkyKey>> GET_DIRECT_DEPS_FUNCTION = new Function<NodeEntry, Iterable<SkyKey>>() { @Override public Iterable<SkyKey> apply(NodeEntry entry) { return entry.getDirectDeps(); } }; @Override public Map<SkyKey, Iterable<SkyKey>> getDirectDeps(Iterable<SkyKey> keys) { return Maps.transformValues(getEntries(keys), GET_DIRECT_DEPS_FUNCTION); } private static final Function<NodeEntry, Iterable<SkyKey>> GET_REVERSE_DEPS_FUNCTION = new Function<NodeEntry, Iterable<SkyKey>>() { @Override public Iterable<SkyKey> apply(NodeEntry entry) { return entry.getReverseDeps(); } }; @Override public Map<SkyKey, Iterable<SkyKey>> getReverseDeps(Iterable<SkyKey> keys) { return Maps.transformValues(getEntries(keys), GET_REVERSE_DEPS_FUNCTION); } }
32.484615
96
0.697372
a55c8a0ee5361d559f92aa8688f749bc58000390
3,434
package htsjdk.tribble.readers; import htsjdk.HtsjdkTest; import htsjdk.samtools.util.BlockCompressedFilePointerUtil; import htsjdk.samtools.util.BlockCompressedInputStream; import htsjdk.samtools.util.BlockCompressedOutputStream; import org.testng.Assert; import org.testng.annotations.Test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; public class BlockCompressedAsciiLineReaderTest extends HtsjdkTest { private static final String sentinelLine = "Sentinel line"; @Test public void testLineReaderPosition() throws IOException { final File multiBlockFile = File.createTempFile("BlockCompressedAsciiLineReaderTest", ".gz"); multiBlockFile.deleteOnExit(); // write a file that has more than a single compressed block final long expectedFinalLineOffset = populateMultiBlockCompressedFile(multiBlockFile); try (final BlockCompressedInputStream bcis = new BlockCompressedInputStream(multiBlockFile); final BlockCompressedAsciiLineReader asciiLineReader = new BlockCompressedAsciiLineReader(bcis)) { String line = null; long actualFinalLineOffset = -1; do { actualFinalLineOffset = asciiLineReader.getPosition(); line = asciiLineReader.readLine(); } while (line != null && !line.equals(sentinelLine)); // test that we read the sentinel line; its at the expected offset, and that offset // represents a virtual file pointer Assert.assertNotNull(line); Assert.assertEquals(line, sentinelLine); Assert.assertEquals(expectedFinalLineOffset, actualFinalLineOffset); Assert.assertTrue(BlockCompressedFilePointerUtil.getBlockAddress(actualFinalLineOffset) != 0); } } @Test(expectedExceptions = UnsupportedOperationException.class) public void testRejectPositionalInputStream() throws IOException { final File multiBlockFile = File.createTempFile("BlockCompressedAsciiLineReaderTest", ".gz"); multiBlockFile.deleteOnExit(); populateMultiBlockCompressedFile(multiBlockFile); try (final BlockCompressedInputStream bcis = new BlockCompressedInputStream(multiBlockFile); final BlockCompressedAsciiLineReader asciiLineReader = new BlockCompressedAsciiLineReader(bcis)) { asciiLineReader.readLine(new PositionalBufferedStream(new ByteArrayInputStream(new byte[1100]))); } } // Populate a block compressed file so that has more than a single compressed block private long populateMultiBlockCompressedFile(final File tempBlockCompressedFile) throws IOException { long sentinelLineOffset = -1; try (BlockCompressedOutputStream bcos = new BlockCompressedOutputStream(tempBlockCompressedFile)) { // write lines until we exceed the size of the first block (block address != 0) do { bcos.write("Write this line enough times to exceed the size or a compressed block\n".getBytes()); } while (BlockCompressedFilePointerUtil.getBlockAddress(bcos.getFilePointer()) == 0); sentinelLineOffset = bcos.getFilePointer(); // write a terminating line that is guaranteed to not be in the first block bcos.write(sentinelLine.getBytes()); } return sentinelLineOffset; } }
44.597403
113
0.718404
76306bb9e85d6545f730c14f644cbe27a32c2622
7,557
/* * 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.tinkerpop.gremlin.process.traversal.step.map; import org.apache.tinkerpop.gremlin.LoadGraphWith; import org.apache.tinkerpop.gremlin.process.AbstractGremlinProcessTest; import org.apache.tinkerpop.gremlin.process.GremlinProcessRunner; import org.apache.tinkerpop.gremlin.process.traversal.Path; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import static org.apache.tinkerpop.gremlin.LoadGraphWith.GraphData.MODERN; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Daniel Kuppitz (http://gremlin.guru) */ @RunWith(GremlinProcessRunner.class) public abstract class LoopsTest extends AbstractGremlinProcessTest { /* g.V(1).repeat(both().simplePath()).until(has('name', 'peter').or().loops().is(3)).has('name', 'peter').path().by('name'). forEachRemaining(System.out::println); System.out.println('--'); g.V(v1Id).repeat(both().simplePath()).until(has('name', 'peter').or().loops().is(2)).has('name', 'peter').path().by('name'). forEachRemaining(System.out::println); System.out.println('--'); g.V(v1Id).repeat(both().simplePath()).until(has('name', 'peter').and().loops().is(3)).has('name', 'peter').path().by('name'). forEachRemaining(System.out::println); System.out.println('--'); g.V().emit(has('name', 'marko').or().loops().is(2)).repeat(out()).values('name'). forEachRemaining(System.out::println); */ public abstract Traversal<Vertex, Path> get_g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_or_loops_isX3XX_hasXname_peterX_path_byXnameX(final Object v1Id); public abstract Traversal<Vertex, Path> get_g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_or_loops_isX2XX_hasXname_peterX_path_byXnameX(final Object v1Id); public abstract Traversal<Vertex, Path> get_g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_and_loops_isX3XX_hasXname_peterX_path_byXnameX(final Object v1Id); public abstract Traversal<Vertex, String> get_g_V_emitXhasXname_markoX_or_loops_isX2XX_repeatXoutX_valuesXnameX(); @Test @LoadGraphWith(MODERN) public void g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_or_loops_isX3XX_hasXname_peterX_path_byXnameX() { final Traversal<Vertex, Path> traversal = get_g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_or_loops_isX3XX_hasXname_peterX_path_byXnameX(convertToVertexId("marko")); printTraversalForm(traversal); int paths = 0; boolean has3 = false, has4 = false; while (traversal.hasNext()) { final Path path = traversal.next(); switch (path.size()) { case 3: assertEquals("marko", path.get(0)); assertEquals("lop", path.get(1)); assertEquals("peter", path.get(2)); has3 = true; break; case 4: assertEquals("marko", path.get(0)); assertEquals("josh", path.get(1)); assertEquals("lop", path.get(2)); assertEquals("peter", path.get(3)); has4 = true; break; } paths++; } assertTrue(has3 && has4); assertEquals(2, paths); } @Test @LoadGraphWith(MODERN) public void g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_or_loops_isX2XX_hasXname_peterX_path_byXnameX() { final Traversal<Vertex, Path> traversal = get_g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_or_loops_isX2XX_hasXname_peterX_path_byXnameX(convertToVertexId("marko")); printTraversalForm(traversal); assertTrue(traversal.hasNext()); final Path path = traversal.next(); assertEquals(3, path.size()); assertEquals("marko", path.get(0)); assertEquals("lop", path.get(1)); assertEquals("peter", path.get(2)); assertFalse(traversal.hasNext()); } @Test @LoadGraphWith(MODERN) public void g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_and_loops_isX3XX_hasXname_peterX_path_byXnameX() { final Traversal<Vertex, Path> traversal = get_g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_and_loops_isX3XX_hasXname_peterX_path_byXnameX(convertToVertexId("marko")); printTraversalForm(traversal); assertTrue(traversal.hasNext()); final Path path = traversal.next(); assertEquals(4, path.size()); assertEquals("marko", path.get(0)); assertEquals("josh", path.get(1)); assertEquals("lop", path.get(2)); assertEquals("peter", path.get(3)); assertFalse(traversal.hasNext()); } @Test @LoadGraphWith(MODERN) public void g_V_emitXhasXname_markoX_or_loops_isX2XX_repeatXoutX_valuesXnameX() { final Traversal<Vertex, String> traversal = get_g_V_emitXhasXname_markoX_or_loops_isX2XX_repeatXoutX_valuesXnameX(); printTraversalForm(traversal); checkResults(Arrays.asList("marko", "ripple", "lop"), traversal); } public static class Traversals extends LoopsTest { @Override public Traversal<Vertex, Path> get_g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_or_loops_isX3XX_hasXname_peterX_path_byXnameX(final Object v1Id) { return g.V(v1Id).repeat(__.both().simplePath()).until(__.has("name", "peter").or().loops().is(3)).has("name", "peter").path().by("name"); } @Override public Traversal<Vertex, Path> get_g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_or_loops_isX2XX_hasXname_peterX_path_byXnameX(final Object v1Id) { return g.V(v1Id).repeat(__.both().simplePath()).until(__.has("name", "peter").or().loops().is(2)).has("name", "peter").path().by("name"); } @Override public Traversal<Vertex, Path> get_g_VX1X_repeatXboth_simplePathX_untilXhasXname_peterX_and_loops_isX3XX_hasXname_peterX_path_byXnameX(final Object v1Id) { return g.V(v1Id).repeat(__.both().simplePath()).until(__.has("name", "peter").and().loops().is(3)).has("name", "peter").path().by("name"); } @Override public Traversal<Vertex, String> get_g_V_emitXhasXname_markoX_or_loops_isX2XX_repeatXoutX_valuesXnameX() { return g.V().emit(__.has("name", "marko").or().loops().is(2)).repeat(__.out()).values("name"); } } }
49.071429
182
0.695117
0184471b24406c6fb23db82adaf5bbc359cb8aa3
3,718
/* * MIT License * * Copyright (c) 2020, 2021 Alexander Nikiforov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package ch.alni.certblues.acme.client.impl; import org.slf4j.Logger; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import ch.alni.certblues.acme.client.AcmeClient; import ch.alni.certblues.acme.client.AcmeServerException; import ch.alni.certblues.acme.client.Directory; import ch.alni.certblues.acme.client.DirectoryHandle; import ch.alni.certblues.acme.json.JsonObjects; import static org.slf4j.LoggerFactory.getLogger; /** * ACME client implementation using the standard HTTP client (as of Java 11). */ class AcmeClientImpl implements AcmeClient { private static final Logger LOG = getLogger(AcmeClientImpl.class); private final HttpClient httpClient; private final Duration timeout; AcmeClientImpl(HttpClient httpClient, Duration timeout) { this.httpClient = httpClient; this.timeout = timeout; } @Override public DirectoryHandle getDirectory(String url) { LOG.info("reading ACME directory at URL {}", url); final HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .timeout(timeout) .GET() .build(); final HttpResponse<String> response = Requests.withErrorHandling( () -> httpClient.send(request, HttpResponse.BodyHandlers.ofString()) ); final int statusCode = response.statusCode(); if (statusCode == 200) { LOG.info("directory object successfully returned: {}", response.body()); return toDirectoryHandle(response); } else if (statusCode < 400) { LOG.warn("unexpected status code {}, trying to convert body", statusCode); return toDirectoryHandle(response); } else { Payloads.extractError(response).ifPresent( error -> { throw new AcmeServerException(error); }); throw new AcmeServerException(response.body()); } } private DirectoryHandle toDirectoryHandle(HttpResponse<String> response) { final Directory directory = JsonObjects.deserialize(response.body(), Directory.class); final Session session = new Session(httpClient, timeout, directory); return RetryableHandle.create( session, new DirectoryHandleImpl(httpClient, timeout, session, directory), DirectoryHandle.class ); } }
35.75
94
0.685046
9a3637be172e04f95e202cc81e77ebfa01273276
2,017
package The_Scribe.relics; import The_Scribe.actions.RunicRepeaterAction; import The_Scribe.powers.SpellAttack; import The_Scribe.powers.SpellModifierInterface; import The_Scribe.powers.SpellPoison; import com.badlogic.gdx.graphics.Texture; import com.evacipated.cardcrawl.mod.stslib.relics.OnAfterUseCardRelic; import com.evacipated.cardcrawl.mod.stslib.relics.OnReceivePowerRelic; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.actions.utility.UseCardAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.core.AbstractCreature; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.powers.AbstractPower; import com.megacrit.cardcrawl.relics.AbstractRelic; import basemod.abstracts.CustomRelic; import The_Scribe.ScribeMod; public class RunicRepeater extends CustomRelic implements OnReceivePowerRelic { /* * https://github.com/daviscook477/BaseMod/wiki/Custom-Relics * * Gain 1 energy. */ // ID, images, text. public static final String ID = ScribeMod.makeID("RunicRepeater"); public static final String IMG = ScribeMod.makePath(ScribeMod.RUNIC_REPEATER); public static final String OUTLINE = ScribeMod.makePath(ScribeMod.RUNIC_REPEATER_OUTLINE); public RunicRepeater() { super(ID, new Texture(IMG), new Texture(OUTLINE), RelicTier.RARE, LandingSound.FLAT); } @Override public boolean onReceivePower(AbstractPower power, AbstractCreature source) { if(power instanceof SpellModifierInterface) { AbstractDungeon.actionManager.addToBottom(new RunicRepeaterAction()); this.flash(); } return true; } // Description @Override public String getUpdatedDescription() { return DESCRIPTIONS[0]; } // Which relic to return on making a copy of this relic. @Override public AbstractRelic makeCopy() { return new RunicRepeater(); } }
32.015873
94
0.752107
e6bc8074ce9e7f4e5301f381aa584b56a73610ee
429
package com.yyang.learning.ita.util; import lombok.Getter; import lombok.Setter; @Getter@Setter public class Timer { private Long begin; private Long end; public void begin() { this.begin = System.currentTimeMillis(); } public void stop() { this.end = System.currentTimeMillis(); } public Long runMilliSeconds() { return end - begin; } public long runSeconds() { return (end - begin)/1000; } }
13.83871
42
0.680653
483f225226f49aa69fc11944d9f9016871c3ff02
32,829
package com.jfinalshop.service; import java.math.BigDecimal; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.hasor.core.Inject; import net.hasor.core.Singleton; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.collections.Predicate; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateUtils; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Page; import com.jfinal.plugin.ehcache.CacheKit; import com.jfinalshop.Filter; import com.jfinalshop.Order; import com.jfinalshop.Pageable; import com.jfinalshop.Setting; import com.jfinalshop.dao.AttributeDao; import com.jfinalshop.dao.BrandDao; import com.jfinalshop.dao.ProductCategoryDao; import com.jfinalshop.dao.ProductDao; import com.jfinalshop.dao.ProductTagDao; import com.jfinalshop.dao.PromotionDao; import com.jfinalshop.dao.SkuBarcodeDao; import com.jfinalshop.dao.SkuDao; import com.jfinalshop.dao.SnDao; import com.jfinalshop.dao.StockLogDao; import com.jfinalshop.dao.StoreDao; import com.jfinalshop.dao.StoreProductCategoryDao; import com.jfinalshop.dao.StoreProductTagDao; import com.jfinalshop.entity.SpecificationItem; import com.jfinalshop.model.Attribute; import com.jfinalshop.model.Brand; import com.jfinalshop.model.Product; import com.jfinalshop.model.ProductCategory; import com.jfinalshop.model.ProductProductTag; import com.jfinalshop.model.ProductPromotion; import com.jfinalshop.model.ProductStoreProductTag; import com.jfinalshop.model.ProductTag; import com.jfinalshop.model.Promotion; import com.jfinalshop.model.Sku; import com.jfinalshop.model.SkuBarcode; import com.jfinalshop.model.Sn; import com.jfinalshop.model.StockLog; import com.jfinalshop.model.Store; import com.jfinalshop.model.StoreProductCategory; import com.jfinalshop.model.StoreProductTag; import com.jfinalshop.util.Assert; import com.jfinalshop.util.SystemUtils; import com.xiaoleilu.hutool.util.CollectionUtil; /** * Service - 商品 * */ @Singleton public class ProductService extends BaseService<Product> { /** * 构造方法 */ public ProductService() { super(Product.class); } private final CacheManager cacheManager = CacheKit.getCacheManager(); @Inject private ProductDao productDao; @Inject private SkuDao skuDao; @Inject private SnDao snDao; @Inject private ProductCategoryDao productCategoryDao; @Inject private StoreProductCategoryDao storeProductCategoryDao; @Inject private BrandDao brandDao; @Inject private PromotionDao promotionDao; @Inject private ProductTagDao productTagDao; @Inject private StoreProductTagDao storeProductTagDao; @Inject private AttributeDao attributeDao; @Inject private StockLogDao stockLogDao; @Inject private StoreDao storeDao; @Inject private SpecificationValueService specificationValueService; @Inject private SkuBarcodeDao skuBarcodeDao; /** * 判断编号是否存在 * * @param sn * 编号(忽略大小写) * @return 编号是否存在 */ public boolean snExists(String sn) { return productDao.exists("sn", sn, true); } /** * 根据编号查找商品 * * @param sn * 编号(忽略大小写) * @return 商品,若不存在则返回null */ public Product findBySn(String sn) { return productDao.find("sn", sn, true); } /** * 查找商品 * * @param type * 类型 * @param store * 店铺 * @param productCategory * 商品分类 * @param storeProductCategory * 店铺商品分类 * @param brand * 品牌 * @param promotion * 促销 * @param productTag * 商品标签 * @param storeProductTag * 店铺商品标签 * @param attributeValueMap * 属性值Map * @param startPrice * 最低价格 * @param endPrice * 最高价格 * @param isMarketable * 是否上架 * @param isList * 是否列出 * @param isTop * 是否置顶 * @param isActive * 是否有效 * @param isOutOfStock * 是否缺货 * @param isStockAlert * 是否库存警告 * @param hasPromotion * 是否存在促销 * @param orderType * 排序类型 * @param count * 数量 * @param filters * 筛选 * @param orders * 排序 * @return 商品 */ public List<Product> findList(Product.Type type, Store store, ProductCategory productCategory, StoreProductCategory storeProductCategory, Brand brand, Promotion promotion, ProductTag productTag, StoreProductTag storeProductTag, Map<Attribute, String> attributeValueMap, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable, Boolean isList, Boolean isTop, Boolean isActive, Boolean isOutOfStock, Boolean isStockAlert, Boolean hasPromotion, Product.OrderType orderType, Integer count, List<Filter> filters, List<Order> orders) { return productDao.findList(type, store, productCategory, storeProductCategory, brand, promotion, productTag, storeProductTag, attributeValueMap, startPrice, endPrice, isMarketable, isList, isTop, isActive, isOutOfStock, isStockAlert, hasPromotion, orderType, count, filters, orders); } /** * 查找商品 * * @param type * 类型 * @param storeId * 店铺ID * @param productCategoryId * 商品分类ID * @param storeProductCategoryId * 店铺商品分类ID * @param brandId * 品牌ID * @param promotionId * 促销ID * @param productTagId * 商品标签ID * @param storeProductTagId * 店铺商品标签ID * @param attributeValueMap * 属性值Map * @param startPrice * 最低价格 * @param endPrice * 最高价格 * @param isMarketable * 是否上架 * @param isList * 是否列出 * @param isTop * 是否置顶 * @param isActive * 是否有效 * @param isOutOfStock * 是否缺货 * @param isStockAlert * 是否库存警告 * @param hasPromotion * 是否存在促销 * @param orderType * 排序类型 * @param count * 数量 * @param filters * 筛选 * @param orders * 排序 * @param useCache * 是否使用缓存 * @return 商品 */ public List<Product> findList(Product.Type type, Long storeId, Long productCategoryId, Long storeProductCategoryId, Long brandId, Long promotionId, Long productTagId, Long storeProductTagId, Map<Long, String> attributeValueMap, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable, Boolean isList, Boolean isTop, Boolean isActive, Boolean isOutOfStock, Boolean isStockAlert, Boolean hasPromotion, Product.OrderType orderType, Integer count, List<Filter> filters, List<Order> orders, boolean useCache) { Store store = storeDao.find(storeId); if (storeId != null && store == null) { return Collections.emptyList(); } ProductCategory productCategory = productCategoryDao.find(productCategoryId); if (productCategoryId != null && productCategory == null) { return Collections.emptyList(); } StoreProductCategory storeProductCategory = storeProductCategoryDao.find(storeProductCategoryId); if (storeProductCategoryId != null && storeProductCategory == null) { return Collections.emptyList(); } Brand brand = brandDao.find(brandId); if (brandId != null && brand == null) { return Collections.emptyList(); } Promotion promotion = promotionDao.find(promotionId); if (promotionId != null && promotion == null) { return Collections.emptyList(); } ProductTag productTag = productTagDao.find(productTagId); if (productTagId != null && productTag == null) { return Collections.emptyList(); } StoreProductTag storeProductTag = storeProductTagDao.find(storeProductTagId); if (storeProductTagId != null && storeProductTag == null) { return Collections.emptyList(); } Map<Attribute, String> map = new HashMap<>(); if (attributeValueMap != null) { for (Map.Entry<Long, String> entry : attributeValueMap.entrySet()) { Attribute attribute = attributeDao.find(entry.getKey()); if (attribute != null) { map.put(attribute, entry.getValue()); } } } if (MapUtils.isNotEmpty(attributeValueMap) && MapUtils.isEmpty(map)) { return Collections.emptyList(); } return productDao.findList(type, store, productCategory, storeProductCategory, brand, promotion, productTag, storeProductTag, map, startPrice, endPrice, isMarketable, isList, isTop, isActive, isOutOfStock, isStockAlert, hasPromotion, orderType, count, filters, orders); } /** * 查找商品 * * @param rankingType * 排名类型 * @param store * 店铺 * @param count * 数量 * @return 商品 */ public List<Product> findList(Product.RankingType rankingType, Store store, Integer count) { return productDao.findList(rankingType, store, count); } /** * 查找商品分页 * * @param type * 类型 * @param store * 店铺 * @param productCategory * 商品分类 * @param storeProductCategory * 店铺商品分类 * @param brand * 品牌 * @param promotion * 促销 * @param productTag * 商品标签 * @param storeProductTag * 店铺商品标签 * @param attributeValueMap * 属性值Map * @param startPrice * 最低价格 * @param endPrice * 最高价格 * @param isMarketable * 是否上架 * @param isList * 是否列出 * @param isTop * 是否置顶 * @param isActive * 是否有效 * @param isOutOfStock * 是否缺货 * @param isStockAlert * 是否库存警告 * @param hasPromotion * 是否存在促销 * @param orderType * 排序类型 * @param pageable * 分页信息 * @return 商品分页 */ public Page<Product> findPage(Product.Type type, Store store, ProductCategory productCategory, StoreProductCategory storeProductCategory, Brand brand, Promotion promotion, ProductTag productTag, StoreProductTag storeProductTag, Map<Attribute, String> attributeValueMap, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable, Boolean isList, Boolean isTop, Boolean isActive, Boolean isOutOfStock, Boolean isStockAlert, Boolean hasPromotion, Product.OrderType orderType, Pageable pageable) { return productDao.findPage(type, store, productCategory, storeProductCategory, brand, promotion, productTag, storeProductTag, attributeValueMap, startPrice, endPrice, isMarketable, isList, isTop, isActive, isOutOfStock, isStockAlert, hasPromotion, orderType, pageable); } /** * 查询商品数量 * * @param type * 类型 * @param store * 店铺 * @param isMarketable * 是否上架 * @param isList * 是否列出 * @param isTop * 是否置顶 * @param isActive * 是否有效 * @param isOutOfStock * 是否缺货 * @param isStockAlert * 是否库存警告 * @return 商品数量 */ public Long count(Product.Type type, Store store, Boolean isMarketable, Boolean isList, Boolean isTop, Boolean isActive, Boolean isOutOfStock, Boolean isStockAlert) { return productDao.count(type, store, isMarketable, isList, isTop, isActive, isOutOfStock, isStockAlert); } /** * 查看点击数 * * @param id * ID * @return 点击数 */ public long viewHits(Long id) { Assert.notNull(id); Ehcache cache = cacheManager.getEhcache(Product.HITS_CACHE_NAME); cache.acquireWriteLockOnKey(id); try { Element element = cache.get(id); Long hits; if (element != null) { hits = (Long) element.getObjectValue() + 1; } else { Product product = productDao.find(id); if (product == null) { return 0L; } hits = product.getHits() + 1; } cache.put(new Element(id, hits)); return hits; } finally { cache.releaseWriteLockOnKey(id); } } /** * 增加点击数 * * @param product * 商品 * @param amount * 值 */ public void addHits(Product product, long amount) { Assert.notNull(product); Assert.state(amount >= 0); if (amount == 0) { return; } Calendar nowCalendar = Calendar.getInstance(); Calendar weekHitsCalendar = DateUtils.toCalendar(product.getWeekHitsDate()); Calendar monthHitsCalendar = DateUtils.toCalendar(product.getMonthHitsDate()); if (nowCalendar.get(Calendar.YEAR) > weekHitsCalendar.get(Calendar.YEAR) || nowCalendar.get(Calendar.WEEK_OF_YEAR) > weekHitsCalendar.get(Calendar.WEEK_OF_YEAR)) { product.setWeekHits(amount); } else { product.setWeekHits(product.getWeekHits() + amount); } if (nowCalendar.get(Calendar.YEAR) > monthHitsCalendar.get(Calendar.YEAR) || nowCalendar.get(Calendar.MONTH) > monthHitsCalendar.get(Calendar.MONTH)) { product.setMonthHits(amount); } else { product.setMonthHits(product.getMonthHits() + amount); } product.setHits(product.getHits() + amount); product.setWeekHitsDate(new Date()); product.setMonthHitsDate(new Date()); productDao.update(product); } /** * 增加销量 * * @param product * 商品 * @param amount * 值 */ public void addSales(Product product, long amount) { Assert.notNull(product); Assert.state(amount >= 0); if (amount == 0) { return; } // if (!LockModeType.PESSIMISTIC_WRITE.equals(productDao.getLockMode(product))) { // productDao.flush(); // productDao.refresh(product, LockModeType.PESSIMISTIC_WRITE); // } Calendar nowCalendar = Calendar.getInstance(); Calendar weekSalesCalendar = DateUtils.toCalendar(product.getWeekSalesDate()); Calendar monthSalesCalendar = DateUtils.toCalendar(product.getMonthSalesDate()); if (nowCalendar.get(Calendar.YEAR) > weekSalesCalendar.get(Calendar.YEAR) || nowCalendar.get(Calendar.WEEK_OF_YEAR) > weekSalesCalendar.get(Calendar.WEEK_OF_YEAR)) { product.setWeekSales(amount); } else { product.setWeekSales(product.getWeekSales() + amount); } if (nowCalendar.get(Calendar.YEAR) > monthSalesCalendar.get(Calendar.YEAR) || nowCalendar.get(Calendar.MONTH) > monthSalesCalendar.get(Calendar.MONTH)) { product.setMonthSales(amount); } else { product.setMonthSales(product.getMonthSales() + amount); } product.setSales(product.getSales() + amount); product.setWeekSalesDate(new Date()); product.setMonthSalesDate(new Date()); //productDao.flush(); productDao.update(product); } /** * 创建 * * @param product * 商品 * @param sku * SKU * @return 商品 */ public Product create(Product product, Sku sku) { Assert.notNull(product); Assert.isTrue(product.isNew()); Assert.notNull(product.getType()); Assert.isTrue(!product.hasSpecification()); Assert.notNull(sku); Assert.isTrue(sku.isNew()); Assert.state(!sku.hasSpecification()); switch (product.getTypeName()) { case general: sku.setExchangePoint(0L); break; case exchange: sku.setPrice(BigDecimal.ZERO); sku.setRewardPoint(0L); product.setPromotions(null); break; case gift: sku.setPrice(BigDecimal.ZERO); sku.setRewardPoint(0L); sku.setExchangePoint(0L); product.setPromotions(null); break; default: break; } if (sku.getMarketPrice() == null) { sku.setMarketPrice(calculateDefaultMarketPrice(sku.getPrice())); } if (sku.getRewardPoint() == null) { sku.setRewardPoint(calculateDefaultRewardPoint(sku.getPrice())); } else { long maxRewardPoint = calculateMaxRewardPoint(sku.getPrice()); sku.setRewardPoint(sku.getRewardPoint() > maxRewardPoint ? maxRewardPoint : sku.getRewardPoint()); } sku.setAllocatedStock(0); sku.setIsDefault(true); sku.setProduct(product); product.setPrice(sku.getPrice()); product.setCost(sku.getCost()); product.setMarketPrice(sku.getMarketPrice()); product.setIsActive(true); product.setScore(0F); product.setTotalScore(0L); product.setScoreCount(0L); product.setHits(0L); product.setWeekHits(0L); product.setMonthHits(0L); product.setSales(0L); product.setWeekSales(0L); product.setMonthSales(0L); product.setWeekHitsDate(new Date()); product.setMonthHitsDate(new Date()); product.setWeekSalesDate(new Date()); product.setMonthSalesDate(new Date()); setValue(product); productDao.save(product); setValue(sku); skuDao.save(sku); stockIn(sku); afterProductSave(product); return product; } /** * 创建 * * @param product * 商品 * @param skus * SKU * @return 商品 */ public Product create(Product product, List<Sku> skus) { Assert.notNull(product); Assert.isTrue(product.isNew()); Assert.notNull(product.getType()); Assert.isTrue(product.hasSpecification()); Assert.notEmpty(skus); final List<SpecificationItem> specificationItems = product.getSpecificationItemsConverter(); if (CollectionUtils.exists(skus, new Predicate() { private Set<List<Integer>> set = new HashSet<>(); @Override public boolean evaluate(Object object) { Sku sku = (Sku) object; return sku == null || !sku.isNew() || !sku.hasSpecification() || !set.add(sku.getSpecificationValueIds()) || !specificationValueService.isValid(specificationItems, sku.getSpecificationValuesConverter()); } })) { throw new IllegalArgumentException(); } Sku defaultSku = (Sku) CollectionUtils.find(skus, new Predicate() { @Override public boolean evaluate(Object object) { Sku sku = (Sku) object; return sku != null && sku.getIsDefault(); } }); if (defaultSku == null) { defaultSku = skus.get(0); defaultSku.setIsDefault(true); } for (Sku sku : skus) { switch (product.getTypeName()) { case general: sku.setExchangePoint(0L); break; case exchange: sku.setPrice(BigDecimal.ZERO); sku.setRewardPoint(0L); product.setPromotions(null); break; case gift: sku.setPrice(BigDecimal.ZERO); sku.setRewardPoint(0L); sku.setExchangePoint(0L); product.setPromotions(null); break; default: break; } if (sku.getMarketPrice() == null) { sku.setMarketPrice(calculateDefaultMarketPrice(sku.getPrice())); } if (sku.getRewardPoint() == null) { sku.setRewardPoint(calculateDefaultRewardPoint(sku.getPrice())); } else { long maxRewardPoint = calculateMaxRewardPoint(sku.getPrice()); sku.setRewardPoint(sku.getRewardPoint() > maxRewardPoint ? maxRewardPoint : sku.getRewardPoint()); } if (sku != defaultSku) { sku.setIsDefault(false); } sku.setAllocatedStock(0); sku.setProduct(product); // sku.setCartItems(null); // sku.setOrderItems(null); // sku.setOrderShippingItems(null); // sku.setProductNotifies(null); // sku.setStockLogs(null); // sku.setGiftPromotions(null); } product.setPrice(defaultSku.getPrice()); product.setCost(defaultSku.getCost()); product.setMarketPrice(defaultSku.getMarketPrice()); product.setIsActive(true); product.setScore(0F); product.setTotalScore(0L); product.setScoreCount(0L); product.setHits(0L); product.setWeekHits(0L); product.setMonthHits(0L); product.setSales(0L); product.setWeekSales(0L); product.setMonthSales(0L); product.setWeekHitsDate(new Date()); product.setMonthHitsDate(new Date()); product.setWeekSalesDate(new Date()); product.setMonthSalesDate(new Date()); // product.setReviews(null); // product.setConsultations(null); // product.setProductFavorites(null); // product.setSkus(null); setValue(product); productDao.save(product); afterProductSave(product); for (Sku sku : skus) { setValue(sku); skuDao.save(sku); stockIn(sku); } return product; } /** * 修改 * * @param product * 商品 * @param sku * SKU * @return 商品 */ public Product modify(Product product, Sku sku) { Assert.notNull(product); Assert.isTrue(!product.isNew()); Assert.isTrue(!product.hasSpecification()); Assert.notNull(sku); Assert.isTrue(sku.isNew()); Assert.state(!sku.hasSpecification()); Product pProduct = productDao.find(product.getId()); switch (pProduct.getTypeName()) { case general: sku.setExchangePoint(0L); break; case exchange: sku.setPrice(BigDecimal.ZERO); sku.setRewardPoint(0L); product.setPromotions(null); break; case gift: sku.setPrice(BigDecimal.ZERO); sku.setRewardPoint(0L); sku.setExchangePoint(0L); product.setPromotions(null); break; default: break; } if (sku.getMarketPrice() == null) { sku.setMarketPrice(calculateDefaultMarketPrice(sku.getPrice())); } if (sku.getRewardPoint() == null) { sku.setRewardPoint(calculateDefaultRewardPoint(sku.getPrice())); } else { long maxRewardPoint = calculateMaxRewardPoint(sku.getPrice()); sku.setRewardPoint(sku.getRewardPoint() > maxRewardPoint ? maxRewardPoint : sku.getRewardPoint()); } sku.setAllocatedStock(0); sku.setIsDefault(true); sku.setProduct(product); if (pProduct.hasSpecification()) { for (Sku pSku : pProduct.getSkus()) { skuDao.remove(pSku); } if (sku.getStock() == null) { throw new IllegalArgumentException(); } setValue(sku); skuDao.save(sku); stockIn(sku); } else { Sku defaultSku = pProduct.getDefaultSku(); defaultSku.setPrice(sku.getPrice()); defaultSku.setCost(sku.getCost()); defaultSku.setMarketPrice(sku.getMarketPrice()); defaultSku.setRewardPoint(sku.getRewardPoint()); defaultSku.setExchangePoint(sku.getExchangePoint()); skuDao.update(defaultSku); } product.setPrice(sku.getPrice()); product.setCost(sku.getCost()); product.setMarketPrice(sku.getMarketPrice()); setValue(product); copyProperties(product, pProduct, "sn", "type", "score", "totalScore", "scoreCount", "hits", "weekHits", "monthHits", "sales", "weekSales", "monthSales", "weekHitsDate", "monthHitsDate", "weekSalesDate", "monthSalesDate", "storeId", "createdDate"); productDao.update(pProduct); return pProduct; } /** * 修改 * * @param product * 商品 * @param skus * SKU * @return 商品 */ public Product modify(Product product, List<Sku> skus) { Assert.notNull(product); Assert.isTrue(!product.isNew()); Assert.isTrue(product.hasSpecification()); Assert.notEmpty(skus); final List<SpecificationItem> specificationItems = product.getSpecificationItemsConverter(); if (CollectionUtils.exists(skus, new Predicate() { private Set<List<Integer>> set = new HashSet<>(); @Override public boolean evaluate(Object object) { Sku sku = (Sku) object; return sku == null || !sku.isNew() || !sku.hasSpecification() || !set.add(sku.getSpecificationValueIds()) || !specificationValueService.isValid(specificationItems, sku.getSpecificationValuesConverter()); } })) { throw new IllegalArgumentException(); } Sku defaultSku = (Sku) CollectionUtils.find(skus, new Predicate() { @Override public boolean evaluate(Object object) { Sku sku = (Sku) object; return sku != null && sku.getIsDefault(); } }); if (defaultSku == null) { defaultSku = skus.get(0); defaultSku.setIsDefault(true); } Product pProduct = productDao.find(product.getId()); for (Sku sku : skus) { switch (pProduct.getTypeName()) { case general: sku.setExchangePoint(0L); break; case exchange: sku.setPrice(BigDecimal.ZERO); sku.setRewardPoint(0L); product.setPromotions(null); break; case gift: sku.setPrice(BigDecimal.ZERO); sku.setRewardPoint(0L); sku.setExchangePoint(0L); product.setPromotions(null); break; default: break; } if (sku.getMarketPrice() == null) { sku.setMarketPrice(calculateDefaultMarketPrice(sku.getPrice())); } if (sku.getRewardPoint() == null) { sku.setRewardPoint(calculateDefaultRewardPoint(sku.getPrice())); } else { long maxRewardPoint = calculateMaxRewardPoint(sku.getPrice()); sku.setRewardPoint(sku.getRewardPoint() > maxRewardPoint ? maxRewardPoint : sku.getRewardPoint()); } if (sku != defaultSku) { sku.setIsDefault(false); } sku.setAllocatedStock(0); sku.setProduct(pProduct); // sku.setCartItems(null); // sku.setOrderItems(null); // sku.setOrderShippingItems(null); // sku.setProductNotifies(null); // sku.setStockLogs(null); // sku.setGiftPromotions(null); } if (pProduct.hasSpecification()) { for (Sku pSku : pProduct.getSkus()) { if (!exists(skus, pSku.getSpecificationValueIds())) { clearStockLog(pSku); skuDao.remove(pSku); } } for (Sku sku : skus) { Sku pSku = find(pProduct.getSkus(), sku.getSpecificationValueIds()); if (pSku != null) { pSku.setPrice(sku.getPrice()); pSku.setCost(sku.getCost()); pSku.setMarketPrice(sku.getMarketPrice()); pSku.setRewardPoint(sku.getRewardPoint()); pSku.setExchangePoint(sku.getExchangePoint()); pSku.setIsDefault(sku.getIsDefault()); pSku.setSpecificationValues(sku.getSpecificationValues()); skuDao.update(pSku); } else { if (sku.getStock() == null) { throw new IllegalArgumentException(); } setValue(sku); skuDao.save(sku); stockIn(sku); } } } else { Sku pSku = pProduct.getDefaultSku(); clearStockLog(pSku); skuDao.remove(pSku); for (Sku sku : skus) { if (sku.getStock() == null) { throw new IllegalArgumentException(); } setValue(sku); skuDao.save(sku); stockIn(sku); } } product.setPrice(defaultSku.getPrice()); product.setCost(defaultSku.getCost()); product.setMarketPrice(defaultSku.getMarketPrice()); setValue(product); copyProperties(product, pProduct, "sn", "type", "score", "totalScore", "scoreCount", "hits", "weekHits", "monthHits", "sales", "weekSales", "monthSales", "weekHitsDate", "monthHitsDate", "weekSalesDate", "monthSalesDate", "storeId", "createdDate"); productDao.update(pProduct); return pProduct; } /** * 刷新过期店铺商品有效状态 */ public void refreshExpiredStoreProductActive() { productDao.refreshExpiredStoreProductActive(); } /** * 刷新商品有效状态 * * @param store * 店铺 */ public void refreshActive(Store store) { Assert.notNull(store); productDao.refreshActive(store); } @Override public Product save(Product product) { return super.save(product); } @Override public Product update(Product product) { return super.update(product); } @Override public void delete(Long id) { super.delete(id); } @Override public void delete(Long... ids) { super.delete(ids); } @Override public void delete(Product product) { super.delete(product); } /** * 保存后条码 * * @param product * 商品 */ public void saveBarcode(Product product) { if (product == null) { return; } Sku sku = product.getDefaultSku(); List<SkuBarcode> skuBarcodes = sku.getSkuBarcodes(); if (CollectionUtil.isNotEmpty(skuBarcodes)) { Db.deleteById("sku_barcode", "sku_id", sku.getId()); for (SkuBarcode skuBarcode : skuBarcodes) { skuBarcode.setSkuId(sku.getId()); skuBarcode.setStoreId(product.getStore().getId()); skuBarcodeDao.save(skuBarcode); } } } /** * 清空关连表 * * @param product * 商品 */ public void clear(Product product) { Db.deleteById("product_promotion", "products_id", product.getId()); Db.deleteById("product_product_tag", "products_id", product.getId()); Db.deleteById("product_store_product_tag", "products_id", product.getId()); } /** * 保存后设置促销、产品标签、店铺产品标签 * * @param product * 商品 */ private void afterProductSave(Product product) { if (product == null) { return; } // 关联保存促销 List<Promotion> promotions = product.getPromotions(); if (CollectionUtil.isNotEmpty(promotions)) { for (Promotion promotion : promotions) { ProductPromotion productPromotion = new ProductPromotion(); productPromotion.setProductsId(product.getId()); productPromotion.setPromotionsId(promotion.getId()); productPromotion.save(); } } // 关联保存产品标签 List<ProductTag> productTags = product.getProductTags(); if (CollectionUtil.isNotEmpty(productTags)) { for (ProductTag productTag : productTags) { ProductProductTag productProductTag = new ProductProductTag(); productProductTag.setProductsId(product.getId()); productProductTag.setProductTagsId(productTag.getId()); productProductTag.save(); } } // 关联保存店铺产品标签 List<StoreProductTag> storeProductTags = product.getStoreProductTags(); if (CollectionUtil.isNotEmpty(storeProductTags)) { for (StoreProductTag storeProductTag : storeProductTags) { ProductStoreProductTag productStoreProductTag = new ProductStoreProductTag(); productStoreProductTag.setProductsId(product.getId()); productStoreProductTag.setStoreProductTagsId(storeProductTag.getId()); productStoreProductTag.save(); } } } /** * 清除库表中的sku记录 * @param sku * SKU */ private void clearStockLog(Sku sku) { if (stockLogDao.exists("sku_id", sku.getId())) { Db.deleteById("stock_log", "sku_id", sku.getId()); } } /** * 设置商品值 * * @param product * 商品 */ private void setValue(Product product) { if (product == null) { return; } if (StringUtils.isEmpty(product.getImage()) && StringUtils.isNotEmpty(product.getThumbnail())) { product.setImage(product.getThumbnail()); } if (product.isNew()) { if (StringUtils.isEmpty(product.getSn())) { String sn; do { sn = snDao.generate(Sn.Type.product); } while (snExists(sn)); product.setSn(StringUtils.lowerCase(sn)); } if (CollectionUtils.isNotEmpty(product.getProductImagesConverter())) { Collections.sort(product.getProductImagesConverter()); } } } /** * 设置SKU值 * * @param sku * SKU */ private void setValue(Sku sku) { if (sku == null) { return; } if (sku.isNew()) { Product product = sku.getProduct(); if (product != null && StringUtils.isNotEmpty(product.getSn())) { String sn; int i = sku.hasSpecification() ? 1 : 0; do { sn = product.getSn() + (i == 0 ? "" : "_" + i); i++; } while (skuDao.exists("sn", sn, true)); sku.setSn(sn); sku.setProductId(product.getId()); } } } /** * 计算默认市场价 * * @param price * 价格 * @return 默认市场价 */ private BigDecimal calculateDefaultMarketPrice(BigDecimal price) { Assert.notNull(price); Setting setting = SystemUtils.getSetting(); Double defaultMarketPriceScale = setting.getDefaultMarketPriceScale(); return defaultMarketPriceScale != null ? setting.setScale(price.multiply(new BigDecimal(String.valueOf(defaultMarketPriceScale)))) : BigDecimal.ZERO; } /** * 计算默认赠送积分 * * @param price * 价格 * @return 默认赠送积分 */ private long calculateDefaultRewardPoint(BigDecimal price) { Assert.notNull(price); Setting setting = SystemUtils.getSetting(); Double defaultPointScale = setting.getDefaultPointScale(); return defaultPointScale != null ? price.multiply(new BigDecimal(String.valueOf(defaultPointScale))).longValue() : 0L; } /** * 计算最大赠送积分 * * @param price * 价格 * @return 最大赠送积分 */ private long calculateMaxRewardPoint(BigDecimal price) { Assert.notNull(price); Setting setting = SystemUtils.getSetting(); Double maxPointScale = setting.getMaxPointScale(); return maxPointScale != null ? price.multiply(new BigDecimal(String.valueOf(maxPointScale))).longValue() : 0L; } /** * 根据规格值ID查找SKU * * @param skus * SKU * @param specificationValueIds * 规格值ID * @return SKU */ private Sku find(Collection<Sku> skus, final List<Integer> specificationValueIds) { if (CollectionUtils.isEmpty(skus) || CollectionUtils.isEmpty(specificationValueIds)) { return null; } return (Sku) CollectionUtils.find(skus, new Predicate() { @Override public boolean evaluate(Object object) { Sku sku = (Sku) object; return sku != null && sku.getSpecificationValueIds() != null && sku.getSpecificationValueIds().equals(specificationValueIds); } }); } /** * 根据规格值ID判断SKU是否存在 * * @param skus * SKU * @param specificationValueIds * 规格值ID * @return SKU是否存在 */ private boolean exists(Collection<Sku> skus, final List<Integer> specificationValueIds) { return find(skus, specificationValueIds) != null; } /** * 入库 * * @param sku * SKU */ private void stockIn(Sku sku) { if (sku == null || sku.getStock() == null || sku.getStock() <= 0) { return; } StockLog stockLog = new StockLog(); stockLog.setType(StockLog.Type.stockIn.ordinal()); stockLog.setInQuantity(sku.getStock()); stockLog.setOutQuantity(0); stockLog.setStock(sku.getStock()); stockLog.setMemo(null); stockLog.setSkuId(sku.getId()); stockLogDao.save(stockLog); } }
27.821186
294
0.678638
9ddebb1ffc8997f503fd7f1aebc50e181c473f8d
7,251
package ru.kontur.vostok.hercules.elastic.sink.index; import org.junit.Assert; import org.junit.Test; import ru.kontur.vostok.hercules.protocol.Container; import ru.kontur.vostok.hercules.protocol.Event; import ru.kontur.vostok.hercules.protocol.EventBuilder; import ru.kontur.vostok.hercules.protocol.Variant; import ru.kontur.vostok.hercules.util.time.TimeUtil; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Optional; import java.util.Properties; import static org.junit.Assert.assertFalse; /** * @author Gregory Koshelev */ public class IndexResolverTest { public static final Properties INDEX_RESOLVER_PROPERTIES; static { Properties props = new Properties(); props.setProperty(IndexResolver.Props.INDEX_PATH.name(), "properties/elk-index"); props.setProperty(IndexResolver.Props.INDEX_TAGS.name(), "properties/project,properties/environment?,properties/subproject?"); INDEX_RESOLVER_PROPERTIES = props; } @Test public void shouldNotResolveIndexIfNoSuitableTags() { IndexResolver indexResolver = IndexResolver.forPolicy(IndexPolicy.DAILY, INDEX_RESOLVER_PROPERTIES); final Event event = EventBuilder.create(0, "00000000-0000-1000-994f-8fcf383f0000") //TODO: fix me! .build(); Optional<String> result = indexResolver.resolve(event); assertFalse(result.isPresent()); } @Test public void shouldResolveDailyIndex() { IndexResolver indexResolver = IndexResolver.forPolicy(IndexPolicy.DAILY, INDEX_RESOLVER_PROPERTIES); final Event event = EventBuilder.create( TimeUtil.dateTimeToUnixTicks(ZonedDateTime.of(2019, 12, 1, 10, 42, 0, 0, ZoneOffset.UTC)), "00000000-0000-0000-0000-000000000000"). tag("properties", Variant.ofContainer( Container.builder(). tag("project", Variant.ofString("proj")). tag("environment", Variant.ofString("dev")). tag("subproject", Variant.ofString("subproj")). build())). build(); Optional<String> index = indexResolver.resolve(event); Assert.assertTrue(index.isPresent()); Assert.assertEquals("proj-dev-subproj-2019.12.01", index.get()); } @Test public void shouldResolveIlmIndex() { IndexResolver indexResolver = IndexResolver.forPolicy(IndexPolicy.ILM, INDEX_RESOLVER_PROPERTIES); final Event event = EventBuilder.create( TimeUtil.dateTimeToUnixTicks(ZonedDateTime.of(2019, 12, 1, 10, 42, 0, 0, ZoneOffset.UTC)), "00000000-0000-0000-0000-000000000000"). tag("properties", Variant.ofContainer( Container.builder(). tag("project", Variant.ofString("proj")). tag("environment", Variant.ofString("dev")). tag("subproject", Variant.ofString("subproj")). build())). build(); Optional<String> index = indexResolver.resolve(event); Assert.assertTrue(index.isPresent()); Assert.assertEquals("proj-dev-subproj", index.get()); } @Test public void shouldIgnoreBadIndexName() { IndexResolver indexResolver = IndexResolver.forPolicy(IndexPolicy.DAILY, INDEX_RESOLVER_PROPERTIES); final Event event = EventBuilder.create( TimeUtil.dateTimeToUnixTicks(ZonedDateTime.of(2019, 12, 1, 10, 42, 0, 0, ZoneOffset.UTC)), "00000000-0000-0000-0000-000000000000"). tag("properties", Variant.ofContainer( Container.builder(). tag("project", Variant.ofString("{#project}")). tag("environment", Variant.ofString("dev")). tag("subproject", Variant.ofString("subproj")). build())). build(); Optional<String> index = indexResolver.resolve(event); Assert.assertFalse(index.isPresent()); } @Test public void shouldSanitizeIndexName() { IndexResolver indexResolver = IndexResolver.forPolicy(IndexPolicy.DAILY, INDEX_RESOLVER_PROPERTIES); final Event event = EventBuilder.create( TimeUtil.dateTimeToUnixTicks(ZonedDateTime.of(2019, 12, 1, 10, 42, 0, 0, ZoneOffset.UTC)), "00000000-0000-0000-0000-000000000000"). tag("properties", Variant.ofContainer( Container.builder(). tag("project", Variant.ofString("Project<To,Test>")). tag("environment", Variant.ofString("D.E.V")). tag("subproject", Variant.ofString(">Ю")). build())). build(); Optional<String> index = indexResolver.resolve(event); Assert.assertTrue(index.isPresent()); Assert.assertEquals("project_to_test_-d.e.v-__-2019.12.01", index.get()); } @Test public void shouldResolveIndexNameWithoutOptionalParts() { IndexResolver indexResolver = IndexResolver.forPolicy(IndexPolicy.ILM, INDEX_RESOLVER_PROPERTIES); final Event event = EventBuilder.create( TimeUtil.dateTimeToUnixTicks(ZonedDateTime.of(2019, 12, 1, 10, 42, 0, 0, ZoneOffset.UTC)), "00000000-0000-0000-0000-000000000000"). tag("properties", Variant.ofContainer( Container.builder(). tag("project", Variant.ofString("proj")). tag("env", Variant.ofString("dev")).// But configured tag is environment tag("subproject", Variant.ofString("subproj")). build())). build(); Optional<String> index = indexResolver.resolve(event); Assert.assertTrue(index.isPresent()); Assert.assertEquals("proj-subproj", index.get()); } @Test public void shouldResolvePredefinedIndexName() { IndexResolver indexResolver = IndexResolver.forPolicy(IndexPolicy.ILM, INDEX_RESOLVER_PROPERTIES); final Event event = EventBuilder.create( TimeUtil.dateTimeToUnixTicks(ZonedDateTime.of(2019, 12, 1, 10, 42, 0, 0, ZoneOffset.UTC)), "00000000-0000-0000-0000-000000000000"). tag("properties", Variant.ofContainer( Container.builder(). tag("project", Variant.ofString("proj")). tag("environment", Variant.ofString("dev")). tag("subproject", Variant.ofString("subproj")). tag("elk-index", Variant.ofString("custom-index")). build())). build(); Optional<String> index = indexResolver.resolve(event); Assert.assertTrue(index.isPresent()); Assert.assertEquals("custom-index", index.get()); } }
47.084416
134
0.590953
50b2c02cc956beb0a60e9759962c5d5cc5c18d02
5,590
package com.stylefeng.guns.po; import org.hibernate.annotations.Proxy; import javax.persistence.*; import java.util.Date; import java.util.Objects; @Entity @Proxy(lazy = false) @Table(name = "sys_user", schema = "guns", catalog = "") public class User { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String avatar; private String account; private String password; private String salt; private String name; private Date birthday; private Integer sex; private String email; private String phone; private String roleid; private Integer deptid; private Integer status; private Date createtime; private Integer version; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Basic @Column(name = "avatar") public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } @Basic @Column(name = "account") public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } @Basic @Column(name = "password") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Basic @Column(name = "salt") public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } @Basic @Column(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Basic @Column(name = "birthday") public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Basic @Column(name = "sex") public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } @Basic @Column(name = "email") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Basic @Column(name = "phone") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Basic @Column(name = "roleid") public String getRoleid() { return roleid; } public void setRoleid(String roleid) { this.roleid = roleid; } @Basic @Column(name = "deptid") public Integer getDeptid() { return deptid; } public void setDeptid(Integer deptid) { this.deptid = deptid; } @Basic @Column(name = "status") public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Basic @Column(name = "createtime") public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } @Basic @Column(name = "version") public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id && Objects.equals(avatar, user.avatar) && Objects.equals(account, user.account) && Objects.equals(password, user.password) && Objects.equals(salt, user.salt) && Objects.equals(name, user.name) && Objects.equals(birthday, user.birthday) && Objects.equals(sex, user.sex) && Objects.equals(email, user.email) && Objects.equals(phone, user.phone) && Objects.equals(roleid, user.roleid) && Objects.equals(deptid, user.deptid) && Objects.equals(status, user.status) && Objects.equals(createtime, user.createtime) && Objects.equals(version, user.version); } @Override public int hashCode() { return Objects.hash(id, avatar, account, password, salt, name, birthday, sex, email, phone, roleid, deptid, status, createtime, version); } @Override public String toString() { final StringBuffer sb = new StringBuffer("User{"); sb.append("id=").append(id); sb.append(", avatar='").append(avatar).append('\''); sb.append(", account='").append(account).append('\''); sb.append(", password='").append(password).append('\''); sb.append(", salt='").append(salt).append('\''); sb.append(", name='").append(name).append('\''); sb.append(", birthday=").append(birthday); sb.append(", sex=").append(sex); sb.append(", email='").append(email).append('\''); sb.append(", phone='").append(phone).append('\''); sb.append(", roleid='").append(roleid).append('\''); sb.append(", deptid=").append(deptid); sb.append(", status=").append(status); sb.append(", createtime=").append(createtime); sb.append(", version=").append(version); sb.append('}'); return sb.toString(); } }
24.304348
145
0.569052
1e7ce05a07c4dd58dcc27046029d8acc168e5dd8
1,005
package org.elixirian.kommonlee.type.functional.primitive; /** * <pre> * ___ _____ _____ * / \/ / ______ __________________ ______ __ ______ / / ______ ______ * / / _/ __ // / / / / / /_/ __ // // // / / ___ \/ ___ \ * / \ / /_/ _/ _ _ / _ _ // /_/ _/ __ // /___/ _____/ _____/ * /____/\____\/_____//__//_//_/__//_//_/ /_____//___/ /__//________/\_____/ \_____/ * </pre> * * <pre> * ___ _____ _____ * / \/ /_________ ___ ____ __ ______ / / ______ ______ * / / / ___ \ \/ //___// // / / / / ___ \/ ___ \ * / \ / _____/\ // // __ / / /___/ _____/ _____/ * /____/\____\\_____/ \__//___//___/ /__/ /________/\_____/ \_____/ * </pre> * * @author Lee, SeongHyun (Kevin) * @version 0.0.1 (2012-11-16) */ public interface VoidByteFunction1 { void apply(byte input); }
37.222222
87
0.420896
e941ee56b764efc4b2235f30bd7facae0faebe3b
154
package android.curso.bonuspoo.datamodel; /** * Created by marcomaddo on 27/10/2017. */ public class CarroDataModel { // definições da tabela. }
14
41
0.701299
a29fabe8b74fea29765655a96560c26759badef1
889
package uk.gov.companieshouse.web.accounts.model.smallfull.notes.currentassetsinvestments; import uk.gov.companieshouse.web.accounts.model.Note; import uk.gov.companieshouse.web.accounts.validation.ValidationMapping; import uk.gov.companieshouse.web.accounts.validation.ValidationModel; import javax.validation.constraints.NotBlank; @ValidationModel public class CurrentAssetsInvestments implements Note { @NotBlank(message = "{currentAssetsInvestments.details.missing}") @ValidationMapping("$.current_assets_investments.details") private String currentAssetsInvestmentsDetails; public String getCurrentAssetsInvestmentsDetails() { return currentAssetsInvestmentsDetails; } public void setCurrentAssetsInvestmentsDetails(String currentAssetsInvestmentsDetails) { this.currentAssetsInvestmentsDetails = currentAssetsInvestmentsDetails; } }
37.041667
92
0.821147
af3e28608216ba9a09cc7d35a50c2b93ac2bd0cc
8,410
package com.didi.carrera.console.web.controller.odin; import com.didi.carrera.console.service.ClusterService; import com.didi.carrera.console.service.ConsumeGroupService; import com.didi.carrera.console.service.ConsumeSubscriptionService; import com.didi.carrera.console.service.TopicService; import com.didi.carrera.console.service.ZKV4ConfigService; import com.didi.carrera.console.web.AbstractBaseController; import com.didi.carrera.console.web.ConsoleBaseResponse; import com.didi.carrera.console.web.controller.bo.AcceptTopicConfBo; import com.didi.carrera.console.web.controller.bo.ConsumeSubscriptionOrderBo; import com.didi.carrera.console.web.controller.bo.TopicOrderBo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.validation.Valid; @Controller("odinInternalController") @RequestMapping("/api/odin/internal") public class InternalController extends AbstractBaseController { @Resource(name = "didiTopicServiceImpl") private TopicService topicService; @Resource(name = "didiConsumeGroupServiceImpl") private ConsumeGroupService consumeGroupService; @Resource(name = "didiConsumeSubscriptionServiceImpl") private ConsumeSubscriptionService consumeSubscriptionService; @Autowired private ZKV4ConfigService zkv4ConfigService; @ResponseBody @RequestMapping(value = {"/createTopic"}, method = {RequestMethod.POST}) public ConsoleBaseResponse<?> createTopic(@Valid @RequestBody TopicOrderBo<AcceptTopicConfBo> topicinfo, BindingResult bindingResult) throws Exception { if (bindingResult.hasErrors()) { String msg = getBindingResultErrorInfo(bindingResult); return ConsoleBaseResponse.error(ConsoleBaseResponse.Status.INVALID_PARAM, msg); } return topicService.create(topicinfo); } @ResponseBody @RequestMapping(value = {"/createSub"}, method = {RequestMethod.POST}) public ConsoleBaseResponse<?> createSub(@Valid @RequestBody ConsumeSubscriptionOrderBo subBo, BindingResult bindingResult) throws Exception { if (bindingResult.hasErrors()) { String msg = getBindingResultErrorInfo(bindingResult); return ConsoleBaseResponse.error(ConsoleBaseResponse.Status.INVALID_PARAM, msg); } return consumeSubscriptionService.createConsumeSubscription(subBo); } @ResponseBody @RequestMapping(value = {"/deleteGroup"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> deleteGroup(@RequestParam String user, @RequestParam Long groupId) throws Exception { return consumeGroupService.delete(user, groupId); } @ResponseBody @RequestMapping(value = {"/deleteSub"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> deleteSub(@RequestParam String user, @RequestParam Long subId) throws Exception { return consumeSubscriptionService.delete(user, subId); } @ResponseBody @RequestMapping(value = {"/v4/initZkPath"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> initZkPath() throws Exception { zkv4ConfigService.initZkPath(); return ConsoleBaseResponse.success(); } @ResponseBody @RequestMapping(value = {"/v4/initAllZk"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> initAllZk() throws Exception { zkv4ConfigService.initAllZk(); return ConsoleBaseResponse.success(); } @ResponseBody @RequestMapping(value = {"/v4/addPProxy"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> addPProxy(@RequestParam String cluster, @RequestParam String host) throws Exception { return topicService.addPProxy(cluster, host); } @ResponseBody @RequestMapping(value = {"/v4/addCProxy"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> addCProxy(@RequestParam String cluster, @RequestParam String host) throws Exception { return consumeSubscriptionService.addCProxy(cluster, host); } @ResponseBody @RequestMapping(value = {"/v4/pushTopicConfig"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> pushTopicConfig(@RequestParam String topic) throws Exception { return zkv4ConfigService.pushTopicConfig(topic); } @ResponseBody @RequestMapping(value = {"/v4/pushGroupConfig"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> pushGroupConfig(@RequestParam String group) throws Exception { return zkv4ConfigService.pushGroupConfig(group); } @ResponseBody @RequestMapping(value = {"/v4/pushPProxyConfig"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> pushPproxyConfig(@RequestParam String host) throws Exception { return zkv4ConfigService.pushPproxyConfig(host); } @ResponseBody @RequestMapping(value = {"/v4/pushCProxyConfig"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> pushCproxyConfig(@RequestParam String host) throws Exception { return zkv4ConfigService.pushCproxyConfig(host); } @ResponseBody @RequestMapping(value = {"/v4/pushTopicConfigByCluster"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> pushTopicConfigByCluster(@RequestParam String cluster) throws Exception { return zkv4ConfigService.pushTopicByCluster(cluster); } @ResponseBody @RequestMapping(value = {"/v4/pushGroupConfigByCluster"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> pushGroupConfigByCluster(@RequestParam String cluster) throws Exception { return zkv4ConfigService.pushGroupByCluster(cluster); } @ResponseBody @RequestMapping(value = {"/v4/pushPProxyConfigByCluster"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> pushPProxyConfigByCluster(@RequestParam String cluster) throws Exception { return zkv4ConfigService.pushPProxyByCluster(cluster); } @ResponseBody @RequestMapping(value = {"/v4/pushCProxyConfigByCluster"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> pushCProxyConfigByCluster(@RequestParam String cluster) throws Exception { return zkv4ConfigService.pushCProxyByCluster(cluster); } @ResponseBody @RequestMapping(value = {"/v4/addPProxyByTopic"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> addPProxyByTopic(@RequestParam String topic, @RequestParam String cluster, @RequestParam String host) throws Exception { return topicService.addPProxy(topic, cluster, host); } @ResponseBody @RequestMapping(value = {"/v4/removePProxy"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> removePProxy(@RequestParam String host) throws Exception { return topicService.removePProxy(host); } @ResponseBody @RequestMapping(value = {"/v4/removePProxyByTopic"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> removePProxyByTopic(@RequestParam String topic, @RequestParam String host) throws Exception { return topicService.removePProxy(topic, host); } @ResponseBody @RequestMapping(value = {"/v4/addCProxyByGroup"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> addCProxyByGroup(@RequestParam String group, @RequestParam String cluster, @RequestParam String host) throws Exception { return consumeSubscriptionService.addCProxy(group, cluster, host); } @ResponseBody @RequestMapping(value = {"/v4/removeCProxyByGroup"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> removeCProxyByGroup(@RequestParam String group, @RequestParam String host) throws Exception { return consumeSubscriptionService.removeCProxy(group, host); } @ResponseBody @RequestMapping(value = {"/v4/removeCProxy"}, method = {RequestMethod.GET}) public ConsoleBaseResponse<?> removeCProxy(@RequestParam String host) throws Exception { return consumeSubscriptionService.removeCProxy(host); } }
44.734043
156
0.753151
fb14bfec523a602598e833671929e854f3329ee6
1,074
package com.jinke.kanbox; public interface RequestListener { public void onComplete(String response, int operationType); public void onError(KanboxException error, int operationType); public void onError(KanboxException error, int operationType,String path,String destPath); public void downloadProgress(long currSize); public static final int OP_GET_TOKEN = 1; public static final int OP_REFRESH_TOKEN = 2; public static final int OP_GET_ACCCOUNT_INFO = 3; public static final int OP_GET_FILELIST = 4; public static final int OP_MOVE = 5; public static final int OP_COPY = 6; public static final int OP_DELETE = 7; public static final int OP_MAKE_DIR = 8; public static final int OP_MAKE_SHARE_DIR = 9; //创建共享目录 public static final int OP_GET_SHARE_INVITE_LIST = 10; //获取共享邀请列表 public static final int OP_HANDLE_SHARE_INVITE = 11; //处理共享请求 public static final int OP_SHARED_BY_SELF = 12; //是否是自己创建的共享文件夹 public static final int OP_UPLOAD = 12; public static final int OP_DOWNLOAD = 13; public static final int OP_DOWNLOAD_BITMAP = 14; }
34.645161
91
0.780261
080b90795c2152db4a9aab720a70bfe90ef735b0
3,851
/* * Copyright (c) Microsoft Corporation. * * 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.microsoft.playwright; import com.microsoft.playwright.options.WaitUntilState; import org.junit.jupiter.api.Test; import static com.microsoft.playwright.options.WaitUntilState.COMMIT; import static com.microsoft.playwright.options.WaitUntilState.DOMCONTENTLOADED; import static org.junit.jupiter.api.Assertions.*; public class TestPageSetContent extends TestBase { private static final String expectedOutput = "<html><head></head><body><div>hello</div></body></html>"; @Test void shouldWork() { page.setContent("<div>hello</div>"); Object result = page.content(); assertEquals(expectedOutput, result); } @Test void shouldWorkWithDomcontentloaded() { page.setContent("<div>hello</div>", new Page.SetContentOptions().setWaitUntil(DOMCONTENTLOADED)); Object result = page.content(); assertEquals(expectedOutput, result); } @Test void shouldWorkWithCommit() { page.setContent("<div>hello</div>", new Page.SetContentOptions().setWaitUntil(COMMIT)); Object result = page.content(); assertEquals(expectedOutput, result); } @Test void shouldWorkWithDoctype() { String doctype = "<!DOCTYPE html>"; page.setContent(doctype + "<div>hello</div>"); Object result = page.content(); assertEquals(doctype + expectedOutput, result); } @Test void shouldWorkWithHTML4Doctype() { String doctype = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" " + "\"http://www.w3.org/TR/html4/strict.dtd\">"; page.setContent(doctype + "<div>hello</div>"); Object result = page.content(); assertEquals(doctype + expectedOutput, result); } @Test void shouldRespectTimeout() { String imgPath = "/img.png"; // stall for image server.setRoute(imgPath, exchange -> {}); try { page.setContent("<img src='" + server.PREFIX + imgPath + "'></img>", new Page.SetContentOptions().setTimeout(100)); fail("did not throw"); } catch (TimeoutError e) { } } @Test void shouldRespectDefaultNavigationTimeout() { page.setDefaultNavigationTimeout(100); String imgPath = "/img.png"; // stall for image server.setRoute(imgPath, exchange -> {}); try { page.setContent("<img src='" + server.PREFIX + imgPath + "'></img>"); fail("did not throw"); } catch (TimeoutError e) { assertTrue(e.getMessage().contains("Timeout 100ms exceeded."), e.getMessage()); } } @Test void shouldWorkFastEnough() { for (int i = 0; i < 20; ++i) { page.setContent("<div>yo</div>"); } } @Test void shouldWorkWithTrickyContent() { page.setContent("<div>hello world</div>" + "\\x7F"); assertEquals("hello world", page.evalOnSelector("div", "div => div.textContent")); } @Test void shouldWorkWithAccents() { page.setContent("<div>aberración</div>"); assertEquals("aberración", page.evalOnSelector("div", "div => div.textContent")); } @Test void shouldWorkWithEmojis() { page.setContent("<div>🐥</div>"); assertEquals("🐥", page.evalOnSelector("div", "div => div.textContent")); } @Test void shouldWorkWithNewline() { page.setContent("<div>\n</div>"); assertEquals("\n", page.evalOnSelector("div", "div => div.textContent")); } }
30.808
121
0.67437
1c7aaa7cf2be5b8b41247c802320e5b0e1bbe096
656
package edu.udel.cis.vsl.abc.ast.entity.common; import edu.udel.cis.vsl.abc.ast.entity.IF.CommonEntity; import edu.udel.cis.vsl.abc.ast.entity.IF.Label; import edu.udel.cis.vsl.abc.ast.entity.IF.ProgramEntity; import edu.udel.cis.vsl.abc.ast.node.IF.label.OrdinaryLabelNode; public class CommonLabel extends CommonEntity implements Label { public CommonLabel(OrdinaryLabelNode declaration) { super(EntityKind.LABEL, declaration.getName(), ProgramEntity.LinkageKind.NONE); addDeclaration(declaration); setDefinition(declaration); } @Override public OrdinaryLabelNode getDefinition() { return (OrdinaryLabelNode) super.getDefinition(); } }
29.818182
81
0.794207
fd95eedf83cb486b47b1eb18d0ce0a80e5649b26
10,172
package com.simmgames.waystones.data; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.simmgames.waystones.permissions.Perm; import com.simmgames.waystones.util.Default; import com.simmgames.waystones.util.Work; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; public class Data { private Logger out; private String dataPath; private Server server; private JavaPlugin plugin; public List<Waystone> AllWaystones; public List<WayPlayer> players; public Data(Logger logger, JavaPlugin plugin) { out = logger; AllWaystones = new ArrayList<Waystone>(); players = new ArrayList<WayPlayer>(); dataPath = plugin.getDataFolder().getAbsolutePath(); server = plugin.getServer(); this.plugin = plugin; } public void Save() { SaveWaystones(); // Retire offline players List<String> online = new ArrayList<String>(); for(Player p: server.getOnlinePlayers()) online.add(p.getUniqueId().toString()); if(players != null) { for (int i = players.size()-1; i >= 0; i--) if (!online.contains(players.get(i).UUID)) RetirePlayer(players.get(i)); } else { out.log(Level.SEVERE, "Players list is null. Nothing is being saved for players."); } // Save remaining players for(String p: online) SavePlayer(p); } public void Load() { if(!LoadWaystones()) { MakeWaystoneBackup(); } } public WayPlayer GrabPlayer(String playerUUID) { if(playerUUID.equalsIgnoreCase(Default.UUIDOne)) return new WayPlayer(Default.UUIDOne, "Admin"); if(playerUUID.equalsIgnoreCase(Default.UUIDZero)) return new WayPlayer(Default.UUIDZero, "Null"); WayPlayer player = playerInList(playerUUID); if(player == null) { player = LoadPlayer(playerUUID); } return player; } private WayPlayer LoadPlayer(String playerUUID) { if(playerUUID.equalsIgnoreCase(Default.UUIDOne)) return new WayPlayer(Default.UUIDOne, "Admin"); if(playerUUID.equalsIgnoreCase(Default.UUIDZero)) return new WayPlayer(Default.UUIDZero, "Null"); // Load Waystones List String wayplayersLocation = dataPath + "/Players/"; Gson gson = new Gson(); String pLoc = wayplayersLocation + playerUUID + ".json"; if(!FileExists(pLoc)) { WayPlayer wp = new WayPlayer(playerUUID, "Unknown"); out.log(Level.INFO, ChatColor.AQUA + "New WayPlayer has been created for '" + playerUUID +"'"); players.add(wp); SavePlayer(playerUUID); } String json = ReadFile(pLoc); try { Type WayplayerType = new TypeToken<WayPlayer>() { }.getType(); WayPlayer player = gson.fromJson(json, WayplayerType); if(player == null) { if(json.trim().length() > 2) MakePlayerBackup(playerUUID); player = new WayPlayer(playerUUID, "Unknown"); } if(playerInList(playerUUID) == null) { players.add((player)); } return player; } catch (Exception e) { out.log(Level.WARNING, "Could not load a waystone list. Remaking it..."); WayPlayer player = new WayPlayer(playerUUID, "Unknown"); if(playerInList(playerUUID) == null) { players.add((player)); } MakePlayerBackup(playerUUID); return player; } } public WayPlayer SavePlayer(String playerUUID) { if(playerUUID.equalsIgnoreCase(Default.UUIDOne)) return new WayPlayer(Default.UUIDOne, "Admin"); if(playerUUID.equalsIgnoreCase(Default.UUIDZero)) return new WayPlayer(Default.UUIDZero, "Null"); WayPlayer player = GrabPlayer(playerUUID); String wayplayersLocation = dataPath + "/Players/"; Gson gson = new GsonBuilder().setPrettyPrinting().create(); String wayplayerData = gson.toJson(player); WriteFile(wayplayersLocation + playerUUID + ".json", wayplayerData); return player; } public void RetirePlayer(String playerUUID) { WayPlayer player = SavePlayer(playerUUID); players.remove(player); } public void RetirePlayer(WayPlayer player) { players.remove(player); } public Waystone WaystoneFromUUID(UUID waystoneUUID) { return WaystoneFromUUID(waystoneUUID.toString()); } public Waystone WaystoneFromUUID(String waystoneUUID) { for(Waystone wei: AllWaystones) { if(wei.uuid.equalsIgnoreCase(waystoneUUID)) return wei; } return null; } public List<Waystone> WaystonesFromStringList(List<String> waystoneUUIDs) { List<Waystone> waylist = new ArrayList<>(); for(String uuid: waystoneUUIDs) { Waystone stone = WaystoneFromUUID(uuid); if(stone != null) waylist.add(stone); } return waylist; } private WayPlayer playerInList(String uuid) { for(WayPlayer player : players) { if(player != null) if(player.UUID.equalsIgnoreCase(uuid)) return player; } return null; } private void MakePlayerBackup(String playerUUID) { out.log(Level.WARNING, "Something wrong was detected with " + playerUUID + "'s player json (Maybe it's new?). Making a backup just in case."); File old = new File(dataPath + "/Player/" + playerUUID + ".json"); File backup = new File(dataPath + "/PlayerBackup/" + playerUUID + ".0.json"); int i = 0; while(backup.exists()) { i++; backup = new File(dataPath + "/PlayerBackup/" + playerUUID + "." + i + ".json"); } old.renameTo(backup); out.log(Level.INFO, "Moving " + old.getName() + " to " + backup.getName() + " in case you just has a typo."); SavePlayer(playerUUID); } private void MakeWaystoneBackup() { out.log(Level.WARNING, "Something wrong was detected with the current waystone json (Maybe it's new?). Making a backup just in case."); File old = new File(dataPath + "/Waystones.json"); File backup = new File(dataPath + "/Waystones.old.0.json"); int i = 0; while(backup.exists()) { i++; backup = new File(dataPath + "/Waystones.old." + i + ".json"); } old.renameTo(backup); out.log(Level.INFO, "Renaming old config to " + backup.getName() + " in case you just has a typo."); SaveWaystones(); } private boolean LoadWaystones() { // Load Waystones List String waystonesLocation = dataPath + "/Waystones.json"; Gson gson = new Gson(); String json = ReadFile(waystonesLocation); try { Type WaystoneListType = new TypeToken<ArrayList<Waystone>>() { }.getType(); AllWaystones = gson.fromJson(json, WaystoneListType); if (AllWaystones == null) { if(json.trim().length() > 2) MakeWaystoneBackup(); AllWaystones = new ArrayList<Waystone>(); } return true; } catch (Exception e) { out.log(Level.WARNING, "Could not load a waystone list. Remaking it..."); return false; } } private boolean SaveWaystones() { // Save Waystones List String waystonesLocation = dataPath + "/Waystones.json"; Gson gson = new GsonBuilder().setPrettyPrinting().create(); String waystoneData = gson.toJson(AllWaystones); WriteFile(waystonesLocation, waystoneData); return true; } private boolean FileExists(String location) { File myObj = new File(location); return myObj.exists(); } private String ReadFile(String location) { EnsureFileExists(location); try { BufferedReader buffer = new BufferedReader(new FileReader(location)); String output = ""; String current; while((current = buffer.readLine()) != null) { output += current + "\n"; } if(buffer != null) { buffer.close(); } return output; } catch (IOException e) { out.log(Level.SEVERE, "Could not read file:\n" + location); e.printStackTrace(); return null; } } private boolean WriteFile(String location, String data) { EnsureFileExists(location); try { FileWriter myWriter = new FileWriter(location); myWriter.write(data); myWriter.close(); return true; } catch (IOException e) { out.log(Level.WARNING, "Could not write to a file:\n" + location); e.printStackTrace(); return false; } } private void EnsureFileExists(String location) { try { File myObj = new File(location); myObj.getParentFile().mkdir(); myObj.createNewFile(); } catch (IOException e) { out.log(Level.WARNING, "Could not get a file:\n" + location); e.printStackTrace(); } } }
31.987421
150
0.57442
730ba9ae92af3b97d05fb26f41a61c30aacf2f44
400
import java.util.Arrays; /*Write code that fills an array values with each set of numbers below. g.0 1 2 3 4 0 1 2 3 4*/ public class R6_01G { public static void main(String[] args) { int[] numbers = new int[10]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i % 5; } System.out.println(Arrays.toString(numbers)); } }
26.666667
71
0.555
ff3694df54689b25e57483b1dc3ff7544155fe3c
1,421
/* * Copyright 2019 https://github.com/romeoblog/spring-cloud.git Group. * * 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.cloud.example.eureka.config; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * Created with default template * Author: Joe Benji * Date: 2019-04-03 * Time: 15:38 * Description: */ @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // http.csrf().disable(); http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic(); } }
39.472222
102
0.73399
ee220f7aa2b398a638158c5cc78fc7453ed498f6
794
package com.codingapi.txlcn.tc.utils; import org.junit.jupiter.api.Test; import org.springframework.util.Assert; import org.springframework.util.StopWatch; import java.util.HashSet; import java.util.Set; import static com.codingapi.txlcn.tc.utils.IdUtils.generateLogId; /** * @author WhomHim * @date Create in 2020-8-10 22:09:30 */ public class IdUtilsTest { @Test public void id() { StopWatch stopWatch = new StopWatch(); Set<Long> logSet = new HashSet<>(); stopWatch.start(); for (int i = 0; i < 1000; i++) { long logId = generateLogId(); logSet.add(logId); System.out.println("logId:" + logId); } stopWatch.stop(); Assert.isTrue(1000 == logSet.size(), "size must the same"); } }
24.8125
67
0.625945
c6919feb1415d5477cb8b4e11cf85685ee6384ce
1,126
package backend.cell; import backend.util.ModifiableVoogaCollection; import java.util.Collection; /** * @author Created by th174 on 3/30/2017. */ public class Region extends ModifiableVoogaCollection<Terrain, Region> { private static final long serialVersionUID = 1L; public transient static final Region DEFAULT_REGION = new Region("Default Region") .setDescription("The default region contains all the pre-defined terrains") .setImgPath("resources/images/blackScreen.png") .addAll(Terrain.getPredefinedTerrain()); public Region(String name) { super(name, "", ""); } public Region(String name, String description, String imgPath, Terrain... gameObjects) { super(name, description, imgPath, gameObjects); } public Region(String name, String description, String imgPath, Collection<? extends Terrain> gameObjects) { super(name, description, imgPath, gameObjects); } @Deprecated public static Collection<Region> getPredefinedRegions() { return getPredefined(Region.class); } @Override public Region copy() { return new Region(getName(), getDescription(), getImgPath(), getAll()); } }
28.15
108
0.750444
ec372b734e48908bd3de5c9a32bb1032dedda82a
5,250
package com.xhy.weibo.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.xhy.weibo.model.Login; import com.xhy.weibo.model.User; import java.util.ArrayList; import java.util.List; /** * Created by xuhaoyang on 16/6/3. */ public class UserDB { private Context context; public UserDB(Context context) { this.context = context; } public List<Login> QueryLogin(SQLiteDatabase db, String selection, String[] selectionArgs) { List<Login> logins = new ArrayList<>(); Cursor cursor = db.query(DatabaseHelper.USER_TABLE, null, selection, selectionArgs, null, null, null); if (cursor.moveToFirst()) { do { Login login = new Login(); login.setId(cursor.getInt(cursor.getColumnIndex("id"))); login.setAccount(cursor.getString(cursor.getColumnIndex("account"))); login.setPassword(cursor.getString(cursor.getColumnIndex("password"))); login.setRegistime(cursor.getInt(cursor.getColumnIndex("registime"))); login.setToken(cursor.getString(cursor.getColumnIndex("token"))); login.setTokenStartTime(cursor.getLong(cursor.getColumnIndex("tokenStartTime"))); logins.add(login); } while (cursor.moveToNext()); } cursor.close(); return logins; } public List<User> QueryUsers(SQLiteDatabase db, String selection, String[] selectionArgs) { List<User> users = new ArrayList<>(); Cursor cursor = db.query(DatabaseHelper.USER_TABLE, null, selection, selectionArgs, null, null, null); if (cursor.moveToFirst()) { do { User user = new User(); user.setUid(cursor.getInt(cursor.getColumnIndex("id"))); user.setFace(cursor.getString(cursor.getColumnIndex("face"))); user.setFollow(cursor.getInt(cursor.getColumnIndex("follow"))); user.setFans(cursor.getInt(cursor.getColumnIndex("fans"))); user.setWeibo(cursor.getInt(cursor.getColumnIndex("weibo"))); user.setUptime(cursor.getLong(cursor.getColumnIndex("uptime"))); user.setIntro(cursor.getString(cursor.getColumnIndex("intro"))); users.add(user); } while (cursor.moveToNext()); } cursor.close(); return users; } public boolean updateUser(SQLiteDatabase db, User user) { boolean flag; db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("face", user.getFace()); values.put("username", user.getUsername()); values.put("follow", user.getFollow()); values.put("fans", user.getFans()); values.put("weibo", user.getWeibo()); values.put("intro", user.getIntro()); values.put("uptime", System.currentTimeMillis()); String selection = "id=?"; String[] selectionArgs = new String[]{user.getUid() + ""}; db.update(DatabaseHelper.USER_TABLE, values, selection, selectionArgs); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { db.endTransaction(); flag = true; } return flag; } public boolean insertUser(SQLiteDatabase db, User user) { boolean flag; //开启事务 db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("id", user.getUid()); values.put("face", user.getFace()); values.put("username", user.getUsername()); values.put("follow", user.getFollow()); values.put("fans", user.getFans()); values.put("weibo", user.getWeibo()); values.put("intro", user.getIntro()); values.put("uptime", System.currentTimeMillis()); db.insert(DatabaseHelper.USER_TABLE, null, values); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { db.endTransaction(); flag = true; } return flag; } public boolean insertLogin(SQLiteDatabase db, Login login) { boolean flag; //开启事务 db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("id", login.getId()); values.put("account", login.getAccount()); values.put("password", login.getPassword()); values.put("registime", login.getRegistime()); values.put("token", login.getToken()); values.put("tokenStartTime", login.getTokenStartTime()); values.put("used", 1); db.insert(DatabaseHelper.USER_TABLE, null, values); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { db.endTransaction(); flag = true; } return flag; } }
35.714286
110
0.581524
da4c5290ba72c9562a42f1fe218da19bea543e7e
3,726
/* * Copyright 2020 b333vv * * 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.b333vv.metric.task; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import org.b333vv.metric.event.MetricsEventListener; import org.b333vv.metric.model.code.JavaClass; import org.b333vv.metric.model.code.JavaProject; import org.b333vv.metric.model.metric.Metric; import org.b333vv.metric.model.metric.MetricType; import org.b333vv.metric.ui.chart.builder.MetricPieChartBuilder; import org.b333vv.metric.util.MetricsUtils; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Map; import java.util.Objects; import static org.b333vv.metric.builder.ClassesByMetricsValuesDistributor.classesByMetricsValuesDistribution; import static org.b333vv.metric.task.MetricTaskManager.getClassAndMethodModel; public class PieChartTask extends Task.Backgroundable { private static final String GET_FROM_CACHE_MESSAGE = "Try to get classes distribution by metric values pie chart from cache"; private static final String STARTED_MESSAGE = "Building classes distribution by metric values pie chart started"; private static final String FINISHED_MESSAGE = "Building classes distribution by metric values pie chart finished"; private static final String CANCELED_MESSAGE = "Building classes distribution by metric values pie chart canceled"; public PieChartTask() { super(MetricsUtils.getCurrentProject(), "Building Pie Chart"); } @Override public void run(@NotNull ProgressIndicator indicator) { myProject.getMessageBus().syncPublisher(MetricsEventListener.TOPIC).printInfo(GET_FROM_CACHE_MESSAGE); Map<MetricType, Map<JavaClass, Metric>> classesByMetricTypes = MetricTaskCache.instance() .getUserData(MetricTaskCache.CLASSES_BY_METRIC_TYPES); List<MetricPieChartBuilder.PieChartStructure> pieChartList = MetricTaskCache.instance() .getUserData(MetricTaskCache.PIE_CHART_LIST); if (classesByMetricTypes == null || pieChartList == null) { myProject.getMessageBus().syncPublisher(MetricsEventListener.TOPIC).printInfo(STARTED_MESSAGE); JavaProject javaProject = getClassAndMethodModel(indicator); classesByMetricTypes = classesByMetricsValuesDistribution(Objects.requireNonNull(javaProject)); MetricPieChartBuilder builder = new MetricPieChartBuilder(); pieChartList = builder.createChart(javaProject); MetricTaskCache.instance().putUserData(MetricTaskCache.CLASSES_BY_METRIC_TYPES, classesByMetricTypes); MetricTaskCache.instance().putUserData(MetricTaskCache.PIE_CHART_LIST, pieChartList); } } @Override public void onSuccess() { super.onSuccess(); myProject.getMessageBus().syncPublisher(MetricsEventListener.TOPIC).printInfo(FINISHED_MESSAGE); myProject.getMessageBus().syncPublisher(MetricsEventListener.TOPIC).pieChartIsReady(); } @Override public void onCancel() { super.onCancel(); myProject.getMessageBus().syncPublisher(MetricsEventListener.TOPIC).printInfo(CANCELED_MESSAGE); } }
47.769231
129
0.765432
ce3fbac23953f2c97ff91448c1358e4529046f0e
332
package org.endeavourhealth.core.database.dal.audit; import org.endeavourhealth.core.database.dal.audit.models.ApplicationHeartbeat; import java.util.List; public interface ApplicationHeartbeatDalI { void saveHeartbeat(ApplicationHeartbeat h) throws Exception; List<ApplicationHeartbeat> getLatest() throws Exception; }
27.666667
79
0.822289
aff91028bc8804491804abcb908e327075f4105c
1,579
package uk.gov.hmcts.reform.sscs.controller; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import uk.gov.hmcts.reform.sscs.ccd.service.CcdService; import uk.gov.hmcts.reform.sscs.idam.IdamService; import uk.gov.hmcts.reform.sscs.idam.IdamTokens; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("integration") @AutoConfigureMockMvc public class SmokeControllerTest { @MockBean private CcdService ccdService; @MockBean private IdamService idamService; @Autowired private MockMvc mockMvc; @Test public void shouldReturn200WhenSendingRequestToController() throws Exception { when(idamService.getIdamTokens()).thenReturn(IdamTokens.builder().build()); mockMvc.perform(get("/smoke-test")) .andDo(print()) .andExpect(status().isOk()); } }
35.886364
87
0.79544
7bd5ede897dc281f7843059b6d547444289153ee
586
package com.lemon.blog.model; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import lombok.Data; import java.time.LocalDateTime; @Data public class Comment { private Long id; private Long articleId; private Long userId; private Long parentId; private Long replyToUserId; private String content; private Integer status; @TableField(fill = FieldFill.INSERT) private LocalDateTime createdAt; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updatedAt; }
18.3125
54
0.750853
de93e22f0732b78c7fb696e082da99b2bf0deaf0
139
package test0352; public class Test2 { void m1(final int a, final int[] b) { } void m(final int a, final int b[]) { } }
12.636364
41
0.561151
69e6ec4890b08e3d245b0f6fc36bf597efb460f4
3,085
package ru.job4j.io; import org.junit.Test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Created on 11.12.17. * Testing external sort. * * @author Wamdue * @version 1.0 */ public class FileEntrySortTest { /** * Testing. * Have file with lines: * one * two * three * four * five * six * seven * eight * nine * ten * * Making external sort, and expect file with lines: * one * two * six * ten * four * five * nine * three * seven * eight */ @Test public void whenHaveUnsortedFileThenSortIt() { File temp = null; File target = null; try { temp = File.createTempFile("temp", "tmp"); target = File.createTempFile("target", ""); this.fillTemp(temp); FileEntrySort sort = new FileEntrySort(); sort.sort(temp, target); String expected = this.expectedFile(); try (FileReader reader = new FileReader(target); BufferedReader bufferedReader = new BufferedReader(reader)) { StringBuilder targ = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { targ.append(line); } assertThat(targ.toString(), is(expected)); } } catch (IOException e) { e.printStackTrace(); } } /** * Fill file with data. * @param f - file to fill. */ private void fillTemp(File f) { try (FileWriter writer = new FileWriter(f); BufferedWriter out = new BufferedWriter(writer)) { out.write("one"); out.newLine(); out.write("two"); out.newLine(); out.write("three"); out.newLine(); out.write("four"); out.newLine(); out.write("five"); out.newLine(); out.write("six"); out.newLine(); out.write("seven"); out.newLine(); out.write("eight"); out.newLine(); out.write("nine"); out.newLine(); out.write("ten"); out.newLine(); } catch (IOException e) { e.printStackTrace(); } } /** * Fill expected String for testing. * @return - expecting string. */ private String expectedFile() { StringBuilder sb = new StringBuilder(); sb.append("one"); sb.append("two"); sb.append("six"); sb.append("ten"); sb.append("four"); sb.append("five"); sb.append("nine"); sb.append("three"); sb.append("seven"); sb.append("eight"); return sb.toString(); } }
24.68
78
0.5047
d3c50800111b7bcda8c3894f84fea8afdb1ed8e1
3,358
/* * 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.samza.container.grouper.stream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.samza.SamzaException; import org.apache.samza.config.Config; import org.apache.samza.config.ConfigException; import org.apache.samza.config.JobConfig; import org.apache.samza.config.TaskConfigJava; import org.apache.samza.container.TaskName; import org.apache.samza.system.SystemStreamPartition; /** * AllSspToSingleTaskGrouper creates TaskInstances equal to the number of containers and assigns all partitions to be * consumed by each TaskInstance. This is useful, in case of using load-balanced consumers like the high-level Kafka * consumer and Kinesis consumer, where Samza doesn't control the partitions being consumed by the task. * * Note that this grouper does not take in broadcast streams yet. */ class AllSspToSingleTaskGrouper implements SystemStreamPartitionGrouper { private final List<String> processorList; public AllSspToSingleTaskGrouper(List<String> processorList) { this.processorList = processorList; } @Override public Map<TaskName, Set<SystemStreamPartition>> group(final Set<SystemStreamPartition> ssps) { Map<TaskName, Set<SystemStreamPartition>> groupedMap = new HashMap<>(); if (ssps == null) { throw new SamzaException("ssp set cannot be null!"); } if (ssps.size() == 0) { throw new SamzaException("Cannot process stream task with no input system stream partitions"); } processorList.forEach(processor -> { // Create a task name for each processor and assign all partitions to each task name. final TaskName taskName = new TaskName(String.format("Task-%s", processor)); groupedMap.put(taskName, ssps); }); return groupedMap; } } public class AllSspToSingleTaskGrouperFactory implements SystemStreamPartitionGrouperFactory { @Override public SystemStreamPartitionGrouper getSystemStreamPartitionGrouper(Config config) { if (!(new TaskConfigJava(config).getBroadcastSystemStreams().isEmpty())) { throw new ConfigException("The job configured with AllSspToSingleTaskGrouper cannot have broadcast streams."); } String processors = config.get(JobConfig.PROCESSOR_LIST()); List<String> processorList = Arrays.asList(processors.split(",")); if (processorList.isEmpty()) { throw new SamzaException("processor list cannot be empty!"); } return new AllSspToSingleTaskGrouper(processorList); } }
38.597701
117
0.756105
68f6e09ad974e1403124d1d76f3daadf519f0c5d
2,044
/* * 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.tomitribe.firedrill.rs; import org.tomitribe.crest.api.Options; import org.tomitribe.util.IO; import javax.ws.rs.core.Response; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.io.File; import java.io.IOException; import java.util.function.Function; import java.util.stream.Stream; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "disk-clear") @Options public class DiskClear implements Function<Response.ResponseBuilder, Response.ResponseBuilder> { public DiskClear() { } public boolean matches(File file) { final String name = file.getName(); return name.startsWith("firedrill-") && name.endsWith(".bytes"); } @Override public Response.ResponseBuilder apply(Response.ResponseBuilder responseBuilder) { try { final File tempFile = File.createTempFile("firedrill-", ".bytes"); Stream.of(tempFile.getParentFile().listFiles()) .filter(this::matches) .forEach(IO::delete); } catch (IOException e) { e.printStackTrace(); } return responseBuilder; } }
35.241379
96
0.716243
7d4180906ac045afe2a9aa8509c91e23e81c9fed
11,854
package jk.core.excel.parse.base; import jk.core.ex.ConvertDataException; import jk.core.ex.ParseHeaderException; import jk.core.util.RegExpUtil; import jk.core.util.Utils; import l.jk.json.JSONObject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.*; /** * <p> * Title: [子系统名称]_[模块名] * </p> * <p> * Description: [描述该类概要功能介绍] * </p> * * @file: ExcelUtil.java * @author: liguohui [email protected] * @version: v1.0 */ public class ParserUtil { public static final Logger logger = LogManager.getLogger(ParserUtil.class); public static synchronized void parseHeader(String sheetName, ParseInfo info, List<String> list) { int len = 0; resetHeaderList(info,sheetName); if (info.isNoHeader()) { if (info.getHeaders() == null) { info.setHeaders(new ArrayList<Header>()); len = list.size(); } else if (list.size() > info.getHeaders().size()) { len = list.size() - info.getHeaders().size(); } while (len > 0) { int size = info.getHeaders().size() + 1; Header h = new Header(String.valueOf(size), null, size); h.setMatcher(true); info.getHeaders().add(h); len--; } } else { if(info.getHeaders() == null || info.getHeaders().size() == 0){ return; } for (String excelName : list) { if (excelName == null) { len++; continue; } excelName = clearName(excelName); for (Header h : info.getHeaders()) { if(isMappingHeader(excelName,h,info.isParseUnit())){ h.setIndex(len); h.setMatcher(true); break; } // if (excelName.equals(h.getExcelName())) { // // } } len++; } } } /** * 判断头部,同时找出单位,并设置为header * @param excelName * @param header * @param parseUnit * @return */ private static boolean isMappingHeader(String excelName, Header header, boolean parseUnit) { if(excelName.equals(header.getExcelName())){ return true; } if(header.getExcelName() == null || header.getExcelName().length() == 0){ return false; } if(parseUnit){ //去掉excel的单位的name HeaderUnit _excelUnit = getExcelName(excelName); if(_excelUnit.name == null || _excelUnit.name.length() == 0){ return false; } //如果_excelName为空,则说明整个excel的头部名称只有单位,不做处理,当做异常数据 if(_excelUnit.name.equals(header.getExcelName())){ header.setUnit(_excelUnit.unit); return true; } //去掉header的单位与excel去掉单位的name进行比对 HeaderUnit headerExcelUnit = getExcelName(header.getExcelName()); if(headerExcelUnit.name == null || headerExcelUnit.name.length() == 0){ return false; } //就近原则,如果header mapping上有单位且excel头有单位,则以excel头单位为准 if(_excelUnit.name.equals(headerExcelUnit.name)){ if(_excelUnit.unit != null && _excelUnit.unit.length() > 0){ header.setUnit(_excelUnit.unit); }else { header.setUnit(headerExcelUnit.unit); } return true; } } return false; } /** * 如果有单位,则返回没有单位的列头名称,如果没有单位,则返回原始数据; * 单位只接受以)或者)结尾的表头。 * 判断单位的逻辑是:1、必须满足单位的表头格式,2、必须是在系统预设的类中存在(Units) * @param excelName * @return */ private static HeaderUnit getExcelName(String excelName) { excelName = excelName.replaceAll("(+","("); excelName = excelName.replaceAll(")+",")"); if(excelName.endsWith(")") && excelName.contains("(")){ String _excelName = excelName.substring(0,excelName.lastIndexOf("(")); String unit = excelName.substring(excelName.lastIndexOf("(")+1,excelName.length()-1); if(Units.contains(unit)){ HeaderUnit hu = new HeaderUnit(); hu.name = _excelName; hu.unit = unit; return hu; } } HeaderUnit hu = new HeaderUnit(); hu.name = excelName; return hu; } private static String clearName(String excelName) { if(excelName == null){ return excelName; } excelName = excelName.trim(); excelName = excelName.replaceAll("\\n", ""); return excelName; } private static void resetHeaderList(ParseInfo info, String sheetName) { sheetName = ParseUtils.isEmpty(sheetName) ? ParseInfo.COMMONE_SHEET_NAME : sheetName; sheetName = sheetName.trim(); sheetName = sheetName.toLowerCase(); if(info.getSheetHeaderMap().containsKey(sheetName)){ info.setHeaders(info.getSheetHeaderMap().get(sheetName)); }else if(info.getSheetHeaderMap().containsKey(ParseInfo.COMMONE_SHEET_NAME)){ //兼容未指定sheet name的header信息 info.setHeaders(info.getSheetHeaderMap().get(ParseInfo.COMMONE_SHEET_NAME)); } else{ //清空不解析的头部信息 info.setHeaders(null); } } /** * @param info */ public static void checkHeaderInfos(ParseInfo info, String sheenName) { if (info.isForceMatcher()) { List<Header> headers = info.getHeaders(); if(headers == null || headers.size() == 0){ throw new ParseHeaderException("表头信息未配置或者表头为空-->sheetName(" + sheenName + ")"); } StringBuffer buffer = new StringBuffer(); for (Header h : headers) { if (h != null && !h.isMatcher()) { buffer.append(",").append(h.getExcelName()); } } if (buffer.length() > 0) { throw new ParseHeaderException("以下表头未正确匹配-->(" + buffer.substring(1) + ")"); } } } public static Map<Integer, Header> toMap(List<Header> list) { if (list != null) { Map<Integer, Header> map = new HashMap<Integer, Header>(); for (Header h : list) { if (h != null && h.isMatcher()) { map.put(h.getIndex(), h); } } return map; } return null; } /** * <p> * Discription:[方法功能中文描述] * </p> * * @param data * @param c * @return */ public static <T> List<T> convertData(List<Map> data, Class<T> c) { if (data == null) { return null; } try { List<T> list = new ArrayList<T>(); List<Property> pros = getProperties(c); Map<String, Property> proMap = ParseUtils.listToMap(pros, "name"); for (Map map : data) { if (map != null) { // T t = c.newInstance(); // for (Iterator<String> iter = map.keySet().iterator(); iter // .hasNext();) { // String key = iter.next(); // Object val = map.get(key); // setValue(t, proMap.get(key), val); // } T t = JSONObject.toJavaObject(map,c); list.add(t); } } return list; } catch (Exception e) { throw new ConvertDataException(e.getMessage(), e); } } /** * <p> * Discription:[方法功能中文描述] * </p> * * @param property * @param val */ private static void setValue(Object obj, Property property, Object val) { if (property == null) { return; } try { Method m = obj.getClass().getMethod(property.getWriteMethod(), property.getType()); m.invoke(obj, getValueByType(property.getType(), val)); } catch (Exception e) { if (logger.isDebugEnabled()) logger.info(e.getLocalizedMessage() + "---->" + property.getName() + "[" + property.getType() + "]" + "-->value=" + val); } } private static Object getValueByType(Class<?> type, Object v) { if (v == null) { return null; } if (!(v instanceof String)) { return v; } String value = String.valueOf(v); if (type.getName().equals(Boolean.class.getName()) || type.getName().equals(boolean.class.getName())) { boolean f = value == null || "".equals(value) || "false".equals(value.toLowerCase()) || "1".equals(value) ? false : true; return f; } else if (type.getName().equals(String.class.getName())) { return value; } else if (type.getName().equals(Integer.class.getName()) || type.getName().equals(int.class.getName())) { value = RegExpUtil.removeSpecialSymbol(value); if (RegExpUtil.isInt(value)) { return Integer.parseInt(value); } return 0; } else if (type.getName().equals(Float.class.getName()) || type.getName().equals(float.class.getName())) { value = RegExpUtil.removeSpecialSymbol(value); if (RegExpUtil.isFloat(value)) { return Float.parseFloat(value); } return 0; } else if (type.getName().equals(Long.class.getName()) || type.getName().equals(long.class.getName())) { value = RegExpUtil.removeSpecialSymbol(value); if (RegExpUtil.isLong(value)) { return Long.parseLong(value); } return 0; } else if (type.getName().equals(Double.class.getName()) || type.getName().equals(double.class.getName())) { value = RegExpUtil.removeSpecialSymbol(value); if (RegExpUtil.isFloat(value)) { return Double.parseDouble(value); } return 0; } else if (type.getName().equals(Short.class.getName()) || type.getName().equals(short.class.getName())) { value = RegExpUtil.removeSpecialSymbol(value); if (RegExpUtil.isShort(value)) { return Short.parseShort(value); } return (short) 0; } else if (type.getName().equals(Date.class.getName())) { if (RegExpUtil.isDate(value)) { Date date = parseDate(value); return date; } return value; } else if (type.getName().equals(java.sql.Date.class.getName())) { if (RegExpUtil.isDate(value)) { Date date = parseDate(value); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); return sqlDate; } return value; } else if (type.getName().equals(BigDecimal.class.getName())) { value = RegExpUtil.removeSpecialSymbol(value); if (RegExpUtil.isNumber(value)) { return new BigDecimal(value); } return value; } return null; } /** * <p> * Discription:转换字符串为日期对象 * </p> * * @param dateStr * 日期字符串 * 支持 * yyyy-MM-dd HH:mm:ss, yyyy-MM-dd HH:mm, yyyy-MM-dd 格式字符串时间 * @return */ public static Date parseDate(String dateStr) { String[] formats = new String[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd" }; if (!Utils.isEmpty(dateStr)) { Date date = null; for (String s : formats) { try { SimpleDateFormat format = new SimpleDateFormat(s); date = format.parse(dateStr); } catch (Exception e) { } if (date != null) { return date; } } return null; } return null; } public static String formatDate(Date date){ String[] formats = new String[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd" }; if (!Utils.isEmpty(date)) { String rs = null; for (String s : formats) { try { SimpleDateFormat format = new SimpleDateFormat(s); rs = format.format(date); } catch (Exception e) { } if (rs != null) { return rs; } } return null; } return null; } public static List<Property> getProperties(Class c) { List<Property> pros = new ArrayList<Property>(); find(pros, c); return pros; } /** * <p> * Discription:[方法功能中文描述] * </p> * * @param pros * @param c */ private static void find(List<Property> pros, Class c) { Field[] fields = c.getDeclaredFields(); for (Field f : fields) { if (Modifier.isFinal(f.getModifiers()) || Modifier.isStatic(f.getModifiers()) || "fields".equals(f.getName())) { continue; } Property p = new Property(); p.setName(f.getName()); p.setType(f.getType()); String read = ""; String write = ""; if (f.getType() == Boolean.class || f.getType() == boolean.class) { write = "is" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1); } else { write = "set" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1); } read = "get" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1); p.setReadMethod(read); p.setWriteMethod(write); pros.add(p); } if (c.getSuperclass() != Object.class) { find(pros, c.getSuperclass()); } } public static void main(String[] args) { System.out.println("123 \n 1456 \n789".replaceAll("\\n", "")); } } class HeaderUnit{ public String name; public String unit; }
25.995614
93
0.628649
80df1975c14594428da4af0159414b2750104c64
2,419
package aggrathon.agendaonce; import android.Manifest; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.ContentUris; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.provider.CalendarContract; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ListView; public class AgendaActivity extends AppCompatActivity { public static int CALENDAR_READ_PERMISSION = 13249; ListView listAgenda; AgendaListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.agenda_activity); listAgenda = findViewById(R.id.agenda_list); adapter = new AgendaListAdapter(this); listAgenda.setAdapter(adapter); } @Override protected void onResume() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED) { adapter.RefreshEvents(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALENDAR}, CALENDAR_READ_PERMISSION); } super.onResume(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == CALENDAR_READ_PERMISSION) { adapter.RefreshEvents(); AppWidgetManager mgr = AppWidgetManager.getInstance(this); int[] ids = mgr.getAppWidgetIds(new ComponentName(getApplication(), AgendaWidget.class)); mgr.notifyAppWidgetViewDataChanged(ids, R.id.agenda_list); } else super.onRequestPermissionsResult(requestCode, permissions, grantResults); } public void OnCalendar(View v) { startActivity(OpenCalendarIntent()); } public static Intent OpenCalendarIntent() { Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon(); builder.appendPath("time"); ContentUris.appendId(builder, System.currentTimeMillis()); return new Intent(Intent.ACTION_VIEW).setData(builder.build()); } public static Intent OpenEventIntent(long id) { Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id); return new Intent(Intent.ACTION_VIEW).setData(uri); } }
33.136986
120
0.796197
78d8570ec61b5309908e7709008e117c3529157a
247
package edu.ccsu.cs417.exceptiondemo; /** * Exception representing that B should never be zero * @author Chad Williams */ public class BZeroException extends Exception{ private static final long serialVersionUID = -6584365451451687134L; }
24.7
71
0.777328
22254f4be2d1a1dbbad17b9256c054811a0fb9fe
1,309
/* * Copyright 2014-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spectator.log4j; import org.apache.log4j.Level; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class LevelTagTest { @Test public void levels() { Level[] levels = { Level.OFF, Level.FATAL, Level.ERROR, Level.WARN, Level.INFO, Level.DEBUG, Level.TRACE, Level.ALL }; for (Level level : levels) { Assertions.assertEquals(level, LevelTag.get(level).standardLevel()); } } @Test public void values() { for (LevelTag tag : LevelTag.values()) { String v = tag.ordinal() + "_" + tag.name(); Assertions.assertEquals(v, tag.value()); } } }
26.18
75
0.663102
97da484037d281b3f4680311a9ee3d4f6591b9e3
5,385
package com.episode6.hackit.disposable; import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * Utility class containing static methods to create Disposables. */ public class Disposables { /** * Create a new {@link DisposableManager} to manage disposables created by your component. * @param prefillDisposables An disposables to prepopulate the disposable manager with * @return the new {@link DisposableManager} */ public static DisposableManager newManager(Disposable... prefillDisposables) { return new BasicDisposableManager(prefillDisposables.length > 0 ? Arrays.asList(prefillDisposables) : null); } /** * Create a {@link CheckedDisposable} from a simple {@link Disposable}. If the provided * disposable already implements {@link CheckedDisposable}, it will be returned directly. * Otherwise it will be wrapped in a CheckedDisposable and the underlying dispose method is * guaranteed to be called only once. * @param disposable The {@link Disposable} to wrap * @return A {@link CheckedDisposable} wrapping the supplied disposable. */ public static CheckedDisposable checked(Disposable disposable) { if (disposable instanceof CheckedDisposable) { return (CheckedDisposable) disposable; } return new SimpleCheckedDisposable(disposable); } /** * Create a {@link CheckedDisposable} that holds a {@link WeakReference} to the supplied instance * instead of a strong one. Calls to {@link CheckedDisposable#isDisposed()} will check to see if * the reference still exists. Calls to {@link Disposable#dispose()} will clear the weak reference * after executing your {@link Disposer} (assuming the reference still exists) * * @param instance The object that needs disposal (will be weakly referenced) * @param disposer The {@link Disposer} that can perform disposal on the provided instance * @param <T> The type of object being disposed. * @return A new {@link CheckedDisposable} that hold a {@link WeakReference} to the supplied instance. */ public static <T> CheckedDisposable weak(T instance, Disposer<T> disposer) { return new WeakDisposableComponents<T>( instance, disposer); } /** * Creates a {@link DisposableRunnable} out of the provided {@link Runnable}. The resulting * DisposableRunnable will only allow its delegate to execute once before marking itself disposed. * If the runnable is disposed before being executed, the delegate singleUseRunnable will not * execute at all. * * If the provided runnable implements Disposable, its dispose/isDisposed methods will NOT be passed on. * * @param runnable The {@link Runnable} to wrap as a disposable. * @return A new {@link DisposableRunnable} */ public static DisposableRunnable singleUseRunnable(Runnable runnable) { return new SingleUseRunnable(runnable); } private static class WeakDisposableComponents<V> implements CheckedDisposable { final WeakReference<V> instanceRef; final Disposer<V> disposer; WeakDisposableComponents( V instance, Disposer<V> disposer) { this.instanceRef = new WeakReference<V>(instance); this.disposer = disposer; } @Override public boolean isDisposed() { return MaybeDisposables.isDisposed(instanceRef.get(), disposer); } @Override public void dispose() { MaybeDisposables.dispose(instanceRef.get(), disposer); instanceRef.clear(); } } private static class SingleUseRunnable extends AbstractDelegateDisposable<Runnable> implements DisposableRunnable { SingleUseRunnable(Runnable delegate) { super(delegate); } @Override public void run() { final Runnable delegate = markDisposed(); if (delegate != null) { delegate.run(); } } @Override public void dispose() { markDisposed(); } @Override public boolean isDisposed() { return getDelegateOrNull() == null; } } private static class BasicDisposableManager extends AbstractDelegateDisposable<List<Disposable>> implements DisposableManager { BasicDisposableManager(@Nullable Collection<Disposable> prefill) { super(prefill == null ? new LinkedList<Disposable>() : new LinkedList<Disposable>(prefill)); } @Override public void addDisposable(Disposable disposable) { synchronized (this) { getDelegateOrThrow().add(disposable); } } @Override public boolean flushDisposed() { if (isMarkedDisposed()) { return true; } synchronized (this) { MaybeDisposables.flushList(getDelegateOrNull()); return isMarkedDisposed(); } } @Override public void dispose() { MaybeDisposables.disposeList(markDisposed()); } } private static class SimpleCheckedDisposable extends AbstractDelegateDisposable<Disposable> implements CheckedDisposable { public SimpleCheckedDisposable(Disposable delegate) { super(delegate); } @Override public void dispose() { MaybeDisposables.dispose(markDisposed()); } @Override public boolean isDisposed() { return MaybeDisposables.isDisposed(getDelegateOrNull()); } } }
32.245509
129
0.709378
3d3f2c502f44bc83c105b4ba54efd3b7286f2c60
1,659
package clustercamp.gateway; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.util.concurrent.TimeUnit; @Slf4j @Getter public class ThrottleGatewayFilter implements GatewayFilter { int capacity; int refillTokens; int refillPeriod; TimeUnit refillUnit; public ThrottleGatewayFilter setCapacity(int capacity) { this.capacity = capacity; return this; } public ThrottleGatewayFilter setRefillTokens(int refillTokens) { this.refillTokens = refillTokens; return this; } public ThrottleGatewayFilter setRefillPeriod(int refillPeriod) { this.refillPeriod = refillPeriod; return this; } public ThrottleGatewayFilter setRefillUnit(TimeUnit refillUnit) { this.refillUnit = refillUnit; return this; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // TokenBucket tokenBucket = TokenBuckets.builder().withCapacity(capacity) // .withFixedIntervalRefillStrategy(refillTokens, refillPeriod, refillUnit) // .build(); // // // TODO: get a token bucket for a key // log.debug("TokenBucket capacity: " + tokenBucket.getCapacity()); // boolean consumed = tokenBucket.tryConsume(); // if (consumed) { // return chain.filter(exchange); // } // exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); // return exchange.getResponse().setComplete(); return null; } }
26.758065
82
0.748644
236f01c0805905fdd4586a9b27ca4f3b8a51b216
1,942
package com.ceiba.reserva.servicio; import com.ceiba.dominio.excepcion.ExcepcionSinDatos; import com.ceiba.reserva.modelo.entidad.Reserva; import com.ceiba.reserva.puerto.repositorio.RepositorioReserva; import com.ceiba.reserva.servicio.ServicioActualizarReserva; import com.ceiba.reserva.servicio.testdatabuilder.ReservaTestDataBuilder; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.verify; import java.time.LocalDate; import org.junit.Test; import org.mockito.Mockito; import com.ceiba.BasePrueba; public class ServicioActualizarReservaTest { private static final String LA_RESERVA_NO_EXISTE_EN_EL_SISTEMA = "La reserva no existe en el sistema"; @Test public void devolverPeliculaTest() { // arrange Reserva reserva = new ReservaTestDataBuilder().conId(1L).build(); LocalDate fechaDeEntregaActualizada = reserva.getFechaDeEntrega().plusDays(1); RepositorioReserva repositorioReserva = Mockito.mock(RepositorioReserva.class); ServicioActualizarReserva servicioActualizarReserva = new ServicioActualizarReserva(repositorioReserva); Mockito.when(repositorioReserva.existe(Mockito.anyLong())).thenReturn(true); ; // act reserva.setFechaDeEntrega(fechaDeEntregaActualizada); servicioActualizarReserva.ejecutar(reserva); // assert verify(repositorioReserva, atLeast(1)).actualizar(reserva); ; } @Test public void actualizarReservaQueNoExisteTest() { // arrange Reserva reserva = new ReservaTestDataBuilder().conId(1L).build(); RepositorioReserva repositorioReserva = Mockito.mock(RepositorioReserva.class); ServicioActualizarReserva servicioActualizarReserva = new ServicioActualizarReserva(repositorioReserva); Mockito.when(repositorioReserva.existe(Mockito.anyLong())).thenReturn(false); // act - assert BasePrueba.assertThrows(() -> servicioActualizarReserva.ejecutar(reserva), ExcepcionSinDatos.class, LA_RESERVA_NO_EXISTE_EN_EL_SISTEMA); } }
32.366667
106
0.81102
badfbb24231279e50fa02b13a9995151c428c3d3
28,163
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.data.tables; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; import com.azure.core.credential.AzureNamedKeyCredential; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpResponse; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.data.tables.implementation.TableUtils; import com.azure.data.tables.implementation.models.ResponseFormat; import com.azure.data.tables.implementation.models.TableProperties; import com.azure.data.tables.models.ListTablesOptions; import com.azure.data.tables.models.TableItem; import com.azure.data.tables.models.TableServiceException; import com.azure.data.tables.models.TableServiceProperties; import com.azure.data.tables.models.TableServiceStatistics; import com.azure.data.tables.sas.TableAccountSasSignatureValues; import reactor.core.publisher.Mono; import java.time.Duration; import static com.azure.core.util.FluxUtil.monoError; import static com.azure.data.tables.implementation.TableUtils.blockWithOptionalTimeout; /** * Provides a synchronous service client for accessing the Azure Tables service. * * <p>The client encapsulates the URL for the Tables service endpoint and the credentials for accessing the storage or * CosmosDB table API account. It provides methods to create, delete, and list tables within the account. These methods * invoke REST API operations to make the requests and obtain the results that are returned.</p> * * <p>Instances of this client are obtained by calling the {@link TableServiceClientBuilder#buildClient()} method on a * {@link TableServiceClientBuilder} object.</p> * * <p><strong>Samples to construct a sync client</strong></p> * <!-- src_embed com.azure.data.tables.tableServiceClient.instantiation --> * <pre> * TableServiceClient tableServiceClient = new TableServiceClientBuilder&#40;&#41; * .endpoint&#40;&quot;https:&#47;&#47;myvault.azure.net&#47;&quot;&#41; * .credential&#40;new AzureNamedKeyCredential&#40;&quot;name&quot;, &quot;key&quot;&#41;&#41; * .buildClient&#40;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.instantiation --> * * @see TableServiceClientBuilder */ @ServiceClient(builder = TableServiceClientBuilder.class) public final class TableServiceClient { private final TableServiceAsyncClient client; TableServiceClient(TableServiceAsyncClient client) { this.client = client; } /** * Gets the name of the account containing the table. * * @return The name of the account containing the table. */ public String getAccountName() { return client.getAccountName(); } /** * Gets the endpoint for the Tables service. * * @return The endpoint for the Tables service. */ public String getServiceEndpoint() { return client.getServiceEndpoint(); } /** * Gets the REST API version used by this client. * * @return The REST API version used by this client. */ public TableServiceVersion getServiceVersion() { return client.getServiceVersion(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return This client's {@link HttpPipeline}. */ HttpPipeline getHttpPipeline() { return client.getHttpPipeline(); } /** * Generates an account SAS for the Azure Storage account using the specified * {@link TableAccountSasSignatureValues}. * * <p><strong>Note:</strong> The client must be authenticated via {@link AzureNamedKeyCredential}.</p> * <p>See {@link TableAccountSasSignatureValues} for more information on how to construct an account SAS.</p> * * @param tableAccountSasSignatureValues {@link TableAccountSasSignatureValues}. * * @return A {@code String} representing the SAS query parameters. * * @throws IllegalStateException If this {@link TableClient} is not authenticated with an * {@link AzureNamedKeyCredential}. */ public String generateAccountSas(TableAccountSasSignatureValues tableAccountSasSignatureValues) { return client.generateAccountSas(tableAccountSasSignatureValues); } /** * Gets a {@link TableClient} instance for the table in the account with the provided {@code tableName}. * * @param tableName The name of the table. * * @return A {@link TableClient} instance for the table in the account with the provided {@code tableName}. * * @throws IllegalArgumentException If {@code tableName} is {@code null} or empty. */ public TableClient getTableClient(String tableName) { return new TableClient(client.getTableClient(tableName)); } /** * Creates a table within the Tables service. * * <p><strong>Code Samples</strong></p> * <p>Creates a table. Prints out the details of the created table.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.createTable#String --> * <pre> * TableClient tableClient = tableServiceClient.createTable&#40;&quot;myTable&quot;&#41;; * * System.out.printf&#40;&quot;Table with name '%s' was created.&quot;, tableClient.getTableName&#40;&#41;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.createTable#String --> * * @param tableName The name of the table to create. * * @return A {@link TableClient} for the created table. * * @throws IllegalArgumentException If {@code tableName} is {@code null} or empty. * @throws TableServiceException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public TableClient createTable(String tableName) { return createTableWithResponse(tableName, null, null).getValue(); } /** * Creates a table within the Tables service. * * <p><strong>Code Samples</strong></p> * <p>Creates a table. Prints out the details of the {@link Response HTTP response} and the created table.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.createTableWithResponse#String-Duration-Context --> * <pre> * Response&lt;TableClient&gt; response = tableServiceClient.createTableWithResponse&#40;&quot;myTable&quot;, Duration.ofSeconds&#40;5&#41;, * new Context&#40;&quot;key1&quot;, &quot;value1&quot;&#41;&#41;; * * System.out.printf&#40;&quot;Response successful with status code: %d. Table with name '%s' was created.&quot;, * response.getStatusCode&#40;&#41;, response.getValue&#40;&#41;.getTableName&#40;&#41;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.createTableWithResponse#String-Duration-Context --> * * @param tableName The name of the table to create. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline HTTP pipeline} during * the service call. * * @return The {@link Response HTTP response} containing a {@link TableClient} for the created table. * * @throws IllegalArgumentException If {@code tableName} is {@code null} or empty. * @throws TableServiceException If a table with the same name already exists within the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<TableClient> createTableWithResponse(String tableName, Duration timeout, Context context) { return blockWithOptionalTimeout(createTableWithResponse(tableName, context), timeout); } Mono<Response<TableClient>> createTableWithResponse(String tableName, Context context) { context = context == null ? Context.NONE : context; final TableProperties properties = new TableProperties().setTableName(tableName); try { return client.getImplementation().getTables().createWithResponseAsync(properties, null, ResponseFormat.RETURN_NO_CONTENT, null, context) .onErrorMap(TableUtils::mapThrowableToTableServiceException) .map(response -> new SimpleResponse<>(response, getTableClient(tableName))); } catch (RuntimeException ex) { return monoError(client.getLogger(), ex); } } /** * Creates a table within the Tables service if the table does not already exist. * * <p><strong>Code Samples</strong></p> * <p>Creates a table if it does not already exist. Prints out the details of the created table.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.createTableIfNotExists#String --> * <pre> * TableClient tableClient = tableServiceClient.createTableIfNotExists&#40;&quot;myTable&quot;&#41;; * * System.out.printf&#40;&quot;Table with name '%s' was created.&quot;, tableClient.getTableName&#40;&#41;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.createTableIfNotExists#String --> * * @param tableName The name of the table to create. * * @return A {@link TableClient} for the created table. * * @throws IllegalArgumentException If {@code tableName} is {@code null} or empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public TableClient createTableIfNotExists(String tableName) { return createTableIfNotExistsWithResponse(tableName, null, null).getValue(); } /** * Creates a table within the Tables service if the table does not already exist. * * <p><strong>Code Samples</strong></p> * <p>Creates a table if it does not already exist. Prints out the details of the {@link Response HTTP response} * and the created table.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.createTableIfNotExistsWithResponse#String-Duration-Context --> * <pre> * Response&lt;TableClient&gt; response = * tableServiceClient.createTableIfNotExistsWithResponse&#40;&quot;myTable&quot;, Duration.ofSeconds&#40;5&#41;, * new Context&#40;&quot;key1&quot;, &quot;value1&quot;&#41;&#41;; * * System.out.printf&#40;&quot;Response successful with status code: %d. Table with name '%s' was created.&quot;, * response.getStatusCode&#40;&#41;, response.getValue&#40;&#41;.getTableName&#40;&#41;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.createTableIfNotExistsWithResponse#String-Duration-Context --> * * @param tableName The name of the table to create. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline HTTP pipeline} during * the service call. * * @return The {@link Response HTTP response} containing a {@link TableClient} for the created table. * * @throws IllegalArgumentException If {@code tableName} is {@code null} or empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<TableClient> createTableIfNotExistsWithResponse(String tableName, Duration timeout, Context context) { return blockWithOptionalTimeout(createTableIfNotExistsWithResponse(tableName, context), timeout); } Mono<Response<TableClient>> createTableIfNotExistsWithResponse(String tableName, Context context) { return createTableWithResponse(tableName, context).onErrorResume(e -> e instanceof TableServiceException && ((TableServiceException) e).getResponse() != null && ((TableServiceException) e).getResponse().getStatusCode() == 409, e -> { HttpResponse response = ((TableServiceException) e).getResponse(); return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); }); } /** * Deletes a table within the Tables service. * * <p><strong>Code Samples</strong></p> * <p>Deletes a table.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.deleteTable#String --> * <pre> * String tableName = &quot;myTable&quot;; * * tableServiceClient.deleteTable&#40;tableName&#41;; * * System.out.printf&#40;&quot;Table with name '%s' was deleted.&quot;, tableName&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.deleteTable#String --> * * @param tableName The name of the table to delete. * * @throws IllegalArgumentException If {@code tableName} is {@code null} or empty. * @throws TableServiceException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public void deleteTable(String tableName) { client.deleteTable(tableName).block(); } /** * Deletes a table within the Tables service. * * <p><strong>Code Samples</strong></p> * <p>Deletes a table. Prints out the details of the {@link Response HTTP response}.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.deleteTableWithResponse#String-Duration-Context --> * <pre> * String myTableName = &quot;myTable&quot;; * * Response&lt;Void&gt; response = tableServiceClient.deleteTableWithResponse&#40;myTableName, Duration.ofSeconds&#40;5&#41;, * new Context&#40;&quot;key1&quot;, &quot;value1&quot;&#41;&#41;; * * System.out.printf&#40;&quot;Response successful with status code: %d. Table with name '%s' was deleted.&quot;, * response.getStatusCode&#40;&#41;, myTableName&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.deleteTableWithResponse#String-Duration-Context --> * * @param tableName The name of the table to delete. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline HTTP pipeline} during * the service call. * * @return The {@link Response HTTP response}. * * @throws IllegalArgumentException If {@code tableName} is {@code null} or empty. * @throws TableServiceException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> deleteTableWithResponse(String tableName, Duration timeout, Context context) { return blockWithOptionalTimeout(client.deleteTableWithResponse(tableName, context), timeout); } /** * Lists all tables within the account. * * <p><strong>Code Samples</strong></p> * <p>Lists all tables. Prints out the details of the retrieved tables.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.listTables --> * <pre> * PagedIterable&lt;TableItem&gt; tableItems = tableServiceClient.listTables&#40;&#41;; * * tableItems.forEach&#40;tableItem -&gt; * System.out.printf&#40;&quot;Retrieved table with name '%s'.%n&quot;, tableItem.getName&#40;&#41;&#41;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.listTables --> * * @return A {@link PagedIterable} containing all tables within the account. * * @throws TableServiceException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<TableItem> listTables() { return new PagedIterable<>(client.listTables()); } /** * If the {@code filter} parameter in the options is set, only tables matching the filter will be returned. If the * {@code top} parameter is set, the maximum number of returned tables per page will be limited to that value. * * <p><strong>Code Samples</strong></p> * <p>Lists all tables that match the filter. Prints out the details of the retrieved tables.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.listTables#ListTablesOptions-Duration-Context --> * <pre> * ListTablesOptions options = new ListTablesOptions&#40;&#41;.setFilter&#40;&quot;TableName eq 'myTable'&quot;&#41;; * * PagedIterable&lt;TableItem&gt; retrievedTableItems = tableServiceClient.listTables&#40;options, Duration.ofSeconds&#40;5&#41;, * new Context&#40;&quot;key1&quot;, &quot;value1&quot;&#41;&#41;; * * retrievedTableItems.forEach&#40;tableItem -&gt; * System.out.printf&#40;&quot;Retrieved table with name '%s'.%n&quot;, tableItem.getName&#40;&#41;&#41;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.listTables#ListTablesOptions-Duration-Context --> * * @param options The {@code filter} and {@code top} OData query options to apply to this operation. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline HTTP pipeline} during * the service call. * * @return A {@link PagedIterable} containing matching tables within the account. * * @throws IllegalArgumentException If one or more of the OData query options in {@code options} is malformed. * @throws TableServiceException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<TableItem> listTables(ListTablesOptions options, Duration timeout, Context context) { return new PagedIterable<>(client.listTables(options, context, timeout)); } /** * Gets the properties of the account's Table service, including properties for Analytics and CORS (Cross-Origin * Resource Sharing) rules. * * <p>This operation is only supported on Azure Storage endpoints.</p> * * <p><strong>Code Samples</strong></p> * <p>Gets the properties of the account's Table service.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.getProperties --> * <pre> * TableServiceProperties properties = tableServiceClient.getProperties&#40;&#41;; * * System.out.print&#40;&quot;Retrieved service properties successfully.&quot;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.getProperties --> * * @return The {@link TableServiceProperties properties} of the account's Table service. * * @throws TableServiceException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public TableServiceProperties getProperties() { return client.getProperties().block(); } /** * Gets the properties of the account's Table service, including properties for Analytics and CORS (Cross-Origin * Resource Sharing) rules. * * <p>This operation is only supported on Azure Storage endpoints.</p> * * <p><strong>Code Samples</strong></p> * <p>Gets the properties of the account's Table service. Prints out the details of the * {@link Response HTTP response}.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.getPropertiesWithResponse#Duration-Context --> * <pre> * Response&lt;TableServiceProperties&gt; response = * tableServiceClient.getPropertiesWithResponse&#40;Duration.ofSeconds&#40;5&#41;, new Context&#40;&quot;key1&quot;, &quot;value1&quot;&#41;&#41;; * * System.out.printf&#40;&quot;Retrieved service properties successfully with status code: %d.&quot;, response.getStatusCode&#40;&#41;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.getPropertiesWithResponse#Duration-Context --> * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline HTTP pipeline} during * the service call. * * @return The {@link Response HTTP response} and the {@link TableServiceProperties properties} of the account's * Table service. * * @throws TableServiceException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<TableServiceProperties> getPropertiesWithResponse(Duration timeout, Context context) { return blockWithOptionalTimeout(client.getPropertiesWithResponse(context), timeout); } /** * Sets the properties of the account's Table service, including properties for Analytics and CORS (Cross-Origin * Resource Sharing) rules. * * <p>This operation is only supported on Azure Storage endpoints.</p> * * <p><strong>Code Samples</strong></p> * <p>Sets the properties of the account's Table service.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.setProperties#TableServiceProperties --> * <pre> * TableServiceProperties properties = new TableServiceProperties&#40;&#41; * .setHourMetrics&#40;new TableServiceMetrics&#40;&#41; * .setVersion&#40;&quot;1.0&quot;&#41; * .setEnabled&#40;true&#41;&#41; * .setLogging&#40;new TableServiceLogging&#40;&#41; * .setAnalyticsVersion&#40;&quot;1.0&quot;&#41; * .setReadLogged&#40;true&#41; * .setRetentionPolicy&#40;new TableServiceRetentionPolicy&#40;&#41; * .setEnabled&#40;true&#41; * .setDaysToRetain&#40;5&#41;&#41;&#41;; * * tableServiceClient.setProperties&#40;properties&#41;; * * System.out.print&#40;&quot;Set service properties successfully.&quot;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.setProperties#TableServiceProperties --> * * @param tableServiceProperties The {@link TableServiceProperties} to set. * * @throws TableServiceException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public void setProperties(TableServiceProperties tableServiceProperties) { client.setProperties(tableServiceProperties).block(); } /** * Sets the properties of an account's Table service, including properties for Analytics and CORS (Cross-Origin * Resource Sharing) rules. * * <p>This operation is only supported on Azure Storage endpoints.</p> * * <p><strong>Code Samples</strong></p> * <p>Sets the properties of the account's Table service. Prints out the details of the * {@link Response HTTP response}.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.setPropertiesWithResponse#TableServiceProperties-Duration-Context --> * <pre> * TableServiceProperties myProperties = new TableServiceProperties&#40;&#41; * .setHourMetrics&#40;new TableServiceMetrics&#40;&#41; * .setVersion&#40;&quot;1.0&quot;&#41; * .setEnabled&#40;true&#41;&#41; * .setLogging&#40;new TableServiceLogging&#40;&#41; * .setAnalyticsVersion&#40;&quot;1.0&quot;&#41; * .setReadLogged&#40;true&#41; * .setRetentionPolicy&#40;new TableServiceRetentionPolicy&#40;&#41; * .setEnabled&#40;true&#41; * .setDaysToRetain&#40;5&#41;&#41;&#41;; * * Response&lt;Void&gt; response = tableServiceClient.setPropertiesWithResponse&#40;myProperties, Duration.ofSeconds&#40;5&#41;, * new Context&#40;&quot;key1&quot;, &quot;value1&quot;&#41;&#41;; * * System.out.printf&#40;&quot;Retrieved service properties successfully with status code: %d.&quot;, response.getStatusCode&#40;&#41;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.setPropertiesWithResponse#TableServiceProperties-Duration-Context --> * * @param tableServiceProperties The {@link TableServiceProperties} to set. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline HTTP pipeline} during * the service call. * * @return The {@link Response HTTP response}. * * @throws TableServiceException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setPropertiesWithResponse(TableServiceProperties tableServiceProperties, Duration timeout, Context context) { return blockWithOptionalTimeout(client.setPropertiesWithResponse(tableServiceProperties, context), timeout); } /** * Retrieves statistics related to replication for the account's Table service. It is only available on the * secondary location endpoint when read-access geo-redundant replication is enabled for the account. * * <p>This operation is only supported on Azure Storage endpoints.</p> * * <p><strong>Code Samples</strong></p> * <p>Gets the replication statistics of the account's Table service.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.getStatistics --> * <pre> * TableServiceStatistics statistics = tableServiceClient.getStatistics&#40;&#41;; * * System.out.print&#40;&quot;Retrieved service statistics successfully.&quot;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.getStatistics --> * * @return {@link TableServiceStatistics Statistics} for the account's Table service. * * @throws TableServiceException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public TableServiceStatistics getStatistics() { return client.getStatistics().block(); } /** * Retrieves statistics related to replication for the account's Table service. It is only available on the * secondary location endpoint when read-access geo-redundant replication is enabled for the account. * * <p>This operation is only supported on Azure Storage endpoints.</p> * * <p><strong>Code Samples</strong></p> * <p>Gets the replication statistics of the account's Table service. Prints out the details of the * {@link Response HTTP response}.</p> * <!-- src_embed com.azure.data.tables.tableServiceClient.getStatisticsWithResponse#Duration-Context --> * <pre> * Response&lt;TableServiceStatistics&gt; response = tableServiceClient.getStatisticsWithResponse&#40;Duration.ofSeconds&#40;5&#41;, * new Context&#40;&quot;key1&quot;, &quot;value1&quot;&#41;&#41;; * * System.out.printf&#40;&quot;Retrieved service statistics successfully with status code: %d.&quot;, * response.getStatusCode&#40;&#41;&#41;; * </pre> * <!-- end com.azure.data.tables.tableServiceClient.getStatisticsWithResponse#Duration-Context --> * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline HTTP pipeline} during * the service call. * * @return An {@link Response HTTP response} containing {@link TableServiceStatistics statistics} for the * account's Table service. * * @throws TableServiceException If the request is rejected by the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<TableServiceStatistics> getStatisticsWithResponse(Duration timeout, Context context) { return blockWithOptionalTimeout(client.getStatisticsWithResponse(context), timeout); } }
49.236014
154
0.684551
15c8899718ead75de2311c7468c0c125ed5ffcaf
473
package com.zw.platform.util.imports.lock.dto; import com.zw.platform.util.imports.lock.ImportModule; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; /** * 进度条DTO * * @author Zhang Yanhui * @since 2020/9/14 17:16 */ @Data @NoArgsConstructor @AllArgsConstructor public class ImportProgress { private List<ProgressDTO> progress; private ImportModule module; private List<String> errors; }
16.892857
54
0.756871
741c3739b296090cbc5787e2e0d44251864bf0a2
157
class J { void foo1(String[] ss) {} String[] foo2() { return new String[]{""}; } void bar1(int[] is) {} int[] bar2() { return new int[]{0}; } }
11.214286
26
0.509554
d246229b932ee69abeaf8fdb51d9d9df11a9d505
6,081
/****************************************************************************** * Copyright 2017 The Baidu Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package com.baidu.che.codriverlauncher.ui; import com.baidu.che.codriverlauncher.R; import com.baidu.che.codriverlauncher.entity.MusicInfo; import com.baidu.che.codriverlauncher.imageloader.ImageLoader; import com.baidu.che.codriverlauncher.util.LauncherUtil; import com.baidu.che.codriverlauncher.util.LogUtil; import android.app.Fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; /** * music information fragment */ public class FeedFragment extends Fragment { public static final String TAG = "FeedFragment"; public static final String CAR_RADIO_PLAY_INFO = "baidu.car.radio.play.info"; public static final String CAR_RADIO_START_ACTION = "baidu.car.radio.action.start"; public static final String CAR_RADIO_PACKAGENAME = "com.baidu.car.radio"; private static final String CAR_RADIO_PLAY_INFO_START_ACTION = "baidu.car.radio.play.info.start"; private static final String CAR_RADIO_PLAY_INFO_PAUSE_ACTION = "baidu.car.radio.play.info.pause"; private static final String BAIDU_CAR_RADIO_INTENT_KEY = "car_radio_key"; private static final String BAIDU_CAR_RADIO_INTENT_PLAY = "car_radio_play"; private TextView mTitle; private TextView mSubTitle; private ProgressBar mProgress; private ImageView mImage; private MusicInfo mMusicInfo = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_feed, null); mTitle = (TextView) view.findViewById(R.id.feed_title); mSubTitle = (TextView) view.findViewById(R.id.feed_subtitle); mProgress = (ProgressBar) view.findViewById(android.R.id.progress); mImage = (ImageView) view.findViewById(R.id.feed_img); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(CAR_RADIO_START_ACTION); intent.putExtra(BAIDU_CAR_RADIO_INTENT_KEY, BAIDU_CAR_RADIO_INTENT_PLAY); LauncherUtil.startActivitySafely(intent); } }); IntentFilter intentFilter = new IntentFilter(CAR_RADIO_PLAY_INFO); getActivity().registerReceiver(mFeedReceiver, intentFilter); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onResume() { super.onResume(); Intent intent = new Intent(CAR_RADIO_PLAY_INFO_START_ACTION); intent.setPackage(CAR_RADIO_PACKAGENAME); getActivity().sendBroadcast(intent); updateFeedView(mMusicInfo); } @Override public void onPause() { super.onPause(); Intent intent = new Intent(CAR_RADIO_PLAY_INFO_PAUSE_ACTION); intent.setPackage(CAR_RADIO_PACKAGENAME); getActivity().sendBroadcast(intent); } @Override public void onDestroyView() { super.onDestroyView(); getActivity().unregisterReceiver(mFeedReceiver); } @Override public void onDestroy() { super.onDestroy(); } private BroadcastReceiver mFeedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mMusicInfo = parseMusicInfo(intent); updateFeedView(mMusicInfo); } }; private MusicInfo parseMusicInfo(Intent intent) { String action = intent.getAction(); if (CAR_RADIO_PLAY_INFO.equals(action)) { int duration = intent.getIntExtra("duration", Integer.MAX_VALUE); if (duration == 0) { duration = Integer.MAX_VALUE; } int currentPosition = intent.getIntExtra("currentPosition", 0); String musicId = intent.getStringExtra("musicId"); LogUtil.d(TAG, "onReceive musicId:" + musicId + " duration:" + duration + " currentPosition:" + currentPosition); if (musicId != null) { String musicName = intent.getStringExtra("musicName"); String imageUrl = intent.getStringExtra("musicPic"); String albumName = intent.getStringExtra("albumName"); LogUtil.d(TAG, "onReceive musicName:" + musicName + " albumName:" + albumName + " imageUrl:" + imageUrl); MusicInfo info = new MusicInfo(musicId, duration, currentPosition, musicName, albumName, imageUrl); return info; } } return null; } private void updateFeedView(MusicInfo info) { if (info != null) { mProgress.setProgress(info.progress * 100 / info.duration); mTitle.setText(info.musicName); mSubTitle.setText(info.albumName); ImageLoader.load(getActivity(), mImage, info.imgUrl, R.drawable.feed_default); } } }
39.487013
115
0.668147
814e66eaac83d4597176510ea728f361e9db5618
763
package net.testaholic_acme_site.repository; import net.testaholic_acme_site.domain.ThImageInput; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.*; import java.util.List; /** * Spring Data JPA repository for the ThImageInput entity. */ public interface ThImageInputRepository extends JpaRepository<ThImageInput,Long> { @Query("select thImageInput from ThImageInput thImageInput where thImageInput.user.login = ?#{principal}") List<ThImageInput> findByUserIsCurrentUser(); @Query("select thImageInput from ThImageInput thImageInput where thImageInput.user.login = ?#{principal}") Page<ThImageInput> findByUserIsCurrentUser(Pageable pageable); }
33.173913
110
0.802097
c9c175d1def18f0a036f963a9e66df17f89cda64
1,042
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ //$Id: Transaction.java 6234 2005-03-29 03:07:30Z oneovthafew $ package org.hibernate.test.cut; /** * @author Gavin King */ public class Transaction { private Long id; private String description; private MonetoryAmount value; private CompositeDateTime timestamp; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public MonetoryAmount getValue() { return value; } public void setValue(MonetoryAmount value) { this.value = value; } public CompositeDateTime getTimestamp() { return timestamp; } public void setTimestamp(CompositeDateTime timestamp) { this.timestamp = timestamp; } }
18.945455
94
0.71785
9d910dbe6491eb12dab4174fdec246598d0a6371
1,165
package ru.job4j.stream.convert; import org.junit.Test; import java.util.List; import java.util.Map; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Test. * * @author Yury Doronin ([email protected]) * @version 1.0 * @since 20.05.2019 */ public class ListToMapTest { /** * Test collect. */ @Test public void whenListThenMap() { ListToMap convertList = new ListToMap(); List<Student> students = List.of( new Student("Ivanov", 70), new Student("Petrov", 99), new Student("Harlamov", 55), new Student("Petrova", 83), new Student("Ivanova", 13) ); Map<String, Student> result = convertList.convert(students); Map<String, Student> expected = Map.of( "Ivanov", new Student("Ivanov", 70), "Petrov", new Student("Petrov", 99), "Harlamov", new Student("Harlamov", 55), "Petrova", new Student("Petrova", 83), "Ivanova", new Student("Ivanova", 13)); assertThat(result, is(expected)); } }
27.738095
68
0.561373
413684894fe5fa5a122adbdd9bc96fd9e3b42909
3,732
package com.acmerobotics.relicrecovery.opmodes; import com.acmerobotics.library.cameraoverlay.CameraStreamServer; import com.acmerobotics.relicrecovery.configuration.MatchType; import com.acmerobotics.relicrecovery.configuration.OpModeConfiguration; import com.acmerobotics.relicrecovery.subsystems.JewelSlapper; import com.acmerobotics.relicrecovery.subsystems.Robot; import com.acmerobotics.relicrecovery.vision.FixedJewelTracker; import com.acmerobotics.library.vision.VuforiaCamera; import com.acmerobotics.relicrecovery.vision.VuforiaVuMarkTracker; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; public abstract class AutoOpMode extends LinearOpMode { public static final double PICTOGRAPH_READ_TIMEOUT = 5; // seconds public static final long POLL_INTERVAL = 5; // ms public static final double LATERAL_BIAS = 1.25; // in protected Robot robot; protected VuforiaCamera camera; protected FixedJewelTracker jewelTracker; protected VuforiaVuMarkTracker vuMarkTracker; private CameraStreamServer streamServer; protected abstract void setup(); protected abstract void run(); @Override public final void runOpMode() throws InterruptedException { robot = new Robot(this); robot.drive.enablePositionEstimation(); robot.start(); streamServer = new CameraStreamServer(); camera = new VuforiaCamera(); jewelTracker = new FixedJewelTracker(); vuMarkTracker = new VuforiaVuMarkTracker(); camera.addTracker(jewelTracker); camera.addTracker(vuMarkTracker); camera.addTracker(streamServer.getTracker()); camera.initialize(); String autoTransition = robot.config.getAutoTransition(); if (!autoTransition.equals(OpModeConfiguration.NO_AUTO_TRANSITION)) { AutoTransitioner.transitionOnStop(this, autoTransition); } setup(); displayInitTelemetry(); waitForStart(); telemetry.clearAll(); telemetry.update(); streamServer.stop(); if (isStopRequested()) { return; } robot.intake.releaseBar(); run(); } private void displayInitTelemetry() { telemetry.addData("matchType", robot.config.getMatchType()); if (robot.config.getMatchType() != MatchType.PRACTICE) { telemetry.addData("matchNumber", robot.config.getMatchNumber()); } telemetry.addData("delay", robot.config.getDelay()); telemetry.addData("allianceColor", robot.config.getAllianceColor()); telemetry.addData("balancingStone", robot.config.getBalancingStone()); telemetry.addData("autoTransition", robot.config.getAutoTransition()); telemetry.update(); } protected void lowerArmAndSlapper() { if (robot.jewelSlapper.getArmPosition() == JewelSlapper.ArmPosition.DOWN) { return; } robot.jewelSlapper.setArmPosition(JewelSlapper.ArmPosition.HALFWAY); robot.sleep(0.25); robot.jewelSlapper.setSlapperPosition(JewelSlapper.SlapperPosition.CENTER); robot.sleep(0.5); robot.jewelSlapper.setArmPosition(JewelSlapper.ArmPosition.DOWN); robot.sleep(0.5); } protected void raiseArmAndSlapper() { if (robot.jewelSlapper.getArmPosition() == JewelSlapper.ArmPosition.UP) { return; } robot.jewelSlapper.setArmPosition(JewelSlapper.ArmPosition.HALFWAY); robot.sleep(0.25); robot.jewelSlapper.setSlapperPosition(JewelSlapper.SlapperPosition.STOW); robot.sleep(0.5); robot.jewelSlapper.setArmPosition(JewelSlapper.ArmPosition.UP); robot.sleep(0.25); } }
34.555556
83
0.701233
484f68db8f637a58deeb829da6a1ab2a4a29f86d
389
package com.sababado.ezdb; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by robert on 9/15/15. */ @Retention(RetentionPolicy.RUNTIME) public @interface Column { public static final String FK_COL_NAME = "___fk"; public static final String ID = "id"; String value(); boolean ignoreInQueryGenerator() default false; }
21.611111
53
0.735219