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
b44e63de496df30926fb704185c03009f9689a5c
2,562
/* * The MIT License * * Copyright (c) 2015, Delta Star Team * * 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 com.deltastar.task7.core.repository.api; import com.deltastar.task7.core.repository.domain.Customer; import java.util.List; /** * Interface for customer repository. * <p> * Delta Star Team */ public interface CustomerRepository { /** * Get customer by userName. * * @param userName the customer's userName * @return the customer with the given userName or null if no such customer */ Customer getCustomerByUserName(final String userName); Customer getCustomerBySessionToken(final String sessionToken); /** * Create a customer. * * @param customer the customer to create * @return the created customer */ Customer create(final Customer customer); /** * Update a customer. * * @param customer the customer to update. * @return the updated customer */ Customer update(Customer customer); /** * Remove a customer. * * @param customer the customer to remove */ void remove(final Customer customer); /** * find all customer * * @return all customer */ List<Customer> findAllCustomer(); List<Customer> findCustomerByUserNameOrFirstNameOrLastName(String userName, String firstName, String lastName); Customer findCustomerById(int customerId); // void customerGetCash(int customerId, long amount) throws CfsException; }
31.62963
115
0.706089
20743187800bd7d5cddf9a8b1a54fc609d9b8fca
608
package concurrency; /** * @ClassName ThreadLocalTest * @Author bin * @Date 2020/8/13 下午12:07 * @Decr TODO * 线程本地存储-测试 * @Link TODO **/ public class ThreadLocalTest implements Runnable{ private int id; public ThreadLocalTest(int id) {this.id = id;} public void run() { while (!Thread.currentThread().isInterrupted()) { ThreadLocalVarialbleHolder.increment(); System.out.println(this); Thread.yield(); } } @Override public String toString() { return "#" + id + ":" + ThreadLocalVarialbleHolder.get(); } }
20.965517
65
0.597039
d03205a8efadd0b7188a7cf391caba3fdfd59365
1,667
package io.github.malikzh.qchain.controllers; import io.github.malikzh.qchain.responses.TransactionCreateResponse; import io.github.malikzh.qchain.services.TransactionPoolService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(path = "qchain/api/v1/transactions") @RequiredArgsConstructor @Tag(name = "Transaction", description = "Методы для работы с транзакциями") public class TransactionController { final TransactionPoolService transactionPoolService; /** * Добавление транзакции в пул транзакций. * * @param xml * @return */ @PostMapping(value = "", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @Operation(tags = "transaction", summary = "Добавляет транзакцию в пул для дальнейшей обработки. " + "Транзакция - это подписанный XML (при помощи библиотеки kalkancrypt), содержащий определённые данные.") public ResponseEntity<TransactionCreateResponse> add(@RequestBody String xml) { return new ResponseEntity<>(TransactionCreateResponse.builder() .hash(transactionPoolService.add(xml)).build(), HttpStatus.CREATED); } }
43.868421
116
0.777445
41e0f03119e31f18d8445245a3b8e4349b29b4b8
18
// Horizontal, //
4.5
11
0.555556
3a6dd83e464affac6fa2e91a62f3738f4f6a1d65
1,506
package com.teamplay.core.function; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.util.Objects; @FunctionalInterface public interface Predicate<T> extends Function<T, Boolean>, java.util.function.Predicate<T> { @NotNull @Contract(pure = true) static <T> Predicate<T> from(@NotNull Function<T, Boolean> function) { return function::apply; } @NotNull @Contract(pure = true) static <T> Predicate<T> isEqual(Object targetRef) { return null == targetRef ? Objects::isNull : targetRef::equals; } @NotNull @Contract(pure = true) static <T> Predicate<T> not(@NotNull Predicate<T> target) { return target.negate(); } // Please Use When T Is Unit @Contract(pure = true) default boolean test() { return apply(); } @Override @Contract(pure = true) default boolean test(T var1) { return apply(var1); } @Override @NotNull @Contract(pure = true) Boolean apply(T var1); @NotNull @Contract(pure = true) default Predicate<T> and(@NotNull Predicate<? super T> other) { return (t) -> this.test(t) && other.test(t); } @NotNull @Contract(pure = true) default Predicate<T> negate() { return (t) -> !this.test(t); } @NotNull @Contract(pure = true) default Predicate<T> or(@NotNull Predicate<? super T> other) { return (t) -> this.test(t) || other.test(t); } }
23.904762
93
0.618858
2108ac15fe248269c8e9f340f01eb24350fc65ae
883
package br.edu.ulbra.election.candidate.client; import br.edu.ulbra.election.candidate.output.v1.PartyOutput; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @Service public class PartyClientService { private final PartyClient partyClient; @Autowired public PartyClientService(PartyClient partyClient) { this.partyClient = partyClient; } public PartyOutput getById(Long id) { return this.partyClient.getById(id); } @FeignClient(value = "party-service", url = "${url.party-service}") private interface PartyClient { @GetMapping("/v1/party/{partyId}") PartyOutput getById(@PathVariable(name = "partyId") Long partyId); } }
28.483871
68
0.793884
36df2cc460136e45cb913d2aff235ab87d142868
4,057
/* * 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.netbeans.modules.web.jsf.hints; import com.sun.source.tree.Tree; import com.sun.source.util.SourcePositions; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.api.java.source.CompilationInfo; import org.netbeans.spi.editor.hints.ErrorDescription; import org.netbeans.spi.editor.hints.ErrorDescriptionFactory; import org.netbeans.spi.editor.hints.Fix; import org.netbeans.spi.editor.hints.Severity; import org.netbeans.spi.java.hints.HintContext; /** * * @author Martin Fousek <[email protected]> */ public class JsfHintsUtils { private static final Logger LOG = Logger.getLogger(JsfHintsUtils.class.getName()); private static final String CACHED_CONTEXT = "cached-jsfProblemContext"; //NOI18N /** * Gets problem context used by standard JSF hints. * Uses cached value if found, otherwise creates a new one which stores into the CompilationInfo. * * @param context Hints API context * @return {@code JsfHintsContext} */ public static JsfHintsContext getOrCacheContext(HintContext context) { Object cached = context.getInfo().getCachedValue(CACHED_CONTEXT); if (cached == null) { LOG.log(Level.FINEST, "HintContext doesn't contain cached JsfHintsContext which is going to be created."); JsfHintsContext newContext = createJsfHintsContext(context); context.getInfo().putCachedValue(CACHED_CONTEXT, newContext, CompilationInfo.CacheClearPolicy.ON_SIGNATURE_CHANGE); return newContext; } else { LOG.log(Level.FINEST, "JsfHintsContext cached value used."); return (JsfHintsContext) cached; } } private static JsfHintsContext createJsfHintsContext(HintContext context) { return new JsfHintsContext(context.getInfo().getFileObject()); } public static ErrorDescription createProblem(Tree tree, CompilationInfo cinfo, String description, Severity severity, List<Fix> fixes) { TextSpan underlineSpan = getUnderlineSpan(cinfo, tree); return ErrorDescriptionFactory.createErrorDescription( severity, description, fixes, cinfo.getFileObject(), underlineSpan.getStartOffset(), underlineSpan.getEndOffset()); } /** * This method returns the part of the syntax tree to be highlighted. */ public static TextSpan getUnderlineSpan(CompilationInfo info, Tree tree) { SourcePositions srcPos = info.getTrees().getSourcePositions(); int startOffset = (int) srcPos.getStartPosition(info.getCompilationUnit(), tree); int endOffset = (int) srcPos.getEndPosition(info.getCompilationUnit(), tree); return new TextSpan(startOffset, endOffset); } /** * Represents a span of text. */ public static class TextSpan { private int startOffset; private int endOffset; public TextSpan(int startOffset, int endOffset) { this.startOffset = startOffset; this.endOffset = endOffset; } public int getStartOffset() { return startOffset; } public int getEndOffset() { return endOffset; } } }
38.638095
140
0.706433
5dbe02a1d9cf47b8d03659ff099aec5a9e74b394
8,205
/** * Copyright © 2013, Masih H. Derkani * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.mashti.sina.util; import org.junit.Test; import static org.junit.Assert.fail; /** * Tests {@link NumericalRangeValidator}. * * @author Masih Hajiarabderkani ([email protected]) */ public class NumericalRangeValidatorTest { /** Tests {@link NumericalRangeValidator#validateRangeLargerThanZeroInclusive(Number)}. */ @Test public void testValidateRangeLargerThanZeroInclusive() { final double[] bad_args = {Double.NEGATIVE_INFINITY, -Double.MAX_VALUE, -1.0, -100.0, Double.NaN}; for (final double arg : bad_args) { try { NumericalRangeValidator.validateRangeLargerThanZeroInclusive(arg); fail(); } catch (final IllegalArgumentException e) { continue; } } final double[] good_args = {Double.POSITIVE_INFINITY, Double.MAX_VALUE, 1.0, 100.0, -0.0, +0.0}; for (final double arg : good_args) { NumericalRangeValidator.validateRangeLargerThanZeroInclusive(arg); } } /** Tests {@link NumericalRangeValidator#validateRangeLargerThanZeroExclusive(Number)}. */ @Test public void testValidateRangeLargerThanZeroExclusive() { final double[] bad_args = {Double.NEGATIVE_INFINITY, -Double.MAX_VALUE, -1.0, -100.0, -0.0, +0.0, Double.NaN}; for (final double arg : bad_args) { try { NumericalRangeValidator.validateRangeLargerThanZeroExclusive(arg); fail(); } catch (final IllegalArgumentException e) { continue; } } final double[] good_args = {Double.POSITIVE_INFINITY, Double.MAX_VALUE, 1.0, 100.0}; for (final double arg : good_args) { NumericalRangeValidator.validateRangeLargerThanZeroExclusive(arg); } } /** Tests {@link NumericalRangeValidator#validateRangeLargerThan(Number, Number, boolean)}. */ @Test public void testValidateRangeLargerThan() { //@formatter:off final Object[][] bad_args = { {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, false}, {Double.NEGATIVE_INFINITY, Double.NaN, false}, {0.0, Double.POSITIVE_INFINITY, false}, {-100.0, 5.0, true} }; //@formatter:on for (final Object[] arg : bad_args) { try { NumericalRangeValidator.validateRangeLargerThan((Number) arg[0], (Number) arg[1], (Boolean) arg[2]); fail(); } catch (final IllegalArgumentException e) { continue; } } //@formatter:off final Object[][] good_args = { {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, true}, {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, true}, {Double.POSITIVE_INFINITY, 0.0, false}, {-5.0, -500.0, true} }; //@formatter:on for (final Object[] arg : good_args) { NumericalRangeValidator.validateRangeLargerThan((Number) arg[0], (Number) arg[1], (Boolean) arg[2]); } } /** Tests {@link NumericalRangeValidator#validateRange(Number, Number, Number, boolean, boolean)}. */ @Test public void testValidateRange() { //@formatter:off final Object[][] bad_args = { {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, false, false}, {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, false, false}, {Double.NEGATIVE_INFINITY, 10, Double.POSITIVE_INFINITY, false, false}, {Double.NaN, Double.NaN, Double.NaN, false, false}, {Double.NaN, Double.NaN, Double.NaN, true, true}, {Double.NaN, Double.NaN, Double.NaN, false, true}, {Double.NaN, Double.NaN, Double.NaN, true, false}, {0.0, 100, -100, true, false}, {-100.0, 5.0, 10, true, true} }; //@formatter:on for (final Object[] arg : bad_args) { int i; try { i = 0; NumericalRangeValidator.validateRange((Number) arg[i++], (Number) arg[i++], (Number) arg[i++], (Boolean) arg[i++], (Boolean) arg[i++]); fail(); } catch (final IllegalArgumentException e) { continue; } } //@formatter:off final Object[][] good_args = { {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, true, true}, {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, true, true}, {10, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, false, false}, {5, -9, 5, false, true}, {5, -9, 50, false, false}, {5, 5, 5, true, true} }; //@formatter:on int i; for (final Object[] arg : good_args) { i = 0; NumericalRangeValidator.validateRange((Number) arg[i++], (Number) arg[i++], (Number) arg[i++], (Boolean) arg[i++], (Boolean) arg[i++]); } } /** Tests {@link NumericalRangeValidator#validateRangeZeroToOneInclusive(Number)}. */ @Test public void testValidateRangeZeroToOneInclusive() { final double[] bad_args = {Double.NEGATIVE_INFINITY, -Double.MAX_VALUE, Double.POSITIVE_INFINITY, Double.MAX_VALUE, -1.0, -100.0, 1.000001, Double.NaN}; for (final double arg : bad_args) { try { NumericalRangeValidator.validateRangeZeroToOneInclusive(arg); fail(); } catch (final IllegalArgumentException e) { continue; } } final double[] good_args = {+0.0, -0.0, 0.999999999999999999, 1.0}; for (final double arg : good_args) { NumericalRangeValidator.validateRangeZeroToOneInclusive(arg); } } /** Tests {@link NumericalRangeValidator#validateNumber(Number...)}. */ @Test public void testValidateNumber() { try { NumericalRangeValidator.validateNumber(Double.NaN, Double.NaN, Double.NaN); fail(); } catch (final IllegalArgumentException e) { //ignore; expected } final Number[] good_args = {+0.0, -0.0, 0.999999999999999999, 1.0, Double.NEGATIVE_INFINITY, -Double.MAX_VALUE, Double.POSITIVE_INFINITY, Double.MAX_VALUE, -1.0, -100.0, 1.000001}; for (final Number arg : good_args) { NumericalRangeValidator.validateNumber(arg); } NumericalRangeValidator.validateNumber(good_args); } }
42.293814
345
0.628154
edfd0d41ab049fd1662f0783743ea1176860d571
401
package com.yuzhyn.bigbird.app.application.internal.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.yuzhyn.bigbird.app.application.internal.entity.SysFile; import com.yuzhyn.bigbird.app.application.internal.entity.SysFileDownloadLog; import org.apache.ibatis.annotations.Mapper; @Mapper public interface SysFileDownloadLogMapper extends BaseMapper<SysFileDownloadLog> { }
36.454545
82
0.852868
fe2e992dca84400528ad6fdc1032bf3813d00247
394
package com.liyongquan.math; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.*; @Slf4j public class ValidNumberTest { private ValidNumber vn = new ValidNumber(); @Test public void isNumber() { boolean res = vn.isNumber("7e69e"); log.info("{}", res); Assert.assertEquals(true, res); } }
20.736842
47
0.667513
7d0a98f2b1e5872057971be49e187334e7188cfa
241
package model.newCommands; import java.util.List; import model.commands.Command; import model.commands.SpecialCommand; public abstract class MultipleTurtleCommand extends SpecialCommand { public abstract List<Integer> getTurtleList(); }
21.909091
68
0.825726
5f2a6010e66831e9890b36ac509593b4c7faf49f
2,320
package org.agilewiki.jactor2.util.durable.incDes; import junit.framework.TestCase; import org.agilewiki.jactor2.core.facilities.Plant; import org.agilewiki.jactor2.core.reactors.NonBlockingReactor; import org.agilewiki.jactor2.core.reactors.Reactor; import org.agilewiki.jactor2.util.durable.Durables; import org.agilewiki.jactor2.util.durable.Factory; import org.agilewiki.jactor2.util.durable.FactoryLocator; public class TupleTest extends TestCase { public void test() throws Exception { final Plant plant = Durables.createPlant(); try { final FactoryLocator factoryLocator = Durables .getFactoryLocator(plant); Durables.registerTupleFactory(factoryLocator, "sst", JAString.FACTORY_NAME, JAString.FACTORY_NAME); final Factory tjf = factoryLocator.getFactory("sst"); final Reactor reactor = new NonBlockingReactor(plant); final Tuple t0 = (Tuple) tjf.newSerializable(reactor, factoryLocator); final JAString e0 = (JAString) t0.iGetReq(0).call(); assertNull(e0.getValueReq().call()); final JAString e1 = (JAString) t0.iGetReq(1).call(); assertNull(e1.getValueReq().call()); e0.setValueReq("Apples").call(); assertEquals("Apples", e0.getValueReq().call()); e1.setValueReq("Oranges").call(); assertEquals("Oranges", e1.getValueReq().call()); final Tuple t1 = (Tuple) t0.copyReq(null).call(); final JAString f0 = (JAString) t1.resolvePathnameReq("0").call(); assertEquals("Apples", f0.getValueReq().call()); final JAString f1 = (JAString) t1.resolvePathnameReq("1").call(); assertEquals("Oranges", f1.getValueReq().call()); final JAString jaString1 = (JAString) Durables.newSerializable( plant, JAString.FACTORY_NAME); jaString1.setValueReq("Peaches").call(); final byte[] sb = jaString1.getSerializedBytesReq().call(); t1.iSetReq(1, sb).call(); final JAString f1b = (JAString) t1.resolvePathnameReq("1").call(); assertEquals("Peaches", f1b.getValueReq().call()); } finally { plant.close(); } } }
46.4
78
0.630603
8c7f7b562b81084833ecfbd1a93e11cf95f299b6
5,152
/* * Copyright (c) 2016—2017 Andrei Tomashpolskiy and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package bt.data; import bt.BtException; import bt.data.digest.Digester; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.IntStream; public class DefaultChunkVerifier implements ChunkVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultChunkVerifier.class); private final Digester digester; private final int numOfHashingThreads; public DefaultChunkVerifier(Digester digester, int numOfHashingThreads) { this.digester = digester; this.numOfHashingThreads = numOfHashingThreads; } @Override public boolean verify(List<ChunkDescriptor> chunks, LocalBitfield bitfield) { if (chunks.size() != bitfield.getPiecesTotal()) { throw new IllegalArgumentException("Bitfield has different size than the list of chunks. Bitfield size: " + bitfield.getPiecesTotal() + ", number of chunks: " + chunks.size()); } collectParallel(chunks, bitfield); return bitfield.getPiecesRemaining() == 0; } @Override public boolean verify(ChunkDescriptor chunk) { byte[] expected = chunk.getChecksum(); byte[] actual = digester.digestForced(chunk.getData()); return Arrays.equals(expected, actual); } @Override public boolean verifyIfPresent(ChunkDescriptor chunk) { return verifyIfPresent(chunk, digester.createCopy()); } private static boolean verifyIfPresent(ChunkDescriptor chunk, Digester localDigester) { byte[] expected = chunk.getChecksum(); byte[] actual = localDigester.digest(chunk.getData()); return Arrays.equals(expected, actual); } private void collectParallel(List<ChunkDescriptor> chunks, LocalBitfield bitfield) { int n = numOfHashingThreads; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Verifying torrent data with {} workers", n); } if(n > 1) { ForkJoinPool pool = new ForkJoinPool(n); try { pool.submit(() -> verifyChunks(chunks, bitfield, true)).get(); } catch (Exception ex) { throw new BtException("Failed to verify torrent data:" + errorToString(ex)); } finally { pool.shutdownNow(); } } else { verifyChunks(chunks, bitfield, n < 1); } } /** * Returns the integer indices of chunks that are verified * @param chunks the chunks to verify * @param bitfield the bitfield to mark a chunk as verified * @param parallel whether to use a parallel stream */ private void verifyChunks(List<ChunkDescriptor> chunks, LocalBitfield bitfield, boolean parallel) { IntStream stream = IntStream.range(0, chunks.size()).unordered(); if (parallel) stream = stream.parallel(); final Digester localDigester = digester.createCopy(); stream.filter(i -> this.checkIfChunkVerified(chunks.get(i), localDigester)) .forEach(bitfield::markLocalPieceVerified); } private static boolean checkIfChunkVerified(ChunkDescriptor chunk, Digester localDigester) { // optimization to speedup the initial verification of torrent's data AtomicBoolean containsEmptyFile = new AtomicBoolean(false); chunk.getData().visitUnits((u, off, lim) -> { // limit of 0 means an empty file, // and we don't want to account for those if (u.size() == 0 && lim != 0) { containsEmptyFile.set(true); return false; // no need to continue } return true; }); // if any of this chunk's storage units is empty, // then the chunk is neither complete nor verified if (!containsEmptyFile.get()) { return verifyIfPresent(chunk, localDigester); } return false; } private String errorToString(Throwable e) { StringBuilder buf = new StringBuilder(); buf.append("\n"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream out = new PrintStream(bos); e.printStackTrace(out); buf.append(bos.toString()); return buf.toString(); } }
36.027972
119
0.654891
5f240f73b5be0aba6e6b3f5f47e892e21d52f945
2,315
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.util; import android.os.Debug; import android.os.StrictMode; public final class MemInfoReader { final long[] mInfos = new long[Debug.MEMINFO_COUNT]; public void readMemInfo() { // Permit disk reads here, as /proc/meminfo isn't really "on // disk" and should be fast. TODO: make BlockGuard ignore // /proc/ and /sys/ files perhaps? StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads(); try { Debug.getMemInfo(mInfos); } finally { StrictMode.setThreadPolicy(savedPolicy); } } public long getTotalSize() { return mInfos[Debug.MEMINFO_TOTAL] * 1024; } public long getFreeSize() { return mInfos[Debug.MEMINFO_FREE] * 1024; } public long getCachedSize() { return mInfos[Debug.MEMINFO_CACHED] * 1024; } public long getTotalSizeKb() { return mInfos[Debug.MEMINFO_TOTAL]; } public long getFreeSizeKb() { return mInfos[Debug.MEMINFO_FREE]; } public long getCachedSizeKb() { return mInfos[Debug.MEMINFO_CACHED]; } public long getBuffersSizeKb() { return mInfos[Debug.MEMINFO_BUFFERS]; } public long getShmemSizeKb() { return mInfos[Debug.MEMINFO_SHMEM]; } public long getSlabSizeKb() { return mInfos[Debug.MEMINFO_SLAB]; } public long getSwapTotalSizeKb() { return mInfos[Debug.MEMINFO_SWAP_TOTAL]; } public long getSwapFreeSizeKb() { return mInfos[Debug.MEMINFO_SWAP_FREE]; } public long getZramTotalSizeKb() { return mInfos[Debug.MEMINFO_ZRAM_TOTAL]; } }
27.235294
80
0.665659
b5b3ac7d15686a883fb9e59313dfa3420e1ae3bc
1,869
package com.bitprogress.discover.reactive; import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; import com.alibaba.cloud.nacos.discovery.reactive.NacosReactiveDiscoveryClientConfiguration; import com.bitprogress.discover.NacosCustomDiscoveryAutoConfiguration; import com.bitprogress.discover.NacosServiceDiscovery; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnReactiveDiscoveryEnabled; import org.springframework.cloud.client.ReactiveCommonsClientAutoConfiguration; import org.springframework.cloud.client.discovery.composite.reactive.ReactiveCompositeDiscoveryClientAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author <a href="mailto:[email protected]">echooymxq</a> **/ @Configuration(proxyBeanMethods = false) @ConditionalOnDiscoveryEnabled @ConditionalOnReactiveDiscoveryEnabled @ConditionalOnNacosDiscoveryEnabled @AutoConfigureAfter({ NacosCustomDiscoveryAutoConfiguration.class, ReactiveCompositeDiscoveryClientAutoConfiguration.class }) @AutoConfigureBefore({ ReactiveCommonsClientAutoConfiguration.class }) @EnableAutoConfiguration(exclude = {NacosReactiveDiscoveryClientConfiguration.class}) public class NacosCustomReactiveDiscoveryClientConfiguration { @Bean @ConditionalOnMissingBean public NacosReactiveDiscoveryClient nacosReactiveDiscoveryClient( NacosServiceDiscovery nacosServiceDiscovery) { return new NacosReactiveDiscoveryClient(nacosServiceDiscovery); } }
49.184211
125
0.881755
41e5b6a10d0f7ba3b33503adbc86d3f24f200187
1,443
/* * Copyright 2007 Google 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.google.classpath; import org.junit.jupiter.api.Test; import java.io.File; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; public class DirectoryClassPathTest extends ClassPathTest { @Override protected ClassPath createClassPath() { return new DirectoryClassPath(new File("test-data")); } @Test void testNonExistantDirectory() { File rootDirectory = new File("NON_EXISTENT"); DirectoryClassPath classPath = new DirectoryClassPath(rootDirectory); String[] packages = classPath.listPackages("NON_EXISTENT"); String[] resources = classPath.listResources("NON_EXISTENT"); assertAll( () -> assertThat(packages).isEmpty(), () -> assertThat(resources).isEmpty()); } }
32.066667
80
0.711019
04f5f4ff6d8b8c97b18cecea2d1a8dc5ec021d54
328
public class Main { public static void main(String[] agrs){ //instanciar objeto do tipo pessoa Pessoa p1 = new Pessoa(); p1.nome = "Fulano"; System.out.println("Nome p1: " + p1.nome); Pessoa p2 = new Pessoa("Maria"); System.out.println("Nome p2: " + p2.nome); } }
17.263158
50
0.54878
b343ffc7e9c6bc7dfa57a968475c5e98e55ca1ff
6,042
/* * 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.axis2.saaj; import org.apache.axiom.soap.SOAPFactory; import org.apache.axiom.soap.SOAPHeaderBlock; import org.apache.axiom.soap.SOAPVersion; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPHeaderElement; public class SOAPHeaderElementImpl extends SOAPElementImpl<SOAPHeaderBlock> implements SOAPHeaderElement { /** @param element */ public SOAPHeaderElementImpl(SOAPHeaderBlock element) { super(element); } /** * Sets the actor associated with this <CODE> SOAPHeaderElement</CODE> object to the specified * actor. The default value of an actor is: <CODE> SOAPConstants.URI_SOAP_ACTOR_NEXT</CODE> * * @param actorURI a <CODE>String</CODE> giving the URI of the actor to set * @throws IllegalArgumentException * if there is a problem in setting the actor. * @see #getActor() getActor() */ public void setActor(String actorURI) { this.omTarget.setRole(actorURI); } /** * Returns the uri of the actor associated with this <CODE> SOAPHeaderElement</CODE> object. * * @return a <CODE>String</CODE> giving the URI of the actor * @see #setActor(String) setActor(java.lang.String) */ public String getActor() { return this.omTarget.getRole(); } /** * Sets the mustUnderstand attribute for this <CODE> SOAPHeaderElement</CODE> object to be on or * off. * <p/> * <P>If the mustUnderstand attribute is on, the actor who receives the * <CODE>SOAPHeaderElement</CODE> must process it correctly. This ensures, for example, that if * the <CODE> SOAPHeaderElement</CODE> object modifies the message, that the message is being * modified correctly.</P> * * @param mustUnderstand <CODE>true</CODE> to set the mustUnderstand attribute on; * <CODE>false</CODE> to turn if off * @throws IllegalArgumentException * if there is a problem in setting the actor. * @see #getMustUnderstand() getMustUnderstand() */ public void setMustUnderstand(boolean mustUnderstand) { this.omTarget.setMustUnderstand(mustUnderstand); } /** * Returns whether the mustUnderstand attribute for this <CODE>SOAPHeaderElement</CODE> object * is turned on. * * @return <CODE>true</CODE> if the mustUnderstand attribute of this * <CODE>SOAPHeaderElement</CODE> object is turned on; <CODE>false</CODE> otherwise */ public boolean getMustUnderstand() { return this.omTarget.getMustUnderstand(); } /** * Sets the Role associated with this SOAPHeaderElement object to the specified Role. * * @param uri - the URI of the Role * @throws SOAPException - if there is an error in setting the role java.lang.UnsupportedOperationException * - if this message does not support the SOAP 1.2 concept of Fault Role. */ public void setRole(String uri) throws SOAPException { if (((SOAPFactory)this.omTarget.getOMFactory()).getSOAPVersion() == SOAPVersion.SOAP11) { throw new UnsupportedOperationException(); } else { this.omTarget.setRole(uri); } } public String getRole() { if (((SOAPFactory)this.omTarget.getOMFactory()).getSOAPVersion() == SOAPVersion.SOAP11) { throw new UnsupportedOperationException(); } else { return this.omTarget.getRole(); } } /** * Sets the relay attribute for this SOAPHeaderElement to be either true or false. The SOAP * relay attribute is set to true to indicate that the SOAP header block must be relayed by any * node that is targeted by the header block but not actually process it. This attribute is * ignored on header blocks whose mustUnderstand attribute is set to true or that are targeted * at the ultimate reciever (which is the default). The default value of this attribute is * false. * * @param relay - the new value of the relay attribute * @throws SOAPException - if there is a problem in setting the relay attribute. * java.lang.UnsupportedOperationException - if this message does not * support the SOAP 1.2 concept of Relay attribute. */ public void setRelay(boolean flag) throws SOAPException { if (((SOAPFactory)this.omTarget.getOMFactory()).getSOAPVersion() == SOAPVersion.SOAP11) { throw new UnsupportedOperationException(); } else { this.omTarget.setRelay(flag); } } public boolean getRelay() { if (((SOAPFactory)this.omTarget.getOMFactory()).getSOAPVersion() == SOAPVersion.SOAP11) { throw new UnsupportedOperationException(); } else { return this.omTarget.getRelay(); } } public void setParentElement(SOAPElement parent) throws SOAPException { if (!(parent instanceof SOAPHeader)) { throw new IllegalArgumentException("Parent is not a SOAPHeader"); } super.setParentElement(parent); } }
40.28
111
0.67279
7ace53e7040322df81bb94d0371c75f5e758ea9a
615
class Solution { public boolean validateStackSequences(int[] pushed, int[] popped) { Stack<Integer> st = new Stack<>(); // Create a stack int j = 0; // Intialise one pointer pointing on popped array for(int val : pushed){ st.push(val); // insert the values in stack while(!st.isEmpty() && st.peek() == popped[j]){ // if st.peek() values equal to popped[j]; st.pop(); // then pop out j++; // increment j } } return st.isEmpty(); // check if stack is empty return true else false } }
38.4375
102
0.528455
3c589e79afa94411bc0f1f1846efc1b1c7988d61
3,420
/* * 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.netbeans.modules.css.lib.api; import java.util.Collection; import java.util.List; /** * Allows to visit the css source parse trees. * * @author marekfukala */ public abstract class NodeVisitor<T> { private T result; private boolean cancelled = false; public NodeVisitor(T result) { this.result = result; } public NodeVisitor() { this(null); } /** * Performs the given node visit. * @param node * @return true if the visiting process should be interrupted */ public abstract boolean visit(Node node); public T getResult() { return result; } /** * Implementors may use this flag to possibly stop the visit(...) method * execution. The nodes recursive visiting is canceled automatically once * cancel() method is called. * * @return true if the visitor should stop performing the code. */ protected boolean isCancelled() { return cancelled; } public void cancel() { cancelled = true; } public void visitAncestors(Node node) { Node parent = node.parent(); if (parent != null) { if(isCancelled()) { return ; } if(visit(parent)) { return; //visiting stopped by the visitor } visitAncestors(parent); } } public Node visitChildren(Node node) { List<Node> children = node.children(); if (children != null) { for (Node child : children) { if(isCancelled()) { return null; } if(visit(child)) { return child; //visiting stopped by the visitor } //recursion Node breakNode = visitChildren(child); if(breakNode != null) { return breakNode; } } } return null; } public static <TE> void visitChildren(Node node, Collection<NodeVisitor<TE>> visitors) { List<Node> children = node.children(); if (children != null) { for (Node child : children) { for(NodeVisitor v : visitors) { if(v.isCancelled()) { continue; //skip the cancelled visitors } v.visit(child); } //recursion visitChildren(child, visitors); } } } }
28.5
92
0.559942
3a7438f7701f32fd4aa25d4bb5ae5012c8df8b3b
1,807
package com.melardev.android.crud.todos.list; import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.melardev.android.crud.R; import com.melardev.android.crud.common.Todo; import com.melardev.android.crud.common.TodoRepository; import com.melardev.android.crud.remote.VolleyRepository; import com.melardev.android.crud.todos.show.TodoDetailsActivity; import com.melardev.android.crud.todos.write.TodoCreateEditActivity; public class MainActivity extends AppCompatActivity implements TodoRecyclerAdapter.TodoRowEventListener { private TodoRepository todoRepository; private RecyclerView recyclerView; private TodoRecyclerAdapter todoRecyclerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.todoRepository = VolleyRepository.getInstance(); recyclerView = findViewById(R.id.rvTodos); todoRepository.getAll(todos -> todoRecyclerAdapter.setItems(todos)); todoRecyclerAdapter = new TodoRecyclerAdapter(this); recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false)); recyclerView.setAdapter(todoRecyclerAdapter); } public void createTodo(View view) { Intent intent = new Intent(this, TodoCreateEditActivity.class); startActivity(intent); } @Override public void onClicked(Todo todo) { Intent intent = new Intent(this, TodoDetailsActivity.class); intent.putExtra("TODO_ID", todo.getId()); startActivity(intent); } }
31.701754
105
0.765357
c6cc9bde776c581d5eff3e8673cb6cdbc7b1172c
758
package com.mcoding.base.auth.service; import java.util.List; import com.mcoding.base.auth.bean.Operator; import com.mcoding.base.auth.bean.OperatorExample; import com.mcoding.base.core.BaseService; import com.mcoding.base.core.PageView; /** * Created by LiBing on 2014-07-17 14:02 */ public interface OperatorService extends BaseService<Operator, OperatorExample> { PageView<Operator> queryOperatorsByPage(String menuId); List<Operator> queryOperatorsByMenuId(String menuId); void editOperatorsByMenuId(Operator operator); List<Operator> queryUserOperatorsByMenuId(String menuId, List<Integer> userRoleIds); PageView<Operator> queryRoleOperatorsByMenuId(int roleId, int menuId, List<Integer> userRoleIds); }
30.32
99
0.771768
04faa24029e85ab898d74131bc35fc2d0a50777a
4,762
package io.envoyproxy.envoymobile.engine; import java.util.List; import java.util.regex.Pattern; import java.util.regex.Matcher; import io.envoyproxy.envoymobile.engine.types.EnvoyHTTPFilterFactory; /* Typed configuration that may be used for starting Envoy. */ public class EnvoyConfiguration { public final String statsDomain; public final Integer connectTimeoutSeconds; public final Integer dnsRefreshSeconds; public final Integer dnsFailureRefreshSecondsBase; public final Integer dnsFailureRefreshSecondsMax; public final List<EnvoyHTTPFilterFactory> httpFilterFactories; public final Integer statsFlushSeconds; public final String appVersion; public final String appId; public final String virtualClusters; private static final Pattern UNRESOLVED_KEY_PATTERN = Pattern.compile("\\{\\{ (.+) \\}\\}"); /** * Create a new instance of the configuration. * * @param statsDomain the domain to flush stats to. * @param connectTimeoutSeconds timeout for new network connections to hosts in * the cluster. * @param dnsRefreshSeconds rate in seconds to refresh DNS. * @param dnsFailureRefreshSecondsBase base rate in seconds to refresh DNS on failure. * @param dnsFailureRefreshSecondsMax max rate in seconds to refresh DNS on failure. * @param statsFlushSeconds interval at which to flush Envoy stats. * @param appVersion the App Version of the App using this Envoy Client. * @param appId the App ID of the App using this Envoy Client. * @param virtualClusters the JSON list of virtual cluster configs. */ public EnvoyConfiguration(String statsDomain, int connectTimeoutSeconds, int dnsRefreshSeconds, int dnsFailureRefreshSecondsBase, int dnsFailureRefreshSecondsMax, List<EnvoyHTTPFilterFactory> httpFilterFactories, int statsFlushSeconds, String appVersion, String appId, String virtualClusters) { this.statsDomain = statsDomain; this.connectTimeoutSeconds = connectTimeoutSeconds; this.dnsRefreshSeconds = dnsRefreshSeconds; this.dnsFailureRefreshSecondsBase = dnsFailureRefreshSecondsBase; this.dnsFailureRefreshSecondsMax = dnsFailureRefreshSecondsMax; this.httpFilterFactories = httpFilterFactories; this.statsFlushSeconds = statsFlushSeconds; this.appVersion = appVersion; this.appId = appId; this.virtualClusters = virtualClusters; } /** * Resolves the provided configuration template using properties on this * configuration. * * @param templateYAML the template configuration to resolve. * @return String, the resolved template. * @throws ConfigurationException, when the template provided is not fully * resolved. */ String resolveTemplate(final String templateYAML, final String filterTemplateYAML) { final StringBuilder filterConfigBuilder = new StringBuilder(); for (EnvoyHTTPFilterFactory filterFactory : httpFilterFactories) { String filterConfig = filterTemplateYAML.replace("{{ platform_filter_name }}", filterFactory.getFilterName()); filterConfigBuilder.append(filterConfig); } String filterConfigChain = filterConfigBuilder.toString(); String resolvedConfiguration = templateYAML.replace("{{ stats_domain }}", statsDomain) .replace("{{ platform_filter_chain }}", filterConfigChain) .replace("{{ connect_timeout_seconds }}", String.format("%s", connectTimeoutSeconds)) .replace("{{ dns_refresh_rate_seconds }}", String.format("%s", dnsRefreshSeconds)) .replace("{{ dns_failure_refresh_rate_seconds_base }}", String.format("%s", dnsFailureRefreshSecondsBase)) .replace("{{ dns_failure_refresh_rate_seconds_max }}", String.format("%s", dnsFailureRefreshSecondsMax)) .replace("{{ stats_flush_interval_seconds }}", String.format("%s", statsFlushSeconds)) .replace("{{ device_os }}", "Android") .replace("{{ app_version }}", appVersion) .replace("{{ app_id }}", appId) .replace("{{ virtual_clusters }}", virtualClusters); final Matcher unresolvedKeys = UNRESOLVED_KEY_PATTERN.matcher(resolvedConfiguration); if (unresolvedKeys.find()) { throw new ConfigurationException(unresolvedKeys.group(1)); } return resolvedConfiguration; } static class ConfigurationException extends RuntimeException { ConfigurationException(String unresolvedKey) { super("Unresolved template key: " + unresolvedKey); } } }
47.62
100
0.698866
edc601f309c532a93bbde918ddfe35aa82224550
346
package com.github.combinedmq.activemq; import com.github.combinedmq.message.BaseMessage; /** * @author xiaoyu */ public class ActiveMqMessage extends BaseMessage { public ActiveMqMessage(byte[] bytes) { super(bytes); } public ActiveMqMessage(byte[] bytes, Long delayMillis) { super(bytes, delayMillis); } }
19.222222
60
0.690751
783fc7e1518169978e3691a0873773b92a36f3b9
11,959
import java.net.*; import java.io.*; import org.json.*; /** * The class CompetitionEvaluator connects the evaluation cost function of the competition to the online * server of the competition */ public class CompetitionEvaluator extends WindFarmLayoutEvaluator { protected int nScenario; // scenario id (from 0 to 4) protected String user_token; protected String run_token; public double R; // turbines size public double height; // farm height public double width; // farm width public double obstacles[][]; // rows of [xmin, ymin, xmax, ymax] protected double energyOutputs[][]; protected double energyOutput; protected double turbineFitnesses[]; protected double wakeFreeRatio; protected double energyCost; //protected String hostname = "http://windflo.com"; protected String hostname = "http://52.28.81.122"; /** * Initializes the evaluator with a scenario and a user token. This method generates a new run token. * This method doesn't increase the number of evaluations counter. * @param nScenario id of the scenario (from 0 to 4) to initialize the evaluator with * @param user_token the id of the user (see online leaderboard) */ public void initialize(int nScenario, String user_token) { this.nScenario = nScenario; this.user_token = user_token; energyOutputs=null; turbineFitnesses=null; energyOutput=0; wakeFreeRatio=0; energyCost=Double.MAX_VALUE; try { // getting scenario's data URL targetURL = new URL(hostname+"/scenarios/"+nScenario); URLConnection connection = targetURL.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); String inputLine; String jsonString = new String(); while ((inputLine = in.readLine()) != null) { //System.out.println(inputLine); jsonString += inputLine; } in.close(); JSONObject jsonObj = new JSONObject(jsonString); height = jsonObj.getDouble("height"); width = jsonObj.getDouble("width"); R = jsonObj.getDouble("r"); JSONArray jsonObs = jsonObj.getJSONArray("obstacles"); obstacles = new double[jsonObs.length()][4]; for (int i=0; i<jsonObs.length(); i++) { obstacles[i][0] = jsonObs.getJSONObject(i).getDouble("xmin"); obstacles[i][1] = jsonObs.getJSONObject(i).getDouble("ymin"); obstacles[i][2] = jsonObs.getJSONObject(i).getDouble("xmax"); obstacles[i][3] = jsonObs.getJSONObject(i).getDouble("ymax"); //System.out.println(obstacles[i][0] + " " + obstacles[i][1] + " " + obstacles[i][2] + " " + obstacles[i][3] + " "); } //System.out.println(height+" "+width+" "+R); // initializing a run targetURL = new URL(hostname+"/runs/"); connection = targetURL.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream()); out.write("{\"api_token\":\""+user_token+"\"}"); out.close(); BufferedReader response = new BufferedReader( new InputStreamReader( connection.getInputStream())); jsonString = ""; while ((inputLine = response.readLine()) != null) { //System.out.println(inputLine); jsonString+=inputLine; } jsonObj = new JSONObject(jsonString); run_token = jsonObj.getString("token"); nEvals = jsonObj.getInt("evals"); System.out.println("Your run token is: "+run_token); } catch (Exception e) { e.printStackTrace(); } } /** * Initializes the evaluator with a scenario, a user token and an existing run token * This method doesn't increase the number of evaluations counter. * @param nScenario id of the scenario (from 0 to 4) to initialize the evaluator with * @param user_token the id of the user (see online leaderboard) * @param run_token the id of the run (see online leaderboard) */ public void initialize(int nScenario, String user_token, String run_token) { this.nScenario = nScenario; this.user_token = user_token; this.run_token = run_token; energyOutputs=null; turbineFitnesses=null; energyOutput=0; wakeFreeRatio=0; energyCost=Double.MAX_VALUE; try { // getting scenario's data URL targetURL = new URL(hostname+"/scenarios/"+nScenario); URLConnection connection = targetURL.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); String inputLine; String jsonString = new String(); while ((inputLine = in.readLine()) != null) { //System.out.println(inputLine); jsonString += inputLine; } in.close(); JSONObject jsonObj = new JSONObject(jsonString); height = jsonObj.getDouble("height"); width = jsonObj.getDouble("width"); R = jsonObj.getDouble("r"); JSONArray jsonObs = jsonObj.getJSONArray("obstacles"); obstacles = new double[jsonObs.length()][4]; for (int i=0; i<jsonObs.length(); i++) { obstacles[i][0] = jsonObs.getJSONObject(i).getDouble("xmin"); obstacles[i][1] = jsonObs.getJSONObject(i).getDouble("ymin"); obstacles[i][2] = jsonObs.getJSONObject(i).getDouble("xmax"); obstacles[i][3] = jsonObs.getJSONObject(i).getDouble("ymax"); // System.out.println(obstacles[i][0] + " " + obstacles[i][1] + " " + obstacles[i][2] + " " + obstacles[i][3] + " "); } // System.out.println(height+" "+width+" "+R); } catch (Exception e) { e.printStackTrace(); } } /** * 2015 WIND FARM LAYOUT OPTIMIZATION EVALUATION FUNCTION * * Evaluates online a given layout and returns its cost of energy * Calling this method increases the number of evaluations counter. * @param layout The layout to evaluate * @return the cost of energy (positive) * and max_double if the layout is invalid */ public double evaluate(double[][] layout) { try { // initializing a run URL targetURL = new URL(hostname+"/evaluate/"); URLConnection connection = targetURL.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream()); String request = new String(); request += "{\"api_token\":\""+user_token+"\", \"run\":\""+run_token+"\", \"scenario\":"+nScenario+", "; request += "\"xs\":["+layout[0][0]; for (int i=1; i<layout.length; i++) { request += ", "+layout[i][0]; } request += "], \"ys\":[ "+layout[0][1]; for (int i=1; i<layout.length; i++) { request += ", "+layout[i][1]; } request += "]}"; //System.out.println(request); out.write(request); out.close(); BufferedReader response = new BufferedReader( new InputStreamReader( connection.getInputStream())); String inputLine; String jsonString = ""; while ((inputLine = response.readLine()) != null) { // System.out.println(inputLine); jsonString+=inputLine; } JSONObject jsonObj = new JSONObject(jsonString); this.energyCost = jsonObj.getDouble("energy_cost"); this.energyOutput = jsonObj.getDouble("energy_output"); this.wakeFreeRatio = jsonObj.getDouble("wake_free_ratio"); this.nEvals = jsonObj.getInt("evals"); JSONArray jsonTurbFit = jsonObj.getJSONArray("turbine_fitnesses"); turbineFitnesses = new double[jsonTurbFit.length()]; for (int i=0; i<jsonTurbFit.length(); i++) { turbineFitnesses[i] = jsonTurbFit.getJSONArray(i).getDouble(0); } JSONArray jsonEnergyOutputs = jsonObj.getJSONArray("energy_outputs"); energyOutputs = new double[jsonEnergyOutputs.length()][jsonEnergyOutputs.getJSONArray(0).length()]; for (int i=0; i<jsonEnergyOutputs.length(); i++) { JSONArray jsonEnergy = jsonEnergyOutputs.getJSONArray(i); for (int j=0; j<jsonEnergy.length(); j++) { energyOutputs[i][j] = jsonEnergy.getDouble(j); } } /* for (int i=0; i<energyOutputs.length; i++) { for (int j=0; j<energyOutputs[i].length; j++) { System.out.print(energyOutputs[i][j]+" "); } System.out.println(); }*/ } catch (Exception e) { e.printStackTrace(); } return 0.0; } @Override public boolean checkConstraint(double layout[][]) { double minDist = 64.0*R*R; // squared minimum distance for (int i=0; i<layout.length; i++) { // checking turbine position if (layout[i][0]!=layout[i][0] || layout[i][1]!=layout[i][1] || layout[i][0]<0.0 || layout[i][1]<0.0 || layout[i][0]>width || layout[i][1]>height) { System.out.println("Turbine "+i+"("+layout[i][0]+", "+layout[i][1]+") is invalid."); return false; } // checking obstacle constraints for (int j=0; j<obstacles.length; j++) { if (layout[i][0] > obstacles[j][0] && layout[i][0] < obstacles[j][2] && layout[i][1] > obstacles[j][1] && layout[i][1] < obstacles[j][3]) { System.out.println("Turbine "+i+"("+layout[i][0]+", "+layout[i][1]+") is in the obstacle "+j+" ["+obstacles[j][0]+", "+obstacles[j][1]+", "+obstacles[j][2]+", "+obstacles[j][3]+"]."); return false; } } // checking the security constraints for (int j=0; j<layout.length; j++) { if (i!=j) { // calculate the sqared distance between both turb double dist=(layout[i][0]-layout[j][0])*(layout[i][0]-layout[j][0])+ (layout[i][1]-layout[j][1])*(layout[i][1]-layout[j][1]); if (dist<minDist) { System.out.println("Security distance contraint violated between turbines "+i+" ("+layout[i][0]+", "+layout[i][1]+") and "+j+" ("+layout[j][0]+", "+layout[j][1]+"): "+Math.sqrt(dist)+" > "+Math.sqrt(minDist)); return false; } } } } return true; } @Override public double[][] getEnergyOutputs() { return this.energyOutputs; } @Override public double[] getTurbineFitnesses() { return this.turbineFitnesses; } @Override public double getEnergyOutput() { return energyOutput; } @Override public double getWakeFreeRatio() { return this.wakeFreeRatio; } @Override public double getEnergyCost() { return energyCost; } @Override public double getTurbineRadius() { return R; } @Override public double getFarmWidth() { return width; } @Override public double getFarmHeight() { return height; } @Override public double[][] getObstacles() { return obstacles; } /** * Returns the current run token * @return the run token */ public String getRunToken() { return run_token; } /** * Test function with random layouts */ public static void main(String args[]) { java.util.Random rng = new java.util.Random(System.currentTimeMillis()); CompetitionEvaluator eval = new CompetitionEvaluator(); eval.initialize(0, "USER TOKEN GOES HERE", "RUN TOKEN GOES HERE"); double layout[][]; // do { do { double minDist = 8.0*eval.R; int layoutWidth = rng.nextInt((int)(eval.width/minDist))+3; int layoutHeight = rng.nextInt((int)(eval.height/minDist))+3; double tileWidth = eval.width/layoutWidth; double tileHeight = eval.height/layoutHeight; layout = new double[layoutWidth*layoutHeight][2]; for (int i=0; i<layoutWidth; i++) { for (int j=0; j<layoutHeight; j++) { layout[i+j*layoutWidth][0] = ((double)i*tileWidth)+rng.nextDouble()*0.2*tileWidth; layout[i+j*layoutWidth][1] = ((double)j*tileHeight)+rng.nextDouble()*0.2*tileHeight; } } } while (!eval.checkConstraint(layout)); eval.evaluate(layout); System.out.println("Energy cost: "+eval.getEnergyCost()); // } while (eval.getNumberOfEvaluation() < 8000 && eval.getEnergyCost()>0.001724); } }
35.381657
212
0.640773
0c85548a3affc2ece859ba8472daa3e28ec3b06d
8,731
package rnk.bb.views; import org.primefaces.PrimeFaces; import org.primefaces.event.FileUploadEvent; import org.primefaces.event.FlowEvent; import org.primefaces.model.StreamedContent; import org.primefaces.model.UploadedFile; import rnk.bb.domain.hotel.staff.Staff; import rnk.bb.services.HotelService; import rnk.bb.services.StaffService; import rnk.bb.views.bean.hotel.EditHotelBean; import rnk.bb.views.bean.hotel.EditFoodConceptBean; import rnk.bb.views.bean.hotel.EditRoomFeatureBean; import rnk.bb.views.bean.hotel.EditRoomPoolBean; import rnk.bb.views.bean.registration.StaffUserBean; import rnk.bb.views.bean.util.HotelImagesView; import javax.annotation.PostConstruct; import javax.enterprise.context.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import java.io.Serializable; import java.security.Principal; import java.util.logging.Logger; @Named("staffView") @SessionScoped public class StaffView implements Serializable { private static Logger log=Logger.getLogger(StaffView.class.getName()); private StaffUserBean staffBean; private EditFoodConceptBean selectedFoodConcept; private EditRoomFeatureBean selectedRoomFeature; private EditRoomPoolBean selectedRoomPool; private Boolean hotelEditState=false; private Boolean editFoodConceptState=false; private Boolean editRoomFeatureState=false; private Boolean editRoomPoolState=false; private String hotelWizardCurrentState=""; private UploadedFile uploaded; @Inject HotelService hotelService; @Inject StaffService staffService; @Inject HotelImagesView imagesView; @PostConstruct public void init(){ initInternal(false); } private void initInternal(Boolean reset){ ExternalContext exContext=FacesContext.getCurrentInstance().getExternalContext(); Principal principal=exContext.getUserPrincipal(); if (staffBean==null){ staffBean=new StaffUserBean(); } if (principal!=null){ String userName=principal.getName(); Staff staff=staffService.findByLogin(userName); staffService.initStaffBean(staffBean,staff,reset); } } private Boolean isNewHotel(){ return staffBean.getHotel().getId()==null; } public StaffUserBean getUser(){ return staffBean; } public EditHotelBean getHotel(){return staffBean.getHotel();} public void update(){ init(); } public String getEditHotelButtonTitle(){ if (isNewHotel()){ return "Зарегистрировать новый отель"; }else{ return "Изменить данные отеля"; } } public String editHotel(){ hotelEditState=true; return ""; } public void resetHotelBean(){ initInternal(true); PrimeFaces.current().executeScript("PF('hotelWizardW').loadStep('hotelInfoTab', false)"); } public String saveHotel(){ hotelEditState=false; staffService.doSaveStaff(staffBean,true); initInternal(false); PrimeFaces.current().executeScript("PF('hotelWizardW').loadStep('hotelInfoTab', false)"); return "#"; } public void publishHotel(){ if (hotelApproved()){ staffService.publishHotel(staffBean.getApproval().getAwaitingHotel(), staffBean); } } public String onHotelFlow(FlowEvent event){ String step=event.getNewStep(); return step; } public Boolean getShowHotelWizardNavBar(){ return hotelEditState; } public void setHotelEditState(Boolean editState){ this.hotelEditState=editState; } public Boolean getHotelEditState(){ return this.hotelEditState; } public String getHotelWizardCurrentStep(){ if (hotelEditState){ if (staffBean.hasAwaitingHotel()){ return "hotelConfirmTab"; }else{ return "hotelEditGeneralTab"; } }else{ return "hotelInfoTab"; } } public String getEditHotelHeaderTitle(){ if (staffBean.getHotel().getId()==null){ return "Регистрация отеля"; }else{ return "Изменение данных отеля"; } } public String requestApproval(){ if (hotelCanRequestApproval()){ hotelService.requestApproval(staffBean.getApproval()); } return ""; } public Boolean hotelCanRequestApproval(){ return (!hotelEditState) &&(staffBean.getApproval()!=null) &&(staffBean.getApproval().getAwaitingHotel()!=null) &&(staffBean.getApproval().getAwaitingHotel().getId()!=null) &&(staffBean.getApproval().getApprovedState()==0); } public boolean hotelApproved(){ return staffBean.getApprovedState(); } public EditFoodConceptBean getSelectedFoodConcept(){ return selectedFoodConcept; } public void setSelectedFoodConcept(EditFoodConceptBean fc){ this.selectedFoodConcept=fc; } public Boolean getEditFoodConceptState(){ return this.editFoodConceptState; } public void setEditFoodConceptState(Boolean state){ this.editFoodConceptState=state; } public void editFoodConcept(){ if (selectedFoodConcept==null){ selectedFoodConcept=new EditFoodConceptBean(); } this.editFoodConceptState=true; } public void removeFoodConcept(){ hotelService.removeFoodConceptBean(staffBean.getHotel(),selectedFoodConcept); this.selectedFoodConcept=null; } public void cancelFoodConcept(){ this.editFoodConceptState=false; this.selectedFoodConcept=null; } public void saveFoodConcept(){ hotelService.saveFoodConceptBean(staffBean.getHotel(),selectedFoodConcept); this.editFoodConceptState=false; this.selectedFoodConcept=null; } public EditRoomFeatureBean getSelectedRoomFeature(){ return selectedRoomFeature; } public void setSelectedRoomFeature(EditRoomFeatureBean fc){ this.selectedRoomFeature=fc; } public Boolean getEditRoomFeatureState(){ return this.editRoomFeatureState; } public void setEditRoomFeatureState(Boolean state){ this.editRoomFeatureState=state; } public void editRoomFeature(){ if (selectedRoomFeature==null){ selectedRoomFeature=new EditRoomFeatureBean(); } this.editRoomFeatureState=true; } public void removeRoomFeature(){ hotelService.removeRoomFeatureBean(staffBean.getHotel(),selectedRoomFeature); this.selectedRoomFeature=null; } public void cancelRoomFeature(){ this.editRoomFeatureState=false; this.selectedRoomFeature=null; } public void saveRoomFeature(){ hotelService.saveRoomFeatureBean(staffBean.getHotel(),selectedRoomFeature); this.editRoomFeatureState=false; this.selectedRoomFeature=null; } public EditRoomPoolBean getSelectedRoomPool(){ return selectedRoomPool; } public void setSelectedRoomPool(EditRoomPoolBean fc){ this.selectedRoomPool=fc; } public Boolean getEditRoomPoolState(){ return this.editRoomPoolState; } public void setEditRoomPoolState(Boolean state){ this.editRoomPoolState=state; } public void editRoomPool(){ if (selectedRoomPool==null){ selectedRoomPool=new EditRoomPoolBean(); } this.editRoomPoolState=true; } public void removeRoomPool(){ hotelService.removeRoomPoolBean(staffBean.getHotel(),selectedRoomPool); this.selectedRoomPool=null; } public void cancelRoomPool(){ this.editRoomPoolState=false; this.selectedRoomPool=null; } public void saveRoomPool(){ hotelService.saveRoomPoolBean(staffBean.getHotel(),selectedRoomPool); this.editRoomPoolState=false; this.selectedRoomPool=null; } public UploadedFile getUploaded(){ return uploaded; } public void setUploaded(UploadedFile uploaded){ this.uploaded=uploaded; } public StreamedContent getUploadedHotelImage(){ return imagesView.getStreamedContent(staffBean.getHotel().getPicture()); } public void handleHotelPictureUpload(FileUploadEvent event){ byte [] contents=event.getFile().getContents(); String fileName=event.getFile().getFileName(); staffBean.getHotel().setPicture(contents); } }
27.805732
97
0.678273
1d6529c5bc52ef1728658b1c595e9eba7555a086
2,064
package org.multiot.em4so.model; public class Player { private int id; private Location myLocation; private int timeJoined; private int timeRecorded; private int timesWorked; private String role; public int getTimesWorked() { return timesWorked; } public void setTimesWorked(int timesWorked) { this.timesWorked = timesWorked; } public Player(int id, String role, int timeJoined, int timeRecorded){ this.id = id; this.role = role; this.timeJoined = timeJoined; this.timeRecorded = timeRecorded; this.timesWorked = 0; } public Player(int id, String role, int timeJoined, int timeRecorded, Location location){ this.id = id; this.role = role; this.timeJoined = timeJoined; this.timeRecorded = timeRecorded; this.timesWorked = 0; this.myLocation = location; } public Location getMyLocation() { return myLocation; } public void setMyLocation(Location myLocation) { this.myLocation = myLocation; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getTimeJoined() { return timeJoined; } public void setTimeJoined(int timeJoined) { this.timeJoined = timeJoined; } public int getTimeRecorded() { return timeRecorded; } public void setTimeRecorded(int timeRecorded) { this.timeRecorded = timeRecorded; } public String toString(){ return "Player_"+id+":{ role: "+role+", timeJoined:"+timeJoined+", timesWorked: "+timesWorked+", timeRecorded: "+timeRecorded+"}"; } //TODO TBD public double getDistanceTo(Location location){ return 0; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Player other = (Player) obj; if (id != other.id) return false; return true; } }
20.435644
132
0.691376
7ff6f32350b7d4d6c8bf3bfbb8d64e3c48d5c24e
13,059
// Copyright © 2016-2019 Shawn Baker using the MIT License. package ca.frozen.rpicameraviewer.activities; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import java.lang.ref.WeakReference; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import ca.frozen.library.classes.Log; import ca.frozen.rpicameraviewer.App; import ca.frozen.rpicameraviewer.classes.Camera; import ca.frozen.rpicameraviewer.classes.Settings; import ca.frozen.rpicameraviewer.classes.TcpIpReader; import ca.frozen.rpicameraviewer.classes.Utils; import ca.frozen.rpicameraviewer.R; public class ScannerFragment extends DialogFragment { // instance variables private WeakReference<DeviceScanner> scannerWeakRef; private TextView message, status; private ProgressBar progress; private Button cancelButton = null; private Runnable dismissRunner; private Handler dismissHandler = new Handler(); private String savedTag; //****************************************************************************** // onCreate //****************************************************************************** @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); // initialize the logger savedTag = Log.getTag(); Utils.initLogFile(getClass().getSimpleName()); // load the settings and cameras Utils.loadData(); // create and run the scanner asynchronously DeviceScanner scanner = new DeviceScanner(this); scannerWeakRef = new WeakReference<>(scanner); scanner.execute(); } //****************************************************************************** // onCreateView //****************************************************************************** @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // get the controls View view = inflater.inflate(R.layout.fragment_scanner, container, false); message = view.findViewById(R.id.scanner_message); status = view.findViewById(R.id.scanner_status); progress = view.findViewById(R.id.scanner_progress); cancelButton = view.findViewById(R.id.scanner_cancel); // configure the dialog Dialog dialog = getDialog(); if (dialog != null) { dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); dialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(android.content.DialogInterface dialog, int keyCode, android.view.KeyEvent event) { if ((keyCode == android.view.KeyEvent.KEYCODE_BACK)) { cancel(); } return false; } }); } // handle the cancel button cancelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { cancel(); dismiss(); } }); // create the dismiss handler and runnable dismissHandler = new Handler(); dismissRunner = new Runnable() { @Override public void run() { dismiss(); } }; // configure the view if we've already done the scan if (savedInstanceState != null) { DeviceScanner scanner = (scannerWeakRef != null) ? scannerWeakRef.get() : null; if (scanner != null) { scanner.setStatus(scanner.isComplete()); } } return view; } //****************************************************************************** // onDestroyView //****************************************************************************** @Override public void onDestroyView() { dismissHandler.removeCallbacks(dismissRunner); if (getDialog() != null && getRetainInstance()) { getDialog().setDismissMessage(null); } super.onDestroyView(); Log.setTag(savedTag); } //****************************************************************************** // cancel //****************************************************************************** private void cancel() { Log.info("cancel"); DeviceScanner scanner = (scannerWeakRef != null) ? scannerWeakRef.get() : null; if (scanner != null) { scanner.cancel(true); } } //////////////////////////////////////////////////////////////////////////////// // DeviceScanner //////////////////////////////////////////////////////////////////////////////// private class DeviceScanner extends AsyncTask<Void, Boolean, Void> { // local constants private final static int NO_DEVICE = -1; private final static int NUM_THREADS = 42; private final static int SLEEP_TIMEOUT = 10; private final static int DISMISS_TIMEOUT = 1500; // instance variables private WeakReference<ScannerFragment> fragmentWeakRef; private String ipAddress, network; private int device, numDone; private List<Camera> cameras, newCameras; private Settings settings; //****************************************************************************** // DeviceScanner //****************************************************************************** private DeviceScanner(ScannerFragment fragment) { fragmentWeakRef = new WeakReference<>(fragment); } //****************************************************************************** // onPreExecute //****************************************************************************** @Override protected void onPreExecute() { // get our IP address and the default port network = Utils.getNetworkName(); ipAddress = Utils.getLocalIpAddress(); settings = Utils.getSettings(); device = 0; numDone = 0; cameras = Utils.getNetworkCameras(network, false); newCameras = new ArrayList<>(); Log.info("onPreExecute: " + network + "," + ipAddress + "," + settings.toString()); } //****************************************************************************** // doInBackground //****************************************************************************** @Override protected Void doInBackground(Void... params) { Log.info("doInBackground"); if (ipAddress != null && !ipAddress.isEmpty()) { int i = ipAddress.lastIndexOf('.'); final int myDevice = Integer.parseInt(ipAddress.substring(i + 1)); final String baseAddress = ipAddress.substring(0, i + 1); Runnable runner = new Runnable() { @Override public void run() { for (int dev = getNextDevice(); !isCancelled() && dev != NO_DEVICE; dev = getNextDevice()) { if (dev == myDevice) { doneDevice(dev); continue; } String address = baseAddress + Integer.toString(dev); // look for a TCP/IP connection try { // try to connect to the device Socket socket = TcpIpReader.getConnection(address, settings.port, settings.scanTimeout); if (socket != null) { Camera camera = new Camera(network, address, settings.port); addCamera(camera); socket.close(); } } catch (Exception ex) {} doneDevice(dev); } } }; // create and start the threads for (int t = 0; t < NUM_THREADS; t++) { Thread thread = new Thread(runner); thread.start(); } // wait for the threads to finish while (!isCancelled() && numDone < 254) { SystemClock.sleep(SLEEP_TIMEOUT); } // add the new cameras if (!isCancelled() && newCameras.size() > 0) { addCameras(); } publishProgress(true); } return null; } //****************************************************************************** // onPostExecute //****************************************************************************** @Override protected void onPostExecute(Void unused) { Log.info("onPostExecute"); MainActivity activity = getActivity(cancelButton); if (activity != null) { cancelButton.setText(getString(R.string.done)); if (newCameras.size() > 0) { activity.updateCameras(); dismissHandler.postDelayed(dismissRunner, DISMISS_TIMEOUT); } } } //****************************************************************************** // onProgressUpdate //****************************************************************************** @Override protected void onProgressUpdate(Boolean... values) { setStatus(values[0]); } //****************************************************************************** // addCameras //****************************************************************************** private void addCameras() { // sort the new cameras by IP address Log.info("addCameras"); Collections.sort(newCameras, new Comparator<Camera>() { @Override public int compare(Camera camera1, Camera camera2) { int octet1 = getLastOctet(camera1.address); int octet2 = getLastOctet(camera2.address); return octet1 - octet2; } }); // get the maximum number from the existing camera names int max = Utils.getMaxCameraNumber(cameras); // set the camera names and add the new cameras to the list of all cameras String defaultName = Utils.getDefaultCameraName() + " "; List<Camera> allCameras = Utils.getCameras(); for (Camera camera : newCameras) { camera.name = defaultName + ++max; allCameras.add(camera); Log.info("camera: " + camera.toString()); } } //****************************************************************************** // getLastOctet //****************************************************************************** private int getLastOctet(String address) { String ip = address; int i = ip.indexOf("://"); if (i != -1) { ip = ip.substring(i + 3); } i = ip.indexOf("?"); if (i != -1) { ip = ip.substring(0, i); } i = ip.indexOf("/"); if (i != -1) { ip = ip.substring(0, i); } String[] octets = ip.split("\\."); int octet = -1; try { octet = Integer.parseInt(octets[3]); } catch (Exception ex) {} return octet; } //****************************************************************************** // addCamera //****************************************************************************** private synchronized void addCamera(Camera newCamera) { boolean found = false; for (Camera camera : cameras) { if (newCamera.address.equals(camera.address) && newCamera.port == camera.port) { found = true; break; } } if (!found) { Log.info("addCamera: " + newCamera.toString()); newCameras.add(newCamera); } } //****************************************************************************** // getNextDevice //****************************************************************************** private synchronized int getNextDevice() { if (device < 254) { device++; return device; } return NO_DEVICE; } //****************************************************************************** // doneDevice //****************************************************************************** private synchronized void doneDevice(int device) { numDone++; publishProgress(false); } //****************************************************************************** // setStatus //****************************************************************************** private synchronized void setStatus(boolean last) { message.setText(String.format(getString(R.string.scanning_on_port), settings.port)); progress.setProgress(numDone); status.setText(String.format(getString(R.string.num_new_cameras_found), newCameras.size())); if (newCameras.size() > 0) { status.setTextColor(App.getClr(R.color.good_text)); } else if (last) { status.setTextColor(App.getClr(R.color.bad_text)); } if (last) { cancelButton.setText(getString(R.string.done)); } } //****************************************************************************** // getActivity //****************************************************************************** private MainActivity getActivity(View view) { MainActivity activity = null; if (view != null) { ScannerFragment fragment = (fragmentWeakRef != null) ? fragmentWeakRef.get() : null; if (fragment != null) { activity = (MainActivity)fragment.getActivity(); } } return activity; } //****************************************************************************** // isComplete //****************************************************************************** boolean isComplete() { return device == 255; } } }
28.701099
106
0.518034
e20350e1d0be5dc883206375f8f8066ab5eaf41a
1,397
package com.android.book.ui; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.android.book.R; public class SplashFragment extends Fragment { public static SplashFragment newInstance() { return new SplashFragment(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.splash_fragment, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); new Handler().postDelayed(new Runnable() { @Override public void run() { // ((MainActivity) requireActivity()).navController.navigate(R.id.action_splashFragment_to_homeFragment, // null, // new NavOptions.Builder().setPopUpTo(R.id.splashFragment, true).build() // ); ((MainActivity) requireActivity()).navController.navigate(R.id.action_splashFragment_to_homeFragment); } }, 3_000); } }
31.044444
119
0.670007
d6121803ff7d70dc66f6f98e9e58bceec2cba3d0
1,019
package org.jruby.truffle.parser.ast; import org.jcodings.Encoding; import org.jcodings.specific.ASCIIEncoding; import org.jruby.truffle.parser.lexer.ISourcePosition; /** * Base class for all D (e.g. Dynamic) node types like DStrParseNode, DSymbolParseNode, etc... */ public abstract class DParseNode extends ListParseNode { protected Encoding encoding; public DParseNode(ISourcePosition position) { // FIXME: I believe this possibly should be default parsed encoding but this is // what we currently default to if we happen to receive a null encoding. This is // an attempt to at least always have a valid encoding set to something. this(position, ASCIIEncoding.INSTANCE); } public DParseNode(ISourcePosition position, Encoding encoding) { super(position); assert encoding != null: getClass().getName() + " passed in a null encoding"; this.encoding = encoding; } public Encoding getEncoding() { return encoding; } }
31.84375
94
0.705594
eaafa835c97a0a2d90d55114bbc15ca16981f2d5
793
package encontreimatriz; import java.util.Scanner; public class EncontreiMatriz { public static void main(String[] args) { int valor, cont = 0; int matriz[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}}; Scanner leitura = new Scanner(System.in); System.out.print("Digite o valor que você gostaria de procurar: "); valor = leitura.nextInt(); for (int i = 0; i < matriz.length; i++) { for (int j = 0; j < matriz[0].length; j++) { if (valor == matriz[i][j]) { System.out.println("\nAchei na linha " + i + " e na coluna " + j); cont++; } } } if (cont == 0){ System.out.println("Valor não encontrado!"); } } }
27.344828
86
0.477932
e117f332bf1bf3501ae0dba29a964e07ae2b95a7
5,222
/* * Copyright (C) 2012-2016. TomTom International BV (http://tomtom.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tomtom.camera.viewfinder; import android.support.annotation.Nullable; import com.tomtom.camera.util.Logger; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Used for parsing images from camera's viewfinder stream. */ class ImageStreamParser { private static final String TAG = "StreamParser"; public enum MessageFrame { MESSAGE_FRAME_START(0), MESSAGE_FRAME_DATA(1); private int mIntValue; MessageFrame(int intValue) { mIntValue = intValue; } public int getValue() { return mIntValue; } } private static final short PACKET_SYNC = 0x55AA; private static final int FRAME_HEADER_LENGTH = 7; private static final int FPS_MEASUREMENT_TIME = 1000; private OnImageParsedListener mOnImageParsedListener; private ByteBuffer mImageData; private int mImageDataLength; private int mPacketCount; private boolean mIsWaitingNewFrame; private int mFramesCount; private long mStartTime; private float mCurrentPts; public ImageStreamParser() { mIsWaitingNewFrame = true; } public void parseStream(byte[] data) { parseData(data); } private void parseData(byte[] data) { int packetLength = data.length; if (packetLength < FRAME_HEADER_LENGTH) { Logger.error(TAG, String.format("Got packet data of length %d but expected at least %d length", packetLength, FRAME_HEADER_LENGTH)); return; } ByteBuffer bigEndianBuffer = ByteBuffer.wrap(data); bigEndianBuffer.order(ByteOrder.BIG_ENDIAN); bigEndianBuffer.rewind(); short sync = bigEndianBuffer.getShort(); int message = bigEndianBuffer.get(); int packetNumber = bigEndianBuffer.getShort() & 0xffff; short payloadLength = bigEndianBuffer.getShort(); if (packetLength != payloadLength + FRAME_HEADER_LENGTH) { Logger.error(TAG, String.format("Got packet data of length %d but expected %d length", packetLength, payloadLength + FRAME_HEADER_LENGTH)); return; } if (sync != PACKET_SYNC) { Logger.error(TAG, "Sync data not same"); return; } if (message != MessageFrame.MESSAGE_FRAME_START.getValue() && message != MessageFrame.MESSAGE_FRAME_DATA.getValue()) { Logger.error(TAG, String.format("Got unexpected message %d", message)); return; } if (message == MessageFrame.MESSAGE_FRAME_START.getValue()) { mImageDataLength = bigEndianBuffer.getInt(); float pts = bigEndianBuffer.getFloat(); if (mCurrentPts != pts) { mCurrentPts = pts; } mPacketCount = packetNumber + 1; mIsWaitingNewFrame = false; if (mFramesCount == 0) { mStartTime = System.currentTimeMillis(); } clearData(); } else { if (mIsWaitingNewFrame) { return; } if (mPacketCount != packetNumber) { Logger.debug(TAG, String.format("Expected packet number %d but got %d", mPacketCount, packetNumber)); sendImageData(mCurrentPts, null); mIsWaitingNewFrame = true; } else { byte[] packetImageData = new byte[payloadLength]; bigEndianBuffer.get(packetImageData); mImageData.put(packetImageData); if (mImageData.remaining() == 0) { mIsWaitingNewFrame = true; mFramesCount++; if ((System.currentTimeMillis() - mStartTime) >= FPS_MEASUREMENT_TIME) { mFramesCount = 0; } sendImageData(mCurrentPts, mImageData.array()); } mPacketCount++; } } } private void clearData () { mImageData = ByteBuffer.allocate(mImageDataLength); mImageData.rewind(); } private void sendImageData(float timestamp, byte[] bytes) { if (mOnImageParsedListener != null) { mOnImageParsedListener.onImageParsed(timestamp, bytes); } } public void setOnImageParsedListener(OnImageParsedListener listener){ mOnImageParsedListener = listener; } public interface OnImageParsedListener { void onImageParsed(float timeSecs, @Nullable byte[] image); } }
31.083333
151
0.615664
4c9ccb55924b663ec3748f2c7198cba7889547d1
510
package com.baise.baselibs.net.converter; import java.io.IOException; import okhttp3.MediaType; import okhttp3.RequestBody; import retrofit2.Converter; final class JsonRequestBodyConverter<T> implements Converter<T, RequestBody> { private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8"); JsonRequestBodyConverter() { } public RequestBody convert(T value) throws IOException { return RequestBody.create(MEDIA_TYPE, value.toString()); } }
25.5
99
0.760784
0625cd4b4f03a84c898ec3a6c2cc4fb5990760bf
2,962
package org.credo.jdk.iotest.in; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class TestObjectStream { private static final String TMP_FILE = "box.tmp"; public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IOException { testWrite(); System.out.println("==============="); testRead(); } /** * ObjectOutputStream 测试函数 */ @SuppressWarnings({ "rawtypes", "unchecked" }) private static void testWrite() { try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(TMP_FILE)); out.writeBoolean(true); out.writeByte((byte)65); out.writeChar('a'); out.writeInt(20131015); out.writeFloat(3.14F); out.writeDouble(1.414D); // 写入HashMap对象 HashMap map = new HashMap(); map.put("one", "red"); map.put("two", "green"); map.put("three", "blue"); out.writeObject(map); // 写入自定义的Box对象,Box实现了Serializable接口 Box box = new Box("desk", 80, 48); out.writeObject(box); System.out.println("box: " + box.toString()); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } @SuppressWarnings("rawtypes") private static void testRead() throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream in = new ObjectInputStream(new FileInputStream(TMP_FILE)); System.out.printf("boolean:%b\n", in.readBoolean()); System.out.printf("byte:%d\n", (in.readByte() & 0xff)); System.out.printf("char:%c\n", in.readChar()); System.out.printf("int:%d\n", in.readInt()); System.out.printf("float:%f\n", in.readFloat()); System.out.printf("double:%f\n", in.readDouble()); // 读取HashMap对象 HashMap map = (HashMap) in.readObject(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); System.out.printf("%-6s -- %s\n", entry.getKey(), entry.getValue()); } // 读取Box对象,Box实现了Serializable接口 Box box = (Box) in.readObject(); System.out.println("box: " + box.toString()); in.close(); } } class Box implements Serializable { private int width; private int height; private String name; public Box(String name, int width, int height) { this.name = name; this.width = width; this.height = height; } @Override public String toString() { return "[" + name + ": (" + width + ", " + height + ") ]"; } }
29.919192
106
0.599932
5dde799e759ff692ce8cccf0872c0df633715481
4,594
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.asset; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.WeakHashMap; /** * An <code>AssetCache</code> allows storage of loaded resources in order * to improve their access time if they are requested again in a short period * of time. The AssetCache stores weak references to the resources, allowing * Java's garbage collector to request deletion of rarely used resources * when heap memory is low. */ public class AssetCache { public static final class SmartAssetInfo { public WeakReference<AssetKey> smartKey; public Asset asset; } private final WeakHashMap<AssetKey, SmartAssetInfo> smartCache = new WeakHashMap<AssetKey, SmartAssetInfo>(); private final HashMap<AssetKey, Object> regularCache = new HashMap<AssetKey, Object>(); /** * Adds a resource to the cache. * <br/><br/> * <font color="red">Thread-safe.</font> * @see #getFromCache(java.lang.String) */ public void addToCache(AssetKey key, Object obj){ synchronized (regularCache){ if (obj instanceof Asset && key.useSmartCache()){ // put in smart cache Asset asset = (Asset) obj; asset.setKey(null); // no circular references SmartAssetInfo smartInfo = new SmartAssetInfo(); smartInfo.asset = asset; // use the original key as smart key smartInfo.smartKey = new WeakReference<AssetKey>(key); smartCache.put(key, smartInfo); }else{ // put in regular cache regularCache.put(key, obj); } } } /** * Delete an asset from the cache, returns true if it was deleted successfuly. * <br/><br/> * <font color="red">Thread-safe.</font> */ public boolean deleteFromCache(AssetKey key){ synchronized (regularCache){ if (key.useSmartCache()){ return smartCache.remove(key) != null; }else{ return regularCache.remove(key) != null; } } } /** * Gets an object from the cache given an asset key. * <br/><br/> * <font color="red">Thread-safe.</font> * @param key * @return */ public Object getFromCache(AssetKey key){ synchronized (regularCache){ if (key.useSmartCache()) { return smartCache.get(key).asset; } else { return regularCache.get(key); } } } /** * Retrieves smart asset info from the cache. * @param key * @return */ public SmartAssetInfo getFromSmartCache(AssetKey key){ return smartCache.get(key); } /** * Deletes all the assets in the regular cache. */ public void deleteAllAssets(){ synchronized (regularCache){ regularCache.clear(); smartCache.clear(); } } }
34.80303
91
0.644972
fc90a5250b175bf3b59cfdcc600d2d69078fadf8
5,903
package com.sagisu.vault.ui.businessprofile; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.google.android.material.chip.Chip; import com.sagisu.vault.R; import com.sagisu.vault.databinding.AddBusinessBinding; import com.sagisu.vault.models.Business; import com.sagisu.vault.ui.home.JoinWaitListBottomDialogFragment; import com.sagisu.vault.utils.BusinessTypeDescriptor; import java.util.List; public class AddBusinessFragment extends Fragment implements DirectorDetailsSheet.IDirectorSheetNavigator { private AddBusinessViewModel mViewModel; private AddBusinessBinding binding; private IBusinessNavigator navigator; public static AddBusinessFragment newInstance() { return new AddBusinessFragment(); } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); if (context instanceof IBusinessNavigator) { navigator = (IBusinessNavigator) context; navigator.setActionBarTittle(getResources().getString(R.string.business_profile_add_tittle)); } else { try { throw new Exception("Please implement IBusinessNavigator"); } catch (Exception e) { e.printStackTrace(); } } } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.add_business_fragment, container, false); binding = DataBindingUtil.bind(view); binding.addDirector.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Load sheet for taking director details showAddDirectorSheet(); } }); return binding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel = new ViewModelProvider(this).get(AddBusinessViewModel.class); mViewModel.init(BusinessTypeDescriptor.BUSINESS); binding.setViewModel(mViewModel); binding.setLifecycleOwner(this); mViewModel.getDirectorsList().observe(getViewLifecycleOwner(), new Observer<List<Business.Director>>() { @Override public void onChanged(List<Business.Director> directors) { } }); mViewModel.getErrorBean().observe(getViewLifecycleOwner(), new Observer<BusinessErrorBean>() { @Override public void onChanged(BusinessErrorBean businessErrorBean) { binding.addBusinessName.setError(businessErrorBean.getNameError() == null ? null : getString(businessErrorBean.getNameError())); binding.addBusinessName.setErrorEnabled(businessErrorBean.getNameError() != null); binding.businessEinNumber.setError(businessErrorBean.getEinError() == null ? null : getString(businessErrorBean.getEinError())); binding.businessEinNumber.setErrorEnabled(businessErrorBean.getEinError() != null); binding.corporationType.setError(businessErrorBean.getCorporationTypeError() == null ? null : getString(businessErrorBean.getCorporationTypeError())); binding.corporationType.setErrorEnabled(businessErrorBean.getCorporationTypeError() != null); binding.department.setError(businessErrorBean.getDepartmentError() == null ? null : getString(businessErrorBean.getDepartmentError())); binding.department.setErrorEnabled(businessErrorBean.getDepartmentError() != null); } }); mViewModel.getPostBusinessSuccess().observe(getViewLifecycleOwner(), new Observer<String>() { @Override public void onChanged(String msg) { //GO to the previous fragment Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show(); getActivity().onBackPressed(); } }); mViewModel.getLoadingObservable().observe(getViewLifecycleOwner(), new Observer<String>() { @Override public void onChanged(String s) { navigator.loading(s); } }); } private void showAddDirectorSheet() { DirectorDetailsSheet sheet = new DirectorDetailsSheet(this); sheet.show(getActivity().getSupportFragmentManager(), "add_director"); } private void addDirectorView(Business.Director director) { Chip chip = new Chip(getActivity()); chip.setText(director.getName()); chip.setChipBackgroundColorResource(R.color.blue_200); chip.setCloseIconVisible(true); //chip.setCloseIconTint(getResources().getColorStateList(R.color.text_500)); //chip.setTextColor(getResources().getColor(R.color.text_500)); //chip.setTextAppearance(R.style.ChipTextAppearance); chip.setOnCloseIconClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mViewModel.removeDirectors(director); binding.directorGrp.removeView(chip); } }); binding.directorGrp.addView(chip); } @Override public void onAddClick(Business.Director director) { mViewModel.addDirectors(director); addDirectorView(director); } }
39.353333
166
0.677791
076cd4dce9a4a5bf6655eb800fb77bd793b27705
513
package uk.gov.hmcts.cmc.domain.models.orders; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import java.util.ArrayList; import java.util.List; @Builder @EqualsAndHashCode @Getter public class BespokeOrderDirection { private final List<BespokeDirection> bespokeDirections = new ArrayList<>(); private boolean bespokeDirectionOrderWarning; public void addBespokeDirection(BespokeDirection bespokeDirection) { bespokeDirections.add(bespokeDirection); } }
24.428571
79
0.793372
f4ee7f4e760c5237cbbf4b7bff311ac4b9cc7224
9,387
/* * Copyright 2015 Midokura SARL * * 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.midonet.client.resource; import java.net.URI; import java.util.Map; import java.util.UUID; import org.midonet.client.WebResource; import org.midonet.client.dto.DtoRule; import org.midonet.cluster.services.rest_api.MidonetMediaTypes; public class Rule extends ResourceBase<Rule, DtoRule> { public Rule(WebResource resource, URI uriForCreation, DtoRule r) { super(resource, uriForCreation, r, MidonetMediaTypes.APPLICATION_RULE_JSON_V2()); } @Override public URI getUri() { return principalDto.getUri(); } public boolean isCondInvert() { return principalDto.isCondInvert(); } public boolean isInvDlDst() { return principalDto.isInvDlDst(); } public boolean isInvDlSrc() { return principalDto.isInvDlSrc(); } public boolean isInvDlType() { return principalDto.isInvDlType(); } public boolean isInvInPorts() { return principalDto.isInvInPorts(); } public boolean isInvNwDst() { return principalDto.isInvNwDst(); } public boolean isInvNwProto() { return principalDto.isInvNwProto(); } public boolean isInvNwSrc() { return principalDto.isInvNwSrc(); } public boolean isInvNwTos() { return principalDto.isInvNwTos(); } public String getFragmentPolicy() { return principalDto.getFragmentPolicy(); } public boolean isInvOutPorts() { return principalDto.isInvOutPorts(); } public boolean isInvPortGroup() { return principalDto.isInvPortGroup(); } public boolean isInvTpDst() { return principalDto.isInvTpDst(); } public boolean isInvTpSrc() { return principalDto.isInvTpSrc(); } public boolean isMatchForwardFlow() { return principalDto.isMatchForwardFlow(); } public boolean isMatchReturnFlow() { return principalDto.isMatchReturnFlow(); } public UUID getChainId() { return principalDto.getChainId(); } public String getDlDst() { return principalDto.getDlDst(); } public String getDlSrc() { return principalDto.getDlSrc(); } public Integer getDlType() { return principalDto.getDlType(); } public String getFlowAction() { return principalDto.getFlowAction(); } public UUID getId() { return principalDto.getId(); } public UUID[] getInPorts() { return principalDto.getInPorts(); } public String getJumpChainName() { return principalDto.getJumpChainName(); } public UUID getJumpChainId() { return principalDto.getJumpChainId(); } public DtoRule.DtoNatTarget[] getNatTargets() { return principalDto.getNatTargets(); } public String getNwDstAddress() { return principalDto.getNwDstAddress(); } public int getNwDstLength() { return principalDto.getNwDstLength(); } public int getNwProto() { return principalDto.getNwProto(); } public String getNwSrcAddress() { return principalDto.getNwSrcAddress(); } public int getNwSrcLength() { return principalDto.getNwSrcLength(); } public int getNwTos() { return principalDto.getNwTos(); } public UUID[] getOutPorts() { return principalDto.getOutPorts(); } public UUID getPortGroup() { return principalDto.getPortGroup(); } public int getPosition() { return principalDto.getPosition(); } public String getMeterName() { return principalDto.getMeterName(); } public Map<String, String> getProperties() { return principalDto.getProperties(); } public DtoRule.DtoRange<Integer> getTpDst() { return principalDto.getTpDst(); } public DtoRule.DtoRange<Integer> getTpSrc() { return principalDto.getTpSrc(); } public String getType() { return principalDto.getType(); } public Rule invNwDst(boolean invNwDst) { principalDto.setInvNwDst(invNwDst); return this; } public Rule invNwTos(boolean invNwTos) { principalDto.setInvNwTos(invNwTos); return this; } public Rule setFragmentPolicy(String fragmentPolicy) { principalDto.setFragmentPolicy(fragmentPolicy); return this; } public Rule chainId(UUID chainId) { principalDto.setChainId(chainId); return this; } public Rule position(int position) { principalDto.setPosition(position); return this; } public Rule meterName(String meterName) { principalDto.setMeterName(meterName); return this; } public Rule invTpDst(boolean invTpDst) { principalDto.setInvTpDst(invTpDst); return this; } public Rule invNwSrc(boolean invNwSrc) { principalDto.setInvNwSrc(invNwSrc); return this; } public Rule invOutPorts(boolean invOutPorts) { principalDto.setInvOutPorts(invOutPorts); return this; } public Rule outPorts(UUID[] outPorts) { principalDto.setOutPorts(outPorts); return this; } public Rule nwProto(int nwProto) { principalDto.setNwProto(nwProto); return this; } public Rule invDlType(boolean invDlType) { principalDto.setInvDlType(invDlType); return this; } public Rule tpDst(DtoRule.DtoRange<Integer> tpDst) { principalDto.setTpDst(tpDst); return this; } public Rule dlDst(String dlDst) { principalDto.setDlDst(dlDst); return this; } public Rule portGroup(UUID portGroup) { principalDto.setPortGroup(portGroup); return this; } public Rule matchReturnFlow(boolean matchReturnFlow) { principalDto.setMatchReturnFlow(matchReturnFlow); return this; } public Rule nwDstAddress(String nwDstAddress) { principalDto.setNwDstAddress(nwDstAddress); return this; } public Rule invDlDst(boolean invDlDst) { principalDto.setInvDlDst(invDlDst); return this; } public Rule invInPorts(boolean invInPorts) { principalDto.setInvInPorts(invInPorts); return this; } public Rule dlType(Integer dlType) { principalDto.setDlType(dlType); return this; } public Rule natTargets(DtoRule.DtoNatTarget[] natTargets) { principalDto.setNatTargets(natTargets); return this; } public Rule invTpSrc(boolean invTpSrc) { principalDto.setInvTpSrc(invTpSrc); return this; } public Rule properties(Map<String, String> properties) { principalDto.setProperties(properties); return this; } public Rule jumpChainName(String jumpChainName) { principalDto.setJumpChainName(jumpChainName); return this; } public Rule jumpChainId(UUID jumpChainId) { principalDto.setJumpChainId(jumpChainId); return this; } public Rule matchForwardFlow(boolean matchForwardFlow) { principalDto.setMatchForwardFlow(matchForwardFlow); return this; } public Rule nwSrcLength(int nwSrcLength) { principalDto.setNwSrcLength(nwSrcLength); return this; } public Rule flowAction(String flowAction) { principalDto.setFlowAction(flowAction); return this; } public Rule condInvert(boolean condInvert) { principalDto.setCondInvert(condInvert); return this; } public Rule dlSrc(String dlSrc) { principalDto.setDlSrc(dlSrc); return this; } public Rule invDlSrc(boolean invDlSrc) { principalDto.setInvDlSrc(invDlSrc); return this; } public Rule nwDstLength(int nwDstLength) { principalDto.setNwDstLength(nwDstLength); return this; } public Rule invPortGroup(boolean invPortGroup) { principalDto.setInvPortGroup(invPortGroup); return this; } public Rule nwTos(int nwTos) { principalDto.setNwTos(nwTos); return this; } public Rule nwSrcAddress(String nwSrcAddress) { principalDto.setNwSrcAddress(nwSrcAddress); return this; } public Rule inPorts(UUID[] inPorts) { principalDto.setInPorts(inPorts); return this; } public Rule tpSrc(DtoRule.DtoRange<Integer> tpSrc) { principalDto.setTpSrc(tpSrc); return this; } public Rule invNwProto(boolean invNwProto) { principalDto.setInvNwProto(invNwProto); return this; } public Rule type(String type) { principalDto.setType(type); return this; } }
23.764557
75
0.647811
d3bf005d90ae9d74453cebe3d338aef9298a64b2
1,558
package be.brusselsbook.servs; import java.io.IOException; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; 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 be.brusselsbook.sql.access.AccessFactory; import be.brusselsbook.sql.access.BookCommentAccess; import be.brusselsbook.sql.data.BookComment; import be.brusselsbook.utils.AccessUtils; import be.brusselsbook.utils.ServerUtils; @WebServlet("/commentmod") public class CommentMod extends HttpServlet { private static final long serialVersionUID = 1L; private List<BookComment> selectSignaledComments(){ BookCommentAccess bookCommentAccess = AccessFactory.getInstance().getBookCommentAccess(); List<BookComment> results = new ArrayList<>(); ResultSet set = AccessUtils.executeQuery(AccessFactory.getInstance(), ServerUtils.SELECT_SIGNALED_COMMENT); while(AccessUtils.next(set)){ results.add(bookCommentAccess.safeMap(set)); } return results; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<BookComment> comments = selectSignaledComments(); request.setAttribute("comments", comments); if(comments.isEmpty()){ request.setAttribute("warning", "No comments have been reported."); } getServletContext().getRequestDispatcher(ServerUtils.COMMENTMODJSPFILE).forward(request, response); } }
34.622222
109
0.806162
9aa7a187256c6163c9a6aa8c5901759a99a2cb6b
375
package net.blay09.mods.hardcorerevival.mixin; import net.minecraft.entity.LivingEntity; import net.minecraft.util.DamageSource; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(LivingEntity.class) public interface LivingEntityAccessor { @Invoker boolean callCheckTotemDeathProtection(DamageSource damageSource); }
25
69
0.824
de3b66051f70b270407fffb528ed9df64bed82e1
1,104
package dillig; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import gov.nasa.jpf.jvm.Verify; public class ListOfKeyValuePairs { public static void main(String[] args) { Map<Integer, Integer> m = new HashMap<Integer, Integer>(); m.put(45,8); m.put(23,19); List<Pair> kv_pairs = new ArrayList<Pair>(); Set<Integer> st = m.keySet(); Iterator<Integer> it = st.iterator(); int key = 0; int val = 0; Pair p; while (it.hasNext()) { key = it.next(); val = m.get(key); p = new Pair(); p.first = key; p.second = val; kv_pairs.add(0, p); } Iterator<Pair> it2 = kv_pairs.iterator(); int k = 0; int v = 0; int v2 = 0; while (it2.hasNext()) { p = it2.next(); k = p.first; v = p.second; v2 = m.get(k); if ( v2 != v ) Verify.assertTrue("m.get(k) != v", false); } } public static int unknown() { return 1; } } class Pair { public int first; public int second; }
14.72
60
0.593297
b073e6361b682a52593a3b66532a8acaede896a0
359
package net.mnio.springbooter; import net.mnio.springbooter.persistence.model.User; public class TestUtil { public static User createUser(final String email, final String name, final String pwd) { final User user = new User(); user.setName(name); user.setEmail(email); user.setPassword(pwd); return user; } }
25.642857
92
0.671309
52a64f30d975f80d5c9e99686df0e5f4d8a8015c
40,959
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.privatedns.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.PollerFlux; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.privatedns.fluent.models.PrivateZoneInner; import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsDelete; import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsGet; import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsListing; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in PrivateZonesClient. */ public interface PrivateZonesClient extends InnerSupportsGet<PrivateZoneInner>, InnerSupportsListing<PrivateZoneInner>, InnerSupportsDelete<Void> { /** * Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the CreateOrUpdate operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @param ifNoneMatch Set to '*' to allow a new Private DNS zone to be created, but to prevent updating an existing * zone. Other values will be ignored. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch, String ifNoneMatch); /** * Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the CreateOrUpdate operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @param ifNoneMatch Set to '*' to allow a new Private DNS zone to be created, but to prevent updating an existing * zone. Other values will be ignored. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) PollerFlux<PollResult<PrivateZoneInner>, PrivateZoneInner> beginCreateOrUpdateAsync( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch, String ifNoneMatch); /** * Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the CreateOrUpdate operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @param ifNoneMatch Set to '*' to allow a new Private DNS zone to be created, but to prevent updating an existing * zone. Other values will be ignored. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<PrivateZoneInner>, PrivateZoneInner> beginCreateOrUpdate( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch, String ifNoneMatch); /** * Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the CreateOrUpdate operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @param ifNoneMatch Set to '*' to allow a new Private DNS zone to be created, but to prevent updating an existing * zone. Other values will be ignored. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<PrivateZoneInner>, PrivateZoneInner> beginCreateOrUpdate( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch, String ifNoneMatch, Context context); /** * Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the CreateOrUpdate operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @param ifNoneMatch Set to '*' to allow a new Private DNS zone to be created, but to prevent updating an existing * zone. Other values will be ignored. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<PrivateZoneInner> createOrUpdateAsync( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch, String ifNoneMatch); /** * Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the CreateOrUpdate operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<PrivateZoneInner> createOrUpdateAsync( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters); /** * Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the CreateOrUpdate operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @param ifNoneMatch Set to '*' to allow a new Private DNS zone to be created, but to prevent updating an existing * zone. Other values will be ignored. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) PrivateZoneInner createOrUpdate( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch, String ifNoneMatch); /** * Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the CreateOrUpdate operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) PrivateZoneInner createOrUpdate(String resourceGroupName, String privateZoneName, PrivateZoneInner parameters); /** * Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the CreateOrUpdate operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @param ifNoneMatch Set to '*' to allow a new Private DNS zone to be created, but to prevent updating an existing * zone. Other values will be ignored. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) PrivateZoneInner createOrUpdate( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch, String ifNoneMatch, Context context); /** * Updates a Private DNS zone. Does not modify virtual network links or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the Update operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<Flux<ByteBuffer>>> updateWithResponseAsync( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch); /** * Updates a Private DNS zone. Does not modify virtual network links or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the Update operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) PollerFlux<PollResult<PrivateZoneInner>, PrivateZoneInner> beginUpdateAsync( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch); /** * Updates a Private DNS zone. Does not modify virtual network links or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the Update operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<PrivateZoneInner>, PrivateZoneInner> beginUpdate( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch); /** * Updates a Private DNS zone. Does not modify virtual network links or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the Update operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<PrivateZoneInner>, PrivateZoneInner> beginUpdate( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch, Context context); /** * Updates a Private DNS zone. Does not modify virtual network links or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the Update operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<PrivateZoneInner> updateAsync( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch); /** * Updates a Private DNS zone. Does not modify virtual network links or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the Update operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<PrivateZoneInner> updateAsync(String resourceGroupName, String privateZoneName, PrivateZoneInner parameters); /** * Updates a Private DNS zone. Does not modify virtual network links or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the Update operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) PrivateZoneInner update( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch); /** * Updates a Private DNS zone. Does not modify virtual network links or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the Update operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) PrivateZoneInner update(String resourceGroupName, String privateZoneName, PrivateZoneInner parameters); /** * Updates a Private DNS zone. Does not modify virtual network links or DNS records within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param parameters Parameters supplied to the Update operation. * @param ifMatch The ETag of the Private DNS zone. Omit this value to always overwrite the current zone. Specify * the last-seen ETag value to prevent accidentally overwriting any concurrent changes. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return describes a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) PrivateZoneInner update( String resourceGroupName, String privateZoneName, PrivateZoneInner parameters, String ifMatch, Context context); /** * Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be * undone. Private DNS zone cannot be deleted unless all virtual network links to it are removed. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param ifMatch The ETag of the Private DNS zone. Omit this value to always delete the current zone. Specify the * last-seen ETag value to prevent accidentally deleting any concurrent changes. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<Flux<ByteBuffer>>> deleteWithResponseAsync( String resourceGroupName, String privateZoneName, String ifMatch); /** * Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be * undone. Private DNS zone cannot be deleted unless all virtual network links to it are removed. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param ifMatch The ETag of the Private DNS zone. Omit this value to always delete the current zone. Specify the * last-seen ETag value to prevent accidentally deleting any concurrent changes. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) PollerFlux<PollResult<Void>, Void> beginDeleteAsync( String resourceGroupName, String privateZoneName, String ifMatch); /** * Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be * undone. Private DNS zone cannot be deleted unless all virtual network links to it are removed. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param ifMatch The ETag of the Private DNS zone. Omit this value to always delete the current zone. Specify the * last-seen ETag value to prevent accidentally deleting any concurrent changes. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<Void>, Void> beginDelete(String resourceGroupName, String privateZoneName, String ifMatch); /** * Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be * undone. Private DNS zone cannot be deleted unless all virtual network links to it are removed. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param ifMatch The ETag of the Private DNS zone. Omit this value to always delete the current zone. Specify the * last-seen ETag value to prevent accidentally deleting any concurrent changes. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<Void>, Void> beginDelete( String resourceGroupName, String privateZoneName, String ifMatch, Context context); /** * Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be * undone. Private DNS zone cannot be deleted unless all virtual network links to it are removed. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param ifMatch The ETag of the Private DNS zone. Omit this value to always delete the current zone. Specify the * last-seen ETag value to prevent accidentally deleting any concurrent changes. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Void> deleteAsync(String resourceGroupName, String privateZoneName, String ifMatch); /** * Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be * undone. Private DNS zone cannot be deleted unless all virtual network links to it are removed. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Void> deleteAsync(String resourceGroupName, String privateZoneName); /** * Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be * undone. Private DNS zone cannot be deleted unless all virtual network links to it are removed. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param ifMatch The ETag of the Private DNS zone. Omit this value to always delete the current zone. Specify the * last-seen ETag value to prevent accidentally deleting any concurrent changes. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String privateZoneName, String ifMatch); /** * Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be * undone. Private DNS zone cannot be deleted unless all virtual network links to it are removed. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String privateZoneName); /** * Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be * undone. Private DNS zone cannot be deleted unless all virtual network links to it are removed. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param ifMatch The ETag of the Private DNS zone. Omit this value to always delete the current zone. Specify the * last-seen ETag value to prevent accidentally deleting any concurrent changes. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String privateZoneName, String ifMatch, Context context); /** * Gets a Private DNS zone. Retrieves the zone properties, but not the virtual networks links or the record sets * within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<PrivateZoneInner>> getByResourceGroupWithResponseAsync( String resourceGroupName, String privateZoneName); /** * Gets a Private DNS zone. Retrieves the zone properties, but not the virtual networks links or the record sets * within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<PrivateZoneInner> getByResourceGroupAsync(String resourceGroupName, String privateZoneName); /** * Gets a Private DNS zone. Retrieves the zone properties, but not the virtual networks links or the record sets * within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) PrivateZoneInner getByResourceGroup(String resourceGroupName, String privateZoneName); /** * Gets a Private DNS zone. Retrieves the zone properties, but not the virtual networks links or the record sets * within the zone. * * @param resourceGroupName The name of the resource group. * @param privateZoneName The name of the Private DNS zone (without a terminating dot). * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a Private DNS zone. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<PrivateZoneInner> getByResourceGroupWithResponse( String resourceGroupName, String privateZoneName, Context context); /** * Lists the Private DNS zones in all resource groups in a subscription. * * @param top The maximum number of Private DNS zones to return. If not specified, returns up to 100 zones. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response to a Private DNS zone list operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<PrivateZoneInner> listAsync(Integer top); /** * Lists the Private DNS zones in all resource groups in a subscription. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response to a Private DNS zone list operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<PrivateZoneInner> listAsync(); /** * Lists the Private DNS zones in all resource groups in a subscription. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response to a Private DNS zone list operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<PrivateZoneInner> list(); /** * Lists the Private DNS zones in all resource groups in a subscription. * * @param top The maximum number of Private DNS zones to return. If not specified, returns up to 100 zones. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response to a Private DNS zone list operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<PrivateZoneInner> list(Integer top, Context context); /** * Lists the Private DNS zones within a resource group. * * @param resourceGroupName The name of the resource group. * @param top The maximum number of record sets to return. If not specified, returns up to 100 record sets. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response to a Private DNS zone list operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<PrivateZoneInner> listByResourceGroupAsync(String resourceGroupName, Integer top); /** * Lists the Private DNS zones within a resource group. * * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response to a Private DNS zone list operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<PrivateZoneInner> listByResourceGroupAsync(String resourceGroupName); /** * Lists the Private DNS zones within a resource group. * * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response to a Private DNS zone list operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<PrivateZoneInner> listByResourceGroup(String resourceGroupName); /** * Lists the Private DNS zones within a resource group. * * @param resourceGroupName The name of the resource group. * @param top The maximum number of record sets to return. If not specified, returns up to 100 record sets. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response to a Private DNS zone list operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<PrivateZoneInner> listByResourceGroup(String resourceGroupName, Integer top, Context context); }
61.407796
120
0.743475
017fb2e290d49fea1e8972327db80156a33b88a8
9,165
package br.usp.icmc.ssc0103; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; enum Command { NOOP, USERADD, CATALOGADD, CHECKOUT, CHECKIN, LIST, EXIT } /** * Shell: Instantiable command interpreter for application */ public class Shell { /** * Scope attributes */ private Date date; private String line; private Command command; /** * Constructor tries to parse input arguments * * @param args arguments * @throws ParseException exception for wrong args */ public Shell(String[] args) throws ParseException, IOException { // Set reference date if (args.length != 1) date = new Date(); else date = new SimpleDateFormat("MM/dd/yyyy").parse(args[0]); // Probe the database Database.getInstance().serializeAndUpdate(); // Set watchdog service Watchdog.getInstance().start(); // Set starting command command = Command.NOOP; System.out.println(date.toString()); } /** * Watches for user inputs * * @throws IOException */ public void runCommand() throws IOException { BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in)); while (command != Command.EXIT) { System.out.print("> "); line = userInput.readLine(); if (checkCommand()) triggerCommand(); } } /** * Check user input for a valid command format * * @return boolean true for valid format, false otherwise */ private boolean checkCommand() { if (line.matches("^(.*[^\\\\];)$")) { if (line.matches("^\\s*user\\s+add\\s+(?:[^\\\\,]*);\\s*$")) command = Command.USERADD; else if (line.matches("^\\s*catalog\\s+add\\s+(?:[^\\\\,]*);\\s*$")) command = Command.CATALOGADD; else if (line.matches("^\\s*lend(?:[^\\\\,]*)to(?:[^\\\\,]*);\\s*$")) command = Command.CHECKOUT; else if (line.matches("^\\s*return\\s+(?:[^\\\\,]*);\\s*$")) command = Command.CHECKIN; else if (line.matches("^\\s*list\\s+(?:[^\\\\,]*);\\s*$")) command = Command.LIST; else if (line.matches("^\\s*exit\\s*;\\s*$")) command = Command.EXIT; else { command = Command.NOOP; Formatter.outputError("Could not be parsed..."); } return true; } else { System.out.println("\n> Try one of the following syntaxes: \n" + "ADD USER:\n" + "user add \"username\" <type>;" + "\n\n" + "ADD BOOK:\n" + "catalog add \"bookname\" <type>;" + "\n\n" + "LEND BOOK:\n" + "lend \"bookname\" to \"username;" + "\n\n" + "RETURN BOOK:\n" + "return \"bookname\";" + "\n\n" + "CLOSE APP:\n" + "exit;\n"); return false; } } /** * Tries to parse the command, triggers it if possible * * @return true if trigger succeeds, false otherwise */ private boolean triggerCommand() { // Make it local Pattern pattern; Matcher matcher; // Simple switch switch (command) { case USERADD: //https://regex101.com/r/cZ7lK1/8 pattern = Pattern.compile("^(?i)\\s*user\\s+add\\s+\\\"\\s*" + "([a-zA-Z0-9][a-zA-Z0-9\\s]+[a-zA-Z0-9])\\s*\\\"(?:\\s+" + "(tutor|student|community))?\\s*;\\s*$"); if ((matcher = pattern.matcher(line)).find()) { try { if (matcher.group(2) != null && matcher.group(2).equals("tutor")) Database.getInstance().userAdd(matcher.group(1), UserType.TUTOR); else if (matcher.group(2) != null && matcher.group(2).equals("student")) Database.getInstance().userAdd(matcher.group(1), UserType.STUDENT); else if (matcher.group(2) == null || matcher.group(2).equals("community")) Database.getInstance().userAdd(matcher.group(1), UserType.COMMUNITY); } catch (DatabaseException e) { Formatter.outputError(e.getMessage()); } } else Formatter.outputError("Invalid syntax..."); return true; case CATALOGADD: //https://regex101.com/r/nU9qD4/2 pattern = Pattern.compile("^(?i)\\s*catalog\\s+add\\s+\\\"\\s*" + "([a-zA-Z0-9][a-zA-Z0-9\\s]+[a-zA-Z0-9])\\s*\\\"(?:\\s+" + "(text|general))?\\s*;\\s*$"); if ((matcher = pattern.matcher(line)).find()) { try { if (matcher.group(2) != null && matcher.group(2).equals("text")) Database.getInstance().catalogAdd(matcher.group(1), BookType.TEXT); else if (matcher.group(2) == null || matcher.group(2).equals("general")) Database.getInstance().catalogAdd(matcher.group(1), BookType.GENERAL); } catch (DatabaseException e) { Formatter.outputError(e.getMessage()); } } else Formatter.outputError("Invalid syntax..."); return true; case CHECKOUT: //https://regex101.com/r/lV3vI3/2 pattern = Pattern.compile( "^(?i)\\s*lend\\s+\\\"\\s*([a-zA-Z0-9][a-zA-Z0-9\\s]+[a-zA-Z0-9])" + "\\s*\\\"\\s+to\\s+\\\"\\s*([a-zA-Z0-9][a-zA-Z0-9\\s]+[a-zA-Z0-9])" + "\\s*\\\"\\s*;\\s*$"); if ((matcher = pattern.matcher(line)).find()) { try { Database.getInstance().checkOut(matcher.group(2), matcher.group(1), date); } catch (Exception e) { Formatter.outputError(e.getMessage()); } } else Formatter.outputError("Invalid syntax..."); return true; case CHECKIN: //https://regex101.com/r/rT4hC9/3 pattern = Pattern.compile( "^(?i)\\s*return\\s+\\\"\\s*([a-zA-Z0-9][a-zA-Z0-9\\s]+[a-zA-Z0-9])" + "\\s*\\\"\\s*;\\s*$"); if ((matcher = pattern.matcher(line)).find()) { try { Database.getInstance().checkIn(matcher.group(1), date); } catch (Exception e) { Formatter.outputError(e.getMessage()); } } else Formatter.outputError("Invalid syntax..."); return true; case LIST: //https://regex101.com/r/qI7wF9/10 if (line.matches("^(?i)\\s*list(?:\\s+(?:users|books|loans))+\\s*;\\s*$")) { pattern = Pattern.compile("(users|books|loans)"); matcher = pattern.matcher(line); while (matcher.find()) { if (matcher.group(1).equals("users")) Formatter.outputUsers(Database.getInstance().getUsers(), Database.getInstance().getLoans(), date); else if (matcher.group(1).equals("books")) Formatter.outputBooks(Database.getInstance().getBooks()); else if (matcher.group(1).equals("loans")) Formatter.outputLoans(Database.getInstance().getLoans(), date); } } return true; case EXIT: try { // Stop watchdog service Watchdog.getInstance().stop(); // Update the database and quit app Database.getInstance().serializeAndUpdate(); } catch (Exception e) { Formatter.outputError(e.getMessage()); } return true; default: return false; } } }
38.1875
100
0.440262
f5af285adc52842d54fd868140fa83c5f551ef5a
1,800
package org.softuni.residentevil.web.controllers.user; import org.softuni.residentevil.config.WebConfig; import org.softuni.residentevil.domain.models.binding.user.UserRegisterBindingModel; import org.softuni.residentevil.service.UserService; import org.softuni.residentevil.web.annotations.Layout; import org.softuni.residentevil.web.controllers.BaseController; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid; import java.util.List; @Layout @Controller @RequestMapping(WebConfig.URL_USER_REGISTER) public class RegisterUserController extends BaseController { public static final String USER = "user"; private static final String VIEW_REGISTER = "user/register"; private final UserService userService; public RegisterUserController(UserService userService) { this.userService = userService; } @Override protected List<String> getUnmodifiedTextFieldsList() { return List.of("password", "confirmPassword"); } @GetMapping public String get(Model model) { model.addAttribute(USER, new UserRegisterBindingModel()); return VIEW_REGISTER; } @PostMapping public String post(@Valid @ModelAttribute(USER) UserRegisterBindingModel user, Errors errors) { if (errors.hasErrors()) { return VIEW_REGISTER; } userService.registerUser(user); return redirect(WebConfig.URL_USER_HOME); } }
31.034483
84
0.759444
55237d3b9b288d736f2d0630235b87a4ad9b4fa0
5,958
package gov.usgs.cida.wqp.dao.count; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DbUnitConfiguration; import gov.usgs.cida.wqp.ColumnSensingFlatXMLDataSetLoader; import gov.usgs.cida.wqp.dao.CountDao; import gov.usgs.cida.wqp.dao.NameSpace; import gov.usgs.cida.wqp.parameter.FilterParameters; import gov.usgs.cida.wqp.springinit.DBTestConfig; import java.util.List; import java.util.Map; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.NONE, classes={DBTestConfig.class, CountDao.class}) @DatabaseSetup("classpath:/testData/clearAll.xml") @DatabaseSetup("classpath:/testData/station.xml") @DbUnitConfiguration(dataSetLoader = ColumnSensingFlatXMLDataSetLoader.class) public class CountDaoSummaryMonitoringLocationIT extends BaseStationCountDaoTest { protected NameSpace nameSpace = NameSpace.SUMMARY_MONITORING_LOCATION; public static final String TOTAL_SITE_SUMMARY_COUNT = "11"; public static final String SUMMARY_YEARS_12_MONTHS = "1"; public static final String SUMMARY_YEARS_60_MONTHS = "5"; public static final String SUMMARY_YEARS_ALL_MONTHS = "all"; @Test public void testHarness() { bboxTest(nameSpace); countryTest(nameSpace); emptyParameterTest(nameSpace); huc8Test(nameSpace); mimeTypeSummaryTest(nameSpace); nullParameterTest(nameSpace); organizationTest(nameSpace); providersTest(nameSpace); siteIdTest(nameSpace); siteTypeTest(nameSpace); stateTest(nameSpace); withinTest(nameSpace); multipleParameterStationSumTest(nameSpace); allYearsSummaryTest(nameSpace); oneYearSummaryTest(nameSpace); fiveYearsSummaryTest(nameSpace); } public void bboxTest(NameSpace nameSpace) { List<Map<String, Object>> counts = bboxTest(nameSpace, 4); assertStationResults(counts, "8", "2", "2", "4", null); } public void countryTest(NameSpace nameSpace) { List<Map<String, Object>> counts = countryTest(nameSpace, 5); assertStationResults(counts, "10", "2", "2", "5", "1"); } public void emptyParameterTest(NameSpace nameSpace) { List<Map<String, Object>> counts = emptyParameterTest(nameSpace, 5); assertStationResults(counts, TOTAL_SITE_SUMMARY_COUNT, "2", "2", "6", "1"); } public void huc8Test(NameSpace nameSpace) { List<Map<String, Object>> counts = huc8Test(nameSpace, 2); assertStationResults(counts, "1", null, null, "1", null); } public void mimeTypeSummaryTest(NameSpace nameSpace) { List<Map<String, Object>> counts = mimeTypeJsonTest(nameSpace, 5); assertStationResults(counts, TOTAL_SITE_SUMMARY_COUNT, "2", "2", "6", "1"); counts = mimeTypeGeoJsonTest(nameSpace, 5); assertStationResults(counts, TOTAL_SITE_SUMMARY_COUNT, "2", "2", "6", "1"); } public void nullParameterTest(NameSpace nameSpace) { List<Map<String, Object>> counts = nullParameterTest(nameSpace, 5); assertStationResults(counts, TOTAL_SITE_SUMMARY_COUNT, "2", "2", "6", "1"); } public void organizationTest(NameSpace nameSpace) { List<Map<String, Object>> counts = organizationTest(nameSpace, 4); assertStationResults(counts, "9", "2", "2", "5", null); } public void providersTest(NameSpace nameSpace) { List<Map<String, Object>> counts = providersTest(nameSpace, 4); assertStationResults(counts, "10", "2", "2", "6", null); } public void siteIdTest(NameSpace nameSpace) { List<Map<String, Object>> counts = siteIdTest(nameSpace, 4); assertStationResults(counts, "8", "2", "2", "4", null); } public void siteTypeTest(NameSpace nameSpace) { List<Map<String, Object>> counts = siteTypeTest(nameSpace, 5); assertStationResults(counts, "10", "1", "2", "6", "1"); } public void stateTest(NameSpace nameSpace) { List<Map<String, Object>> counts = stateTest(nameSpace, 4); assertStationResults(counts, "9", "2", "2", "5", null); } public void withinTest(NameSpace nameSpace) { List<Map<String, Object>> counts = withinTest(nameSpace, 4); assertStationResults(counts, "9", "2", "2", "5", null); } @Override public List<Map<String, Object>> multipleParameterStationSumTest(NameSpace nameSpace, int expectedSize) { FilterParameters filter = getNoEffectParameters(nameSpace); filter.setBBox(getBBox()); filter.setCountrycode(getCountry()); filter.setCountycode(getCounty()); filter.setHuc(getHuc()); filter.setLat(getLatitude()); filter.setLong(getLongitude()); filter.setNldiurl(getNldiurl()); filter.setOrganization(getOrganization()); filter.setProviders(getProviders()); filter.setSiteid(getSiteId()); filter.setSiteType(getSiteType()); filter.setStatecode(getState()); filter.setSummaryYears(getSummaryYears()); filter.setWithin(getWithin()); return callDao(nameSpace, expectedSize, filter); } public void multipleParameterStationSumTest(NameSpace nameSpace) { List<Map<String, Object>> counts = multipleParameterStationSumTest(nameSpace, 3); assertStationResults(counts, "3", null, "2", "1", null); } public List<Map<String, Object>> summaryYearsTest(NameSpace nameSpace, String summaryYears, int expectedSize) { FilterParameters filter = new FilterParameters(); filter.setSummaryYears(summaryYears); return callDao(nameSpace, expectedSize, filter); } public void allYearsSummaryTest(NameSpace nameSpace) { List<Map<String, Object>> counts = summaryYearsTest(nameSpace, SUMMARY_YEARS_ALL_MONTHS, 5); assertStationResults(counts, TOTAL_SITE_SUMMARY_COUNT, "2", "2", "6", "1"); } public void oneYearSummaryTest(NameSpace nameSpace) { List<Map<String, Object>> counts = summaryYearsTest(nameSpace, SUMMARY_YEARS_12_MONTHS, 5); assertStationResults(counts, "9", "2", "2", "4", "1"); } public void fiveYearsSummaryTest(NameSpace nameSpace) { List<Map<String, Object>> counts = summaryYearsTest(nameSpace, SUMMARY_YEARS_60_MONTHS, 5); assertStationResults(counts, "10", "2", "2", "5", "1"); } }
37.006211
112
0.749748
7f6fa8188d2c28698dcbff95ded81a9576dc697d
1,891
/* * Copyright 2006 University of Virginia * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package edu.virginia.vcgr.genii.security.wincrypto; import javax.net.ssl.TrustManagerFactorySpi; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.X509TrustManager; import javax.net.ssl.TrustManager; import java.security.KeyStoreException; import java.security.KeyStore; /** * This class defines the Service Provider Interface (SPI) for the WinX509TM TrustManagerFactory class. * * @author Duane Merrill * */ public final class WinX509TrustManagerFactorySpi extends TrustManagerFactorySpi { /** Wrapped X509TrustManager */ private X509TrustManager _trustManager; /** * Returns one trust manager for each type of trust material. */ protected TrustManager[] engineGetTrustManagers() { return new TrustManager[] { _trustManager }; } /** * Initializes this factory with a source of certificate authorities and related trust material. */ synchronized protected void engineInit(KeyStore ks) throws KeyStoreException { if (_trustManager == null) { _trustManager = new WinX509TrustManager(); } } /** * Initializes this factory with a source of provider-specific key material. */ synchronized protected void engineInit(ManagerFactoryParameters spec) { if (_trustManager == null) { _trustManager = new WinX509TrustManager(); } } }
30.015873
139
0.760444
106c91327d2fb833aa3a08e643c4a0c18a2bdbac
525
package net.n2oapp.criteria.filters.rule; import net.n2oapp.criteria.filters.FilterType; import net.n2oapp.criteria.filters.Pair; import net.n2oapp.criteria.filters.rule.base.AlwaysSuccessRule; /** * Rule for merge isNotNull and contains filters * */ public class Contains_IsNotNull extends AlwaysSuccessRule { public Contains_IsNotNull() { super(FilterType.contains); } @Override public Pair<FilterType> getType() { return new Pair<>(FilterType.contains, FilterType.isNotNull); } }
25
69
0.739048
894073777c55c6c36ebd481a50523ec1c658ad4d
3,502
/* * 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 org.mage.test.cards.abilities.keywords; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Ignore; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * * @author escplan9 (Derek Monturo - dmontur1 at gmail dot com) */ public class ProwlTest extends CardTestPlayerBase { @Ignore // have not figured out how to have the test API cast a card using Prowl yet @Test public void testBasicProwlCasting() { // Auntie's Snitch {2}{B} Creature — Goblin Rogue (3/1) // Auntie's Snitch can't block. // Prowl {1}{B} (You may cast this for its prowl cost if you dealt combat damage to a player this turn with a Goblin or Rogue.) // Whenever a Goblin or Rogue you control deals combat damage to a player, if Auntie's Snitch is in your graveyard, you may return Auntie's Snitch to your hand. addCard(Zone.HAND, playerA, "Auntie's Snitch"); // {1}{R} Creature — Goblin Warrior 1/1 // Red creatures you control have first strike. addCard(Zone.BATTLEFIELD, playerA, "Bloodmark Mentor"); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 2); attack(1, playerA, "Bloodmark Mentor"); castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Auntie's Snitch using prowl"); setChoice(playerA, "Yes"); // choosing to pay prowl cost setStopAt(1, PhaseStep.END_TURN); execute(); assertLife(playerB, 19); assertPermanentCount(playerA, "Bloodmark Mentor", 1); assertPermanentCount(playerA, "Auntie's Snitch", 1); } /* * Reported bug: Prowl is not taking into consideration other cost reducing effects. For instance Goblin Warchief * does not reduce the Prowl cost of other Goblin cards with Prowl ability. */ @Ignore // have not figured out how to have the test API cast a card using Prowl yet @Test public void testProwlWithCostDiscount() { // Auntie's Snitch {2}{B} Creature — Goblin Rogue (3/1) // Auntie's Snitch can't block. // Prowl {1}{B} (You may cast this for its prowl cost if you dealt combat damage to a player this turn with a Goblin or Rogue.) // Whenever a Goblin or Rogue you control deals combat damage to a player, if Auntie's Snitch is in your graveyard, you may return Auntie's Snitch to your hand. addCard(Zone.HAND, playerA, "Auntie's Snitch"); // Goblin Warchief {1}{R}{R} Creature — Goblin Warrior (2/2) // Goblin spells you cast cost 1 less to cast. // Goblin creatures you control have haste. addCard(Zone.BATTLEFIELD, playerA, "Goblin Warchief"); addCard(Zone.BATTLEFIELD, playerA, "Swamp"); attack(1, playerA, "Goblin Warchief"); castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Auntie's Snitch using prowl"); // should only cost {B} with Warchief discount setChoice(playerA, "Yes"); // choosing to pay prowl cost setStopAt(1, PhaseStep.END_TURN); execute(); assertLife(playerB, 18); assertPermanentCount(playerA, "Goblin Warchief", 1); assertPermanentCount(playerA, "Auntie's Snitch", 1); } }
44.897436
168
0.652199
46963d79df944d21363a507c4512a07c56c79ff5
4,133
package com.ait.lienzo.charts.client.xy; import com.ait.lienzo.charts.client.model.DataTable; import com.ait.lienzo.charts.client.model.DataTableColumn; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; public class XYChartDataSummary { private XYChartData data; private double maxNumericValue; private Date maxDateValue; private double minNumericValue; private Date minDateValue; private int numSeries; private List<String> addedSeries = new ArrayList(); private List<String> removedSeries = new ArrayList(); public XYChartDataSummary(XYChartData data) { this.data = data; build(); } public XYChartDataSummary(XYChartData data, Collection<String> currentSerieNames) { // Build the summary. this(data); if (data != null && currentSerieNames != null) { // Chech added or removed series from last chart data. XYChartSerie[] newSeries = data.getSeries(); for (XYChartSerie newSerie : newSeries) { if (!currentSerieNames.contains(newSerie.getName())) addedSeries.add(newSerie.getName()); } for (String oldSerieName : currentSerieNames) { if (isSerieRemoved(newSeries, oldSerieName)) removedSeries.add(oldSerieName); } } } private boolean isSerieRemoved(XYChartSerie[] series, String serieName) { if (serieName == null || series == null) return false; for (XYChartSerie _serie : series) { if (_serie.getName().equals(serieName)) return false; } return true; } public void build() { if (data == null) return; final XYChartSerie[] series = data.getSeries(); this.numSeries = series.length; for (int i = 0; i < series.length; i++) { XYChartSerie serie = series[i]; String categoryAxisProperty = data.getCategoryAxisProperty(); String valuesAxisProperty = serie.getValuesAxisProperty(); DataTable dataTable = data.getDataTable(); DataTableColumn categoryColumn = dataTable.getColumn(categoryAxisProperty); DataTableColumn valuesColumn = dataTable.getColumn(valuesAxisProperty); DataTableColumn.DataTableColumnType valuesColumnType = valuesColumn.getType(); Object[] values = null; switch (valuesColumnType) { case NUMBER: values = valuesColumn.getNumericValues(); if (values != null && values.length > 0) { for (int j = 0; j < values.length; j++) { Double value = (Double) values[j]; if (value >= maxNumericValue) maxNumericValue = value; if (value <= minNumericValue) minNumericValue = value; } } break; case DATE: values = valuesColumn.getDateValues(); if (values != null && values.length > 0) { for (int j = 0; j < values.length; j++) { Date value = (Date) values[j]; if (value.after(maxDateValue)) maxDateValue = value; if (value.before(minDateValue)) minDateValue = value; } } break; } } } public double getMaxNumericValue() { return maxNumericValue; } public Date getMaxDateValue() { return maxDateValue; } public double getMinNumericValue() { return minNumericValue; } public Date getMinDateValue() { return minDateValue; } public XYChartData getData() { return data; } public int getNumSeries() { return numSeries; } public List<String> getAddedSeries() { return addedSeries; } public List<String> getRemovedSeries() { return removedSeries; } }
32.03876
105
0.573191
18a7e6eee2e4b41d41929b232da7c008d31c7159
3,050
package com.helloingob.gifter.data.to; import java.sql.Timestamp; public class Giveaway { private String title; private Integer points; private Integer copies; private Integer entries; private Double winChance; private String author; private String giveawayLink; private String steamLink; private String imageLink; private Integer levelRequirement; private String code; private Integer subId; private Integer appId; private Timestamp endDate; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getPoints() { return points; } public void setPoints(Integer points) { this.points = points; } public Integer getCopies() { return copies; } public void setCopies(Integer copies) { this.copies = copies; } public Integer getEntries() { return entries; } public void setEntries(Integer entries) { this.entries = entries; } public Double getWinChance() { return winChance; } public void setWinChance(Double winChance) { this.winChance = winChance; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getGiveawayLink() { return giveawayLink; } public void setGiveawayLink(String giveawayLink) { this.giveawayLink = giveawayLink; } public String getSteamLink() { return steamLink; } public void setSteamLink(String steamLink) { this.steamLink = steamLink; } public String getImageLink() { return imageLink; } public void setImageLink(String imageLink) { this.imageLink = imageLink; } public Integer getLevelRequirement() { return levelRequirement; } public void setLevelRequirement(Integer levelRequirement) { this.levelRequirement = levelRequirement; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Integer getSubId() { return subId; } public void setSubId(Integer subId) { this.subId = subId; } public Integer getAppId() { return appId; } public void setAppId(Integer appId) { this.appId = appId; } public Timestamp getEndDate() { return endDate; } public void setEndDate(Timestamp endDate) { this.endDate = endDate; } @Override public String toString() { return String.format("GiveawayTO [title=%s, points=%s, copies=%s, entries=%s, winChance=%s, author=%s, giveawayLink=%s, steamLink=%s, imageLink=%s, levelRequirement=%s, code=%s, subId=%s, appId=%s, endDate=%s]", title, points, copies, entries, winChance, author, giveawayLink, steamLink, imageLink, levelRequirement, code, subId, appId, endDate); } }
21.785714
354
0.630164
26cdc95cfbe4839dbe60c247341752f3dd2c01df
3,475
import com.datarangers.sdk.RangersClient; import java.util.HashMap; /** * @Author [email protected] * @Date 2020-06-15 */ public class ExampleBySdk { public static void getDataExportUrl() throws Exception { String ak = "xxx"; String sk = "xxx"; RangersClient rangersClient = new RangersClient(ak, sk); String res = rangersClient.dataRangers("/openapi/v1/xxx/date/2020-05-03/2020-05-09/downloads", "get"); System.out.println(res); } public static void testFinderAll() throws Exception { String ak = "xxx"; String sk = "xxx"; RangersClient rangersClient = new RangersClient(ak, sk); String res = rangersClient.dataFinder("/openapi/v1/xxx/dashboards/all", "get"); System.out.println(res); } public static void testFinderDashboard() throws Exception { String ak = "xxx"; String sk = "xxx"; RangersClient rangersClient = new RangersClient(ak, sk); String res = rangersClient.dataFinder("/openapi/v1/xxx/dashboards/xxx", "get"); System.out.println(res); } public static void testFinderDashboardReports() throws Exception { String ak = "xxx"; String sk = "xxx"; RangersClient rangersClient = new RangersClient(ak, sk); String res = rangersClient.dataFinder("/openapi/v1/xxx/dashboards/xxx/reports", "get"); System.out.println(res); } public static void testFinderDashboardReport(String id) throws Exception { String ak = "xxx"; String sk = "xxx"; RangersClient rangersClient = new RangersClient(ak, sk); HashMap<String, String> headers = new HashMap<>(); HashMap<String, String> params = new HashMap<>(); params.put("count", "10"); String res = rangersClient.dataFinder("/openapi/v1/xxx/reports/" + id, "get", headers, params, null); System.out.println(res); } public static void testFinderCohorts() throws Exception { String ak = "xxx"; String sk = "xxx"; RangersClient rangersClient = new RangersClient(ak, sk); String res = rangersClient.dataFinder("/openapi/v1/xxx/cohorts", "get"); System.out.println(res); } public static void testFinderCohort() throws Exception { String ak = "xxx"; String sk = "xxx"; RangersClient rangersClient = new RangersClient(ak, sk); String res = rangersClient.dataFinder("/openapi/v1/xxxx/cohorts/xxx", "get"); System.out.println(res); } public static void testFinderCohortsSample() throws Exception { String ak = "xxxx"; String sk = "xxxx"; RangersClient rangersClient = new RangersClient(ak, sk); HashMap<String, String> headers = new HashMap<>(); HashMap<String, String> params = new HashMap<>(); params.put("count", "10"); String res = rangersClient.dataFinder("/openapi/v1/xxx/cohorts/xxx/sample", "get", headers, params, null); System.out.println(res); } public static void main(String[] args) { try { getDataExportUrl(); testFinderAll(); testFinderDashboard(); testFinderDashboardReports(); testFinderDashboardReport("xxx"); testFinderCohorts(); testFinderCohort(); testFinderCohortsSample(); } catch (Exception e) { e.printStackTrace(); } } }
35.824742
114
0.620719
bb0653684d828e12c49685d31e1f946df9223631
8,632
package com.bacloud.word2vecdemo; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Environment; import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import org.deeplearning4j.models.embeddings.loader.WordVectorSerializer; import org.deeplearning4j.models.word2vec.Word2Vec; import org.deeplearning4j.nn.api.Model; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.util.ModelSerializer; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.stream.Collectors; public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback { private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkDependencies(); verifyStoragePermission(MainActivity.this); startBackgroundThread(); // Model myNetwork = null; // String path =""; // saveNetLocal(myNetwork, path); // loadNetLocal(path); // INDArray input = null; // loadNetExternal(input); } private void startBackgroundThread() { Thread thread; thread = new Thread(() -> { createAndUseNetwork(); }); thread.start(); } private final static int ngrams = 2; private void createAndUseNetwork() { // int seed = 248; // MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() // .seed(seed) // .weightInit(WeightInit.XAVIER) // .updater(Updater.ADAM) // .list() // .layer(new DenseLayer.Builder() // .nIn(2) // .nOut(3) // .activation(Activation.RELU) // .build()) // .layer(new DenseLayer.Builder() // .nOut(2) // .activation(Activation.RELU) // .build()) // .layer(new OutputLayer.Builder(LossFunctions.LossFunction.XENT) //NEGATIVELOGLIKELIHOOD // .weightInit(WeightInit.XAVIER) // .activation(Activation.SIGMOID) // .nOut(1).build()) // .build(); // // // MultiLayerNetwork model = new MultiLayerNetwork(conf); // model.init(); String filePath = "raw_sentences.txt"; ArrayList<Collection<String>> emojisVectors = new ArrayList(); String modelPath = "pathToWriteto.txt"; File test = new File(this.getFilesDir().getAbsolutePath(), modelPath); Word2Vec vec = WordVectorSerializer.readWord2VecModel(test); try { FileInputStream fis = new FileInputStream("emojisVectors"); ObjectInputStream ois = new ObjectInputStream(fis); emojisVectors = (ArrayList<Collection<String>>) ois.readObject(); ois.close(); fis.close(); } catch (IOException ioe) { ioe.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println("Class not found"); c.printStackTrace(); return; } String emojisPath = "emojis.json"; JSONParser parser = new JSONParser(); ArrayList<String[]> rows = new ArrayList<String[]>(); try { JSONArray jsonArray = (JSONArray) parser.parse(new FileReader(emojisPath)); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonobject = (JSONObject) jsonArray.get(i); String[] row = new String[3]; row[0] = (String) jsonobject.get("name"); row[1] = (String) jsonobject.get("unicode"); JSONArray keywords = (JSONArray) jsonobject.get("keywords"); String row2 = ""; for (int j = 0; j < keywords.size(); j++) { row2 = row2 + " " + keywords.get(j); } row[2] = row2; rows.add(row); } } catch (ParseException | FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } DLUtils.check(vec, emojisVectors, rows, "star"); DLUtils.check(vec, emojisVectors, rows, "nice people"); DLUtils.check(vec, emojisVectors, rows, "black man"); DLUtils.check(vec, emojisVectors, rows, "very excited"); DLUtils.check(vec, emojisVectors, rows, "skateboard snow"); } private String pathToString(String s) { String content = null; BufferedReader reader = null; try { reader = new BufferedReader( new InputStreamReader(getAssets().open(s))); // do reading, usually loop until end of file reading // String mLine; // while ((mLine = reader.readLine()) != null) { // //process line // } content = reader.lines().collect(Collectors.joining()); } catch (IOException e) { //log the exception } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { //log the exception } } } return content; } private void loadNetExternal(INDArray input) { try { // Load name of model file (yourModel.zip). InputStream is = getResources().openRawResource(R.raw.your_model); // Load yourModel.zip. MultiLayerNetwork restored = ModelSerializer.restoreMultiLayerNetwork(is); // Use yourModel. INDArray results = restored.output(input); System.out.println("Results: " + results); // Handle the exception error } catch (IOException e) { e.printStackTrace(); } } private MultiLayerNetwork loadNetLocal(String path) { MultiLayerNetwork restored = null; try { //Load the model File file = new File(Environment.getExternalStorageDirectory() + "/trained_model.zip"); restored = ModelSerializer.restoreMultiLayerNetwork(file); } catch (Exception e) { Log.e("Load from External Storage error", e.getMessage()); } return restored; } private void saveNetLocal(Model myNetwork, String path) { try { File file = new File(Environment.getExternalStorageDirectory() + "/trained_model.zip"); OutputStream outputStream = new FileOutputStream(file); boolean saveUpdater = true; ModelSerializer.writeModel(myNetwork, outputStream, saveUpdater); } catch (Exception e) { Log.e("saveToExternalStorage error", e.getMessage()); } } public void verifyStoragePermission(Activity activity) { // Get permission status int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don't have permission we request it ActivityCompat.requestPermissions( activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); } } private void checkDependencies() { // this will limit frequency of gc calls to 5000 milliseconds Nd4j.getMemoryManager().setAutoGcWindow(5000); } }
35.817427
114
0.597544
b518e096314086a49da054a646db81b245a8e8ce
336
package bitflow4j.steps.query.exceptions; import java.io.IOException; /** * Abstract class for exceptions where is a problem with sample header. */ public abstract class IllegalHeaderException extends IOException { public IllegalHeaderException(String query) { super("Parsing Error when processing: " + query); } }
24
71
0.744048
ba25e33533035554f0521ff4a9cf47daeae8b012
3,351
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.messages; import java.util.List; /** Algebraic type describing the different template (or email) types. */ public abstract class TemplateType { private TemplateType() { } public enum Type { INVITATION(TemplateType.INVITATION), REMEMBER(null), THANK_YOU(null), ACKNOWLEDGE(TemplateType.ACKNOWLEDGE); private final TemplateType type; Type(TemplateType type) { this.type = type; } /** Get the respective template type implementation. */ public TemplateType getType() { return type; } } /** Return the type identifier. */ public abstract Type getType(); // todo provide information about template data suitable to be displayed in the UI public static final Invitation INVITATION = new Invitation(); public static final Acknowledge ACKNOWLEDGE = new Acknowledge(); /** The invitation email template. */ public static final class Invitation extends TemplateType { private Invitation() { } @Override public Type getType() { return Type.INVITATION; } public static Data data(String staff, String optOutLink, List<Module> modules) { return new Data(staff, optOutLink, modules); } public static Module module(String name, String description) { return new Module(name, description); } /** Template data for an invitation email template. */ public static final class Data { private final String staff; private final String optOutLink; private final List<Module> modules; public Data(String staff, String optOutLink, List<Module> modules) { this.staff = staff; this.optOutLink = optOutLink; this.modules = modules; } public String getStaff() { return staff; } public String getOptOutLink() { return optOutLink; } public List<Module> getModules() { return modules; } } public static final class Module { private final String name; private final String description; public Module(String name, String description) { this.name = name; this.description = description; } public String getName() { return name; } public String getDescription() { return description; } } } public static final class Acknowledge extends TemplateType { @Override public Type getType() { return Type.ACKNOWLEDGE; } } // todo implement other template types }
26.595238
112
0.680692
146b01d46a13deeed8b038d03aa6709bec87541e
795
import java.math.*; public class Exo4 { public static boolean estUnEntier(String chaine) { try { Integer.parseInt(chaine); } catch (NumberFormatException e) { return false; } return true; } public static void main(String args[]) { int nombre1=0,nombre=0,resultat=0; if (/*La 1ere chaine n'est pas un entier*/ (estUnEntier(args[0])==false) || /*OUBIEN La 2nde chaine n'est pas l'operateur d'addition*/ (args[1]!="+") || /*OUBIEN La 3eme chaine n'est pas un entier*/ (estUnEntier(args[2])==false) ) { System.out.println("Erreur(s) dans la syntaxe."); } else { nombre1=parseInt(args[0]); nombre2=parseInt(args[1]); resultat=nombre1+nombre2; System.out.println("Resultat = " + resultat); } } }
24.090909
84
0.612579
907ee936f72e8c61a9f8207ee8026572f398adbc
630
package com.sly.hial.business.blog.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sly.hial.business.blog.service.ContentService; import com.sly.hial.business.system.service.impl.DicCodeServiceImpl; /** * 文章service实现类 * @author sly * @time 2019年5月5日 */ @Service @Transactional(rollbackFor=Exception.class) public class ContentServiceImpl implements ContentService { private static final Logger LOGGER = LoggerFactory.getLogger(DicCodeServiceImpl.class); }
30
89
0.795238
473f8a281ca4db400d08a2c1091f7779811d575b
2,099
package com.clinacuity.acv.controls; import com.jfoenix.controls.JFXTextField; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; class AnnotationDropCardRow extends HBox { private static final Logger logger = LogManager.getLogger(); private static final String LOCKED_STYLE = "button-locked"; @FXML private JFXTextField attributeTextField; @FXML private Label attributeLabel; @FXML private Label lockLabel; @FXML private Label removeLabel; private AnnotationDropCard parent; private boolean locked = false; JFXTextField getAttributeTextField() { return attributeTextField; } boolean isLocked() { return locked; } String getName() { return attributeLabel.getText(); } AnnotationDropCardRow(String attribute, String initialValue, boolean includeButtons, AnnotationDropCard parentCard) { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/controls/AnnotationDropCardRow.fxml")); fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch (IOException e) { logger.throwing(e); } attributeLabel.setText(attribute); attributeTextField.setText(initialValue); parent = parentCard; if (!includeButtons) { lockLabel.setVisible(false); removeLabel.setVisible(false); } } @FXML private void toggleLock() { locked = !locked; if (locked) { lockLabel.getStyleClass().add(LOCKED_STYLE); removeLabel.setOpacity(0.25d); parent.toggleLock(this); } else { lockLabel.getStyleClass().remove(LOCKED_STYLE); removeLabel.setOpacity(1.0d); parent.toggleLock(this); } } @FXML private void removeRow() { if (!locked) { parent.removeRow(this); } } }
30.867647
121
0.666508
641c37d53805852eb284d76c17db4d7868fd112f
16,164
/* * Copyright (c) 2014 AsyncHttpClient Project. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package org.asynchttpclient.config; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public final class AsyncHttpClientConfigDefaults { public static final String ASYNC_CLIENT_CONFIG_ROOT = "org.asynchttpclient."; public static final String THREAD_POOL_NAME_CONFIG = "threadPoolName"; public static final String MAX_CONNECTIONS_CONFIG = "maxConnections"; public static final String MAX_CONNECTIONS_PER_HOST_CONFIG = "maxConnectionsPerHost"; public static final String ACQUIRE_FREE_CHANNEL_TIMEOUT = "acquireFreeChannelTimeout"; public static final String CONNECTION_TIMEOUT_CONFIG = "connectTimeout"; public static final String POOLED_CONNECTION_IDLE_TIMEOUT_CONFIG = "pooledConnectionIdleTimeout"; public static final String CONNECTION_POOL_CLEANER_PERIOD_CONFIG = "connectionPoolCleanerPeriod"; public static final String READ_TIMEOUT_CONFIG = "readTimeout"; public static final String REQUEST_TIMEOUT_CONFIG = "requestTimeout"; public static final String CONNECTION_TTL_CONFIG = "connectionTtl"; public static final String FOLLOW_REDIRECT_CONFIG = "followRedirect"; public static final String MAX_REDIRECTS_CONFIG = "maxRedirects"; public static final String COMPRESSION_ENFORCED_CONFIG = "compressionEnforced"; public static final String USER_AGENT_CONFIG = "userAgent"; public static final String ENABLED_PROTOCOLS_CONFIG = "enabledProtocols"; public static final String ENABLED_CIPHER_SUITES_CONFIG = "enabledCipherSuites"; public static final String FILTER_INSECURE_CIPHER_SUITES_CONFIG = "filterInsecureCipherSuites"; public static final String USE_PROXY_SELECTOR_CONFIG = "useProxySelector"; public static final String USE_PROXY_PROPERTIES_CONFIG = "useProxyProperties"; public static final String VALIDATE_RESPONSE_HEADERS_CONFIG = "validateResponseHeaders"; public static final String AGGREGATE_WEBSOCKET_FRAME_FRAGMENTS_CONFIG = "aggregateWebSocketFrameFragments"; public static final String ENABLE_WEBSOCKET_COMPRESSION_CONFIG = "enableWebSocketCompression"; public static final String STRICT_302_HANDLING_CONFIG = "strict302Handling"; public static final String KEEP_ALIVE_CONFIG = "keepAlive"; public static final String MAX_REQUEST_RETRY_CONFIG = "maxRequestRetry"; public static final String DISABLE_URL_ENCODING_FOR_BOUND_REQUESTS_CONFIG = "disableUrlEncodingForBoundRequests"; public static final String USE_LAX_COOKIE_ENCODER_CONFIG = "useLaxCookieEncoder"; public static final String USE_OPEN_SSL_CONFIG = "useOpenSsl"; public static final String USE_INSECURE_TRUST_MANAGER_CONFIG = "useInsecureTrustManager"; public static final String DISABLE_HTTPS_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG = "disableHttpsEndpointIdentificationAlgorithm"; public static final String SSL_SESSION_CACHE_SIZE_CONFIG = "sslSessionCacheSize"; public static final String SSL_SESSION_TIMEOUT_CONFIG = "sslSessionTimeout"; public static final String TCP_NO_DELAY_CONFIG = "tcpNoDelay"; public static final String SO_REUSE_ADDRESS_CONFIG = "soReuseAddress"; public static final String SO_KEEP_ALIVE_CONFIG = "soKeepAlive"; public static final String SO_LINGER_CONFIG = "soLinger"; public static final String SO_SND_BUF_CONFIG = "soSndBuf"; public static final String SO_RCV_BUF_CONFIG = "soRcvBuf"; public static final String HTTP_CLIENT_CODEC_MAX_INITIAL_LINE_LENGTH_CONFIG = "httpClientCodecMaxInitialLineLength"; public static final String HTTP_CLIENT_CODEC_MAX_HEADER_SIZE_CONFIG = "httpClientCodecMaxHeaderSize"; public static final String HTTP_CLIENT_CODEC_MAX_CHUNK_SIZE_CONFIG = "httpClientCodecMaxChunkSize"; public static final String HTTP_CLIENT_CODEC_INITIAL_BUFFER_SIZE_CONFIG = "httpClientCodecInitialBufferSize"; public static final String DISABLE_ZERO_COPY_CONFIG = "disableZeroCopy"; public static final String HANDSHAKE_TIMEOUT_CONFIG = "handshakeTimeout"; public static final String CHUNKED_FILE_CHUNK_SIZE_CONFIG = "chunkedFileChunkSize"; public static final String WEBSOCKET_MAX_BUFFER_SIZE_CONFIG = "webSocketMaxBufferSize"; public static final String WEBSOCKET_MAX_FRAME_SIZE_CONFIG = "webSocketMaxFrameSize"; public static final String KEEP_ENCODING_HEADER_CONFIG = "keepEncodingHeader"; public static final String SHUTDOWN_QUIET_PERIOD_CONFIG = "shutdownQuietPeriod"; public static final String SHUTDOWN_TIMEOUT_CONFIG = "shutdownTimeout"; public static final String USE_NATIVE_TRANSPORT_CONFIG = "useNativeTransport"; public static final String IO_THREADS_COUNT_CONFIG = "ioThreadsCount"; public static final String HASHED_WHEEL_TIMER_TICK_DURATION = "hashedWheelTimerTickDuration"; public static final String HASHED_WHEEL_TIMER_SIZE = "hashedWheelTimerSize"; public static final String AHC_VERSION; static { try (InputStream is = AsyncHttpClientConfigDefaults.class.getResourceAsStream("ahc-version.properties")) { Properties prop = new Properties(); prop.load(is); AHC_VERSION = prop.getProperty("ahc.version", "UNKNOWN"); } catch (IOException e) { throw new ExceptionInInitializerError(e); } } private AsyncHttpClientConfigDefaults() { } public static String defaultThreadPoolName() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getString(ASYNC_CLIENT_CONFIG_ROOT + THREAD_POOL_NAME_CONFIG); } public static int defaultMaxConnections() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + MAX_CONNECTIONS_CONFIG); } public static int defaultMaxConnectionsPerHost() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + MAX_CONNECTIONS_PER_HOST_CONFIG); } public static int defaultAcquireFreeChannelTimeout() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + ACQUIRE_FREE_CHANNEL_TIMEOUT); } public static int defaultConnectTimeout() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + CONNECTION_TIMEOUT_CONFIG); } public static int defaultPooledConnectionIdleTimeout() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + POOLED_CONNECTION_IDLE_TIMEOUT_CONFIG); } public static int defaultConnectionPoolCleanerPeriod() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + CONNECTION_POOL_CLEANER_PERIOD_CONFIG); } public static int defaultReadTimeout() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + READ_TIMEOUT_CONFIG); } public static int defaultRequestTimeout() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + REQUEST_TIMEOUT_CONFIG); } public static int defaultConnectionTtl() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + CONNECTION_TTL_CONFIG); } public static boolean defaultFollowRedirect() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + FOLLOW_REDIRECT_CONFIG); } public static int defaultMaxRedirects() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + MAX_REDIRECTS_CONFIG); } public static boolean defaultCompressionEnforced() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + COMPRESSION_ENFORCED_CONFIG); } public static String defaultUserAgent() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getString(ASYNC_CLIENT_CONFIG_ROOT + USER_AGENT_CONFIG); } public static String[] defaultEnabledProtocols() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getStringArray(ASYNC_CLIENT_CONFIG_ROOT + ENABLED_PROTOCOLS_CONFIG); } public static String[] defaultEnabledCipherSuites() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getStringArray(ASYNC_CLIENT_CONFIG_ROOT + ENABLED_CIPHER_SUITES_CONFIG); } public static boolean defaultFilterInsecureCipherSuites() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + FILTER_INSECURE_CIPHER_SUITES_CONFIG); } public static boolean defaultUseProxySelector() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + USE_PROXY_SELECTOR_CONFIG); } public static boolean defaultUseProxyProperties() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + USE_PROXY_PROPERTIES_CONFIG); } public static boolean defaultValidateResponseHeaders() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + VALIDATE_RESPONSE_HEADERS_CONFIG); } public static boolean defaultAggregateWebSocketFrameFragments() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + AGGREGATE_WEBSOCKET_FRAME_FRAGMENTS_CONFIG); } public static boolean defaultEnableWebSocketCompression() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + ENABLE_WEBSOCKET_COMPRESSION_CONFIG); } public static boolean defaultStrict302Handling() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + STRICT_302_HANDLING_CONFIG); } public static boolean defaultKeepAlive() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + KEEP_ALIVE_CONFIG); } public static int defaultMaxRequestRetry() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + MAX_REQUEST_RETRY_CONFIG); } public static boolean defaultDisableUrlEncodingForBoundRequests() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + DISABLE_URL_ENCODING_FOR_BOUND_REQUESTS_CONFIG); } public static boolean defaultUseLaxCookieEncoder() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + USE_LAX_COOKIE_ENCODER_CONFIG); } public static boolean defaultUseOpenSsl() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + USE_OPEN_SSL_CONFIG); } public static boolean defaultUseInsecureTrustManager() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + USE_INSECURE_TRUST_MANAGER_CONFIG); } public static boolean defaultDisableHttpsEndpointIdentificationAlgorithm() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + DISABLE_HTTPS_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG); } public static int defaultSslSessionCacheSize() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + SSL_SESSION_CACHE_SIZE_CONFIG); } public static int defaultSslSessionTimeout() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + SSL_SESSION_TIMEOUT_CONFIG); } public static boolean defaultTcpNoDelay() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + TCP_NO_DELAY_CONFIG); } public static boolean defaultSoReuseAddress() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + SO_REUSE_ADDRESS_CONFIG); } public static boolean defaultSoKeepAlive() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + SO_KEEP_ALIVE_CONFIG); } public static int defaultSoLinger() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + SO_LINGER_CONFIG); } public static int defaultSoSndBuf() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + SO_SND_BUF_CONFIG); } public static int defaultSoRcvBuf() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + SO_RCV_BUF_CONFIG); } public static int defaultHttpClientCodecMaxInitialLineLength() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + HTTP_CLIENT_CODEC_MAX_INITIAL_LINE_LENGTH_CONFIG); } public static int defaultHttpClientCodecMaxHeaderSize() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + HTTP_CLIENT_CODEC_MAX_HEADER_SIZE_CONFIG); } public static int defaultHttpClientCodecMaxChunkSize() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + HTTP_CLIENT_CODEC_MAX_CHUNK_SIZE_CONFIG); } public static int defaultHttpClientCodecInitialBufferSize() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + HTTP_CLIENT_CODEC_INITIAL_BUFFER_SIZE_CONFIG); } public static boolean defaultDisableZeroCopy() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + DISABLE_ZERO_COPY_CONFIG); } public static int defaultHandshakeTimeout() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + HANDSHAKE_TIMEOUT_CONFIG); } public static int defaultChunkedFileChunkSize() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + CHUNKED_FILE_CHUNK_SIZE_CONFIG); } public static int defaultWebSocketMaxBufferSize() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + WEBSOCKET_MAX_BUFFER_SIZE_CONFIG); } public static int defaultWebSocketMaxFrameSize() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + WEBSOCKET_MAX_FRAME_SIZE_CONFIG); } public static boolean defaultKeepEncodingHeader() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + KEEP_ENCODING_HEADER_CONFIG); } public static int defaultShutdownQuietPeriod() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + SHUTDOWN_QUIET_PERIOD_CONFIG); } public static int defaultShutdownTimeout() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + SHUTDOWN_TIMEOUT_CONFIG); } public static boolean defaultUseNativeTransport() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getBoolean(ASYNC_CLIENT_CONFIG_ROOT + USE_NATIVE_TRANSPORT_CONFIG); } public static int defaultIoThreadsCount() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + IO_THREADS_COUNT_CONFIG); } public static int defaultHashedWheelTimerTickDuration() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + HASHED_WHEEL_TIMER_TICK_DURATION); } public static int defaultHashedWheelTimerSize() { return AsyncHttpClientConfigHelper.getAsyncHttpClientConfig().getInt(ASYNC_CLIENT_CONFIG_ROOT + HASHED_WHEEL_TIMER_SIZE); } }
52.480519
160
0.831477
8b18af62ec2e4fa1f36cb75d70b14677425c0b22
1,423
package com.packagename.myapp.Views; import com.packagename.myapp.Controllers.PersonasController; import com.packagename.myapp.MainLayout; import com.packagename.myapp.Models.Personas; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.html.H3; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import java.util.ArrayList; import java.util.List; @Route(value = "historial_medico", layout = MainLayout.class) @PageTitle("UE JUNAME | HISTORIAL") @CssImport("./styles/shared-styles.css") public class Historial_Medico extends VerticalLayout { List<Personas> personList = new ArrayList<>(); public Historial_Medico() { personList = PersonasController.findAll(); setSizeFull(); setMargin(false); for(int i=0; i<personList.size(); i++){ add(buildPanel(i)); } } private Component buildPanel(int i) { HorizontalLayout panel = new HorizontalLayout(); panel.setWidthFull(); panel.setMargin(false); panel.addClassName("panel-historial"); H3 persona = new H3(personList.get(i).getNombre()+" "+personList.get(i).getApellido()); panel.add(persona); return panel; } }
33.880952
95
0.719606
9b1b9430473537ece367230f40bcf176649557fd
193
package com.krishagni.catissueplus.core.exporter.services; import java.util.List; @FunctionalInterface public interface ObjectsGenerator { List<Object> apply(int startAt, int maxResults); }
21.444444
58
0.813472
9f1a36b5dcfaaf3f0895b81e695be4ecfd1a7b77
829
package com.syj.crowdfunding.mapper; import com.syj.crowdfunding.bean.TMenu; import com.syj.crowdfunding.bean.TMenuExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface TMenuMapper { long countByExample(TMenuExample example); int deleteByExample(TMenuExample example); int deleteByPrimaryKey(Integer id); int insert(TMenu record); int insertSelective(TMenu record); List<TMenu> selectByExample(TMenuExample example); TMenu selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") TMenu record, @Param("example") TMenuExample example); int updateByExample(@Param("record") TMenu record, @Param("example") TMenuExample example); int updateByPrimaryKeySelective(TMenu record); int updateByPrimaryKey(TMenu record); }
27.633333
104
0.768396
09e0cc6f3fa8fd7448cc73b3d990345f327befec
1,821
// This is a generated file. Not intended for manual editing. package org.intellij.erlang.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static org.intellij.erlang.ErlangTypes.*; import org.intellij.erlang.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; public class ErlangCaseExpressionImpl extends ErlangExpressionImpl implements ErlangCaseExpression { public ErlangCaseExpressionImpl(ASTNode node) { super(node); } @Override public void accept(@NotNull ErlangVisitor visitor) { visitor.visitCaseExpression(this); } @Override public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof ErlangVisitor) accept((ErlangVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List<ErlangCrClause> getCrClauseList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, ErlangCrClause.class); } @Override @Nullable public ErlangExpression getExpression() { return PsiTreeUtil.getChildOfType(this, ErlangExpression.class); } @Override @NotNull public PsiElement getCase() { return notNullChild(findChildByType(ERL_CASE)); } @Override @Nullable public PsiElement getEnd() { return findChildByType(ERL_END); } @Override @Nullable public PsiElement getOf() { return findChildByType(ERL_OF); } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { return ErlangPsiImplUtil.processDeclarations(this, processor, state, lastParent, place); } }
26.779412
155
0.768808
2a014332fd9ef7c11b9418d579869349520655a9
372
package com.example.mymvp.view; import com.example.mymvp.model.User; /** * Created by QYer on 2016/6/2. */ public interface IUserLoginView { String getUserName(); String getPassword(); void clearUserName(); void clearPassword(); void showLoading(); void hideLoading(); void toMainActivity(User user); void showFailedError(); }
13.777778
36
0.669355
84c11f4fe48e625424bc7f37584929df70c03103
1,842
package org.quantum.minio.plus.dto; import java.time.Instant; import java.util.Map; /** * 生命周期 创建数据传输对象 * @author ike * @date 2021 年 03 月 29 日 16:39 */ public class BucketLifecycleRuleDTO { /** * 标识 */ private String id; /** * 桶 */ private String bucketName; /** * 状态 Disabled-禁用 Enabled-启用 */ private String status; /** * 前缀 */ private String prefix; /** * 标签 */ private Map<String, String> tags; /** * 清除策略 */ private String cleanStrategy; /** * 天数 */ private Integer days; /** * 日期 */ private Instant date; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBucketName() { return bucketName; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public Map<String, String> getTags() { return tags; } public void setTags(Map<String, String> tags) { this.tags = tags; } public String getCleanStrategy() { return cleanStrategy; } public void setCleanStrategy(String cleanStrategy) { this.cleanStrategy = cleanStrategy; } public Integer getDays() { return days; } public void setDays(Integer days) { this.days = days; } public Instant getDate() { return date; } public void setDate(Instant date) { this.date = date; } }
15.74359
56
0.547231
b43dc8f651ef3f60e07aae4cbb6938e66cdbb0d5
2,415
package edu.eci.arsw.exams.moneylaunderingapi.service; import edu.eci.arsw.exams.moneylaunderingapi.model.SuspectAccount; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; @Service("MoneyLaunderingServiceStub") public class MoneyLaunderingServiceStub implements MoneyLaunderingService { private Hashtable<String,SuspectAccount> suspectAccounts; public MoneyLaunderingServiceStub() { this.suspectAccounts = new Hashtable<>(); suspectAccounts.put("LA",new SuspectAccount("LA",1541)); suspectAccounts.put("LE",new SuspectAccount("LE",1541)); suspectAccounts.put("LI",new SuspectAccount("LI",1541)); suspectAccounts.put("LO",new SuspectAccount("LO",1541)); suspectAccounts.put("LU",new SuspectAccount("LU",1541)); } @Override public void updateAccountStatus(String accountId,SuspectAccount suspectAccount)throws MoneyLaunderingServiceException{ if (suspectAccounts.get(accountId)==null){ throw new MoneyLaunderingServiceException("accountId not exists"); }else { suspectAccounts.get(accountId).setAmountOfSmallTransactions(suspectAccount.amountOfSmallTransactions); } } @Override public SuspectAccount getAccountStatus(String accountId)throws MoneyLaunderingServiceException { if(suspectAccounts.get(accountId)==null){ throw new MoneyLaunderingServiceException("accountId not exists"); }else { return suspectAccounts.get(accountId); } } @Override public List<SuspectAccount> getSuspectAccounts() { List<SuspectAccount> suspectAccountArrayList= new ArrayList<>(); for(String s : suspectAccounts.keySet()){ suspectAccountArrayList.add(suspectAccounts.get(s)); } return suspectAccountArrayList; } @Override public void addAccount(SuspectAccount suspectAccount) throws MoneyLaunderingServiceException { if (suspectAccounts.get(suspectAccount.accountId)==null){ suspectAccounts.put(suspectAccount.accountId,suspectAccount); }else{ throw new MoneyLaunderingServiceException("Account already exist"); } } }
37.734375
122
0.72588
462a1900665db7d6ccfabefc8aa464d67a1f5dbc
537
package p005cm.aptoide.p006pt.view.app; import p026rx.p027b.C0132p; /* renamed from: cm.aptoide.pt.view.app.ea */ /* compiled from: lambda */ public final /* synthetic */ class C5267ea implements C0132p { /* renamed from: a */ private final /* synthetic */ ListStoreAppsPresenter f9044a; public /* synthetic */ C5267ea(ListStoreAppsPresenter listStoreAppsPresenter) { this.f9044a = listStoreAppsPresenter; } public final Object call(Object obj) { return this.f9044a.mo17111c((Void) obj); } }
26.85
83
0.6946
223beb02ddb7a5a27a775d00a86017aa27195cd9
31,308
package org.jboss.resteasy.test.security.doseta; import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl; import java.net.URL; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SignatureException; import java.util.HashMap; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.ProcessingException; import javax.ws.rs.Produces; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.ResponseProcessingException; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.jboss.resteasy.annotations.security.doseta.After; import org.jboss.resteasy.annotations.security.doseta.Signed; import org.jboss.resteasy.annotations.security.doseta.Verify; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer; import org.jboss.resteasy.security.doseta.DKIMSignature; import org.jboss.resteasy.security.doseta.DosetaKeyRepository; import org.jboss.resteasy.security.doseta.KeyRepository; import org.jboss.resteasy.security.doseta.UnauthorizedSignatureException; import org.jboss.resteasy.security.doseta.Verification; import org.jboss.resteasy.security.doseta.Verifier; import org.jboss.resteasy.spi.MarshalledEntity; import org.jboss.resteasy.spi.Registry; import org.jboss.resteasy.spi.ResteasyDeployment; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.test.TestPortProvider; import org.jboss.resteasy.util.Base64; import org.jboss.resteasy.util.ParameterParser; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class SigningTest { private static NettyJaxrsServer server; private static ResteasyDeployment deployment; public static KeyPair keys; public static DosetaKeyRepository repository; public static PrivateKey badKey; public static ResteasyClient client; public Registry getRegistry() { return deployment.getRegistry(); } public ResteasyProviderFactory getProviderFactory() { return deployment.getProviderFactory(); } /** * @param resource */ public static void addPerRequestResource(Class<?> resource) { deployment.getRegistry().addPerRequestResource(resource); } @Test public void testMe() throws Exception { URL url = Thread.currentThread().getContextClassLoader().getResource("dns/zones"); System.out.println(url.getFile()); } @BeforeClass public static void setup() throws Exception { server = new NettyJaxrsServer(); server.setPort(TestPortProvider.getPort()); server.setRootResourcePath("/"); server.start(); deployment = server.getDeployment(); repository = new DosetaKeyRepository(); repository.setKeyStorePath("test.jks"); repository.setKeyStorePassword("password"); repository.setUseDns(false); repository.start(); PrivateKey privateKey = repository.getKeyStore().getPrivateKey("test._domainKey.samplezone.org"); if (privateKey == null) throw new Exception("Private Key is null!!!"); PublicKey publicKey = repository.getKeyStore().getPublicKey("test._domainKey.samplezone.org"); keys = new KeyPair(publicKey, privateKey); KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); badKey = keyPair.getPrivate(); deployment.getDispatcher().getDefaultContextObjects().put(KeyRepository.class, repository); addPerRequestResource(SignedResource.class); client = new ResteasyClientBuilder().build(); } @AfterClass public static void afterIt() throws Exception { client.close(); server.stop(); server = null; deployment = null; } @Path("/signed") public static interface SigningProxy { @GET @Verify @Produces("text/plain") @Path("bad-signature") public String bad(); @GET @Verify @Produces("text/plain") public String hello(); @POST @Consumes("text/plain") @Signed(selector = "test", domain = "samplezone.org") public void postSimple(String input); } @Path("/signed") public static class SignedResource { @DELETE @Path("request-only") public Response deleteRequestOnly(@Context HttpHeaders headers, @Context UriInfo uriInfo, @HeaderParam(DKIMSignature.DKIM_SIGNATURE) DKIMSignature signature) { Assert.assertNotNull(signature); System.out.println("Signature: " + signature); Verification verification = new Verification(keys.getPublic()); verification.setBodyHashRequired(false); verification.getRequiredAttributes().put("method", "GET"); verification.getRequiredAttributes().put("uri", uriInfo.getPath()); try { verification.verify(signature, headers.getRequestHeaders(), null, keys.getPublic()); } catch (SignatureException e) { throw new RuntimeException(e); } String token = signature.getAttributes().get("token"); signature = new DKIMSignature(); signature.setDomain("samplezone.org"); signature.setSelector("test"); signature.setPrivateKey(keys.getPrivate()); signature.setBodyHashRequired(false); signature.getAttributes().put("token", token); return Response.ok().header(DKIMSignature.DKIM_SIGNATURE, signature).build(); } @GET @Produces("text/plain") @Path("bad-signature") public Response badSignature() throws Exception { DKIMSignature signature = new DKIMSignature(); signature.setDomain("samplezone.org"); signature.setSelector("test"); signature.sign(new HashMap(), "hello world".getBytes(), keys.getPrivate()); byte[] sig = {0x0f, 0x03}; String encodedBadSig = Base64.encodeBytes(sig); ParameterParser parser = new ParameterParser(); String s = signature.toString(); String header = parser.setAttribute(s.toCharArray(), 0, s.length(), ';', "b", encodedBadSig); signature.setSignature(sig); return Response.ok("hello world").header(DKIMSignature.DKIM_SIGNATURE, header).build(); } @GET @Produces("text/plain") @Path("bad-hash") public Response badHash() throws Exception { DKIMSignature signature = new DKIMSignature(); signature.setDomain("samplezone.org"); signature.setSelector("test"); signature.sign(new HashMap(), "hello world".getBytes(), keys.getPrivate()); return Response.ok("hello").header(DKIMSignature.DKIM_SIGNATURE, signature.toString()).build(); } @GET @Produces("text/plain") @Path("manual") public Response getManual() { DKIMSignature signature = new DKIMSignature(); signature.setSelector("test"); signature.setDomain("samplezone.org"); Response.ResponseBuilder builder = Response.ok("hello"); builder.header(DKIMSignature.DKIM_SIGNATURE, signature); return builder.build(); } @GET @Path("header") @Produces("text/plain") public Response withHeader() { Response.ResponseBuilder builder = Response.ok("hello world"); builder.header("custom", "value"); DKIMSignature signature = new DKIMSignature(); signature.setSelector("test"); signature.setDomain("samplezone.org"); signature.addHeader("custom"); builder.header(DKIMSignature.DKIM_SIGNATURE, signature); return builder.build(); } @GET @Signed(selector = "test", domain = "samplezone.org") @Produces("text/plain") public String hello() { return "hello world"; } @POST @Consumes("text/plain") @Verify public void post(@HeaderParam(DKIMSignature.DKIM_SIGNATURE) DKIMSignature signature, String input) { Assert.assertNotNull(signature); Assert.assertEquals(input, "hello world"); } @POST @Consumes("text/plain") @Path("verify-manual") public void verifyManual(@HeaderParam(DKIMSignature.DKIM_SIGNATURE) DKIMSignature signature, @Context HttpHeaders headers, MarshalledEntity<String> input) throws Exception { Assert.assertNotNull(signature); Assert.assertEquals(input.getEntity(), "hello world"); signature.verify(headers.getRequestHeaders(), input.getMarshalledBytes(), keys.getPublic()); } @GET @Signed(selector = "test", domain = "samplezone.org", timestamped = true) @Produces("text/plain") @Path("stamped") public String getStamp() { return "hello world"; } @GET @Signed(selector = "test", domain = "samplezone.org", expires = @After(seconds = 1)) @Produces("text/plain") @Path("expires-short") public String getExpiresShort() { return "hello world"; } @GET @Signed(selector = "test", domain = "samplezone.org", expires = @After(minutes = 1)) @Produces("text/plain") @Path("expires-minute") public String getExpiresMinute() { return "hello world"; } @GET @Signed(selector = "test", domain = "samplezone.org", expires = @After(hours = 1)) @Produces("text/plain") @Path("expires-hour") public String getExpiresHour() { return "hello world"; } @GET @Signed(selector = "test", domain = "samplezone.org", expires = @After(days = 1)) @Produces("text/plain") @Path("expires-day") public String getExpiresDay() { return "hello world"; } @GET @Signed(selector = "test", domain = "samplezone.org", expires = @After(months = 1)) @Produces("text/plain") @Path("expires-month") public String getExpiresMonth() { return "hello world"; } @GET @Signed(selector = "test", domain = "samplezone.org", expires = @After(years = 1)) @Produces("text/plain") @Path("expires-year") public String getExpiresYear() { return "hello world"; } } @Test public void testRequestOnly() throws Exception { //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/request-only")); DKIMSignature contentSignature = new DKIMSignature(); contentSignature.setDomain("samplezone.org"); contentSignature.setSelector("test"); contentSignature.setPrivateKey(keys.getPrivate()); contentSignature.setBodyHashRequired(false); contentSignature.setAttribute("method", "GET"); contentSignature.setAttribute("uri", "/signed/request-only"); contentSignature.setAttribute("token", "1122"); Response response = target.request().header(DKIMSignature.DKIM_SIGNATURE, contentSignature).delete(); Assert.assertEquals(200, response.getStatus()); String signatureHeader = (String)response.getHeaderString(DKIMSignature.DKIM_SIGNATURE); contentSignature = new DKIMSignature(signatureHeader); Verification verification = new Verification(keys.getPublic()); verification.setBodyHashRequired(false); verification.getRequiredAttributes().put("token", "1122"); verification.verify(contentSignature, response.getStringHeaders(), null, keys.getPublic()); response.close(); } @Test public void testSigningManual() throws Exception { //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed")); Response response = target.request().get(); Assert.assertEquals(200, response.getStatus()); MarshalledEntity<String> marshalledEntity = response.readEntity(new GenericType<MarshalledEntity<String>>() { }); Assert.assertEquals("hello world", marshalledEntity.getEntity()); String signatureHeader = response.getHeaderString(DKIMSignature.DKIM_SIGNATURE); System.out.println(DKIMSignature.DKIM_SIGNATURE + ": " + signatureHeader); Assert.assertNotNull(signatureHeader); DKIMSignature contentSignature = new DKIMSignature(signatureHeader); contentSignature.verify(response.getStringHeaders(), marshalledEntity.getMarshalledBytes(), keys.getPublic()); response.close(); } @Test public void testBasicVerification() throws Exception { //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed")); DKIMSignature contentSignature = new DKIMSignature(); contentSignature.setDomain("samplezone.org"); contentSignature.setSelector("test"); contentSignature.setPrivateKey(keys.getPrivate()); Response response = target.request().header(DKIMSignature.DKIM_SIGNATURE, contentSignature) .post(Entity.text("hello world")); Assert.assertEquals(204, response.getStatus()); response.close(); } @Test public void testManualVerification() throws Exception { //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/verify-manual")); DKIMSignature contentSignature = new DKIMSignature(); contentSignature.setDomain("samplezone.org"); contentSignature.setSelector("test"); contentSignature.setAttribute("code", "hello"); contentSignature.setPrivateKey(keys.getPrivate()); Response response = target.request().header(DKIMSignature.DKIM_SIGNATURE, contentSignature) .post(Entity.text("hello world")); Assert.assertEquals(204, response.getStatus()); response.close(); } @Test public void testBasicVerificationRepository() throws Exception { //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed")); target.property(KeyRepository.class.getName(), repository); DKIMSignature contentSignature = new DKIMSignature(); contentSignature.setSelector("test"); contentSignature.setDomain("samplezone.org"); Response response = target.request().header(DKIMSignature.DKIM_SIGNATURE, contentSignature) .post(Entity.text("hello world")); Assert.assertEquals(204, response.getStatus()); response.close(); } @Test public void testBasicVerificationBadSignature() throws Exception { //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed")); DKIMSignature contentSignature = new DKIMSignature(); contentSignature.setSelector("test"); contentSignature.setDomain("samplezone.org"); contentSignature.setPrivateKey(badKey); Response response = target.request().header(DKIMSignature.DKIM_SIGNATURE, contentSignature) .post(Entity.text("hello world")); Assert.assertEquals(401, response.getStatus()); response.close(); } @Test public void testBasicVerificationNoSignature() throws Exception { //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed")); Response response = target.request().post(Entity.text("hello world")); Assert.assertEquals(401, response.getStatus()); response.close(); } @Test public void testTimestampSignature() throws Exception { DKIMSignature signature = new DKIMSignature(); signature.setTimestamp(); signature.setSelector("test"); signature.setDomain("samplezone.org"); signature.sign(new HashMap(), "hello world".getBytes(), keys.getPrivate()); String sig = signature.toString(); System.out.println(DKIMSignature.DKIM_SIGNATURE + ": " + sig); signature = new DKIMSignature(sig); } @Test public void testTimestamp() throws Exception { Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); verification.setStaleCheck(true); verification.setStaleSeconds(100); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/stamped")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); try { String output = response.readEntity(String.class); } catch (Exception e) { throw e; } response.close(); } @Test public void testStaleTimestamp() throws Exception { Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); verification.setStaleCheck(true); verification.setStaleSeconds(1); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/stamped")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); Thread.sleep(1500); try { String output = response.readEntity(String.class); Assert.fail(); } catch (ProcessingException pe) { UnauthorizedSignatureException e = (UnauthorizedSignatureException)pe.getCause(); System.out.println("here"); // Assert.assertEquals("Failed to verify signatures:\r\n Signature is stale", e.getMessage()); Assert.assertTrue(e.getMessage().indexOf("Failed to verify signatures:\r\n") >= 0); Assert.assertTrue(e.getMessage().indexOf("Signature is stale") >= 0); } response.close(); } @Test public void testExpiresHour() throws Exception { Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/expires-hour")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); String output = response.readEntity(String.class); response.close(); } @Test public void testExpiresMinutes() throws Exception { Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/expires-minute")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); String output = response.readEntity(String.class); response.close(); } @Test public void testExpiresDays() throws Exception { Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/expires-day")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); String output = response.readEntity(String.class); response.close(); } @Test public void testExpiresMonths() throws Exception { Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/expires-month")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); String output = response.readEntity(String.class); response.close(); } @Test public void testExpiresYears() throws Exception { Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/expires-year")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); String output = response.readEntity(String.class); response.close(); } @Test public void testExpiresFail() throws Exception { Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/expires-short")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); Thread.sleep(1500); try { String output = response.readEntity(String.class); throw new Exception("unreachable!"); } catch (ProcessingException pe) { UnauthorizedSignatureException e = (UnauthorizedSignatureException)pe.getCause(); // Assert.assertEquals("Failed to verify signatures:\r\n Signature expired", e.getMessage()); Assert.assertTrue(e.getMessage().indexOf("Failed to verify signatures:\r\n") >= 0); Assert.assertTrue(e.getMessage().indexOf("Signature expired") >= 0); } response.close(); } @Test public void testManualFail() throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair keyPair = kpg.genKeyPair(); Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setKey(keyPair.getPublic()); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/manual")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertNotNull(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); try { String output = response.readEntity(String.class); throw new Exception("unreachable!"); } catch (ProcessingException pe) { UnauthorizedSignatureException e = (UnauthorizedSignatureException)pe.getCause(); System.out.println("*************" + e.getMessage()); // Assert.assertEquals("Failed to verify signatures:\r\n Failed to verify signature.", e.getMessage()); Assert.assertTrue(e.getMessage().indexOf("Failed to verify signatures:\r\n") >= 0); Assert.assertTrue(e.getMessage().indexOf("Failed to verify signature.") >= 0); } response.close(); } @Test public void testManual() throws Exception { Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/manual")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertNotNull(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); String output = response.readEntity(String.class); Assert.assertEquals("hello", output); response.close(); } @Test public void testManualWithHeader() throws Exception { Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/header")); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); Response response = request.get(); System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertNotNull(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE)); Assert.assertEquals(200, response.getStatus()); String output = response.readEntity(String.class); Assert.assertEquals("hello world", output); response.close(); } @Test public void testBadSignature() throws Exception { //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/bad-signature")); Response response = target.request().get(); Assert.assertEquals(200, response.getStatus()); String signatureHeader = response.getHeaderString(DKIMSignature.DKIM_SIGNATURE); Assert.assertNotNull(signatureHeader); System.out.println(DKIMSignature.DKIM_SIGNATURE + ": " + signatureHeader); DKIMSignature contentSignature = new DKIMSignature(signatureHeader); MarshalledEntity<String> entity = response.readEntity(new GenericType<MarshalledEntity<String>>(){}); boolean failedVerification = false; try { contentSignature.verify(response.getStringHeaders(), entity.getMarshalledBytes(), keys.getPublic()); } catch (SignatureException e) { failedVerification = true; } Assert.assertTrue(failedVerification); response.close(); } @Test public void testBadHash() throws Exception { //ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(TestPortProvider.generateURL("/signed/bad-hash")); Response response = target.request().get(); Assert.assertEquals(200, response.getStatus()); String signatureHeader = response.getHeaderString(DKIMSignature.DKIM_SIGNATURE); Assert.assertNotNull(signatureHeader); System.out.println(DKIMSignature.DKIM_SIGNATURE + ": " + signatureHeader); DKIMSignature contentSignature = new DKIMSignature(signatureHeader); MarshalledEntity<String> entity = response.readEntity(new GenericType<MarshalledEntity<String>>(){}); boolean failedVerification = false; try { contentSignature.verify(response.getStringHeaders(), entity.getMarshalledBytes(), keys.getPublic()); } catch (SignatureException e) { failedVerification = true; } Assert.assertTrue(failedVerification); response.close(); } @Test public void testProxy() throws Exception { //ResteasyClient client = new ResteasyClient(); ResteasyWebTarget target = client.target(generateBaseUrl()); target.property(KeyRepository.class.getName(), repository); SigningProxy proxy = target.proxy(SigningProxy.class); String output = proxy.hello(); proxy.postSimple("hello world"); } @Test public void testBadSignatureProxy() throws Exception { //ResteasyClient client = new ResteasyClient(); ResteasyWebTarget target = client.target(generateBaseUrl()); target.property(KeyRepository.class.getName(), repository); SigningProxy proxy = target.proxy(SigningProxy.class); try { String output = proxy.bad(); throw new Exception("UNREACHABLE"); } catch (ResponseProcessingException e) { System.out.println("*** cause ***: " + e.getCause().getClass().getName()); //Assert.assertTrue(e.getCause() instanceof UnauthorizedSignatureException); } } }
37.182898
178
0.661971
441b47ea74ff93839ac30d7900d0a99c361bc084
2,215
package com.atjl.configdb.service.impl; import org.junit.*; import org.junit.rules.ExpectedException; import com.atjl.util.common.SystemUtil; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:test-service.xml"}) public class ConfigDbPlainServiceImplTest { @Resource ConfigDbPlainServiceImpl configDbPlainService; @Test public void testSet() throws Exception { } @Test public void testGet() throws Exception { // configDbPlainService.get } @Test public void testGetNoCache() throws Exception { } @Test public void testGetBatch() throws Exception { } @Test public void testGetBatchNoCache() throws Exception { } @Test public void testGets() throws Exception { } @Test public void testList2map() throws Exception { /* try { Method method = ConfigDbPlainServiceImpl.getClass().getMethod("list2map", List<Map<String,.class); method.setAccessible(true); method.invoke(<Object>, <Parameters>); } catch(NoSuchMethodException e) { } catch(IllegalAccessException e) { } catch(InvocationTargetException e) { } */ } @Before public void before() throws Exception { } @After public void after() throws Exception { } @BeforeClass public static void beforeClass() throws Exception{ String dir = System.getProperty("user.dir"); System.out.println("now " + dir); String config = dir.substring(0, dir.lastIndexOf("\\")) + "\\config"; System.out.println("config " + config); SystemUtil.addClasspath(config); } @Rule public final ExpectedException expectedException = ExpectedException.none(); }
25.45977
118
0.606772
8e75beaef7dc48ecb1ee10c6b018e3fb6841242c
10,478
/* * Copyright (C) 2013 Peter Gregus for GravityBox Project (C3C076@xda) * 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.wrbug.gravitybox.nougat.preference; import java.util.ArrayList; import com.wrbug.gravitybox.nougat.GravityBoxSettings; import com.wrbug.gravitybox.nougat.ModStatusBar; import com.wrbug.gravitybox.nougat.R; import com.wrbug.gravitybox.nougat.Utils; import com.wrbug.gravitybox.nougat.adapters.IIconCheckListAdapterItem; import com.wrbug.gravitybox.nougat.adapters.IconCheckListAdapter; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.preference.DialogPreference; import android.provider.Settings; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; public class OngoingNotifPreference extends DialogPreference implements OnItemClickListener, OnClickListener { private Context mContext; private Resources mResources; private ListView mListView; private Button mBtnResetList; private ArrayList<IIconCheckListAdapterItem> mListData; private AlertDialog mAlertDialog; private TextView mDescription; private View mDivider; private int mIconSizePx; public OngoingNotifPreference(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mResources = context.getResources(); mIconSizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25, mResources.getDisplayMetrics()); setDialogLayoutResource(R.layout.ongoing_notif_preference); } @Override protected void onBindDialogView(View view) { mListView = (ListView) view.findViewById(R.id.icon_list); mListView.setOnItemClickListener(this); mListView.setEmptyView(view.findViewById(R.id.info_list_empty)); mBtnResetList = (Button) view.findViewById(R.id.btnReset); mBtnResetList.setOnClickListener(this); mDescription = (TextView) view.findViewById(R.id.description); mDivider = (View) view.findViewById(R.id.divider); super.onBindView(view); setData(); } @Override public void onActivityDestroy() { if (mAlertDialog != null) { if (mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } mAlertDialog = null; } super.onActivityDestroy(); } @Override protected void onDialogClosed(boolean positiveResult) { if (positiveResult) { String buf = ""; for(int i = 0; i < mListData.size(); i++) { OngoingNotif on = (OngoingNotif) mListData.get(i); if (on.isChecked()) { if (!buf.isEmpty()) buf += "#C3C0#"; buf += on.getKey(); } } persistString(buf); Intent intent = new Intent(); intent.setAction(GravityBoxSettings.ACTION_PREF_ONGOING_NOTIFICATIONS_CHANGED); intent.putExtra(GravityBoxSettings.EXTRA_ONGOING_NOTIF, buf); mContext.sendBroadcast(intent); } } private void setData() { mListView.setAdapter(null); mListData = new ArrayList<IIconCheckListAdapterItem>(); mBtnResetList.setVisibility(View.GONE); final String prefData = getPersistedString(null); final String notifData = Settings.Secure.getString(mContext.getContentResolver(), ModStatusBar.SETTING_ONGOING_NOTIFICATIONS); if (notifData != null && !notifData.isEmpty()) { final String[] notifications = notifData.split("#C3C0#"); mListData = new ArrayList<IIconCheckListAdapterItem>(); for (String n : notifications) { final String[] nd = n.split(","); if (nd.length == 2) { OngoingNotif on = new OngoingNotif(nd[0], Integer.valueOf(nd[1])); on.setChecked(prefData != null && prefData.contains(on.getKey())); mListData.add(on); } } IconCheckListAdapter adapter = new IconCheckListAdapter(mContext, mListData); adapter.setSubtextEnabled(false); mListView.setAdapter(adapter); ((IconCheckListAdapter)mListView.getAdapter()).notifyDataSetChanged(); mBtnResetList.setVisibility(View.VISIBLE); } if (notifData == null || notifData.isEmpty() || prefData == null) { mDescription.setVisibility(View.VISIBLE); mDivider.setVisibility(View.VISIBLE); } else { mDescription.setVisibility(View.GONE); mDivider.setVisibility(View.GONE); } } class OngoingNotif implements IIconCheckListAdapterItem { private String mPackage; private int mIconId; private boolean mChecked; private String mName; private Drawable mIcon; public OngoingNotif(String pkg, int iconId) { mPackage = pkg; mIconId = iconId; } public String getKey() { if (mPackage == null) return null; return mPackage + "," + mIconId; } @Override public Drawable getIconLeft() { if (mPackage == null || mIconId == 0) return null; if (mIcon == null) { Resources res = mResources; if (!mPackage.equals("android") && !mPackage.equals(mContext.getPackageName())) { try { res = mContext.createPackageContext(mPackage, Context.CONTEXT_IGNORE_SECURITY).getResources(); } catch (NameNotFoundException e) { e.printStackTrace(); return null; } } try { Drawable d = res.getDrawable(mIconId); if (d != null) { Bitmap b = Utils.drawableToBitmap(d.mutate()); b = Bitmap.createScaledBitmap(b, mIconSizePx, mIconSizePx, true); mIcon = new BitmapDrawable(mResources, b); } } catch (Resources.NotFoundException nfe) { // } } return mIcon; } @Override public Drawable getIconRight() { return null; } @Override public String getText() { if (mName == null) { try { PackageManager pm = mContext.getPackageManager(); PackageInfo pi = pm.getPackageInfo(mPackage, 0); mName = (String) pi.applicationInfo.loadLabel(pm); } catch (NameNotFoundException e) { e.printStackTrace(); mName = mPackage; } } return mName; } @Override public String getSubText() { return null; } @Override public void setChecked(boolean checked) { mChecked = checked; } @Override public boolean isChecked() { return mChecked; } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { IIconCheckListAdapterItem item = (IIconCheckListAdapterItem) parent.getItemAtPosition(position); item.setChecked(!item.isChecked()); mListView.invalidateViews(); } @Override public void onClick(View v) { if (v == mBtnResetList) { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setMessage(R.string.ongoing_notif_reset_alert); builder.setNegativeButton(android.R.string.no, null); builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mAlertDialog = null; Intent intent = new Intent(); intent.setAction(GravityBoxSettings.ACTION_PREF_ONGOING_NOTIFICATIONS_CHANGED); intent.putExtra(GravityBoxSettings.EXTRA_ONGOING_NOTIF_RESET, true); mContext.sendBroadcast(intent); persistString(""); mListData.clear(); if (mListView.getAdapter() != null) { ((IconCheckListAdapter) mListView.getAdapter()).notifyDataSetChanged(); } mBtnResetList.setVisibility(View.GONE); mDescription.setVisibility(View.VISIBLE); mDivider.setVisibility(View.VISIBLE); } }); mAlertDialog = builder.create(); mAlertDialog.show(); } } }
37.555556
100
0.587421
d724aab81722986bf13d9a3a77fe6a1784da8793
846
public class AtividadeVotos { public static void main(String[] args) { AtividadeVotos atividadeVotos = new AtividadeVotos(); Double resultValidos = atividadeVotos.validosToTotal(800, 1000); Double resultBrancos = atividadeVotos.brancosToTotal(150, 1000); Double resultNulos = atividadeVotos.nulosToTotal(50, 1000); System.out.println("Porcentagem de validos: " + resultValidos + " %"); System.out.println("Porcentagem de brancos: " + resultBrancos + " %"); System.out.println("Porcentagem de nulos: " + resultNulos + " %"); } public double validosToTotal(double validos, double total) { return (validos / total) * 100 ; } public double brancosToTotal(double brancos, double total) { return (brancos / total) * 100 ; } public double nulosToTotal(double nulos, double total) { return (nulos / total) * 100 ; } }
32.538462
72
0.717494
ce2dabd5a44567054af65bdb82593839f08f3451
205
package uk.gov.cshr.exception; public class UnableToUpdateOrganisationException extends RuntimeException { public UnableToUpdateOrganisationException(String message) { super(message); } }
25.625
75
0.780488
311ee3c1843fda979a986fcce9b93692e2b1d8be
9,585
/* * Copyright (c) 2008-2017, Hazelcast, 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.hazelcast.concurrent.atomicreference; import com.hazelcast.core.HazelcastException; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IAtomicReference; import com.hazelcast.core.IFunction; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.util.EmptyStatement; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.BitSet; import static java.lang.String.format; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public abstract class AtomicReferenceAbstractTest extends HazelcastTestSupport { protected HazelcastInstance[] instances; protected IAtomicReference<String> ref; @Before public void setup() { instances = newInstances(); ref = newInstance(); } @After public void tearDown() { for (HazelcastInstance instance : instances) { instance.getLifecycleService().terminate(); } } protected IAtomicReference newInstance() { HazelcastInstance local = instances[0]; HazelcastInstance target = instances[instances.length - 1]; String name = generateKeyOwnedBy(target); return local.getAtomicReference(name); } protected abstract HazelcastInstance[] newInstances(); @Test public void getAndSet() { assertNull(ref.getAndSet("foo")); assertEquals("foo", ref.getAndSet("bar")); assertEquals("bar", ref.getAndSet("bar")); } @Test public void isNull() { assertTrue(ref.isNull()); ref.set("foo"); assertFalse(ref.isNull()); } @Test public void get() { assertNull(ref.get()); ref.set("foo"); assertEquals("foo", ref.get()); } @Test public void setAndGet() { assertNull(ref.setAndGet(null)); assertNull(ref.get()); assertEquals("foo", ref.setAndGet("foo")); assertEquals("foo", ref.get()); assertEquals("bar", ref.setAndGet("bar")); assertEquals("bar", ref.get()); assertNull(ref.setAndGet(null)); assertNull(ref.get()); } @Test public void set() { ref.set(null); assertNull(ref.get()); ref.set("foo"); assertEquals("foo", ref.get()); ref.setAndGet("bar"); assertEquals("bar", ref.get()); ref.set(null); assertNull(ref.get()); } @Test public void clear() { ref.clear(); assertNull(ref.get()); ref.set("foo"); ref.clear(); assertNull(ref.get()); ref.set(null); assertNull(ref.get()); } @Test public void contains() { assertTrue(ref.contains(null)); assertFalse(ref.contains("foo")); ref.set("foo"); assertFalse(ref.contains(null)); assertTrue(ref.contains("foo")); assertFalse(ref.contains("bar")); } @Test public void compareAndSet() { assertTrue(ref.compareAndSet(null, null)); assertNull(ref.get()); assertFalse(ref.compareAndSet("foo", "bar")); assertNull(ref.get()); assertTrue(ref.compareAndSet(null, "foo")); assertEquals("foo", ref.get()); ref.set("foo"); assertTrue(ref.compareAndSet("foo", "foo")); assertEquals("foo", ref.get()); assertTrue(ref.compareAndSet("foo", "bar")); assertEquals("bar", ref.get()); assertTrue(ref.compareAndSet("bar", null)); assertNull(ref.get()); } @Test(expected = IllegalArgumentException.class) public void apply_whenCalledWithNullFunction() { ref.apply(null); } @Test public void apply() { assertEquals("null", ref.apply(new AppendFunction(""))); assertNull(ref.get()); ref.set("foo"); assertEquals("foobar", ref.apply(new AppendFunction("bar"))); assertEquals("foo", ref.get()); assertNull(ref.apply(new NullFunction())); assertEquals("foo", ref.get()); } @Test public void apply_whenException() { ref.set("foo"); try { ref.apply(new FailingFunction()); fail(); } catch (HazelcastException expected) { EmptyStatement.ignore(expected); } assertEquals("foo", ref.get()); } @Test(expected = IllegalArgumentException.class) public void alter_whenCalledWithNullFunction() { ref.alter(null); } @Test public void alter_whenException() { ref.set("foo"); try { ref.alter(new FailingFunction()); fail(); } catch (HazelcastException expected) { EmptyStatement.ignore(expected); } assertEquals("foo", ref.get()); } @Test public void alter() { ref.alter(new NullFunction()); assertNull(ref.get()); ref.set("foo"); ref.alter(new AppendFunction("bar")); assertEquals("foobar", ref.get()); ref.alter(new NullFunction()); assertNull(ref.get()); } @Test(expected = IllegalArgumentException.class) public void alterAndGet_whenCalledWithNullFunction() { ref.alterAndGet(null); } @Test public void alterAndGet_whenException() { ref.set("foo"); try { ref.alterAndGet(new FailingFunction()); fail(); } catch (HazelcastException expected) { EmptyStatement.ignore(expected); } assertEquals("foo", ref.get()); } @Test public void alterAndGet() { assertNull(ref.alterAndGet(new NullFunction())); assertNull(ref.get()); ref.set("foo"); assertEquals("foobar", ref.alterAndGet(new AppendFunction("bar"))); assertEquals("foobar", ref.get()); assertNull(ref.alterAndGet(new NullFunction())); assertNull(ref.get()); } @Test(expected = IllegalArgumentException.class) public void getAndAlter_whenCalledWithNullFunction() { ref.getAndAlter(null); } @Test public void getAndAlter_whenException() { ref.set("foo"); try { ref.getAndAlter(new FailingFunction()); fail(); } catch (HazelcastException expected) { EmptyStatement.ignore(expected); } assertEquals("foo", ref.get()); } @Test public void getAndAlter() { assertNull(ref.getAndAlter(new NullFunction())); assertNull(ref.get()); ref.set("foo"); assertEquals("foo", ref.getAndAlter(new AppendFunction("bar"))); assertEquals("foobar", ref.get()); assertEquals("foobar", ref.getAndAlter(new NullFunction())); assertNull(ref.get()); } private static class AppendFunction implements IFunction<String, String> { private String add; private AppendFunction(String add) { this.add = add; } @Override public String apply(String input) { return input + add; } } private static class NullFunction implements IFunction<String, String> { @Override public String apply(String input) { return null; } } protected static class FailingFunction implements IFunction<String, String> { @Override public String apply(String input) { throw new HazelcastException(); } } @Test public void testToString() { String name = ref.getName(); assertEquals(format("IAtomicReference{name='%s'}", name), ref.toString()); } @Test public void getAndAlter_when_same_reference() { BitSet bitSet = new BitSet(); IAtomicReference<BitSet> ref2 = newInstance(); ref2.set(bitSet); assertEquals(bitSet, ref2.getAndAlter(new FailingFunctionAlter())); bitSet.set(100); assertEquals(bitSet, ref2.get()); } @Test public void alterAndGet_when_same_reference() { BitSet bitSet = new BitSet(); IAtomicReference<BitSet> ref2 = newInstance(); ref2.set(bitSet); bitSet.set(100); assertEquals(bitSet, ref2.alterAndGet(new FailingFunctionAlter())); assertEquals(bitSet, ref2.get()); } @Test public void alter_when_same_reference() { BitSet bitSet = new BitSet(); IAtomicReference<BitSet> ref2 = newInstance(); ref2.set(bitSet); bitSet.set(100); ref2.alter(new FailingFunctionAlter()); assertEquals(bitSet, ref2.get()); } private static class FailingFunctionAlter implements IFunction<BitSet, BitSet> { @Override public BitSet apply(BitSet input) { input.set(100); return input; } } }
26.188525
84
0.606364
3856012229be38d7e10385c99ab636db5187a5f4
306
package com.github.config.observer; /** * 被观察者关心的主题 */ public interface ISubject { /** * 注册观察者 * * @param watcher */ void register(IObserver watcher); /** * 通知观察者 * * @param key * @param value */ void notify(String key, String value); }
12.75
42
0.522876
c93b97099121e436ca75a9186a52352d93ccbf8d
399
package com.shengda.redis.constant; /** * redis 工具常量 * * @author takesi * @date 2020-03-01 */ public final class RedisToolsConstant { private RedisToolsConstant() { throw new IllegalStateException("Utility class"); } /** * single Redis */ public final static int SINGLE = 1; /** * Redis cluster */ public final static int CLUSTER = 2; }
15.346154
57
0.60401
08155395168a89cc0fc193a9d68eec3976c8e657
303
package toothpick.data; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @javax.inject.Scope @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface CustomScope { }
23.307692
44
0.828383
c8d57b331c2495cdfd07050f2fba72192eb23b66
3,622
/* * * * * Created by Juan Carlos Serrano Pérez on 6/01/19 13:04 * * Any question send an email to [email protected] * * Copyright (c) 2019 . All rights reserved. * * Last modified 29/12/18 21:49 * */ package com.example.xenahort.dss_proyect.Activitys; import android.content.Intent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.example.xenahort.dss_proyect.Comunicacion.ApiUtils; import com.example.xenahort.dss_proyect.Comunicacion.GetPostService; import com.example.xenahort.dss_proyect.ElementosGestion.Carrito; import com.example.xenahort.dss_proyect.ElementosGestion.Producto; import com.example.xenahort.dss_proyect.R; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import retrofit2.Call; import retrofit2.Callback; public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener { private GoogleApiClient googleApiClient; private SignInButton signInButton; private Carrito carrito; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.carrito = new Carrito(); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build(); googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build(); this.signInButton = (SignInButton) findViewById(R.id.signInButton); this.signInButton.setSize(SignInButton.SIZE_WIDE); this.signInButton.setColorScheme(SignInButton.COLOR_DARK); this.signInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient); startActivityForResult(intent, 777); } }); } /** * Muestra un Toast si se ha producido un error en la conexion */ @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Toast.makeText(this, "Error de conexion", Toast.LENGTH_LONG).show(); } /** * Recibe el resulado del inicio de sesion y muestra un error de conexion o nos lleva a la * actividad MapsActivity si los datos de inicio son correctos. * */ @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 777) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) { Toast.makeText(this, "Inicio correcto", Toast.LENGTH_LONG).show(); Intent intent = new Intent(this, MapsActivity.class); intent.putExtra("Carrito", carrito); startActivityForResult(intent, 0); } else { Toast.makeText(this, "No se puede iniciar sesión", Toast.LENGTH_LONG).show(); } } } }
38.126316
134
0.717283
65af8476381c645d4208c2b7e447c10f75b6e30c
11,335
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * 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.jkiss.dbeaver.core.application; import org.eclipse.core.runtime.IProduct; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.resource.StringConverter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.branding.IProductConstants; import org.eclipse.ui.splash.BasicSplashHandler; import org.jkiss.dbeaver.utils.GeneralUtils; /** * @since 3.3 * */ public class DBeaverSplashHandler extends BasicSplashHandler { public static final int TOTAL_LOADING_TASKS = 20; private static DBeaverSplashHandler instance; public static IProgressMonitor getActiveMonitor() { if (instance == null) { return null; } else { return instance.getBundleProgressMonitor(); } } private Font normalFont; private Font boldFont; public DBeaverSplashHandler() { instance = this; } @Override public void init(Shell splash) { super.init(splash); try { initVisualization(); } catch (Exception e) { e.printStackTrace(System.err); } getBundleProgressMonitor().beginTask("Loading", TOTAL_LOADING_TASKS); } private void initVisualization() { String progressRectString = null, messageRectString = null, foregroundColorString = null, versionCoordString = null, versionInfoSizeString = null, versionInfoColorString = null; final IProduct product = Platform.getProduct(); if (product != null) { progressRectString = product.getProperty(IProductConstants.STARTUP_PROGRESS_RECT); messageRectString = product.getProperty(IProductConstants.STARTUP_MESSAGE_RECT); foregroundColorString = product.getProperty(IProductConstants.STARTUP_FOREGROUND_COLOR); versionCoordString = product.getProperty("versionInfoCoord"); versionInfoSizeString = product.getProperty("versionInfoSize"); versionInfoColorString = product.getProperty("versionInfoColor"); } setProgressRect(StringConverter.asRectangle(progressRectString, new Rectangle(275, 300, 280, 10))); setMessageRect(StringConverter.asRectangle(messageRectString, new Rectangle(275,275,280,25))); final Point versionCoord = StringConverter.asPoint(versionCoordString, new Point(485, 215)); final int versionInfoSize = StringConverter.asInt(versionInfoSizeString, 22); final RGB versionInfoRGB = StringConverter.asRGB(versionInfoColorString, new RGB(255,255,255)); int foregroundColorInteger = 0xD2D7FF; try { if (foregroundColorString != null) { foregroundColorInteger = Integer.parseInt(foregroundColorString, 16); } } catch (Exception ex) { // ignore } setForeground( new RGB( (foregroundColorInteger & 0xFF0000) >> 16, (foregroundColorInteger & 0xFF00) >> 8, foregroundColorInteger & 0xFF)); normalFont = getContent().getFont(); //boldFont = UIUtils.makeBoldFont(normalFont); FontData[] fontData = normalFont.getFontData(); fontData[0].setStyle(fontData[0].getStyle() | SWT.BOLD); fontData[0].setHeight(versionInfoSize); boldFont = new Font(normalFont.getDevice(), fontData[0]); final Color versionColor = new Color(getContent().getDisplay(), versionInfoRGB); getContent().addPaintListener(e -> { String productVersion = ""; if (product != null) { productVersion = GeneralUtils.getPlainVersion(); } //String osVersion = Platform.getOS() + " " + Platform.getOSArch(); if (boldFont != null) { e.gc.setFont(boldFont); } e.gc.setForeground(versionColor); e.gc.drawText(productVersion, versionCoord.x, versionCoord.y, true); //e.gc.drawText(osVersion, 115, 200, true); e.gc.setFont(normalFont); }); } @Override public void dispose() { super.dispose(); if (boldFont != null) { boldFont.dispose(); boldFont = null; } instance = null; } public static void showMessage(String message) { if (message == null || message.isEmpty() || message.startsWith(">")) { return; } IProgressMonitor activeMonitor = getActiveMonitor(); if (activeMonitor != null) { activeMonitor.setTaskName(message); activeMonitor.worked(1); } } /* private final static int F_LABEL_HORIZONTAL_INDENT = 175; private final static int F_BUTTON_WIDTH_HINT = 80; private final static int F_TEXT_WIDTH_HINT = 175; private final static int F_COLUMN_COUNT = 3; private Composite fCompositeLogin; private Text fTextUsername; private Text fTextPassword; private Button fButtonOK; private Button fButtonCancel; private boolean fAuthenticated; */ /** * */ /* public DBeaverSplashHandler() { fCompositeLogin = null; fTextUsername = null; fTextPassword = null; fButtonOK = null; fButtonCancel = null; fAuthenticated = false; } public void init(final Shell splash) { // Store the shell super.init(splash); // Configure the shell layout configureUISplash(); // Create UI createUI(); // Create UI listeners createUIListeners(); // Force the splash screen to layout splash.layout(true); // Keep the splash screen visible and prevent the RCP application from // loading until the close button is clicked. doEventLoop(); } private void doEventLoop() { Shell splash = getSplash(); while (fAuthenticated == false) { if (splash.getDisplay().readAndDispatch() == false) { splash.getDisplay().sleep(); } } } private void createUIListeners() { // Create the OK button listeners createUIListenersButtonOK(); // Create the cancel button listeners createUIListenersButtonCancel(); } private void createUIListenersButtonCancel() { fButtonCancel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handleButtonCancelWidgetSelected(); } }); } private void handleButtonCancelWidgetSelected() { // Abort the loading of the RCP application getSplash().getDisplay().close(); System.exit(0); } private void createUIListenersButtonOK() { fButtonOK.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handleButtonOKWidgetSelected(); } }); } private void handleButtonOKWidgetSelected() { String username = fTextUsername.getText(); String password = fTextPassword.getText(); // Aunthentication is successful if a user provides any username and // any password if ((username.length() > 0) && (password.length() > 0)) { fAuthenticated = true; } else { MessageDialog.openError( getSplash(), "Authentication Failed", //NON-NLS-1 "A username and password must be specified to login."); //NON-NLS-1 } } private void createUI() { // Create the login panel createUICompositeLogin(); // Create the blank spanner createUICompositeBlank(); // Create the user name label createUILabelUserName(); // Create the user name text widget createUITextUserName(); // Create the password label createUILabelPassword(); // Create the password text widget createUITextPassword(); // Create the blank label createUILabelBlank(); // Create the OK button createUIButtonOK(); // Create the cancel button createUIButtonCancel(); } private void createUIButtonCancel() { // Create the button fButtonCancel = new Button(fCompositeLogin, SWT.PUSH); fButtonCancel.setText("Cancel"); //NON-NLS-1 // Configure layout data GridData data = new GridData(SWT.NONE, SWT.NONE, false, false); data.widthHint = F_BUTTON_WIDTH_HINT; data.verticalIndent = 10; fButtonCancel.setLayoutData(data); } private void createUIButtonOK() { // Create the button fButtonOK = new Button(fCompositeLogin, SWT.PUSH); fButtonOK.setText("OK"); //NON-NLS-1 // Configure layout data GridData data = new GridData(SWT.NONE, SWT.NONE, false, false); data.widthHint = F_BUTTON_WIDTH_HINT; data.verticalIndent = 10; fButtonOK.setLayoutData(data); } private void createUILabelBlank() { Label label = new Label(fCompositeLogin, SWT.NONE); label.setVisible(false); } private void createUITextPassword() { // Create the text widget int style = SWT.PASSWORD | SWT.BORDER; fTextPassword = new Text(fCompositeLogin, style); // Configure layout data GridData data = new GridData(SWT.NONE, SWT.NONE, false, false); data.widthHint = F_TEXT_WIDTH_HINT; data.horizontalSpan = 2; fTextPassword.setLayoutData(data); } private void createUILabelPassword() { // Create the label Label label = new Label(fCompositeLogin, SWT.NONE); label.setText("&Password:"); //NON-NLS-1 // Configure layout data GridData data = new GridData(); data.horizontalIndent = F_LABEL_HORIZONTAL_INDENT; label.setLayoutData(data); } private void createUITextUserName() { // Create the text widget fTextUsername = new Text(fCompositeLogin, SWT.BORDER); // Configure layout data GridData data = new GridData(SWT.NONE, SWT.NONE, false, false); data.widthHint = F_TEXT_WIDTH_HINT; data.horizontalSpan = 2; fTextUsername.setLayoutData(data); } private void createUILabelUserName() { // Create the label Label label = new Label(fCompositeLogin, SWT.NONE); label.setText("&User Name:"); //NON-NLS-1 // Configure layout data GridData data = new GridData(); data.horizontalIndent = F_LABEL_HORIZONTAL_INDENT; label.setLayoutData(data); } private void createUICompositeBlank() { Composite spanner = new Composite(fCompositeLogin, SWT.NONE); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.horizontalSpan = F_COLUMN_COUNT; spanner.setLayoutData(data); } private void createUICompositeLogin() { // Create the composite fCompositeLogin = new Composite(getSplash(), SWT.BORDER); GridLayout layout = new GridLayout(F_COLUMN_COUNT, false); fCompositeLogin.setLayout(layout); } private void configureUISplash() { // Configure layout FillLayout layout = new FillLayout(); getSplash().setLayout(layout); // Force shell to inherit the splash background getSplash().setBackgroundMode(SWT.INHERIT_DEFAULT); } */ }
30.552561
107
0.692633
46e2a7963419824397065c8aadab19196ad57ee8
1,234
package doctester; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import model.ExportTemplateDefinition; import ninja.NinjaDocTester; import org.doctester.testbrowser.Request; import org.doctester.testbrowser.Response; import org.junit.Test; import com.fasterxml.jackson.core.type.TypeReference; public class TemplateExportControllerTest extends NinjaDocTester { public static final TypeReference<List<ExportTemplateDefinition>> TEMPLATE_LIST_TYPE = new TypeReference<List<ExportTemplateDefinition>>() {}; @Test public void getReturnsListOFTemplates() throws Exception { Response response = getAllTemplates(); assertThat(response.payloadJsonAs(TEMPLATE_LIST_TYPE)).isNotNull(); } @Test public void SizeOfTemplates() throws Exception { Response reponse = getAllTemplates(); assertThat(reponse.payloadJsonAs(TEMPLATE_LIST_TYPE).size()).isEqualTo(2); } @Test public void successfullyexportTemplate() throws Exception { Response response = getAllTemplates(); assertThat(response.httpStatus).isEqualTo(200); } private Response getAllTemplates() { return sayAndMakeRequest(Request.GET().url(testServerUrl().path("api/templates"))); } }
28.045455
88
0.777958
039bddc59d8b1680bbd4df08bd0b0e849ba802c4
17,526
package org.apache.spark.sql.hive.client; /** * A class that wraps the HiveClient and converts its responses to externally visible classes. * Note that this class is typically loaded with an internal classloader for each instantiation, * allowing it to interact directly with a specific isolated version of Hive. Loading this class * with the isolated classloader however will result in it only being visible as a {@link HiveClient}, * not a {@link HiveClientImpl}. * <p> * This class needs to interact with multiple versions of Hive, but will always be compiled with * the 'native', execution version of Hive. Therefore, any places where hive breaks compatibility * must use reflection after matching on <code>version</code>. * <p> * Every HiveClientImpl creates an internal HiveConf object. This object is using the given * <code>hadoopConf</code> as the base. All options set in the <code>sparkConf</code> will be applied to the HiveConf * object and overrides any exiting options. Then, options in extraConfig will be applied * to the HiveConf object and overrides any existing options. * <p> * param: version the version of hive used when pick function calls that are not compatible. * param: sparkConf all configuration options set in SparkConf. * param: hadoopConf the base Configuration object used by the HiveConf created inside * this HiveClientImpl. * param: extraConfig a collection of configuration options that will be added to the * hive conf before opening the hive client. * param: initClassLoader the classloader used when creating the <code>state</code> field of * this {@link HiveClientImpl}. */ class HiveClientImpl implements org.apache.spark.sql.hive.client.HiveClient, org.apache.spark.internal.Logging { /** Converts the native StructField to Hive's FieldSchema. */ static public org.apache.hadoop.hive.metastore.api.FieldSchema toHiveColumn (org.apache.spark.sql.types.StructField c) { throw new RuntimeException(); } /** Get the Spark SQL native DataType from Hive's FieldSchema. */ static private org.apache.spark.sql.types.DataType getSparkSQLDataType (org.apache.hadoop.hive.metastore.api.FieldSchema hc) { throw new RuntimeException(); } /** Builds the native StructField from Hive's FieldSchema. */ static public org.apache.spark.sql.types.StructField fromHiveColumn (org.apache.hadoop.hive.metastore.api.FieldSchema hc) { throw new RuntimeException(); } static private void verifyColumnDataType (org.apache.spark.sql.types.StructType schema) { throw new RuntimeException(); } static private java.lang.Class<? extends org.apache.hadoop.mapred.InputFormat<?, ?>> toInputFormat (java.lang.String name) { throw new RuntimeException(); } static private java.lang.Class<? extends org.apache.hadoop.hive.ql.io.HiveOutputFormat<?, ?>> toOutputFormat (java.lang.String name) { throw new RuntimeException(); } /** * Converts the native table metadata representation format CatalogTable to Hive's Table. * @param table (undocumented) * @param userName (undocumented) * @return (undocumented) */ static public org.apache.hadoop.hive.ql.metadata.Table toHiveTable (org.apache.spark.sql.catalyst.catalog.CatalogTable table, scala.Option<java.lang.String> userName) { throw new RuntimeException(); } /** * Converts the native partition metadata representation format CatalogTablePartition to * Hive's Partition. * @param p (undocumented) * @param ht (undocumented) * @return (undocumented) */ static public org.apache.hadoop.hive.ql.metadata.Partition toHivePartition (org.apache.spark.sql.catalyst.catalog.CatalogTablePartition p, org.apache.hadoop.hive.ql.metadata.Table ht) { throw new RuntimeException(); } /** * Build the native partition metadata from Hive's Partition. * @param hp (undocumented) * @return (undocumented) */ static public org.apache.spark.sql.catalyst.catalog.CatalogTablePartition fromHivePartition (org.apache.hadoop.hive.ql.metadata.Partition hp) { throw new RuntimeException(); } /** * Reads statistics from Hive. * Note that this statistics could be overridden by Spark's statistics if that's available. * @param properties (undocumented) * @return (undocumented) */ static private scala.Option<org.apache.spark.sql.catalyst.catalog.CatalogStatistics> readHiveStats (scala.collection.immutable.Map<java.lang.String, java.lang.String> properties) { throw new RuntimeException(); } static private scala.collection.immutable.Set<java.lang.String> HiveStatisticsProperties () { throw new RuntimeException(); } static public final org.apache.spark.sql.catalyst.catalog.CatalogTable getTable (java.lang.String dbName, java.lang.String tableName) { throw new RuntimeException(); } static public final org.apache.spark.sql.catalyst.catalog.CatalogTablePartition getPartition (java.lang.String dbName, java.lang.String tableName, scala.collection.immutable.Map<java.lang.String, java.lang.String> spec) { throw new RuntimeException(); } static public final org.apache.spark.sql.catalyst.catalog.CatalogFunction getFunction (java.lang.String db, java.lang.String name) { throw new RuntimeException(); } static public final boolean functionExists (java.lang.String db, java.lang.String name) { throw new RuntimeException(); } static public scala.Option<scala.collection.immutable.Map<java.lang.String, java.lang.String>> getPartitionNames$default$2 () { throw new RuntimeException(); } static public scala.Option<scala.collection.immutable.Map<java.lang.String, java.lang.String>> getPartitions$default$2 () { throw new RuntimeException(); } static protected java.lang.String logName () { throw new RuntimeException(); } static protected org.slf4j.Logger log () { throw new RuntimeException(); } static protected void logInfo (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logDebug (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logTrace (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logWarning (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logError (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logInfo (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logDebug (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logTrace (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logWarning (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logError (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected boolean isTraceEnabled () { throw new RuntimeException(); } static protected void initializeLogIfNecessary (boolean isInterpreter) { throw new RuntimeException(); } static protected boolean initializeLogIfNecessary (boolean isInterpreter, boolean silent) { throw new RuntimeException(); } static protected boolean initializeLogIfNecessary$default$2 () { throw new RuntimeException(); } public org.apache.spark.sql.hive.client.HiveVersion version () { throw new RuntimeException(); } public org.apache.spark.sql.hive.client.IsolatedClientLoader clientLoader () { throw new RuntimeException(); } // not preceding public HiveClientImpl (org.apache.spark.sql.hive.client.HiveVersion version, org.apache.spark.SparkConf sparkConf, org.apache.hadoop.conf.Configuration hadoopConf, scala.collection.immutable.Map<java.lang.String, java.lang.String> extraConfig, java.lang.ClassLoader initClassLoader, org.apache.spark.sql.hive.client.IsolatedClientLoader clientLoader) { throw new RuntimeException(); } private org.apache.spark.util.CircularBuffer outputBuffer () { throw new RuntimeException(); } private org.apache.spark.sql.hive.client.Shim_v0_12 shim () { throw new RuntimeException(); } public org.apache.hadoop.hive.ql.session.SessionState state () { throw new RuntimeException(); } private org.apache.hadoop.hive.ql.session.SessionState newState () { throw new RuntimeException(); } /** Returns the configuration for the current session. */ public org.apache.hadoop.hive.conf.HiveConf conf () { throw new RuntimeException(); } private java.lang.String userName () { throw new RuntimeException(); } public java.lang.String getConf (java.lang.String key, java.lang.String defaultValue) { throw new RuntimeException(); } private int retryLimit () { throw new RuntimeException(); } private long retryDelayMillis () { throw new RuntimeException(); } /** * Runs <code>f</code> with multiple retries in case the hive metastore is temporarily unreachable. * @param f (undocumented) * @return (undocumented) */ private <A extends java.lang.Object> A retryLocked (scala.Function0<A> f) { throw new RuntimeException(); } private boolean causedByThrift (java.lang.Throwable e) { throw new RuntimeException(); } private org.apache.hadoop.hive.ql.metadata.Hive client () { throw new RuntimeException(); } /** Return the associated Hive {@link SessionState} of this {@link HiveClientImpl} */ public org.apache.hadoop.hive.ql.session.SessionState getState () { throw new RuntimeException(); } /** * Runs <code>f</code> with ThreadLocal session state and classloaders configured for this version of hive. * @param f (undocumented) * @return (undocumented) */ public <A extends java.lang.Object> A withHiveState (scala.Function0<A> f) { throw new RuntimeException(); } public void setOut (java.io.PrintStream stream) { throw new RuntimeException(); } public void setInfo (java.io.PrintStream stream) { throw new RuntimeException(); } public void setError (java.io.PrintStream stream) { throw new RuntimeException(); } public void setCurrentDatabase (java.lang.String databaseName) { throw new RuntimeException(); } public void createDatabase (org.apache.spark.sql.catalyst.catalog.CatalogDatabase database, boolean ignoreIfExists) { throw new RuntimeException(); } public void dropDatabase (java.lang.String name, boolean ignoreIfNotExists, boolean cascade) { throw new RuntimeException(); } public void alterDatabase (org.apache.spark.sql.catalyst.catalog.CatalogDatabase database) { throw new RuntimeException(); } public org.apache.spark.sql.catalyst.catalog.CatalogDatabase getDatabase (java.lang.String dbName) { throw new RuntimeException(); } public boolean databaseExists (java.lang.String dbName) { throw new RuntimeException(); } public scala.collection.Seq<java.lang.String> listDatabases (java.lang.String pattern) { throw new RuntimeException(); } public boolean tableExists (java.lang.String dbName, java.lang.String tableName) { throw new RuntimeException(); } public scala.Option<org.apache.spark.sql.catalyst.catalog.CatalogTable> getTableOption (java.lang.String dbName, java.lang.String tableName) { throw new RuntimeException(); } public void createTable (org.apache.spark.sql.catalyst.catalog.CatalogTable table, boolean ignoreIfExists) { throw new RuntimeException(); } public void dropTable (java.lang.String dbName, java.lang.String tableName, boolean ignoreIfNotExists, boolean purge) { throw new RuntimeException(); } public void alterTable (java.lang.String dbName, java.lang.String tableName, org.apache.spark.sql.catalyst.catalog.CatalogTable table) { throw new RuntimeException(); } public void alterTableDataSchema (java.lang.String dbName, java.lang.String tableName, org.apache.spark.sql.types.StructType newDataSchema, scala.collection.immutable.Map<java.lang.String, java.lang.String> schemaProps) { throw new RuntimeException(); } public void createPartitions (java.lang.String db, java.lang.String table, scala.collection.Seq<org.apache.spark.sql.catalyst.catalog.CatalogTablePartition> parts, boolean ignoreIfExists) { throw new RuntimeException(); } public void dropPartitions (java.lang.String db, java.lang.String table, scala.collection.Seq<scala.collection.immutable.Map<java.lang.String, java.lang.String>> specs, boolean ignoreIfNotExists, boolean purge, boolean retainData) { throw new RuntimeException(); } public void renamePartitions (java.lang.String db, java.lang.String table, scala.collection.Seq<scala.collection.immutable.Map<java.lang.String, java.lang.String>> specs, scala.collection.Seq<scala.collection.immutable.Map<java.lang.String, java.lang.String>> newSpecs) { throw new RuntimeException(); } public void alterPartitions (java.lang.String db, java.lang.String table, scala.collection.Seq<org.apache.spark.sql.catalyst.catalog.CatalogTablePartition> newParts) { throw new RuntimeException(); } /** * Returns the partition names for the given table that match the supplied partition spec. * If no partition spec is specified, all partitions are returned. * <p> * The returned sequence is sorted as strings. * @param table (undocumented) * @param partialSpec (undocumented) * @return (undocumented) */ public scala.collection.Seq<java.lang.String> getPartitionNames (org.apache.spark.sql.catalyst.catalog.CatalogTable table, scala.Option<scala.collection.immutable.Map<java.lang.String, java.lang.String>> partialSpec) { throw new RuntimeException(); } public scala.Option<org.apache.spark.sql.catalyst.catalog.CatalogTablePartition> getPartitionOption (org.apache.spark.sql.catalyst.catalog.CatalogTable table, scala.collection.immutable.Map<java.lang.String, java.lang.String> spec) { throw new RuntimeException(); } /** * Returns the partitions for the given table that match the supplied partition spec. * If no partition spec is specified, all partitions are returned. * @param table (undocumented) * @param spec (undocumented) * @return (undocumented) */ public scala.collection.Seq<org.apache.spark.sql.catalyst.catalog.CatalogTablePartition> getPartitions (org.apache.spark.sql.catalyst.catalog.CatalogTable table, scala.Option<scala.collection.immutable.Map<java.lang.String, java.lang.String>> spec) { throw new RuntimeException(); } public scala.collection.Seq<org.apache.spark.sql.catalyst.catalog.CatalogTablePartition> getPartitionsByFilter (org.apache.spark.sql.catalyst.catalog.CatalogTable table, scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression> predicates) { throw new RuntimeException(); } public scala.collection.Seq<java.lang.String> listTables (java.lang.String dbName) { throw new RuntimeException(); } public scala.collection.Seq<java.lang.String> listTables (java.lang.String dbName, java.lang.String pattern) { throw new RuntimeException(); } /** * Runs the specified SQL query using Hive. * @param sql (undocumented) * @return (undocumented) */ public scala.collection.Seq<java.lang.String> runSqlHive (java.lang.String sql) { throw new RuntimeException(); } /** * Execute the command using Hive and return the results as a sequence. Each element * in the sequence is one row. * @param cmd (undocumented) * @param maxRows (undocumented) * @return (undocumented) */ protected scala.collection.Seq<java.lang.String> runHive (java.lang.String cmd, int maxRows) { throw new RuntimeException(); } public void loadPartition (java.lang.String loadPath, java.lang.String dbName, java.lang.String tableName, java.util.LinkedHashMap<java.lang.String, java.lang.String> partSpec, boolean replace, boolean inheritTableSpecs, boolean isSrcLocal) { throw new RuntimeException(); } public void loadTable (java.lang.String loadPath, java.lang.String tableName, boolean replace, boolean isSrcLocal) { throw new RuntimeException(); } public void loadDynamicPartitions (java.lang.String loadPath, java.lang.String dbName, java.lang.String tableName, java.util.LinkedHashMap<java.lang.String, java.lang.String> partSpec, boolean replace, int numDP) { throw new RuntimeException(); } public void createFunction (java.lang.String db, org.apache.spark.sql.catalyst.catalog.CatalogFunction func) { throw new RuntimeException(); } public void dropFunction (java.lang.String db, java.lang.String name) { throw new RuntimeException(); } public void renameFunction (java.lang.String db, java.lang.String oldName, java.lang.String newName) { throw new RuntimeException(); } public void alterFunction (java.lang.String db, org.apache.spark.sql.catalyst.catalog.CatalogFunction func) { throw new RuntimeException(); } public scala.Option<org.apache.spark.sql.catalyst.catalog.CatalogFunction> getFunctionOption (java.lang.String db, java.lang.String name) { throw new RuntimeException(); } public scala.collection.Seq<java.lang.String> listFunctions (java.lang.String db, java.lang.String pattern) { throw new RuntimeException(); } public void addJar (java.lang.String path) { throw new RuntimeException(); } public org.apache.spark.sql.hive.client.HiveClientImpl newSession () { throw new RuntimeException(); } public void reset () { throw new RuntimeException(); } }
93.721925
389
0.762353
11952bdda81e98f129d7993e832a0fccca28a939
1,415
package com.open.lcp.queue.kafka; import java.util.Properties; import org.apache.kafka.clients.producer.KafkaProducer; public class KafkaProducerHolder<K, V> { private ZKKafkaProducerConfig producerConfig; void setProducerConfig(ZKKafkaProducerConfig producerConfig) { this.producerConfig = producerConfig; } KafkaProducerHolder(ZKKafkaProducerConfig cfg) { initProducer(); this.producerConfig = cfg; } private KafkaProducer<K, V> kafkaProducer; private void initProducer() { Properties props = new Properties(); // props.put("bootstrap.servers", // "10.1.78.23:9091,10.1.78.23:9092,10.1.78.23:9093"); // props.put("acks", "0"); // props.put("retries", 0); // props.put("batch.size", 16384); // props.put("key.serializer", // "org.apache.kafka.common.serialization.StringSerializer"); // props.put("value.serializer", // "org.apache.kafka.common.serialization.StringSerializer"); props.put("bootstrap.servers", producerConfig.getBootstrapServers()); props.put("acks", producerConfig.getAcks()); props.put("retries", producerConfig.getRetries()); props.put("batch.size", producerConfig.getBatchSize()); props.put("key.serializer", producerConfig.getKeySerializer()); props.put("value.serializer", producerConfig.getValueSerializer()); kafkaProducer = new KafkaProducer<K, V>(props); } KafkaProducer<K, V> getKafkaProducer() { return kafkaProducer; } }
28.877551
71
0.732862
f023d787f00e062fb18ca66919b09de7754cc742
589
package in.ashwanik.dcp.problems.p91_120.p100; class Solution { int getMinimumDistance(int[][] points) { if (points == null || points.length < 2) { return 0; } int distance = 0; for (int index = 0; index < points.length - 1; index++) { distance += distance(points[index], points[index + 1]); } return distance; } private int distance(int[] point1, int[] point2) { int x = Math.abs(point1[0] - point2[0]); int y = Math.abs(point1[1] - point2[1]); return Math.max(x, y); } }
25.608696
67
0.534805
ddbc5c9b57a85875f5a46e908810ea88f6856507
134
package op; import register.Registers; public abstract class Op { public abstract Registers apply(Registers registers); }
14.888889
55
0.738806
69d486f20b9c8ded915072d9b63ee71f44ca7a08
2,440
package data.follow; import com.wrapper.spotify.SpotifyApi; import com.wrapper.spotify.enums.ModelObjectType; import com.wrapper.spotify.exceptions.SpotifyWebApiException; import com.wrapper.spotify.model_objects.specification.Artist; import com.wrapper.spotify.model_objects.specification.PagingCursorbased; import com.wrapper.spotify.requests.data.follow.GetUsersFollowedArtistsRequest; import org.apache.hc.core5.http.ParseException; import java.io.IOException; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; public class GetUsersFollowedArtistsExample { private static final String accessToken = "taHZ2SdB-bPA3FsK3D7ZN5npZS47cMy-IEySVEGttOhXmqaVAIo0ESvTCLjLBifhHOHOIuhFUKPW1WMDP7w6dj3MAZdWT8CLI2MkZaXbYLTeoDvXesf2eeiLYPBGdx8tIwQJKgV8XdnzH_DONk"; private static final ModelObjectType type = ModelObjectType.ARTIST; private static final SpotifyApi spotifyApi = new SpotifyApi.Builder() .setAccessToken(accessToken) .build(); private static final GetUsersFollowedArtistsRequest getUsersFollowedArtistsRequest = spotifyApi .getUsersFollowedArtists(type) // .after("0LcJLqbBmaGUft1e9Mm8HV") // .limit(10) .build(); public static void getUsersFollowedArtists_Sync() { try { final PagingCursorbased<Artist> artistPagingCursorbased = getUsersFollowedArtistsRequest.execute(); System.out.println("Total: " + artistPagingCursorbased.getTotal()); } catch (IOException | SpotifyWebApiException | ParseException e) { System.out.println("Error: " + e.getMessage()); } } public static void getUsersFollowedArtists_Async() { try { final CompletableFuture<PagingCursorbased<Artist>> pagingCursorbasedFuture = getUsersFollowedArtistsRequest.executeAsync(); // Thread free to do other tasks... // Example Only. Never block in production code. final PagingCursorbased<Artist> artistPagingCursorbased = pagingCursorbasedFuture.join(); System.out.println("Total: " + artistPagingCursorbased.getTotal()); } catch (CompletionException e) { System.out.println("Error: " + e.getCause().getMessage()); } catch (CancellationException e) { System.out.println("Async operation cancelled."); } } public static void main(String[] args) { getUsersFollowedArtists_Sync(); getUsersFollowedArtists_Async(); } }
40
193
0.775
8a86ef8eca28c1da4adf18ac70ed0a421eb2636d
2,022
package org.zstack.header.identity; import org.apache.commons.lang.StringUtils; import org.springframework.http.HttpMethod; import org.zstack.header.MapField; import org.zstack.header.message.APIMessage; import org.zstack.header.message.APIParam; import org.zstack.header.message.APIReply; import org.zstack.header.other.APILoginAuditor; import org.zstack.header.rest.RestRequest; import java.util.Map; @SuppressCredentialCheck @RestRequest( path = "/accounts/sessions/{sessionUuid}", method = HttpMethod.DELETE, responseClass = APILogOutReply.class ) public class APILogOutMsg extends APISessionMessage implements APILoginAuditor { private String sessionUuid; @APIParam(required = false) @MapField(keyType = String.class, valueType = String.class) private Map<String, String> clientInfo; public String getSessionUuid() { return sessionUuid; } public void setSessionUuid(String sessionUuid) { this.sessionUuid = sessionUuid; } public Map<String, String> getClientInfo() { return clientInfo; } public void setClientInfo(Map<String, String> clientInfo) { this.clientInfo = clientInfo; } public static APILogOutMsg __example__() { APILogOutMsg msg = new APILogOutMsg(); msg.setSessionUuid(uuid()); return msg; } @Override public LoginResult loginAudit(APIMessage msg, APIReply reply) { String clientIp = ""; String clientBrowser = ""; APILogOutMsg amsg = (APILogOutMsg) msg; Map<String, String> clientInfo = amsg.getClientInfo(); if (clientInfo != null && !clientInfo.isEmpty()) { clientIp = StringUtils.isNotEmpty(clientInfo.get("clientIp")) ? clientInfo.get("clientIp") : ""; clientBrowser = StringUtils.isNotEmpty(clientInfo.get("clientBrowser")) ? clientInfo.get("clientBrowser") : ""; } return new LoginResult(clientIp, clientBrowser, amsg.getSessionUuid(), SessionVO.class); } }
32.095238
123
0.696835
6b79d08a5f86df1f488d09642788c58b054c5db5
6,262
package core.services; import core.apis.discogs.DiscogsApi; import core.apis.discogs.DiscogsSingleton; import core.apis.last.ConcurrentLastFM; import core.apis.spotify.Spotify; import core.apis.spotify.SpotifySingleton; import core.commands.utils.CommandUtil; import core.exceptions.LastFmEntityNotFoundException; import core.exceptions.LastFmException; import dao.ChuuService; import dao.entities.*; import javax.annotation.Nullable; import java.util.*; import java.util.stream.Collectors; import static core.scheduledtasks.UpdaterThread.groupAlbumsToArtist; public class UpdaterHoarder { private final ChuuService service; private final DiscogsApi discogsApi; private final Spotify spotify; private final ConcurrentLastFM lastFM; private final UsersWrapper user; private final LastFMData lastFMData; private final Map<String, Long> dbIdMap = new HashMap<>(); public UpdaterHoarder(UsersWrapper user, ChuuService service, ConcurrentLastFM lastFM, @Nullable LastFMData lastFMData) { this.user = user; this.lastFM = lastFM; this.lastFMData = lastFMData == null ? LastFMData.ofUserWrapper(user) : lastFMData; spotify = SpotifySingleton.getInstance(); discogsApi = DiscogsSingleton.getInstanceUsingDoubleLocking(); this.service = service; } public int updateUser() throws LastFmException { List<TrackWithArtistId> trackWithArtistIds; trackWithArtistIds = lastFM.getWeeklyBillboard(lastFMData, user.getTimestamp() , Integer.MAX_VALUE); updateList(trackWithArtistIds); return trackWithArtistIds.size(); } public void updateList(List<TrackWithArtistId> trackWithArtistIds) { if (trackWithArtistIds.isEmpty()) { return; } doArtistValidation(trackWithArtistIds); int max = trackWithArtistIds.stream().mapToInt(TrackWithArtistId::getUtc).max().orElse(user.getTimestamp()) + 1; Map<ScrobbledAlbum, Long> a = trackWithArtistIds.stream() .collect(Collectors.groupingBy(nowPlayingArtist -> { ScrobbledAlbum scrobbledAlbum = new ScrobbledAlbum(nowPlayingArtist.getAlbum(), nowPlayingArtist.getArtist(), null, null); scrobbledAlbum.setArtistId(nowPlayingArtist.getArtistId()); scrobbledAlbum.setArtistMbid(nowPlayingArtist.getArtistMbid()); scrobbledAlbum.setAlbumMbid(nowPlayingArtist.getAlbumMbid()); return scrobbledAlbum; }, Collectors.counting())); TimestampWrapper<ArrayList<ScrobbledAlbum>> albumDataList = new TimestampWrapper<>( a.entrySet().stream().map( entry -> { ScrobbledAlbum artist = entry.getKey(); artist.setCount(Math.toIntExact(entry.getValue())); return artist; }) .collect(Collectors.toCollection(ArrayList::new)), max); // Correction with current last fm implementation should return the same name so // no correction gives List<ScrobbledAlbum> albumData = albumDataList.getWrapped(); List<ScrobbledArtist> artistData = groupAlbumsToArtist(albumData); service.incrementalUpdate(new TimestampWrapper<>(artistData, albumDataList.getTimestamp()), user.getLastFMName(), albumData, trackWithArtistIds); } private void doArtistValidation(List<TrackWithArtistId> toValidate) { List<TrackWithArtistId> newToValidate = toValidate.stream().peek(x -> { Long aLong1 = dbIdMap.get(x.getArtist()); if (aLong1 != null) x.setArtistId(aLong1); }).filter(x -> x.getArtistId() == -1L || x.getArtistId() == 0L).toList(); Set<String> tobeRemoved = new HashSet<>(); List<ScrobbledArtist> artists = newToValidate.stream().map(Track::getArtist).distinct().map(x -> new ScrobbledArtist(x, 0, null)).toList(); service.filldArtistIds(artists); Map<Boolean, List<ScrobbledArtist>> mappedByExistingId = artists.stream().collect(Collectors.partitioningBy(x -> x.getArtistId() != -1L && x.getArtistId() != 0)); List<ScrobbledArtist> foundArtists = mappedByExistingId.get(true); Map<String, String> changedUserNames = new HashMap<>(); mappedByExistingId.get(false).stream().map(x -> { try { String artist = x.getArtist(); CommandUtil.validate(service, x, lastFM, discogsApi, spotify); String newArtist = x.getArtist(); if (!Objects.equals(artist, newArtist)) { changedUserNames.put(artist, newArtist); } return x; } catch (LastFmEntityNotFoundException exception) { service.upsertArtistSad(x); return x; } catch (LastFmException lastFmException) { tobeRemoved.add(x.getArtist()); return null; } }).filter(Objects::nonNull).forEach(foundArtists::add); Map<String, Long> mapId = foundArtists.stream().collect(Collectors.toMap(ScrobbledArtist::getArtist, ScrobbledArtist::getArtistId, (x, y) -> x)); for (Iterator<TrackWithArtistId> iterator = toValidate.iterator(); iterator.hasNext(); ) { TrackWithArtistId x = iterator.next(); if (x.getArtistId() > 0) { continue; } Long aLong = mapId.get(x.getArtist()); if (tobeRemoved.contains(x.getArtist())) { iterator.remove(); continue; } if (aLong == null) { String s = changedUserNames.get(x.getArtist()); if (s != null) { aLong = mapId.get(s); } if (aLong == null) { aLong = -1L; } } x.setArtistId(aLong); if (x.getArtistId() == -1L) { iterator.remove(); } this.dbIdMap.put(x.getArtist(), x.getArtistId()); } } }
45.05036
170
0.615618
511dd7120db994678b63ad4df80af5fe9b53e6c4
124
package com.draga.spaceTravels3; public enum GameState { COUNTDOWN, PLAY, PAUSE, LOSE, TUTORIAL, WIN }
11.272727
32
0.645161
155730c6fbc89fae88764bf4309129f85c20a9a8
836
package net.glowstone.io.entity; import net.glowstone.entity.passive.GlowBat; import net.glowstone.util.nbt.CompoundTag; import org.bukkit.Location; import org.bukkit.entity.EntityType; class BatStore extends LivingEntityStore<GlowBat> { public BatStore() { super( GlowBat.class, EntityType.BAT ); } @Override public GlowBat createEntity( Location location, CompoundTag compound ) { return new GlowBat( location ); } @Override public void load( GlowBat entity, CompoundTag compound ) { super.load( entity, compound ); if ( compound.isByte( "BatFlags" ) ) { entity.setAwake( compound.getBool( "BatFlags" ) ); } else { entity.setAwake( true ); } } @Override public void save( GlowBat entity, CompoundTag tag ) { super.save( entity, tag ); tag.putBool( "BatFlags", entity.isAwake() ); } }
19
71
0.70933
deb7c7df45cc3f4a7c29fa4a0adfb7e9ec359962
858
package com.design.pattern.singleton.safe; import com.design.pattern.singleton.*; /** * @ClassName SingletonFactory * @Description * @Author Jacob * @Date 2020/3/31 10:31 * @Version 1.0 **/ public class SingletonFactory extends AbstractFactory { @Override public Object getHungry() { return Hungry.getInstance(); } @Override public Object getDoubleCheck() { return LazyDoubleCheck.getInstance(); } @Override public Object getLazyEnum() { return LazyEnum.getInstance(); } @Override public Object getStaticClassInner() { return LazyStaticInnerClass.getInstance(); } @Override public Object getSyncSafe() { return LazyThreadSalfSync.getInstance(); } @Override public Object getSyncUnsafe() { return LazyThreadUnsale.getInstance(); } @Override public Object getRegister() { return LazyRegister.getInstance(); } }
17.875
55
0.7331
944597e5beb09c10fcb72501f0577c9a17fe03cd
8,294
package rocks.inspectit.agent.java.eum.instrumentation; import java.io.PrintWriter; import java.util.Locale; import rocks.inspectit.agent.java.eum.html.StreamedHtmlScriptInjector; /** * A PrintWriter which injects the given tag on the fly into the head (or another appropriate) * section of the document. Automatically detects non-html and then falls back to just piping the * data through. * * @author Jonas Kunz */ public class TagInjectionPrintWriter extends PrintWriter { /** * New-line character. */ private static final String NL = System.getProperty("line.separator"); /** * The HTML parser used for injecting the tag. */ private StreamedHtmlScriptInjector injector; /** * The writer to pass the data to. */ private PrintWriter originalWriter; /** * Creates a new print writer which performs the tag injection. * * @param originalWriter * The writer which is wrapped. * @param tagToInject * The tag(s) to insert. */ public TagInjectionPrintWriter(PrintWriter originalWriter, String tagToInject) { super(originalWriter); this.originalWriter = originalWriter; injector = new StreamedHtmlScriptInjector(tagToInject); } @Override public void flush() { originalWriter.flush(); } @Override public boolean checkError() { return originalWriter.checkError(); } @Override public void close() { originalWriter.close(); } @Override public void write(int c) { String newValue = injector.performInjection(String.valueOf((char) c)); if (newValue == null) { originalWriter.write(c); } else { originalWriter.write(newValue); } } @Override public void write(char[] buf, int off, int len) { String newValue = injector.performInjection(String.valueOf(buf, off, len)); if (newValue == null) { originalWriter.write(buf, off, len); } else { originalWriter.write(newValue); } } @Override @SuppressWarnings({ "PMD", "UseVarags" }) public void write(char[] buf) { String newValue = injector.performInjection(String.valueOf(buf)); if (newValue == null) { originalWriter.write(buf); } else { originalWriter.write(newValue); } } @Override public void write(String s, int off, int len) { String newValue = injector.performInjection(s.substring(off, off + len)); if (newValue == null) { originalWriter.write(s, off, len); } else { originalWriter.write(newValue); } } @Override public void write(String s) { String newValue = injector.performInjection(s); if (newValue == null) { originalWriter.write(s); } else { originalWriter.write(newValue); } } @Override public void print(boolean b) { String newValue = injector.performInjection(String.valueOf(b)); if (newValue == null) { originalWriter.print(b); } else { originalWriter.write(newValue); } } @Override public void print(char c) { String newValue = injector.performInjection(String.valueOf(c)); if (newValue == null) { originalWriter.print(c); } else { originalWriter.write(newValue); } } @Override public void print(int i) { String newValue = injector.performInjection(String.valueOf(i)); if (newValue == null) { originalWriter.print(i); } else { originalWriter.write(newValue); } } @Override public void print(long l) { String newValue = injector.performInjection(String.valueOf(l)); if (newValue == null) { originalWriter.print(l); } else { originalWriter.write(newValue); } } @Override public void print(float f) { String newValue = injector.performInjection(String.valueOf(f)); if (newValue == null) { originalWriter.print(f); } else { originalWriter.write(newValue); } } @Override public void print(double d) { String newValue = injector.performInjection(String.valueOf(d)); if (newValue == null) { originalWriter.print(d); } else { originalWriter.write(newValue); } } @Override @SuppressWarnings({ "PMD", "UseVarags" }) public void print(char[] s) { String newValue = injector.performInjection(String.valueOf(s)); if (newValue == null) { originalWriter.print(s); } else { originalWriter.write(newValue); } } @Override public void print(String s) { String newValue = injector.performInjection(s); if (newValue == null) { originalWriter.print(s); } else { originalWriter.write(newValue); } } @Override public void print(Object obj) { String newValue = injector.performInjection(String.valueOf(obj)); if (newValue == null) { originalWriter.print(obj); } else { originalWriter.write(newValue); } } @Override public void println() { String newValue = injector.performInjection(NL); if (newValue == null) { originalWriter.println(); } else { originalWriter.write(newValue); } } @Override public void println(boolean x) { String newValue = injector.performInjection(x + NL); if (newValue == null) { originalWriter.println(x); } else { originalWriter.write(newValue); } } @Override public void println(char x) { String newValue = injector.performInjection(x + NL); if (newValue == null) { originalWriter.println(x); } else { originalWriter.write(newValue); } } @Override public void println(int x) { String newValue = injector.performInjection(x + NL); if (newValue == null) { originalWriter.println(x); } else { originalWriter.write(newValue); } } @Override public void println(long x) { String newValue = injector.performInjection(x + NL); if (newValue == null) { originalWriter.println(x); } else { originalWriter.write(newValue); } } @Override public void println(float x) { String newValue = injector.performInjection(x + NL); if (newValue == null) { originalWriter.println(x); } else { originalWriter.write(newValue); } } @Override public void println(double x) { String newValue = injector.performInjection(x + NL); if (newValue == null) { originalWriter.println(x); } else { originalWriter.write(newValue); } } @Override @SuppressWarnings({ "PMD", "UseVarags" }) public void println(char[] x) { String newValue = injector.performInjection(String.valueOf(x) + NL); if (newValue == null) { originalWriter.println(x); } else { originalWriter.write(newValue); } } @Override public void println(String x) { String newValue = injector.performInjection(x + NL); if (newValue == null) { originalWriter.println(x); } else { originalWriter.write(newValue); } } @Override public void println(Object x) { String newValue = injector.performInjection(x + NL); if (newValue == null) { originalWriter.println(x); } else { originalWriter.write(newValue); } } @Override public PrintWriter printf(String format, Object... args) { return this.format(format, args); } @Override public PrintWriter printf(Locale l, String format, Object... args) { return this.format(l, format, args); } @Override public PrintWriter format(String format, Object... args) { String newValue = injector.performInjection(String.format(format, args)); if (newValue == null) { originalWriter.format(format, args); } else { originalWriter.write(newValue); } return this; } @Override public PrintWriter format(Locale l, String format, Object... args) { String newValue = injector.performInjection(String.format(l, format, args)); if (newValue == null) { originalWriter.format(l, format, args); } else { originalWriter.write(newValue); } return this; } @Override public PrintWriter append(CharSequence csq) { String newValue = injector.performInjection(csq); if (newValue == null) { originalWriter.append(csq); } else { originalWriter.write(newValue); } return this; } @Override public PrintWriter append(CharSequence csq, int start, int end) { String newValue = injector.performInjection(csq.subSequence(start, end)); if (newValue == null) { originalWriter.append(csq, start, end); } else { originalWriter.write(newValue); } return this; } @Override public PrintWriter append(char c) { String newValue = injector.performInjection(String.valueOf(c)); if (newValue == null) { originalWriter.append(c); } else { originalWriter.write(newValue); } return this; } }
22.355795
97
0.686641
c7b84bf0018281dce4cc88f0fddeff34c2933181
1,776
package me.joeleoli.fairfight.listener; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteStreams; import java.util.Map; import lombok.RequiredArgsConstructor; import me.joeleoli.fairfight.FairFight; import me.joeleoli.fairfight.event.BungeeReceivedEvent; import me.joeleoli.fairfight.event.ModListRetrieveEvent; import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; @RequiredArgsConstructor public class BungeeListener implements PluginMessageListener { private final FairFight plugin; @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { if (!channel.equals("BungeeCord")) { return; } final ByteArrayDataInput in = ByteStreams.newDataInput(message); final String subChannel = in.readUTF(); if (subChannel.equals("ForgeMods")) { try { Map<String, String> mods = (Map<String, String>) new JSONParser().parse(in.readUTF()); ModListRetrieveEvent event = new ModListRetrieveEvent(player, mods); this.plugin.getServer().getPluginManager().callEvent(event); } catch (ParseException e) { e.printStackTrace(); } return; } final short len = in.readShort(); final byte[] messageBytes = new byte[len]; in.readFully(messageBytes); ByteArrayDataInput dis = ByteStreams.newDataInput(messageBytes); String data = dis.readUTF(); Long systemTime = Long.parseLong(data.split(":")[0]); final BungeeReceivedEvent event = new BungeeReceivedEvent(player, subChannel, data.replace(systemTime + ":", ""), message, systemTime > System.currentTimeMillis()); this.plugin.getServer().getPluginManager().callEvent(event); } }
29.114754
166
0.761824
81ca2f95a20956205667ee6c4b07f50448063110
19,991
/******************************************************************************* * Copyright (c) 2022 Eclipse RDF4J contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. ******************************************************************************/ package org.eclipse.rdf4j.query.algebra.evaluation.util; import java.util.Objects; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.Duration; import javax.xml.datatype.XMLGregorianCalendar; import org.eclipse.rdf4j.common.annotation.InternalUseOnly; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; import org.eclipse.rdf4j.model.util.Literals; import org.eclipse.rdf4j.query.algebra.Compare.CompareOp; /** * This class will take over for QueryEvaluationUtil. Currently marked as InternalUseOnly because there may still be * changes to how this class works. * * @author Arjohn Kampman * @author Håvard M. Ottestad */ @InternalUseOnly() public class QueryEvaluationUtility { /** * Determines the effective boolean value (EBV) of the supplied value as defined in the * <a href="http://www.w3.org/TR/rdf-sparql-query/#ebv">SPARQL specification</a>: * <ul> * <li>The EBV of any literal whose type is CoreDatatype.XSD:boolean or numeric is false if the lexical form is not * valid for that datatype (e.g. "abc"^^xsd:integer). * <li>If the argument is a typed literal with a datatype of CoreDatatype.XSD:boolean, the EBV is the value of that * argument. * <li>If the argument is a plain literal or a typed literal with a datatype of CoreDatatype.XSD:string, the EBV is * false if the operand value has zero length; otherwise the EBV is true. * <li>If the argument is a numeric type or a typed literal with a datatype derived from a numeric type, the EBV is * false if the operand value is NaN or is numerically equal to zero; otherwise the EBV is true. * <li>All other arguments, including unbound arguments, produce a type error. * </ul> * * @param value Some value. * @return The EBV of <var>value</var>. */ public static Result getEffectiveBooleanValue(Value value) { if (value.isLiteral()) { Literal literal = (Literal) value; String label = literal.getLabel(); CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatype().orElse(null); if (datatype == CoreDatatype.XSD.STRING) { return Result.fromBoolean(label.length() > 0); } else if (datatype == CoreDatatype.XSD.BOOLEAN) { // also false for illegal values return Result.fromBoolean("true".equals(label) || "1".equals(label)); } else if (datatype == CoreDatatype.XSD.DECIMAL) { try { String normDec = XMLDatatypeUtil.normalizeDecimal(label); return Result.fromBoolean(!normDec.equals("0.0")); } catch (IllegalArgumentException e) { return Result.fromBoolean(false); } } else if (datatype != null && datatype.isIntegerDatatype()) { try { String normInt = XMLDatatypeUtil.normalize(label, datatype); return Result.fromBoolean(!normInt.equals("0")); } catch (IllegalArgumentException e) { return Result.fromBoolean(false); } } else if (datatype != null && datatype.isFloatingPointDatatype()) { try { String normFP = XMLDatatypeUtil.normalize(label, datatype); return Result.fromBoolean(!normFP.equals("0.0E0") && !normFP.equals("NaN")); } catch (IllegalArgumentException e) { return Result.fromBoolean(false); } } } return Result.incompatibleValueExpression; } public static Result compare(Value leftVal, Value rightVal, CompareOp operator) { return compare(leftVal, rightVal, operator, true); } public static Result compare(Value leftVal, Value rightVal, CompareOp operator, boolean strict) { if (leftVal.isLiteral() && rightVal.isLiteral()) { // Both left and right argument is a Literal return compareLiterals((Literal) leftVal, (Literal) rightVal, operator, strict); } else { // All other value combinations switch (operator) { case EQ: return Result.fromBoolean(Objects.equals(leftVal, rightVal)); case NE: return Result.fromBoolean(!Objects.equals(leftVal, rightVal)); default: return Result.incompatibleValueExpression; } } } /** * Compares the supplied {@link Literal} arguments using the supplied operator, using strict (minimally-conforming) * SPARQL 1.1 operator behavior. * * @param leftLit the left literal argument of the comparison. * @param rightLit the right literal argument of the comparison. * @param operator the comparison operator to use. * @return {@code true} if execution of the supplied operator on the supplied arguments succeeds, {@code false} * otherwise. */ public static Result compareLiterals(Literal leftLit, Literal rightLit, CompareOp operator) { return compareLiterals(leftLit, rightLit, operator, true); } public static Order compareLiterals(Literal leftLit, Literal rightLit, boolean strict) { // type precendence: // - simple literal // - numeric // - CoreDatatype.XSD:boolean // - CoreDatatype.XSD:dateTime // - CoreDatatype.XSD:string // - RDF term (equal and unequal only) CoreDatatype leftCoreDatatype = leftLit.getCoreDatatype(); CoreDatatype rightCoreDatatype = rightLit.getCoreDatatype(); boolean leftLangLit = leftCoreDatatype == CoreDatatype.RDF.LANGSTRING; boolean rightLangLit = rightCoreDatatype == CoreDatatype.RDF.LANGSTRING; CoreDatatype.XSD leftXSDDatatype = leftCoreDatatype.asXSDDatatype().orElse(null); CoreDatatype.XSD rightXSDDatatype = rightCoreDatatype.asXSDDatatype().orElse(null); // for purposes of query evaluation in SPARQL, simple literals and string-typed literals with the same lexical // value are considered equal. if (leftCoreDatatype == CoreDatatype.XSD.STRING && rightCoreDatatype == CoreDatatype.XSD.STRING) { return Order.from(leftLit.getLabel().compareTo(rightLit.getLabel())); } else if (!(leftLangLit || rightLangLit)) { CoreDatatype.XSD commonDatatype = getCommonDatatype(strict, leftXSDDatatype, rightXSDDatatype); if (commonDatatype != null) { try { Order order = handleCommonDatatype(leftLit, rightLit, strict, leftXSDDatatype, rightXSDDatatype, leftLangLit, rightLangLit, commonDatatype); if (order == Order.illegalArgument) { if (leftLit.equals(rightLit)) { return Order.equal; } } if (order != null) { return order; } } catch (IllegalArgumentException e) { if (leftLit.equals(rightLit)) { return Order.equal; } } } } // All other cases, e.g. literals with languages, unequal or // unordered datatypes, etc. These arguments can only be compared // using the operators 'EQ' and 'NE'. See SPARQL's RDFterm-equal // operator return otherCases(leftLit, rightLit, leftXSDDatatype, rightXSDDatatype, leftLangLit, rightLangLit); } /** * Compares the supplied {@link Literal} arguments using the supplied operator. * * @param leftLit the left literal argument of the comparison. * @param rightLit the right literal argument of the comparison. * @param operator the comparison operator to use. * @param strict boolean indicating whether comparison should use strict (minimally-conforming) SPARQL 1.1 * operator behavior, or extended behavior. * @return {@code true} if execution of the supplied operator on the supplied arguments succeeds, {@code false} * otherwise. */ public static Result compareLiterals(Literal leftLit, Literal rightLit, CompareOp operator, boolean strict) { Order order = compareLiterals(leftLit, rightLit, strict); return order.toResult(operator); } private static Order handleCommonDatatype(Literal leftLit, Literal rightLit, boolean strict, CoreDatatype.XSD leftCoreDatatype, CoreDatatype.XSD rightCoreDatatype, boolean leftLangLit, boolean rightLangLit, CoreDatatype.XSD commonDatatype) { if (commonDatatype == CoreDatatype.XSD.DOUBLE) { return Order.from(Double.compare(leftLit.doubleValue(), rightLit.doubleValue())); } else if (commonDatatype == CoreDatatype.XSD.FLOAT) { return Order.from(Float.compare(leftLit.floatValue(), rightLit.floatValue())); } else if (commonDatatype == CoreDatatype.XSD.DECIMAL) { return Order.from(leftLit.decimalValue().compareTo(rightLit.decimalValue())); } else if (commonDatatype.isIntegerDatatype()) { return Order.from(leftLit.integerValue().compareTo(rightLit.integerValue())); } else if (commonDatatype == CoreDatatype.XSD.BOOLEAN) { return Order.from(Boolean.compare(leftLit.booleanValue(), rightLit.booleanValue())); } else if (commonDatatype.isCalendarDatatype()) { XMLGregorianCalendar left = leftLit.calendarValue(); XMLGregorianCalendar right = rightLit.calendarValue(); int compare = left.compare(right); // Note: XMLGregorianCalendar.compare() returns compatible values (-1, 0, 1) but INDETERMINATE // needs special treatment if (compare == DatatypeConstants.INDETERMINATE) { // If we compare two CoreDatatype.XSD:dateTime we should use the specific comparison specified in SPARQL // 1.1 if (leftCoreDatatype == CoreDatatype.XSD.DATETIME && rightCoreDatatype == CoreDatatype.XSD.DATETIME) { return Order.incompatibleValueExpression; } } else { return Order.from(compare); } } else if (!strict && commonDatatype.isDurationDatatype()) { Duration left = XMLDatatypeUtil.parseDuration(leftLit.getLabel()); Duration right = XMLDatatypeUtil.parseDuration(rightLit.getLabel()); int compare = left.compare(right); if (compare != DatatypeConstants.INDETERMINATE) { return Order.from(compare); } else { return otherCases(leftLit, rightLit, leftCoreDatatype, rightCoreDatatype, leftLangLit, rightLangLit); } } else if (commonDatatype == CoreDatatype.XSD.STRING) { return Order.from(leftLit.getLabel().compareTo(rightLit.getLabel())); } return null; } private static Order otherCases(Literal leftLit, Literal rightLit, CoreDatatype.XSD leftCoreDatatype, CoreDatatype.XSD rightCoreDatatype, boolean leftLangLit, boolean rightLangLit) { boolean literalsEqual = leftLit.equals(rightLit); if (!literalsEqual) { if (!leftLangLit && !rightLangLit && isSupportedDatatype(leftCoreDatatype) && isSupportedDatatype(rightCoreDatatype)) { // left and right arguments have incompatible but supported datatypes // we need to check that the lexical-to-value mapping for both datatypes succeeds if (!XMLDatatypeUtil.isValidValue(leftLit.getLabel(), leftCoreDatatype)) { return Order.incompatibleValueExpression; } if (!XMLDatatypeUtil.isValidValue(rightLit.getLabel(), rightCoreDatatype)) { return Order.incompatibleValueExpression; } boolean leftString = leftCoreDatatype == CoreDatatype.XSD.STRING; boolean leftNumeric = leftCoreDatatype.isNumericDatatype(); boolean leftDate = leftCoreDatatype.isCalendarDatatype(); boolean rightString = rightCoreDatatype == CoreDatatype.XSD.STRING; boolean rightNumeric = rightCoreDatatype.isNumericDatatype(); boolean rightDate = rightCoreDatatype.isCalendarDatatype(); if (leftString != rightString) { return Order.incompatibleValueExpression; } if (leftNumeric != rightNumeric) { return Order.incompatibleValueExpression; } if (leftDate != rightDate) { return Order.incompatibleValueExpression; } } else if (!leftLangLit && !rightLangLit) { // For literals with unsupported datatypes we don't know if their values are equal return Order.incompatibleValueExpression; } } if (literalsEqual) { return Order.equal; } return Order.notEqual; } private static CoreDatatype.XSD getCommonDatatype(boolean strict, CoreDatatype.XSD leftCoreDatatype, CoreDatatype.XSD rightCoreDatatype) { if (leftCoreDatatype != null && rightCoreDatatype != null) { if (leftCoreDatatype == rightCoreDatatype) { return leftCoreDatatype; } else if (leftCoreDatatype.isNumericDatatype() && rightCoreDatatype.isNumericDatatype()) { // left and right arguments have different datatypes, try to find a more general, shared datatype if (leftCoreDatatype == CoreDatatype.XSD.DOUBLE || rightCoreDatatype == CoreDatatype.XSD.DOUBLE) { return CoreDatatype.XSD.DOUBLE; } else if (leftCoreDatatype == CoreDatatype.XSD.FLOAT || rightCoreDatatype == CoreDatatype.XSD.FLOAT) { return CoreDatatype.XSD.FLOAT; } else if (leftCoreDatatype == CoreDatatype.XSD.DECIMAL || rightCoreDatatype == CoreDatatype.XSD.DECIMAL) { return CoreDatatype.XSD.DECIMAL; } else { return CoreDatatype.XSD.INTEGER; } } else if (!strict && leftCoreDatatype.isCalendarDatatype() && rightCoreDatatype.isCalendarDatatype()) { // We're not running in strict eval mode so we use extended datatype comparsion. return CoreDatatype.XSD.DATETIME; } else if (!strict && leftCoreDatatype.isDurationDatatype() && rightCoreDatatype.isDurationDatatype()) { return CoreDatatype.XSD.DURATION; } } return null; } /** * Checks whether the supplied value is a "plain literal". A "plain literal" is a literal with no datatype and * optionally a language tag. * * @see <a href="http://www.w3.org/TR/2004/REC-rdf-concepts-20040210/#dfn-plain-literal">RDF Literal * Documentation</a> */ public static boolean isPlainLiteral(Value v) { if (v.isLiteral()) { return isPlainLiteral(((Literal) v)); } return false; } public static boolean isPlainLiteral(Literal l) { assert l.getLanguage().isEmpty() || (l.getCoreDatatype() == CoreDatatype.RDF.LANGSTRING); return l.getCoreDatatype() == CoreDatatype.XSD.STRING || l.getCoreDatatype() == CoreDatatype.RDF.LANGSTRING; } /** * Checks whether the supplied value is a "simple literal". A "simple literal" is a literal with no language tag nor * datatype. * * @see <a href="http://www.w3.org/TR/sparql11-query/#simple_literal">SPARQL Simple Literal Documentation</a> */ public static boolean isSimpleLiteral(Value v) { if (v.isLiteral()) { return isSimpleLiteral((Literal) v); } return false; } // public static boolean isPlainLiteral(Literal l) { // return l.getCoreDatatype().filter(d -> d == CoreDatatype.XSD.STRING).isPresent(); //// return l.getCoreDatatype().orElse(null) == CoreDatatype.XSD.STRING; // } /** * Checks whether the supplied literal is a "simple literal". A "simple literal" is a literal with no language tag * and the datatype {@link CoreDatatype.XSD#STRING}. * * @see <a href="http://www.w3.org/TR/sparql11-query/#simple_literal">SPARQL Simple Literal Documentation</a> */ public static boolean isSimpleLiteral(Literal l) { return l.getCoreDatatype() == CoreDatatype.XSD.STRING; } /** * Checks whether the supplied literal is a "simple literal". A "simple literal" is a literal with no language tag * and the datatype {@link CoreDatatype.XSD#STRING}. * * @see <a href="http://www.w3.org/TR/sparql11-query/#simple_literal">SPARQL Simple Literal Documentation</a> */ public static boolean isSimpleLiteral(boolean isLang, CoreDatatype datatype) { return datatype == CoreDatatype.XSD.STRING; } /** * Checks whether the supplied literal is a "string literal". A "string literal" is either a simple literal, a plain * literal with language tag, or a literal with datatype CoreDatatype.XSD:string. * * @see <a href="http://www.w3.org/TR/sparql11-query/#func-string">SPARQL Functions on Strings Documentation</a> */ public static boolean isStringLiteral(Value v) { if (v.isLiteral()) { return isStringLiteral((Literal) v); } return false; } /** * Checks whether the supplied two literal arguments are 'argument compatible' according to the SPARQL definition. * * @param arg1 the first argument * @param arg2 the second argument * @return true iff the two supplied arguments are argument compatible, false otherwise * @see <a href="http://www.w3.org/TR/sparql11-query/#func-arg-compatibility">SPARQL Argument Compatibility * Rules</a> */ public static boolean compatibleArguments(Literal arg1, Literal arg2) { // 1. The arguments are literals typed as CoreDatatype.XSD:string // 2. The arguments are language literals with identical language tags // 3. The first argument is a language literal and the second // argument is a literal typed as CoreDatatype.XSD:string return (isSimpleLiteral(arg1) && isSimpleLiteral(arg2)) || (Literals.isLanguageLiteral(arg1) && Literals.isLanguageLiteral(arg2) && arg1.getLanguage().equals(arg2.getLanguage())) || (Literals.isLanguageLiteral(arg1) && isSimpleLiteral(arg2)); } /** * Checks whether the supplied literal is a "string literal". A "string literal" is either a simple literal, a plain * literal with language tag, or a literal with datatype CoreDatatype.XSD:string. * * @see <a href="http://www.w3.org/TR/sparql11-query/#func-string">SPARQL Functions on Strings Documentation</a> */ public static boolean isStringLiteral(Literal l) { return l.getCoreDatatype() == CoreDatatype.XSD.STRING || l.getCoreDatatype() == CoreDatatype.RDF.LANGSTRING; } private static boolean isSupportedDatatype(CoreDatatype.XSD datatype) { return datatype != null && (datatype == CoreDatatype.XSD.STRING || datatype.isNumericDatatype() || datatype.isCalendarDatatype()); } public enum Result { _true(true), _false(false), incompatibleValueExpression(), illegalArgument(); static Result fromBoolean(boolean b) { if (b) { return _true; } return _false; } private final boolean value; private final boolean isIncompatible; Result(boolean value) { this.value = value; isIncompatible = false; } Result() { isIncompatible = true; value = false; } public boolean orElse(boolean alternative) { if (this == incompatibleValueExpression) { return alternative; } else if (this == illegalArgument) { throw new IllegalStateException("IllegalArgument needs to be handled"); } return value; } } enum Order { smaller(-1), greater(1), equal(0), notEqual(0), incompatibleValueExpression(0), illegalArgument(0); private final int value; Order(int value) { this.value = value; } public static Order from(int value) { if (value < 0) { return smaller; } if (value > 0) { return greater; } return equal; } public int asInt() { if (!isValid() && this != notEqual) { throw new IllegalStateException(); } return value; } public boolean isValid() { return !(this == incompatibleValueExpression || this == illegalArgument); } public Result toResult(CompareOp operator) { if (!isValid()) { if (this == incompatibleValueExpression) { return Result.incompatibleValueExpression; } if (this == illegalArgument) { return Result.illegalArgument; } } if (this == notEqual) { switch (operator) { case EQ: return Result._false; case NE: return Result._true; case LT: case LE: case GE: case GT: return Result.incompatibleValueExpression; default: return Result.illegalArgument; } } switch (operator) { case LT: return Result.fromBoolean(value < 0); case LE: return Result.fromBoolean(value <= 0); case EQ: return Result.fromBoolean(value == 0); case NE: return Result.fromBoolean(value != 0); case GE: return Result.fromBoolean(value >= 0); case GT: return Result.fromBoolean(value > 0); default: return Result.illegalArgument; } } } }
36.479927
117
0.713371
234d856838d81927d5c7bff90460cedf764a91e7
1,127
/* * 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 analisador; import java.util.HashMap; import java.util.Map; /** * * @author lufh */ public class Analisador { private static Map <Integer, String> regras = new HashMap <Integer, String>(); /** * @param args the command line arguments */ public static void main(String[] args) { regras.put(1, "S -> F"); regras.put(2, "S ->(S + F)"); regras.put(3, "F -> a"); Prod.setRegras(regras); System.out.print("Start Symbol: "); Prod.getStartSymbol(); System.out.println("\nGramática:"); Prod.getRegras(); System.out.print("Não terminais: {"); System.out.println(Prod.getNaoTerminais()+" }"); Prod.buscaProd(); } }
21.264151
84
0.492458
ce25e34ec9f5bf9d37044825a02e73200f0f2dab
1,134
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.preference; /** * Interface definition for a callback to be invoked when this * {@link Preference} changes with respect to enabling/disabling * dependents. */ interface OnDependencyChangeListener { /** * Called when this preference has changed in a way that dependents should * care to change their state. * * @param disablesDependent Whether the dependent should be disabled. */ void onDependencyChanged(Preference dependency, boolean disablesDependent); }
34.363636
79
0.734568
8e2460677f7b9bdb0b0f6101349ec33ef70b5d87
571
package com.codepreplabs.consumer; import java.util.Scanner; public class Consumer implements Runnable { private Object lock; private Scanner scanner; public Consumer(Object lock) { this.lock = lock; } public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock) { System.out.println("Starting consumer..... click enter to continue"); scanner = new Scanner(System.in); scanner.nextLine(); System.out.println("Consumer started"); lock.notify(); } } }
15.861111
72
0.670753
2abd00606bb0ecd8684dadb0097de3df2271e679
277
package com.swall.tra; import android.app.Activity; import android.os.Bundle; /** * Created by pxz on 14-1-6. */ public class UploadProgressActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
21.307692
54
0.729242
6ccfbe2b3d6e2ffec11a7e571d8d3b07692767ba
3,686
/* ** Author(s): Miguel Calejo ** Contact: [email protected], http://www.declarativa.com ** Copyright (C) Declarativa, Portugal, 2000-2005 ** Use and distribution, without any warranties, under the terms of the ** GNU Library General Public License, readable in http://www.fsf.org/copyleft/lgpl.html */ package com.declarativa.interprolog; import junit.framework.*; import java.util.*; import com.declarativa.interprolog.util.*; public abstract class SubprocessEngineTest extends PrologEngineTest { public SubprocessEngineTest(String name){ super(name); } protected void setUp() throws java.lang.Exception{ engine = buildNewEngine(); //System.out.println("SubprocessEngineTest version:"+engine.getPrologVersion()); thisID = engine.registerJavaObject(this); loadTestFile(); engine.waitUntilAvailable(); } protected void tearDown() throws java.lang.Exception{ engine.shutdown(); } public void testDeterministicGoal(){ super.testDeterministicGoal(); try{ // Now working thanks to catch: engine.waitUntilAvailable(); engine.deterministicGoal("nowaythisisdefined"); fail("should raise an IPException... with undefined predicate message"); } catch (IPException e){ // Too strict for the stream-based recognizers: // assertTrue("proper message in exception",e.toString().indexOf("Undefined")!=-1); assertTrue("No more listeners",((SubprocessEngine)engine).errorTrigger.numberListeners()==0); } } public void testManyEngines(){ SubprocessEngine[] engines = new SubprocessEngine[4]; // 3 hangs on my Windows 98, at least 10 work on NT 4 Workstation for (int i=0;i<engines.length;i++) { //System.out.println("Creating engine "+i); engines[i] = (SubprocessEngine)buildNewEngine(); } for (int i=0;i<engines.length;i++) engines[i].waitUntilAvailable(); //assertTrue(engines[i].isAvailable()); for (int i=0;i<engines.length;i++) assertTrue(engines[i].deterministicGoal("true")); for (int i=0;i<engines.length;i++) engines[i].shutdown(); } StringBuffer buffer; public void testOutputListening(){ buffer = new StringBuffer(); PrologOutputListener listener = new PrologOutputListener(){ public void print(String s){ buffer.append(s); } }; assertEquals(0,((SubprocessEngine)engine).listeners.size()); ((SubprocessEngine)engine).addPrologOutputListener(listener); assertEquals(1,((SubprocessEngine)engine).listeners.size()); engine.deterministicGoal("write('hello,'), write(' tester'), nl"); engine.waitUntilAvailable(); try{Thread.sleep(100);} catch(Exception e){fail(e.toString());} // let the output flow first... assertTrue("printed something",buffer.toString().indexOf("hello, tester") != -1); assertTrue("available",engine.isAvailable()); assertTrue("detecting regular and break prompts",((SubprocessEngine)engine).isDetectingPromptAndBreak()); //engine.setDebug(true); //try{Thread.sleep(2000);} catch(Exception e){fail(e.toString());} try{ engine.deterministicGoal("thisIsUndefined");// hangs with command... fail("should have thrown exception showing undefined predicate"); } catch(IPPrologError e){/*System.out.println("caught it:"+e);*/} //System.out.println("hanging here6..."+Thread.currentThread()); engine.waitUntilAvailable(); //FAILING ALWAYS: //engine.sendAndFlushLn("bad term."); //System.out.println("now waiting; buffer:"); System.out.println(buffer); //engine.sendAndFlushLn("true."); //This "fixes" the problem on Win98 but not on NT4... engine.waitUntilAvailable(); ((SubprocessEngine)engine).removePrologOutputListener(listener); assertEquals(0,((SubprocessEngine)engine).listeners.size()); } }
40.955556
121
0.724905
5282045719ee8385bad64c1fae382c70bdcdf985
4,576
/* * Copyright 2018 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.titus.master.supervisor.service; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; /** * A JSON-serializable data transfer object for Titus master descriptions. It's used to transfer * metadata between master and workers. * * Use {@link com.netflix.titus.master.supervisor.model.MasterInstance} instead. */ @Deprecated public class MasterDescription { public static final String JSON_PROP_HOSTNAME = "hostname"; public static final String JSON_PROP_HOST_IP = "hostIP"; public static final String JSON_PROP_API_PORT = "apiPort"; public static final String JSON_PROP_API_STATUS_URI = "apiStatusUri"; public static final String JSON_PROP_CREATE_TIME = "createTime"; private final String hostname; private final String hostIP; private final int apiPort; private final String apiStatusUri; private final long createTime; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public MasterDescription( @JsonProperty(JSON_PROP_HOSTNAME) String hostname, @JsonProperty(JSON_PROP_HOST_IP) String hostIP, @JsonProperty(JSON_PROP_API_PORT) int apiPort, @JsonProperty(JSON_PROP_API_STATUS_URI) String apiStatusUri, @JsonProperty(JSON_PROP_CREATE_TIME) long createTime ) { this.hostname = hostname; this.hostIP = hostIP; this.apiPort = apiPort; this.apiStatusUri = apiStatusUri; this.createTime = createTime; } @JsonProperty(JSON_PROP_HOSTNAME) public String getHostname() { return hostname; } @JsonProperty(JSON_PROP_HOST_IP) public String getHostIP() { return hostIP; } @JsonProperty(JSON_PROP_API_PORT) public int getApiPort() { return apiPort; } @JsonProperty(JSON_PROP_API_STATUS_URI) public String getApiStatusUri() { return apiStatusUri; } @JsonProperty(JSON_PROP_CREATE_TIME) public long getCreateTime() { return createTime; } public String getFullApiStatusUri() { String uri = getApiStatusUri().trim(); if (uri.startsWith("/")) { uri = uri.substring(1); } return String.format("http://%s:%d/%s", getHostname(), getApiPort(), uri); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("hostname", hostname) .add("hostIP", hostIP) .add("apiPort", apiPort) .add("apiStatusUri", apiStatusUri) .add("createTime", createTime) .toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MasterDescription that = (MasterDescription) o; if (apiPort != that.apiPort) { return false; } if (createTime != that.createTime) { return false; } if (apiStatusUri != null ? !apiStatusUri.equals(that.apiStatusUri) : that.apiStatusUri != null) { return false; } if (hostIP != null ? !hostIP.equals(that.hostIP) : that.hostIP != null) { return false; } return hostname != null ? hostname.equals(that.hostname) : that.hostname == null; } @Override public int hashCode() { int result = hostname != null ? hostname.hashCode() : 0; result = 31 * result + (hostIP != null ? hostIP.hashCode() : 0); result = 31 * result + apiPort; result = 31 * result + (apiStatusUri != null ? apiStatusUri.hashCode() : 0); result = 31 * result + (int) (createTime ^ (createTime >>> 32)); return result; } }
32
105
0.642701
b776f25d9eae8129ad92083357e868aec5b64ba9
3,156
package com.darkhouse.shardwar.Logic.GameEntity.Spells; import com.darkhouse.shardwar.Logic.GameEntity.GameObject; import com.darkhouse.shardwar.Logic.GameEntity.Tower.*; import com.darkhouse.shardwar.Logic.Slot.Slot; import com.darkhouse.shardwar.Player; import com.darkhouse.shardwar.ShardWar; import com.darkhouse.shardwar.Tools.AssetLoader; import java.util.ArrayList; public class Combiner extends Spell{ public static class P extends SpellPrototype{ public P() { super("combiner", new TargetData[]{ new TargetData(TargetType.SINGLE, FieldTarget.FRIENDLY, Tower.class), new TargetData(TargetType.SINGLE, FieldTarget.FRIENDLY, Tower.class) }); } @Override public String getTooltip() { AssetLoader l = ShardWar.main.getAssetLoader(); return l.getWord("combinerTooltip1") + System.getProperty("line.separator") + l.getWord("combinerTooltip2"); } @Override public Spell createSpell(Player player) { return new Combiner(player, this); } } public Combiner(Player owner, SpellPrototype prototype) { super(owner, prototype); towers = new Tower[2]; } private Tower[] towers; @Override public void use(ArrayList<ArrayList<GameObject>> targets) { towers[0] = ((Tower) targets.get(0).get(0)); towers[1] = ((Tower) targets.get(1).get(0)); // System.out.println(towers[0].getClass()); // System.out.println(towers[1].getClass()); Tower.TowerPrototype newTower = null; if(towers[0].getClass() == Shotgun.class && towers[1].getClass() == Shotgun.class){ newTower = new Musket.P(); } if(towers[0].getClass() == Assault.class && towers[1].getClass() == Assault.class){ newTower = new MachineGun.P(); } if(towers[0].getClass() == Rocket.class && towers[1].getClass() == Rocket.class){ newTower = new Cannon.P(); } if(towers[0].getClass() == Rocket.class && towers[1].getClass() == Assault.class || towers[1].getClass() == Rocket.class && towers[0].getClass() == Assault.class){ newTower = new DoubleRocket.P(); } if(towers[0].getClass() == Rocket.class && towers[1].getClass() == Shotgun.class || towers[1].getClass() == Rocket.class && towers[0].getClass() == Shotgun.class){ newTower = new Sniper.P(); } if(towers[0].getClass() == Shotgun.class && towers[1].getClass() == Assault.class || towers[1].getClass() == Shotgun.class && towers[0].getClass() == Assault.class){ newTower = new DoubleBarrel.P(); } if(newTower != null) { Slot<Tower.TowerPrototype, Tower> targetSlot = towers[1].getSlot(); targetSlot.getObject().die(null, false, false); towers[0].die(null, false, false); targetSlot.build(newTower); } // System.out.println(towers[0]); // System.out.println(towers[1]); } }
33.574468
96
0.592205
5abfb5a37cc2334838afeb542763c112c34e6418
448
package Commands; import Audio.SoundLibrary; import Main.WeenieBot; import net.dv8tion.jda.core.events.Event; public class ReloadCommand extends Command { public ReloadCommand(String user, String message, Event event) { super(user, message, event, CommandType.RELOAD_LIBRARY); } @Override public void processCommand() { SoundLibrary.ReloadLibrary(); WeenieBot.getInstance().ReleaseLock(); } }
21.333333
66
0.703125